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.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_scene.py | from ..._impl.omnigraph_toolkit.toolkit_frame_scene import * # noqa: F401,PLW0401,PLW0614
| 91 | Python | 44.999978 | 90 | 0.758242 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_toolkit/toolkit_frame_memory.py | from ..._impl.omnigraph_toolkit.toolkit_frame_memory import * # noqa: F401,PLW0401,PLW0614
| 92 | Python | 45.499977 | 91 | 0.76087 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/metadata_manager.py | from ..._impl.omnigraph_node_description_editor.metadata_manager import * # noqa
| 82 | Python | 40.49998 | 81 | 0.768293 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_controller.py | from ..._impl.omnigraph_node_description_editor.main_controller import * # noqa
| 81 | Python | 39.99998 | 80 | 0.765432 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/change_management.py | from ..._impl.omnigraph_node_description_editor.change_management import * # noqa
| 83 | Python | 40.99998 | 82 | 0.771084 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_list_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_list_manager import * # noqa
| 88 | Python | 43.499978 | 87 | 0.772727 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/memory_type_manager.py | from ..._impl.omnigraph_node_description_editor.memory_type_manager import * # noqa
| 85 | Python | 41.999979 | 84 | 0.764706 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_language_manager.py | from ..._impl.omnigraph_node_description_editor.node_language_manager import * # noqa
| 87 | Python | 42.999979 | 86 | 0.770115 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_model.py | from ..._impl.omnigraph_node_description_editor.main_model import * # noqa
| 76 | Python | 37.499981 | 75 | 0.75 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/tests_data_manager.py | from ..._impl.omnigraph_node_description_editor.tests_data_manager import * # noqa
| 84 | Python | 41.499979 | 83 | 0.761905 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/node_properties.py | from ..._impl.omnigraph_node_description_editor.node_properties import * # noqa
| 81 | Python | 39.99998 | 80 | 0.765432 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_properties.py | from ..._impl.omnigraph_node_description_editor.attribute_properties import * # noqa
| 86 | Python | 42.499979 | 85 | 0.77907 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_union_type_adder_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_union_type_adder_manager import * # noqa
| 100 | Python | 49.499975 | 99 | 0.78 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/extension_info_manager.py | from ..._impl.omnigraph_node_description_editor.extension_info_manager import * # noqa
| 88 | Python | 43.499978 | 87 | 0.772727 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_editor.py | from ..._impl.omnigraph_node_description_editor.main_editor import * # noqa
| 77 | Python | 37.999981 | 76 | 0.753247 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/test_configurations.py | from ..._impl.omnigraph_node_description_editor.test_configurations import * # noqa
| 85 | Python | 41.999979 | 84 | 0.776471 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/main_generator.py | from ..._impl.omnigraph_node_description_editor.main_generator import * # noqa
| 80 | Python | 39.49998 | 79 | 0.7625 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_base_type_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_base_type_manager import * # noqa
| 93 | Python | 45.999977 | 92 | 0.774194 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/attribute_tuple_count_manager.py | from ..._impl.omnigraph_node_description_editor.attribute_tuple_count_manager import * # noqa
| 95 | Python | 46.999977 | 94 | 0.778947 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/file_manager.py | from ..._impl.omnigraph_node_description_editor.file_manager import * # noqa
| 78 | Python | 38.499981 | 77 | 0.75641 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/scripts/omnigraph_node_description_editor/ogn_editor_utils.py | from ..._impl.omnigraph_node_description_editor.ogn_editor_utils import * # noqa
| 82 | Python | 40.49998 | 81 | 0.756098 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_api.py | """Testing the stability of the API in this module"""
import omni.graph.core.tests as ogts
import omni.graph.ui as ogu
from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents
# ======================================================================
class _TestOmniGraphUiApi(ogts.OmniGraphTestCase):
_UNPUBLISHED = ["bindings", "ogn", "tests", "omni"]
async def test_api(self):
_check_module_api_consistency(ogu, self._UNPUBLISHED) # noqa: PLW0212
_check_module_api_consistency(ogu.tests, is_test_module=True) # noqa: PLW0212
async def test_api_features(self):
"""Test that the known public API features continue to exist"""
_check_public_api_contents( # noqa: PLW0212
ogu,
[
"add_create_menu_type",
"build_port_type_convert_menu",
"ComputeNodeWidget",
"find_prop",
"GraphVariableCustomLayout",
"OmniGraphAttributeModel",
"OmniGraphTfTokenAttributeModel",
"OmniGraphBase",
"OmniGraphPropertiesWidgetBuilder",
"PrimAttributeCustomLayoutBase",
"PrimPathCustomLayoutBase",
"RandomNodeCustomLayoutBase",
"ReadPrimsCustomLayoutBase",
"remove_create_menu_type",
"SETTING_PAGE_NAME",
],
self._UNPUBLISHED,
only_expected_allowed=True,
)
_check_public_api_contents(ogu.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
| 1,638 | Python | 39.974999 | 107 | 0.567155 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_widgets.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import pathlib
from typing import List
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading
from omni.ui.tests.test_base import OmniUiTest
class TestOmniWidgets(OmniUiTest):
"""
Test class for testing omnigraph related widgets
"""
async def setUp(self):
await super().setUp()
usd_path = pathlib.Path(get_test_data_path(__name__))
self._golden_img_dir = usd_path.absolute().joinpath("golden_img").absolute()
self._usd_path = usd_path.absolute()
import omni.kit.window.property as p
self._w = p.get_window()
async def tearDown(self):
await super().tearDown()
async def __widget_image_test(
self,
file_path: str,
prims_to_select: List[str],
golden_img_name: str,
width=450,
height=500,
):
"""Helper to do generate a widget comparison test on a property panel"""
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window, # noqa: PLE0211,PLW0212
width=width,
height=height,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
test_file_path = self._usd_path.joinpath(file_path).absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(prims_to_select, True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name, threshold=0.15)
# Close the stage to avoid dangling references to the graph. (OM-84680)
await omni.usd.get_context().close_stage_async()
async def test_compound_node_type_widget_ui(self):
"""Tests the compound node type property pane matches the expected image"""
await self.__widget_image_test(
file_path="compound_node_test.usda",
prims_to_select=["/World/Compounds/TestCompound"],
golden_img_name="test_compound_widget.png",
height=600,
)
async def test_graph_with_variables_widget(self):
"""Tests the variable property pane on a graph prim"""
await self.__widget_image_test(
file_path="test_variables.usda",
prims_to_select=["/World/ActionGraph"],
golden_img_name="test_graph_variables.png",
height=300,
)
async def test_instance_with_variables_widget(self):
"""Tests the variable property pane on an instance prim"""
await self.__widget_image_test(
file_path="test_variables.usda",
prims_to_select=["/World/Instance"],
golden_img_name="test_instance_variables.png",
height=450,
)
| 3,577 | Python | 34.78 | 118 | 0.649427 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_property_widget.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import tempfile
from pathlib import Path
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
import omni.graph.ui._impl.omnigraph_attribute_base as ogab
import omni.graph.ui._impl.omnigraph_attribute_models as ogam
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
import omni.usd
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Sdf, Usd
_MATRIX_DIMENSIONS = {4: 2, 9: 3, 16: 4}
# ----------------------------------------------------------------------
class TestOmniGraphWidget(OmniUiTest):
"""
Tests for OmniGraphBase and associated models in this module, the custom widget for the kit property panel uses
these models which are customized for OmniGraphNode prims.
"""
TEST_GRAPH_PATH = "/World/TestGraph"
# Before running each test
async def setUp(self):
await super().setUp()
# Ensure we have a clean stage for the test
await omni.usd.get_context().new_stage_async()
# Give OG a chance to set up on the first stage update
await omni.kit.app.get_app().next_update_async()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
extension_root_folder = Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
self._golden_img_dir = extension_root_folder.joinpath("data/tests/golden_img")
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
# Close the stage to avoid dangling references to the graph. (OM-84680)
await omni.usd.get_context().close_stage_async()
await super().tearDown()
def __attribute_type_to_name(self, attribute_type: og.Type) -> str:
"""Converts an attribute type into the canonical attribute name used by the test nodes.
The rules are:
- prefix of a_
- followed by name of attribute base type
- followed by optional _N if the component count N is > 1
- followed by optional '_array' if the type is an array
Args:
type: OGN attribute type to deconstruct
Returns:
Canonical attribute name for the attribute with the given type
"""
attribute_name = f"a_{og.Type(attribute_type.base_type, 1, 0, attribute_type.role).get_ogn_type_name()}"
attribute_name = attribute_name.replace("prim", "bundle")
if attribute_type.tuple_count > 1:
if attribute_type.role in [og.AttributeRole.TRANSFORM, og.AttributeRole.FRAME, og.AttributeRole.MATRIX]:
attribute_name += f"_{_MATRIX_DIMENSIONS[attribute_type.tuple_count]}"
else:
attribute_name += f"_{attribute_type.tuple_count}"
array_depth = attribute_type.array_depth
while array_depth > 0 and attribute_type.role not in [og.AttributeRole.TEXT, og.AttributeRole.PATH]:
attribute_name += "_array"
array_depth -= 1
return attribute_name
async def test_target_attribute(self):
"""
Exercise the target-attribute customizations for Property Panel. The related code is in
omnigraph_attribute_builder.py and targets.py
"""
usd_context = omni.usd.get_context()
keys = og.Controller.Keys
controller = og.Controller()
(_, (get_parent_prims,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("GetParentPrims", "omni.graph.nodes.GetParentPrims"),
],
},
)
# The OG attribute-base UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Select the node.
usd_context.get_selection().set_selected_prim_paths([get_parent_prims.get_prim_path()], True)
# Wait for property panel to converge
await ui_test.human_delay(5)
# Click the Add-Relationship button
attr_name = "inputs:prims"
await ui_test.find(
f"Property//Frame/**/Button[*].identifier=='sdf_relationship_array_{attr_name}.add_relationships'"
).click()
# Wait for dialog to show up
await ui_test.human_delay(5)
# push the select-graph-target button and wait for dialog to close
await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click()
await ui_test.human_delay(5)
# Resize to fit the property panel, and take a snapshot
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
await ui_test.human_delay(5)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute.png")
# ----------------------------------------------------------------------
async def test_target_attribute_browse(self):
"""
Test the changing an existing selection via the dialog works
"""
usd_context = omni.usd.get_context()
keys = og.Controller.Keys
controller = og.Controller()
prim_paths = ["/World/Prim"]
(_, (read_prims_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadPrims", "omni.graph.nodes.ReadPrimsV2"),
],
keys.CREATE_PRIMS: [(prim_path, {}) for prim_path in prim_paths],
},
)
attr_name = "inputs:prims"
usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship(attr_name).AddTarget(
prim_paths[0]
)
# The OG attribute-base UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Select the node.
usd_context.get_selection().set_selected_prim_paths([read_prims_node.get_prim_path()], True)
# Wait for property panel to converge
await ui_test.human_delay(5)
# Click the Browse button
model_index = 0
await ui_test.find(
f"Property//Frame/**/Button[*].identifier=='sdf_browse_relationship_{attr_name}[{model_index}]'"
).click()
# Wait for dialog to show up
await ui_test.human_delay(5)
# push the select-graph-target button and wait for dialog to close
await ui_test.find("Select Targets//Frame/**/Button[*].identifier=='select_graph_target'").click()
await ui_test.human_delay(5)
# Resize to fit the property panel, and take a snapshot
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
await ui_test.human_delay(5)
try:
await self.capture_and_compare(
golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_browse.png"
)
# Now edit the path to verify it displays as expected
test_path = f"{og.INSTANCING_GRAPH_TARGET_PATH}/foo"
# FIXME: This input call doesn't work - set with USD instead
# await ui_test.find(
# f"Property//Frame/**/StringField[*].identifier=='sdf_relationship_{attr_name}[{model_index}]'"
# ).input(test_path)
usd_context.get_stage().GetPrimAtPath(read_prims_node.get_prim_path()).GetRelationship(
attr_name
).SetTargets([Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}")])
await ui_test.human_delay(5)
# Check the USD path has the token after the prim path, before the relative path
self.assertEqual(
usd_context.get_stage()
.GetPrimAtPath(read_prims_node.get_prim_path())
.GetRelationship(attr_name)
.GetTargets()[0],
Sdf.Path(f"{read_prims_node.get_prim_path()}/{test_path}"),
)
# Check that the composed path from OG is relative to the graph path
self.assertEqual(
str(og.Controller.get(f"{read_prims_node.get_prim_path()}.{attr_name}")[0]),
f"{self.TEST_GRAPH_PATH}/foo",
)
# Verify the widget display
await self.capture_and_compare(
golden_img_dir=self._golden_img_dir, golden_img_name="test_target_attribute_edit.png"
)
finally:
await self.finalize_test_no_image()
# ----------------------------------------------------------------------
async def test_prim_node_template(self):
"""
Tests the prim node template under different variations of selected
prims to validate the the user does not get into a state
where the attribute name cannot be edited
"""
usd_context = omni.usd.get_context()
keys = og.Controller.Keys
controller = og.Controller()
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("ReadPrim_Path_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Path_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Path_Connected", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_ValidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_InvalidTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_Connected", "omni.graph.nodes.ReadPrimAttribute"),
("ReadPrim_Prim_OGTarget", "omni.graph.nodes.ReadPrimAttribute"),
("ConstPrims", "omni.graph.nodes.ConstantPrims"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "ReadPrim_Path_Connected.inputs:primPath"),
("ConstPrims.inputs:value", "ReadPrim_Prim_Connected.inputs:prim"),
],
keys.SET_VALUES: [
("ConstToken.inputs:value", "/World/Target"),
("ReadPrim_Path_ValidTarget.inputs:usePath", True),
("ReadPrim_Path_ValidTarget.inputs:primPath", "/World/Target"),
("ReadPrim_Path_ValidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Path_InvalidTarget.inputs:usePath", True),
("ReadPrim_Path_InvalidTarget.inputs:primPath", "/World/MissingTarget"),
("ReadPrim_Path_InvalidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Path_Connected.inputs:usePath", True),
("ReadPrim_Path_Connected.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Prim_ValidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Prim_InvalidTarget.inputs:name", "xformOp:rotateXYZ"),
("ReadPrim_Prim_Connected.inputs:name", "size"),
("ReadPrim_Prim_OGTarget.inputs:name", "fileFormatVersion"),
],
keys.CREATE_PRIMS: [
("/World/Target", "Xform"),
("/World/Cube", "Cube"),
("/World/MissingTarget", "Xform"),
],
},
)
# Change the pipeline stage to On demand to prevent the graph from running and producing errors
og.cmds.ChangePipelineStage(graph=graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND)
# The OG attribute-base UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# add relationships to all
graph_path = self.TEST_GRAPH_PATH
stage = omni.usd.get_context().get_stage()
rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_ValidTarget.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target")
rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_OGTarget.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=og.INSTANCING_GRAPH_TARGET_PATH)
rel = stage.GetPropertyAtPath(f"{graph_path}/ReadPrim_Prim_InvalidTarget.inputs:prim")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/MissingTarget")
rel = stage.GetPropertyAtPath(f"{graph_path}/ConstPrims.inputs:value")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Target")
# avoids an error by removing the invalid prim after the graph is created
omni.kit.commands.execute("DeletePrims", paths=["/World/MissingTarget"])
# Go through all the ReadPrim variations and validate that the image is expected.
# In the case of a valid target the widget for the attribute should be a dropdown
# Otherwise it should be a text field
for node in nodes:
node_name = node.get_prim_path().split("/")[-1]
if not node_name.startswith("ReadPrim"):
continue
with self.subTest(node_name=node_name):
test_img_name = f"test_{node_name.lower()}.png"
# Select the node.
usd_context.get_selection().set_selected_prim_paths([node.get_prim_path()], True)
# Wait for property panel to converge
await ui_test.human_delay(5)
# Resize to fit the property panel, and take a snapshot
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=test_img_name)
# ----------------------------------------------------------------------
async def test_extended_attributes(self):
"""
Exercise the OG properties widget with extended attributes
"""
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
keys = og.Controller.Keys
controller = og.Controller()
# OGN Types that we will test resolving the inputs:value to
supported_types = [
"half",
"timecode",
"half[]",
"timecode[]",
"double[2]",
"double[3]",
"double[4]",
"double[2][]",
"double[3][]",
"double[4][]",
"float[2]",
"float[3]",
"float[4]",
"float[2][]",
"float[3][]",
"float[4][]",
"half[2]",
"half[3]",
"half[4]",
"half[2][]",
"half[3][]",
"half[4][]",
"int[2]",
"int[3]",
"int[4]",
"int[2][]",
"int[3][]",
"int[4][]",
"matrixd[2]",
"matrixd[3]",
"matrixd[4]",
"matrixd[2][]",
"matrixd[3][]",
"matrixd[4][]",
"double",
"double[]",
"frame[4]",
"frame[4][]",
"quatd[4]",
"quatf[4]",
"quath[4]",
"quatd[4][]",
"quatf[4][]",
"quath[4][]",
"colord[3]",
"colord[3][]",
"colorf[3]",
"colorf[3][]",
"colorh[3]",
"colorh[3][]",
"colord[4]",
"colord[4][]",
"colorf[4]",
"colorf[4][]",
"colorh[4]",
"colorh[4][]",
"normald[3]",
"normald[3][]",
"normalf[3]",
"normalf[3][]",
"normalh[3]",
"normalh[3][]",
"pointd[3]",
"pointd[3][]",
"pointf[3]",
"pointf[3][]",
"pointh[3]",
"pointh[3][]",
"vectord[3]",
"vectord[3][]",
"vectorf[3]",
"vectorf[3][]",
"vectorh[3]",
"vectorh[3][]",
"texcoordd[2]",
"texcoordd[2][]",
"texcoordf[2]",
"texcoordf[2][]",
"texcoordh[2]",
"texcoordh[2][]",
"texcoordd[3]",
"texcoordd[3][]",
"texcoordf[3]",
"texcoordf[3][]",
"texcoordh[3]",
"texcoordh[3][]",
"string",
"token[]",
"token",
]
attribute_names = [
self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name))
for type_name in supported_types
]
expected_values = [
ogn.get_attribute_manager_type(type_name).sample_values()[0:2] for type_name in supported_types
]
(graph, (_, write_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_PRIMS: [
(
"/World/Prim",
{
attrib_name: (usd_type, expected_value[0])
for attrib_name, usd_type, expected_value in zip(
attribute_names, supported_types, expected_values
)
},
)
],
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Write", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write.inputs:execIn"),
],
keys.SET_VALUES: [
("Write.inputs:name", "acc"),
("Write.inputs:primPath", "/World/Prim"),
("Write.inputs:usePath", True),
],
},
)
await controller.evaluate(graph)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths([write_node.get_prim_path()], True)
# The UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Test for attrib types that use OmniGraphAttributeValueModel
async def test_numeric(name, value1, value2):
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]})
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(2)
for base in ogab.OmniGraphBase._instances: # noqa: PLW0212
if base._object_paths[0].name == "inputs:value" and ( # noqa: PLW0212
isinstance(base, (ogam.OmniGraphGfVecAttributeSingleChannelModel, ogam.OmniGraphAttributeModel))
):
base.begin_edit()
base.set_value(value1)
await ui_test.human_delay(1)
base.set_value(value2)
await ui_test.human_delay(1)
base.end_edit()
await ui_test.human_delay(1)
break
# Test for attrib types that use ui.AbstractItemModel
async def test_item(name, value1, value2):
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]})
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(2)
for base in ogab.OmniGraphBase._instances: # noqa: PLW0212
if base._object_paths[0].name == "inputs:value": # noqa: PLW0212
base.begin_edit()
base.set_value(value1)
await ui_test.human_delay(1)
base.set_value(value2)
await ui_test.human_delay(1)
base.end_edit()
await ui_test.human_delay(1)
break
# Test for read-only array value - just run the code, no need to verify anything
async def test_array(name, val):
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Write.inputs:name", name)]})
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(2)
for attrib_name, test_values in zip(attribute_names, expected_values):
if attrib_name.endswith("_array"):
await test_array(attrib_name, test_values[1])
elif attrib_name in ("string", "token"):
await test_item(attrib_name, test_values[1], test_values[0])
else:
# The set_value for some types take a component, others take the whole vector/matrix
if isinstance(test_values[0], tuple) and not (
attrib_name.startswith("a_matrix")
or attrib_name.startswith("a_frame")
or attrib_name.startswith("a_quat")
):
await test_numeric(attrib_name, test_values[1][0], test_values[0][0])
else:
await test_numeric(attrib_name, test_values[1], test_values[0])
# Sanity check the final widget state display
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_attributes.png")
async def test_extended_output_attributes(self):
"""
Exercise the OG properties widget with extended attributes on read nodes
"""
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
keys = og.Controller.Keys
controller = og.Controller()
(graph, (_, read_node, _,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_PRIMS: [(("/World/Prim", {"a_token": ("token", "Ahsoka")}))],
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Read", "omni.graph.nodes.ReadPrimAttribute"),
("Write", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write.inputs:execIn"),
("Read.outputs:value", "Write.inputs:value"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Read.inputs:name", "a_token"),
("Read.inputs:primPath", "/World/Prim"),
("Read.inputs:usePath", True),
("Write.inputs:name", "a_token"),
("Write.inputs:primPath", "/World/Prim"),
("Write.inputs:usePath", True),
],
},
)
await controller.evaluate(graph)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths([read_node.get_prim_path()], True)
await ui_test.human_delay(5)
# The UI should refreshes every frame
ogab.AUTO_REFRESH_PERIOD = 0
# Sanity check the final widget state display
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="test_extended_output_attributes.png"
)
async def test_layer_identifier_resolver(self):
"""
Test layer identifier resolver using WritePrimsV2 node
/root.usda
/sub/sublayer.usda (as a sublayer of root.usda)
The OG graph will be created on /sub/sublayer.usda with layer identifier set to "./sublayer.usda"
Then open /root.usda to test the relative path is successfully resolved relative to root.usda instead
"""
with tempfile.TemporaryDirectory() as tmpdirname:
usd_context = omni.usd.get_context()
controller = og.Controller()
keys = og.Controller.Keys
await self.docked_test_window(
window=self._w._window, # noqa: PLW0212
width=450,
height=500,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
sub_dir = os.path.join(tmpdirname, "sub")
sublayer_fn = os.path.join(sub_dir, "sublayer.usda")
sublayer = Sdf.Layer.CreateNew(sublayer_fn)
sublayer.Save()
root_fn = os.path.join(tmpdirname, "root.usda")
root_layer = Sdf.Layer.CreateNew(root_fn)
root_layer.subLayerPaths.append("./sub/sublayer.usda")
root_layer.Save()
success, error = await usd_context.open_stage_async(str(root_fn))
self.assertTrue(success, error)
stage = usd_context.get_stage()
# put the graph on sublayer
# only need WritePrimsV2 node for UI tests
with Usd.EditContext(stage, sublayer):
(_, [write_prims_node], _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Write", "omni.graph.nodes.WritePrimsV2"),
],
keys.SET_VALUES: [
("Write.inputs:layerIdentifier", "./sublayer.usda"),
],
},
)
# exit the "with" and switch edit target back to root layer
usd_context.get_selection().set_selected_prim_paths([write_prims_node.get_prim_path()], True)
await ui_test.human_delay(5)
# Check the final widget state display
# The "Layer Identifier" section should show "./sub/sublayer.usda" without any "<Invalid Layer>"" tag
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="test_layer_identifier_resolver.png"
)
| 27,911 | Python | 39.926686 | 120 | 0.54294 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_action.py | """
Tests that verify action UI-dependent nodes
"""
import unittest
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.kit.test.teamcity import is_running_in_teamcity
from omni.kit.viewport.utility import get_active_viewport
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf
# ======================================================================
class TestOmniGraphAction(ogts.OmniGraphTestCase):
"""Encapsulate simple sanity tests"""
# ----------------------------------------------------------------------
@unittest.skipIf(is_running_in_teamcity(), "Crashes on TC / Linux")
async def test_camera_nodes(self):
"""Test camera-related node basic functionality"""
keys = og.Controller.Keys
controller = og.Controller()
viewport_api = get_active_viewport()
active_cam = viewport_api.camera_path
persp_cam = "/OmniverseKit_Persp"
self.assertEqual(active_cam.pathString, persp_cam)
(graph, _, _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("SetCam", "omni.graph.ui.SetActiveViewportCamera"),
],
keys.SET_VALUES: [
("SetCam.inputs:primPath", "/OmniverseKit_Top"),
],
keys.CONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
active_cam = viewport_api.camera_path
self.assertEqual(active_cam.pathString, "/OmniverseKit_Top")
# be nice - set it back
viewport_api.camera_path = persp_cam
# Tests moving the camera and camera target
controller.edit(
graph,
{
keys.DISCONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
(graph, (_, _, get_pos, get_target), _, _) = controller.edit(
graph,
{
keys.CREATE_NODES: [
("SetPos", "omni.graph.ui.SetCameraPosition"),
("SetTarget", "omni.graph.ui.SetCameraTarget"),
("GetPos", "omni.graph.ui.GetCameraPosition"),
("GetTarget", "omni.graph.ui.GetCameraTarget"),
],
keys.SET_VALUES: [
("SetPos.inputs:primPath", persp_cam),
("SetPos.inputs:position", Gf.Vec3d(1.0, 2.0, 3.0)),
# Target should be different than position
("SetTarget.inputs:target", Gf.Vec3d(-1.0, -2.0, -3.0)),
("SetTarget.inputs:primPath", persp_cam),
("GetPos.inputs:primPath", persp_cam),
("GetTarget.inputs:primPath", persp_cam),
],
keys.CONNECT: [
("OnTick.outputs:tick", "SetPos.inputs:execIn"),
("SetPos.outputs:execOut", "SetTarget.inputs:execIn"),
],
},
)
await controller.evaluate()
# XXX: May need to force these calls through legacy_viewport as C++ nodes call through to that interface.
camera_state = ViewportCameraState(persp_cam) # , viewport=viewport_api, force_legacy_api=True)
x, y, z = camera_state.position_world
for a, b in zip([x, y, z], [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
x, y, z = camera_state.target_world
for a, b in zip([x, y, z], [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# evaluate again, because push-evaluator may not have scheduled the getters after the setters
await controller.evaluate()
get_pos = og.Controller.get(controller.attribute(("outputs:position", get_pos)))
for a, b in zip(get_pos, [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
get_target = og.Controller.get(controller.attribute(("outputs:target", get_target)))
for a, b in zip(get_target, [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# ----------------------------------------------------------------------
@unittest.skipIf(is_running_in_teamcity(), "Flaky - needs investigation")
async def test_on_new_frame(self):
"""Test OnNewFrame node"""
keys = og.Controller.Keys
controller = og.Controller()
# Check that the NewFrame node is getting updated when frames are being generated
(_, (new_frame_node,), _, _) = controller.edit(
"/TestGraph", {keys.CREATE_NODES: [("NewFrame", "omni.graph.ui.OnNewFrame")]}
)
attr = controller.attribute(("outputs:frameNumber", new_frame_node))
await og.Controller.evaluate()
frame_num = og.Controller.get(attr)
# Need to tick Kit before evaluation in order to update
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await og.Controller.evaluate()
self.assertLess(frame_num, og.Controller.get(attr))
| 5,247 | Python | 43.10084 | 113 | 0.545836 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/tests/test_omnigraph_ui_sanity.py | """
Tests that do basic sanity checks on the OmniGraph UI
"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools as ogt
import omni.kit.test
import omni.usd
from carb import log_warn
from .._impl.menu import MENU_WINDOWS, Menu
from .._impl.omnigraph_node_description_editor.main_editor import Editor
# Data-driven information to allow creation of all windows without specifics.
# This assumes every class has a static get_name() method so that prior existence can be checked,
# and a show_window() or show() method which displays the window.
#
# Dictionary key is the attribute name in the test class under which this window is stored.
# Value is a list of [class, args] where:
# ui_class: Class type that instantiates the window
# args: Arguments to be passed to the window's constructor
#
ALL_WINDOW_INFO = {"_ogn_editor_window": [Editor, []]}
# ======================================================================
class TestOmniGraphUiSanity(ogts.OmniGraphTestCase):
"""Encapsulate simple sanity tests"""
# ----------------------------------------------------------------------
async def test_open_and_close_all_omnigraph_ui(self):
"""Open and close all of the OmniGraph UI windows as a basic sanity check
In order for this test to work all of the UI management classes must support these methods:
show(): Build and display the window contents
destroy(): Close the window and destroy the window elements
And the classes must derive from (metaclass=Singleton) to avoid multiple instantiations
"""
class AllWindows:
"""Encapsulate all of the windows to be tested in an object for easier destruction"""
def __init__(self):
"""Open and remember all of the windows (closing first if they were already open)"""
# The graph window needs to be passed a graph.
graph_path = "/World/TestGraph"
og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"})
for (member, (ui_class, args)) in ALL_WINDOW_INFO.items():
setattr(self, member, ui_class(*args))
async def show_all(self):
"""Find all of the OmniGraph UI windows and show them"""
for (member, (ui_class, _)) in ALL_WINDOW_INFO.items():
window = getattr(self, member)
show_fn = getattr(window, "show_window", getattr(window, "show", None))
if show_fn:
show_fn()
# Wait for an update to ensure the window has been opened
await omni.kit.app.get_app().next_update_async()
else:
log_warn(f"Not testing type {ui_class.__name__} - no show_window() or show() method")
def destroy(self):
"""Destroy the members, which cleanly destroys the windows"""
for member in ALL_WINDOW_INFO:
ogt.destroy_property(self, member)
all_windows = AllWindows()
await all_windows.show_all()
await omni.kit.app.get_app().next_update_async()
all_windows.destroy()
all_windows = None
# ----------------------------------------------------------------------
async def test_omnigraph_ui_menu(self):
"""Verify that the menu operations all work"""
menu = Menu()
for menu_path in MENU_WINDOWS:
menu.set_window_state(menu_path, True)
await omni.kit.app.get_app().next_update_async()
menu.set_window_state(menu_path, False)
async def test_omnigraph_ui_node_creation(self):
"""Check that all of the registered omni.graph.ui nodes can be created without error."""
graph_path = "/World/TestGraph"
(graph, *_) = og.Controller.edit({"graph_path": graph_path, "evaluator_name": "push"})
# Add one of every type of omni.graph.ui node to the graph.
node_types = [t for t in og.get_registered_nodes() if t.startswith("omni.graph.ui")]
prefix_len = len("omni.graph.ui_nodes.")
node_names = [name[prefix_len:] for name in node_types]
(_, nodes, _, _) = og.Controller.edit(
graph, {og.Controller.Keys.CREATE_NODES: list(zip(node_names, node_types))}
)
self.assertEqual(len(nodes), len(node_types), "Check that all nodes were created.")
for i, node in enumerate(nodes):
self.assertEqual(
node.get_prim_path(), graph_path + "/" + node_names[i], f"Check node type '{node_types[i]}'"
)
| 4,694 | Python | 43.292452 | 109 | 0.585854 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov_actions.py | import omni.kit.actions.core
def register_actions(extension_id, cls):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "AOV Menu Actions"
# actions
action_registry.register_action(
"omni.kit.menu.aov",
"create_single_aov",
cls._on_create_single_aov,
display_name="Create->AOV",
description="Create AOV",
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)
| 598 | Python | 26.227272 | 70 | 0.673913 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/aov.py | import omni.ext
import omni.kit.menu.utils
import omni.kit.context_menu
import omni.kit.commands
from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder
from pxr import Sdf, Usd, UsdUtils, Gf
from .aov_actions import register_actions, deregister_actions
class AOVMenuExtension(omni.ext.IExt):
def __init__(self):
self._aov_menu_list = []
def on_startup(self, ext_id):
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, AOVMenuExtension)
self._register_menu()
self._register_context_menu()
def on_shutdown(self):
deregister_actions(self._ext_name)
omni.kit.menu.utils.remove_menu_items(self._aov_menu_list, "Create")
self._aov_menu_list = None
self._context_menu = None
def _register_menu(self):
self._aov_menu_list = [
MenuItemDescription(name="AOV", glyph="AOV_dark.svg", appear_after=[MenuItemOrder.LAST], onclick_action=("omni.kit.menu.aov", "create_single_aov"))
]
omni.kit.menu.utils.add_menu_items(self._aov_menu_list, "Create")
def _register_context_menu(self):
menu_dict = {
'glyph': "AOV_dark.svg",
'name': 'AOV',
'show_fn': [],
'onclick_fn': AOVMenuExtension._on_create_single_aov
}
self._context_menu = omni.kit.context_menu.add_menu(menu_dict, "CREATE")
@staticmethod
def _create_render_prim(prim_type, prim_path):
import omni.usd
from omni.kit.widget.layers import LayerUtils
stage = omni.usd.get_context().get_stage()
session_layer = stage.GetSessionLayer()
current_edit_layer = Sdf.Find(LayerUtils.get_edit_target(stage))
swap_edit_targets = current_edit_layer != session_layer
rendervar_list = [ ("ldrColor", {"sourceName": "LdrColor"}),
("hdrColor", {"sourceName": "HdrColor"}),
("PtDirectIllumation", {"sourceName": "PtDirectIllumation"}),
("PtGlobalIllumination", {"sourceName": "PtGlobalIllumination"}),
("PtReflections", {"sourceName": "PtReflections"}),
("PtRefractions", {"sourceName": "PtRefractions"}),
("PtSelfIllumination", {"sourceName": "PtSelfIllumination"}),
("PtBackground", {"sourceName": "PtBackground"}),
("PtWorldNormal", {"sourceName": "PtWorldNormal"}),
("PtWorldPos", {"sourceName": "PtWorldPos"}),
("PtZDepth", {"sourceName": "PtZDepth"}),
("PtVolumes", {"sourceName": "PtVolumes"}),
("PtMultiMatte0", {"sourceName": "PtMultiMatte0"}),
("PtMultiMatte1", {"sourceName": "PtMultiMatte1"}),
("PtMultiMatte2", {"sourceName": "PtMultiMatte2"}),
("PtMultiMatte3", {"sourceName": "PtMultiMatte3"}),
("PtMultiMatte4", {"sourceName": "PtMultiMatte4"}),
("PtMultiMatte5", {"sourceName": "PtMultiMatte5"}),
("PtMultiMatte6", {"sourceName": "PtMultiMatte6"}),
("PtMultiMatte7", {"sourceName": "PtMultiMatte7"}),
]
## create prim. /Render is on session layer but need new prims in currrent layer
try:
if not current_edit_layer.GetPrimAtPath('/Render'):
omni.kit.commands.execute("CreatePrim", prim_path="/Render", prim_type="Scope", attributes={}, select_new_prim=False)
if not current_edit_layer.GetPrimAtPath('/Render/Vars'):
omni.kit.commands.execute("CreatePrim", prim_path="/Render/Vars", prim_type="Scope", attributes={}, select_new_prim=False)
omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="RenderProduct", attributes={}, select_new_prim=False)
for var_name, attributes in rendervar_list:
if not current_edit_layer.GetPrimAtPath(f"/Render/Vars/{var_name}"):
omni.kit.commands.execute("CreatePrim", prim_path=f"/Render/Vars/{var_name}", prim_type="RenderVar", attributes=attributes, select_new_prim=False)
if swap_edit_targets:
LayerUtils.set_edit_target(stage, session_layer.identifier)
# set /Render visible & non-deletable in stage window...
render_prim = stage.GetPrimAtPath("/Render")
omni.usd.editor.set_hide_in_stage_window(render_prim, False)
omni.usd.editor.set_no_delete(render_prim, True)
# set /Render/Vars visible & non-deletable in stage window...
vars_prim = stage.GetPrimAtPath("/Render/Vars")
omni.usd.editor.set_hide_in_stage_window(vars_prim, False)
omni.usd.editor.set_no_delete(vars_prim, True)
finally:
if swap_edit_targets:
LayerUtils.set_edit_target(stage, current_edit_layer.identifier)
prim = stage.GetPrimAtPath(prim_path)
if prim:
for var_name, attributes in rendervar_list:
omni.kit.commands.execute("AddRelationshipTarget", relationship=prim.GetRelationship('orderedVars'), target=f"/Render/Vars/{var_name}")
prim.CreateAttribute("resolution", Sdf.ValueTypeNames.Int2, False).Set(Gf.Vec2i(1280, 720))
@staticmethod
def _on_create_single_aov(objects=None):
with omni.kit.undo.group():
stage = omni.usd.get_context().get_stage()
prim_path = Sdf.Path(omni.usd.get_stage_next_free_path(stage, "/Render/RenderView", False))
AOVMenuExtension._create_render_prim("RenderProduct", prim_path)
| 5,872 | Python | 48.352941 | 166 | 0.585831 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/scripts/__init__.py | from .aov import *
| 19 | Python | 8.999996 | 18 | 0.68421 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/aov_tests.py | import sys
import re
import asyncio
import unittest
import carb
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
class WindowStub():
"""stub window class for use with WidgetRef & """
def undock(_):
pass
def focus(_):
pass
window_stub = WindowStub()
class TestMenuAOVs(omni.kit.test.AsyncTestCase):
async def setUp(self):
import omni.kit.material.library
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
async def tearDown(self):
pass
def get_menubar(self) -> ui_test.WidgetRef:
from omni.kit.mainwindow import get_main_window
window = get_main_window()
return ui_test.WidgetRef(widget=window._ui_main_window.main_menu_bar, path="MainWindow//Frame/MenuBar")
def find_menu(self, menubar: ui_test.WidgetRef, path: str) -> ui_test.WidgetRef:
for widget in menubar.find_all("**/"):
if isinstance(widget.widget, ui.Menu) or isinstance(widget.widget, ui.MenuItem):
if widget.widget.text.encode('ascii', 'ignore').decode().strip() == path:
return ui_test.WidgetRef(widget.widget, path="xxx", window=window_stub)
return None
async def test_aov_menus(self):
from omni.kit.menu.aov import AOVMenuExtension
# get root menu
menubar = self.get_menubar()
# new stage
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# verify one prim
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']]
self.assertTrue(prim_list == ['/Sphere'])
# use menu Create/AOV
create_widget = self.find_menu(menubar, "Create")
await create_widget.click(pos=create_widget.position+ui_test.Vec2(0, 5))
aov_widget = self.find_menu(create_widget, "AOV")
await aov_widget.click(pos=aov_widget.position+ui_test.Vec2(50, 5))
# verify multiple prims
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']]
self.assertFalse(prim_list == ['/Sphere'])
# undo changes
omni.kit.undo.undo()
# verify one prim
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']]
self.assertTrue(prim_list == ['/Sphere'])
# new stage to prevent layout dialogs
await omni.usd.get_context().new_stage_async()
| 2,868 | Python | 34.419753 | 143 | 0.643305 |
omniverse-code/kit/exts/omni.kit.menu.aov/omni/kit/menu/aov/tests/__init__.py | from .aov_tests import *
| 25 | Python | 11.999994 | 24 | 0.72 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_browser_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.usd
from . import editor
from .layer_watch import LayerWatch
from .usda_edit_utils import is_extension_loaded
import os
def content_browser_available() -> bool:
"""Returns True if the extension "omni.kit.widget.content_browser" is loaded"""
return is_extension_loaded("omni.kit.window.content_browser")
class ContentBrowserMenu:
"""
When this object is alive, Layers 2.0 has the additional context menu
with the items that allow to edit the layer in the external editor.
"""
def __init__(self):
import omni.kit.window.content_browser as content
self._content_window = content.get_content_window()
self.__start_name = self._content_window.add_context_menu(
"Edit...", "menu_rename.svg", ContentBrowserMenu.start_editing, ContentBrowserMenu.is_not_editing
)
self.__end_name = self._content_window.add_context_menu(
"Finish editing", "menu_delete.svg", ContentBrowserMenu.stop_editing, ContentBrowserMenu.is_editing
)
def destroy(self):
"""Stop all watchers and remove the menu from Layers 2.0"""
if content_browser_available():
self._content_window.delete_context_menu(self.__start_name)
self._content_window.delete_context_menu(self.__end_name)
self.__start_name = None
self.__end_name = None
self._content_window = None
LayerWatch().stop_all()
@staticmethod
def start_editing(menu: str, content_url: str):
"""Start watching for the layer and run the editor"""
usda_filename = LayerWatch().start_watch(content_url)
editor.run_editor(usda_filename)
@staticmethod
def stop_editing(menu: str, content_url: str):
"""Stop watching for the layer and remove the temporary files"""
LayerWatch().stop_watch(content_url)
@staticmethod
def is_editing(content_url: str) -> bool:
"""Returns true if the layer is already watched"""
return LayerWatch().has_watch(content_url)
@staticmethod
def is_not_editing(content_url: str) -> bool:
"""Returns true if the layer is not watched"""
return omni.usd.is_usd_writable_filetype(content_url) and not ContentBrowserMenu.is_editing(content_url)
| 2,709 | Python | 38.275362 | 112 | 0.689184 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/extension_usda.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .layers_menu import layers_available
from .layers_menu import LayersMenu
from .content_menu import ContentMenu
from .content_browser_menu import content_browser_available
from .content_browser_menu import ContentBrowserMenu
import omni.ext
import omni.kit.app
class UsdaEditExtension(omni.ext.IExt):
def on_startup(self, ext_id):
# Setup a callback for the event
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
self.__extensions_subscription = ext_manager.get_change_event_stream().create_subscription_to_pop(
self._on_event, name="omni.kit.usda_edit"
)
self.__layers_menu = None
self.__content_menu = None
self.__content_browser_menu = None
self._on_event(None)
# When kit exits we won't get a change event for content_browser unloading so we need to resort to
# an explicit subscription to its enable/disable events.
#
# If content_browser is already enabled then we will immediately get a callback for it, so we want
# to do this last.
self.__content_browser_hook = ext_manager.subscribe_to_extension_enable(
self._on_browser_enabled, self._on_browser_disabled, 'omni.kit.window.content_browser')
def _on_browser_enabled(self, ext_id: str):
if not self.__content_browser_menu:
self.__content_browser_menu = ContentBrowserMenu()
def _on_browser_disabled(self, ext_id: str):
if self.__content_browser_menu:
self.__content_browser_menu.destroy()
self.__content_browser_menu = None
def _on_event(self, event):
# Create/destroy the menu in the Layers window
if self.__layers_menu:
if not layers_available():
self.__layers_menu.destroy()
self.__layers_menu = None
else:
if layers_available():
self.__layers_menu = LayersMenu()
# TODO: Create/destroy the menu in the Content Browser
if self.__content_menu:
self.__content_menu.destroy()
self.__content_menu = None
def on_shutdown(self):
self.__extensions_subscription = None
self.__content_browser_hook = None
if self.__layers_menu:
self.__layers_menu.destroy()
self.__layers_menu = None
if self.__content_menu:
self.__content_menu.destroy()
self.__content_menu = None
if self.__content_browser_menu:
self.__content_browser_menu.destroy()
self.__content_browser_menu = None
| 3,068 | Python | 37.3625 | 106 | 0.648305 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layer_watch.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
from pxr import Sdf
from pxr import Tf
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import asyncio
import carb
import functools
import omni.kit.app
import os.path
import random
import string
import tempfile
import traceback
def handle_exception(func):
"""
Decorator to print exception in async functions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
# We always cancel the task. It's not a problem.
pass
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
def Singleton(class_):
"""
A singleton decorator.
TODO: It's also available in omni.kit.widget.stage. We need a utility
extension where we can put the utilities like this.
"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@Singleton
class LayerWatch:
"""
Singleton object that contains all the layer watchers. When the watcher
is removed, the tmp file and directory are also removed.
"""
def __init__(self):
self.__items = {}
def start_watch(self, identifier):
"""
Create a temporary usda file and watch it. When this file is changed,
the layer with the given identifier will be updated.
"""
watch_item = self.__items.get(identifier, None)
if not watch_item:
watch_item = LayerWatchItem(identifier)
self.__items[identifier] = watch_item
return watch_item.file_name
def stop_watch(self, identifier):
"""
Stop watching to the temporary file created to the layer with the
given identifier. It will remove the temporary file.
"""
if identifier in self.__items:
self.__items[identifier].destroy()
del self.__items[identifier]
def has_watch(self, identifier):
"""
Return true if the layer with the given identifier is watched.
"""
return identifier in self.__items
def stop_all(self):
"""
Stop watching for all the layers.
"""
for _, watch in self.__items.items():
watch.destroy()
self.__items = {}
@handle_exception
async def wait_import_async(self, identifier):
"""
Wait for the importing of the layer. It happens when the layer is
changed.
"""
if identifier in self.__items:
await self.__items[identifier].wait_import_async()
class LayerWatchItem(FileSystemEventHandler):
def __init__(self, identifier):
super().__init__()
# SdfLayer
self.__layer = Sdf.Layer.FindOrOpen(identifier)
# Generate random name for temp directory
while True:
letters = string.ascii_lowercase
dir_name = "kit_usda_" + "".join(random.choice(letters) for i in range(8))
tmp_path = Path(tempfile.gettempdir()).joinpath(dir_name)
if not tmp_path.exists():
break
# Create temporary directory
tmp_path.mkdir()
# Create temporary usda file
tmp_file_path = tmp_path.joinpath(Tf.MakeValidIdentifier(Path(identifier).stem) + ".usda")
self.__file_name = tmp_file_path.resolve().__str__()
self.__layer.Export(self.__file_name)
# Save the timestamp
self.__last_mtime = os.path.getmtime(self.__file_name)
self.__build_task = None
self.__loop = asyncio.get_event_loop()
# Watch the file
self.__observer = Observer()
self.__observer.schedule(self, path=tmp_path, recursive=False)
self.__observer.start()
# This event is set when the layer is re-imported.
self.__imported_event = asyncio.Event()
@property
def file_name(self):
"""Return the temporary file name"""
return self.__file_name
def on_modified(self, event):
"""Called by watchdog when the temporary file is changed"""
# Check it's the file we are watching.
if event.src_path != self.file_name:
return
# Check the modification time.
mtime = os.path.getmtime(self.file_name)
if self.__last_mtime == mtime:
return
self.__last_mtime = mtime
# Watchdog calls callback from different thread and USD doesn't like
# it. We need to import USDA from the main thread.
if self.__build_task:
self.__build_task.cancel()
self.__build_task = asyncio.ensure_future(self.__import(), loop=self.__loop)
@handle_exception
async def __import(self):
"""Import temporary file to the USD layer"""
# Wait one frame on the case there was multiple events at the same time
await omni.kit.app.get_app().next_update_async()
file_name = self.file_name
# The file extension. For anonymous layers it's ".sdf"
format_id = f".{self.__layer.GetFileFormat().formatId}"
if format_id == ".omni_usd" or format_id == ".usd_omni_wrapper":
# The layer is on the omni server
# Import is not implemented in the Omniverse file format. So we
# clear it and transfer the content to the layer on the server.
usda = Sdf.Layer.FindOrOpen(file_name)
self.__layer.Clear()
self.__layer.TransferContent(usda)
else:
# USD can't do cross-format Import, but it can do cross-format
# export.
if Path(file_name).suffix != format_id:
# Export usda to the format of the layer.
usda = Sdf.Layer.FindOrOpen(file_name)
file_name = file_name + format_id
usda.Export(file_name)
# Import
self.__layer.Import(file_name)
if not self.__layer.anonymous:
# Save if it's not an anonymous layer. So the edit goes directly to
# the server or to the filesystem.
self.__layer.Save()
self.__imported_event.set()
self.__imported_event.clear()
@handle_exception
async def wait_import_async(self):
"""
Wait for the importing of the layer. It happens when the layer is
changed.
"""
await self.__imported_event.wait()
def destroy(self):
"""Stop watching. Delete the temporary file and the temporary directory."""
if self.__observer:
self.__observer.stop()
# Wait when it stops.
# TODO: We need to stop all of them and then join all of them.
self.__observer.join()
self.__observer = None
if self.__layer:
self.__layer = None
# Remove tmp file and tmp folder
if os.path.exists(self.__file_name):
tmp_path = Path(self.__file_name).parent
for f in tmp_path.iterdir():
if f.is_file():
f.unlink()
tmp_path.rmdir()
self.__imported_event.set()
def __del__(self):
self.destroy()
| 7,901 | Python | 30.73494 | 98 | 0.599291 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/layers_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from . import editor
from .layer_watch import LayerWatch
from .usda_edit_utils import is_extension_loaded
def layers_available() -> bool:
"""Returns True if the extension "omni.kit.widget.layers" is loaded"""
return is_extension_loaded("omni.kit.widget.layers")
class LayersMenu:
"""
When this object is alive, Layers 2.0 has the additional context menu
with the items that allow to edit the layer in the external editor.
"""
def __init__(self):
import omni.kit.widget.layers as layers
self.__menu_subscription = layers.ContextMenu.add_menu(
[
{"name": ""},
{
"name": "Edit...",
"glyph": "menu_rename.svg",
"show_fn": [
layers.ContextMenu.is_layer_item,
layers.ContextMenu.is_not_missing_layer,
layers.ContextMenu.is_layer_writable,
layers.ContextMenu.is_layer_not_locked_by_other,
layers.ContextMenu.is_layer_and_parent_unmuted,
LayersMenu.is_not_editing,
],
"onclick_fn": LayersMenu.start_editing,
},
{
"name": "Finish editing",
"glyph": "menu_delete.svg",
"show_fn": [layers.ContextMenu.is_layer_item, LayersMenu.is_editing],
"onclick_fn": LayersMenu.stop_editing,
},
]
)
def destroy(self):
"""Stop all watchers and remove the menu from Layers 2.0"""
self.__menu_subscription = None
LayerWatch().stop_all()
@staticmethod
def start_editing(objects):
"""Start watching for the layer and run the editor"""
item = objects["item"]
identifier = item().identifier
usda_filename = LayerWatch().start_watch(identifier)
editor.run_editor(usda_filename)
@staticmethod
def stop_editing(objects):
"""Stop watching for the layer and remove the temporary files"""
item = objects["item"]
identifier = item().identifier
LayerWatch().stop_watch(identifier)
@staticmethod
def is_editing(objects):
"""Returns true if the layer is already watched"""
item = objects["item"]
identifier = item().identifier
return LayerWatch().has_watch(identifier)
@staticmethod
def is_not_editing(objects):
"""Returns true if the layer is not watched"""
return not LayersMenu.is_editing(objects)
| 3,067 | Python | 34.264367 | 89 | 0.592762 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/editor.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Optional
import carb.settings
import os
import shutil
import subprocess
def _is_exe(path):
"""Return true if the path is executable"""
return os.path.isfile(path) and os.access(path, os.X_OK)
def run_editor(usda_filename: str):
"""Open text editor with usda_filename in it"""
settings = carb.settings.get_settings()
# Find out which editor it's necessary to use
# Check the settings
editor: Optional[str] = settings.get("/app/editor")
if not editor:
# If settings doesn't have it, check the environment variable EDITOR.
# It's the standard way to set the editor in Linux.
editor = os.environ.get("EDITOR", None)
if not editor:
# VSCode is the default editor
editor = "code"
# Remove quotes because it's a common way for windows to specify paths
if editor[0] == '"' and editor[-1] == '"':
editor = editor[1:-1]
if not _is_exe(editor):
try:
# Check if we can run the editor
editor = shutil.which(editor)
except shutil.Error:
editor = None
if not editor:
if os.name == "nt":
# All Windows have notepad
editor = "notepad"
else:
# Most Linux systems have gedit
editor = "gedit"
if os.name == "nt":
# Using cmd on the case the editor is bat or cmd file
call_command = ["cmd", "/c"]
else:
call_command = []
call_command.append(editor)
call_command.append(usda_filename)
# Non blocking call
subprocess.Popen(call_command)
| 2,054 | Python | 29.671641 | 77 | 0.642648 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/content_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from . import editor
from .layer_watch import LayerWatch
from .usda_edit_utils import is_extension_loaded
from omni.kit.ui import get_custom_glyph_code
from pathlib import Path
class ContentMenu:
"""
When this object is alive, Content Browser has the additional context menu
with the items that allow to edit the USD files in the external editor.
"""
def __init__(self):
import omni.kit.content as content
self._content_window = content.get_content_window()
edit_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_rename.svg")} Edit...'
self.__edit_menu_subscription = self._content_window.add_icon_menu(
edit_menu_name, self._on_start_editing, self._is_edit_visible
)
stop_menu_name = f'{get_custom_glyph_code("${glyphs}/menu_delete.svg")} Finish editing'
self.__stop_menu_subscription = self._content_window.add_icon_menu(
stop_menu_name, self._on_stop_editing, self._is_stop_visible
)
def _is_edit_visible(self, content_url):
'''True if we can show the menu item "Edit"'''
for ext in ["usd", "usda", "usdc"]:
if content_url.endswith(f".{ext}"):
return not LayerWatch().has_watch(content_url)
def _on_start_editing(self, menu, value):
"""Start watching for the layer and run the editor"""
file_path = self._content_window.get_selected_icon_path()
usda_filename = LayerWatch().start_watch(file_path)
editor.run_editor(usda_filename)
def _is_stop_visible(self, content_url):
"""Returns true if the layer is already watched"""
return LayerWatch().has_watch(content_url)
def _on_stop_editing(self, menu, value):
"""Stop watching for the layer and remove the temporary files"""
file_path = self._content_window.get_selected_icon_path()
LayerWatch().stop_watch(file_path)
def destroy(self):
"""Stop all watchers and remove the menu from the content browser"""
del self.__edit_menu_subscription
self.__edit_menu_subscription = None
del self.__stop_menu_subscription
self.__stop_menu_subscription = None
self._content_window = None
LayerWatch().stop_all()
| 2,699 | Python | 39.298507 | 96 | 0.669507 |
omniverse-code/kit/exts/omni.kit.usda_edit/omni/kit/usda_edit/tests/usda_test.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from ..layer_watch import LayerWatch
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from pxr import Usd
from pxr import UsdGeom
import omni.client
import omni.kit
import omni.usd
import os
import time
import unittest
OMNI_SERVER = "omniverse://kit.nucleus.ov-ci.nvidia.com"
OMNI_USER = "omniverse"
OMNI_PASS = "omniverse"
class TestUsdaEdit(OmniUiTest):
def __set_omni_credentials(self):
# Save the environment to be able to restore it
self.__OMNI_USER = os.environ.get("OMNI_USER", None)
self.__OMNI_PASS = os.environ.get("OMNI_PASS", None)
# Set the credentials
os.environ["OMNI_USER"] = OMNI_USER
os.environ["OMNI_PASS"] = OMNI_PASS
def __restore_omni_credentials(self):
if self.__OMNI_USER is not None:
os.environ["OMNI_USER"] = self.__OMNI_USER
else:
os.environ.pop("OMNI_USER")
if self.__OMNI_PASS is not None:
os.environ["OMNI_PASS"] = self.__OMNI_PASS
else:
os.environ.pop("OMNI_PASS")
async def test_open_file(self):
# New stage with a sphere
await omni.usd.get_context().new_stage_async()
omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False)
stage = omni.usd.get_context().get_stage()
# Create USDA
usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier)
# Check it's a valid stage
duplicate = Usd.Stage.Open(usda_filename)
self.assertTrue(duplicate)
# Check it has the sphere
sphere = duplicate.GetPrimAtPath("/Sphere")
self.assertTrue(sphere)
UsdGeom.Cylinder.Define(duplicate, '/Cylinder')
duplicate.Save()
await omni.kit.app.get_app().next_update_async()
# Check cylinder is created
cylinder = duplicate.GetPrimAtPath("/Cylinder")
self.assertTrue(cylinder)
# Remove USDA
LayerWatch().stop_watch(stage.GetRootLayer().identifier)
# Check the file is removed
self.assertFalse(Path(usda_filename).exists())
await omni.kit.app.get_app().next_update_async()
@unittest.skip("Works locally, but fails on TC for server connection in linux -> flaky")
async def test_edit_file_on_nucleus(self):
self.__set_omni_credentials()
# Create a new stage on server
temp_usd_folder = f"{OMNI_SERVER}/Users/test_usda_edit_{str(time.time())}"
temp_usd_file_path = f"{temp_usd_folder}/test_edit_file_on_nucleus.usd"
# cleanup first
await omni.client.delete_async(temp_usd_folder)
# create the folder
result = await omni.client.create_folder_async(temp_usd_folder)
self.assertEqual(result, omni.client.Result.OK)
stage = Usd.Stage.CreateNew(temp_usd_file_path)
await omni.kit.app.get_app().next_update_async()
UsdGeom.Xform.Define(stage, '/xform')
UsdGeom.Sphere.Define(stage, '/xform/sphere')
await omni.kit.app.get_app().next_update_async()
stage.Save()
# Start watching and edit the temp stage
usda_filename = LayerWatch().start_watch(stage.GetRootLayer().identifier)
temp_stage = Usd.Stage.Open(usda_filename)
# Create another sphere
UsdGeom.Sphere.Define(temp_stage, '/xform/sphere1')
# Save the stage
temp_stage.Save()
# UsdStage saves the temorary file and renames it to usda, so we need
# to touch it to let LayerWatch know it's changed.
Path(usda_filename).touch()
# Small delay because watchdog in LayerWatch doesn't call the callback
# right away. So we need to give it some time.
await LayerWatch().wait_import_async(stage.GetRootLayer().identifier)
# Remove USDA
LayerWatch().stop_watch(stage.GetRootLayer().identifier)
stage.Reload()
# Check the second sphere is there
sphere = stage.GetPrimAtPath("/xform/sphere1")
self.assertTrue(sphere)
# Remove the temp folder
result = await omni.client.delete_async(temp_usd_folder)
self.assertEqual(result, omni.client.Result.OK)
self.__restore_omni_credentials()
| 4,700 | Python | 34.885496 | 111 | 0.657021 |
omniverse-code/kit/exts/omni.usd.config/omni/usd_config/extension.py | import os
from glob import glob
from pathlib import Path
import carb
import carb.dictionary
import carb.settings
import omni.ext
import omni.kit.app
from omni.mtlx import get_mtlx_stdlib_search_path
ENABLE_NESTED_GPRIMS_SETTINGS_PATH = "/usd/enableNestedGprims"
DISABLE_CAMERA_ADAPTER_SETTINGS_PATH = "/usd/disableCameraAdapter"
MDL_SEARCH_PATHS_REQUIRED = "/renderer/mdl/searchPaths/required"
MDL_SEARCH_PATHS_TEMPLATES = "/renderer/mdl/searchPaths/templates"
class Extension(omni.ext.IExt):
def __init__(self):
super().__init__()
pass
def on_startup(self):
self._app = omni.kit.app.get_app()
self._settings = carb.settings.acquire_settings_interface()
self._settings.set_default_bool(ENABLE_NESTED_GPRIMS_SETTINGS_PATH, True)
self._usd_enable_nested_gprims = self._settings.get(ENABLE_NESTED_GPRIMS_SETTINGS_PATH)
self._settings.set_default_bool(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH, False)
self._usd_disable_camera_adapter = self._settings.get(DISABLE_CAMERA_ADAPTER_SETTINGS_PATH)
self._setup_usd_env_settings()
self._setup_usd_material_env_settings()
def on_shutdown(self):
self._settings = None
self._app = None
# This must be invoked before USD's TfRegistry for env settings gets initialized.
# See https://gitlab-master.nvidia.com/carbon/Graphene/merge_requests/3115#note_5019170
def _setup_usd_env_settings(self):
is_release_build = not self._app.is_debug_build()
if is_release_build:
# Disable TfEnvSetting banners (alerting users to local environment overriding Usd defaults) in release builds.
os.environ["TF_ENV_SETTING_ALERTS_ENABLED"] = "0"
# Preferring translucent over additive shaders for opacity mapped preview shaders in HdStorm.
os.environ["HDST_USE_TRANSLUCENT_MATERIAL_TAG"] = "1"
if self._usd_disable_camera_adapter:
# Disable UsdImaging camera support.
os.environ["USDIMAGING_DISABLE_CAMERA_ADAPTER"] = "1"
# Experiment with sparse light updates.
# https://github.com/PixarAnimationStudios/USD/commit/1a82d34b1144caa85909b417d18148197fba551c
# Remove this when nv-usd 20.11+ is enabled in the build.
os.environ["USDIMAGING_ENABLE_SPARSE_LIGHT_UPDATES"] = "1"
if self._usd_enable_nested_gprims:
# Enable imaging refresh for nested gprims (needed for light gizmos).
# https://nvidia-omniverse.atlassian.net/browse/OM-9446
os.environ["USDIMAGING_ENABLE_NESTED_GPRIMS"] = "1"
# Enable support for querying doubles in XformCommonAPI::GetXformVectors
os.environ["USDGEOM_XFORMCOMMONAPI_ALLOW_DOUBLES"] = "1"
# Allow material networks to be defined under IDs which are not known to SdrRegistry until we have a registration
# mechnism for mdl.
os.environ["USDIMAGING_ALLOW_UNREGISTERED_SHADER_IDS"] = "1"
# Continue supporting old mdl schema in UsdShade for now.
os.environ["USDSHADE_OLD_MDL_SCHEMA_SUPPORT"] = "1"
# Disable primvar invalidation in UsdImagingGprimAdapter so that Kit's scene delegate can perform its own primvar
# analysis.
os.environ["USDIMAGING_GPRIMADAPTER_PRIMVAR_INVALIDATION"] = "0"
# OM-18759
# Disable auto-scaling of time samples from layers whose timeCodesPerSecond do not match that of
# the stage's root layer.
# Eventually Pixar will retire this runtime switch; we'll need tooling to find and fix all
# non-compliant assets to maintain their original animated intent.
# OM-28725
# Enable auto-scaling because more and more animation content, e.g. Machinima contents, need
# this feature. Kit now has property window to adjust timeCodePerSecond for each layer so it won't
# be a big issue if animator brings in two layers with different timeCodePerSecond. Need a validator
# to notify the authors such info though.
os.environ["PCP_DISABLE_TIME_SCALING_BY_LAYER_TCPS"] = "0"
# OM-18814
# Temporarily disable notification when setting interpolation mode.
# This needs to be investigated further after Ampere demos are delivered.
os.environ["USDSTAGE_DISABLE_INTERP_NOTICE"] = "1"
# Properties which are unknown to UsdImagingGprimAdapter do not invalidate the rprim (disabled for now-
# see OM-9049. Use whitelist, blacklist, and carb logging in
# omni::usd::hydra::SceneDelegate::ProcessNonAdapterBasedPropertyChange to help contribute to re-enabling it).
# os.environ["USDIMAGING_UNKNOWN_PROPERTIES_ARE_CLEAN] = "1"
# OM-38943
# Enable parallel sync for non-material sprims (i.e., lights).
os.environ["HD_ENABLE_MULTITHREADED_NON_MATERIAL_SPRIM_SYNC"] = "1"
# OM-39636
# Disable scene index emulation until we have integated it with our HdMaterialNode changes for MDL support.
os.environ["HD_ENABLE_SCENE_INDEX_EMULATION"] = "0"
# OM-47199
# Disable the MDL Builtin Bypass for omni_usd_resolver
os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_BYPASS"] = "1"
# OM-62080
# Use NV-specific maps for optimized Hydra change tracking
os.environ["HD_CHANGETRACKER_USE_CONTIGUOUS_VALUES_MAP"] = "1"
# OM-93197
# Suppress warning spew about material bindings until assets are addressed
os.environ["USD_SHADE_MATERIAL_BINDING_API_CHECK"] = "allowMissingAPI"
def _setup_usd_material_env_settings(self):
def gather_mdl_modules(path, prefix=""):
try:
if not path.exists():
return
except:
return
for child in path.iterdir():
if child.is_file() and (child.suffix == ".mdl"):
mdl_modules.add(prefix + child.name)
elif child.is_dir():
gather_mdl_modules(child, prefix + child.stem + "/")
def process_mdl_search_path(settings_path):
paths = self._settings.get(settings_path)
if not paths:
carb.log_warn(f"Unable to query '{settings_path}' from carb.settings.")
return
paths = [Path(p.strip()) for p in paths.split(";") if p.strip()]
for p in paths:
gather_mdl_modules(p)
# use a set to avoid dupliate module names
# if Neuray finds multiple modules with the same name only the first is loaded into the database
mdl_modules = set()
process_mdl_search_path(MDL_SEARCH_PATHS_REQUIRED)
process_mdl_search_path(MDL_SEARCH_PATHS_TEMPLATES)
os.environ["OMNI_USD_RESOLVER_MDL_BUILTIN_PATHS"] = ",".join(mdl_modules)
# OM-19420, OM-88291
# Set the MaterialX library path in order to add mtlx nodes to the NDR
mtlx_library_path = get_mtlx_stdlib_search_path()
if "PXR_MTLX_STDLIB_SEARCH_PATHS" in os.environ:
os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] += os.pathsep + mtlx_library_path
else:
os.environ["PXR_MTLX_STDLIB_SEARCH_PATHS"] = mtlx_library_path
| 7,242 | Python | 42.113095 | 123 | 0.660039 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/__init__.py | from .usd_converter import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/usd_converter.py | # *****************************************************************************
# Copyright 2021 NVIDIA Corporation. All rights reserved.
# *****************************************************************************
import omni.ext
import carb
import os
import shutil
import tempfile
import carb.settings
from omni.mdl import pymdlsdk
from omni.mdl import pymdl
import omni.mdl.neuraylib
from . import mdl_usd
import asyncio
from pxr import Usd
from pxr import UsdShade
MDL_AUTOGEN_PATH = "${data}/shadergraphs/mdl_usd"
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def add_search_path_to_system_path(searchPath: str):
if not searchPath == None and not searchPath == "":
MDL_SYSTEM_PATH = "/app/mdl/additionalSystemPaths"
settings = carb.settings.get_settings()
mdl_custom_paths: List[str] = settings.get(MDL_SYSTEM_PATH) or []
mdl_custom_paths.append(searchPath)
mdl_custom_paths = list(set(mdl_custom_paths))
settings.set_string_array(MDL_SYSTEM_PATH, mdl_custom_paths)
# Functions and vars are available to other extension as usual in python: `omni.mdl.usd_converter.mdl_to_usd(x)`
#
# mdl_to_usd(moduleName, targetFolder, targetFilename)
# moduleName: module to convert (example: "nvidia/core_definitions.mdl")
# searchPath: MDL search path to be able to load MDL modules referenced by moduleName
# targetFolder: Destination folder for USD stage (default = "${data}/shadergraphs/mdl_usd")
# targetFilename: Destination stage filename (default is module name, example: "core_definitions.usda")
# output: What to output:
# a shader: omni.mdl.usd_converter.mdl_usd.OutputType.SHADER
# a material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL
# geometry and material: omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY
# nestedShaders: Do we want nested shaders or flat (default = False)
#
def mdl_to_usd(
moduleName: str,
searchPath: str = None,
targetFolder: str = MDL_AUTOGEN_PATH,
targetFilename: str = None,
output: mdl_usd.OutputType = mdl_usd.OutputType.SHADER,
nestedShaders: bool = False):
print(f"[omni.mdl.usd_converter] mdl_to_usd was called with {moduleName}")
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# Set carb.settings with new MDL search path
add_search_path_to_system_path(searchPath)
# Select a view on the database used for the rtx renderer for.
# It should be fine to use this one always. Hydra will deal with applying the changes to the
# other renderer. It would be possible to use an own space entirely but this would double module loading.
# In the long, we want to load modules only into one scope.
dbScopeName = "rtx_scope"
# we need to load modules to OV using the omni.mdl.neuraylib
# on the c++ side this is async, here it is blocking!
print(f"createMdlModule called with: {moduleName}")
ovModule = ovNeurayLib.createMdlModule(moduleName)
print(f"CoreDefinitions: {ovModule.valid()}")
if ovModule.valid():
print(f" dbScopeName: {ovModule.dbScopeName}")
print(f" dbName: {ovModule.dbName}")
print(f" qualifiedName: {ovModule.qualifiedName}")
else:
print(f" createMdlModule failed : {moduleName}")
# after the module is loaded we create a new transaction that can see the loaded module
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
# try out the high level binding
module = pymdl.Module._fetchFromDb(trans, ovModule.dbName)
if module:
print(f"MDL Qualified Name: {module.mdlName}")
print(f"MDL Simple Name: {module.mdlSimpleName}")
print(f"MDL DB Name: {module.dbName}")
print(f"MDL Module filename: {module.filename}")
else:
print("MDL Module: None")
print(f"Failed to convert: {moduleName}")
return False
try:
stage = mdl_usd.Usd.Stage.CreateInMemory()
except:
trans.abort()
trans = None
return False
stage.SetMetadata('comment', 'MDL to USD conversion')
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
context.mdl_to_usd_output = output
context.mdl_to_usd_output_material_nested_shaders = nestedShaders
context.ov_neuray = ovNeurayLib
mdl_usd.module_to_stage(context, module)
# Workaround the issue creating stage under "${data}/shadergraphs/mdl_usd"
# by creating the stage in a temp folder and copying it to dest folder
with TemporaryDirectory() as temp_dir:
unmangle_helper = mdl_usd.Unmangle(context)
# Demangle instance name
(unmangled_flag, simple_name) = unmangle_helper.unmangle_mdl_identifier(module.dbName)
simple_name = simple_name.replace("::", "_")
filename = os.path.join(temp_dir, simple_name + ".usda")
if targetFilename is not None:
if targetFilename[-4:] == ".usd" or targetFilename[-5:] == ".usda":
filename = os.path.join(temp_dir, targetFilename)
else:
filename = os.path.join(temp_dir, targetFilename + ".usda")
stage.GetRootLayer().Export(filename)
# Copy file to destination folder
path = targetFolder
token = carb.tokens.get_tokens_interface()
mdlUSDPath = token.resolve(path)
dest = os.path.abspath(mdlUSDPath)
# Create folder if it does not exist
if not os.path.exists(dest):
os.makedirs(dest)
try:
shutil.copy2(filename, dest)
print(f"Stage saved as: {os.path.join(dest, os.path.basename(filename))}")
except:
print(f"Failed to save stage as: {os.path.join(dest, os.path.basename(filename))}")
pass
try:
omni.kit.window.material_graph.GraphExtension.refresh_compounds()
except:
pass
ovNeurayLib.destroyMdlModule(ovModule)
# since we have been reading only, abort
trans.abort()
trans = None
return True
def test_mdl_prim_to_usd(primPath: str):
stage = omni.usd.get_context().get_stage()
if stage:
prim = stage.GetPrimAtPath(primPath)
if prim:
mdl_prim_to_usd(stage, prim)
def mdl_prim_to_usd(stage: Usd.Stage, prim: Usd.Prim):
# Only handle material for the time beeing
if not UsdShade.Material(prim):
return
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# after the module is loaded we create a new transaction that can see the loaded module
dbScopeName = "rtx_scope"
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
context.mdl_to_usd_output = mdl_usd.OutputType = mdl_usd.OutputType.MATERIAL
context.mdl_to_usd_output_material_nested_shaders = False
context.ov_neuray = ovNeurayLib
mdl_usd.mdl_prim_to_usd(context, stage, prim)
# since we have been reading only, abort
trans.abort()
trans = None
return True
# usd_prim_to_mdl(usdStage, usdPrim, searchPath)
# usdStage: Input stage containing the Prim to convert
# usdPrim: Prim to convert (default = not set, use stage default Prim)
# searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set)
# forceNotOV: If set to True do not use the OV NeurayLib for conversion. Use specific code. (default = False)
#
async def usd_prim_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None, forceNotOV: bool = False):
print(f"[omni.mdl.usd_converter] usd_prim_to_mdl was called with {usdStage} / {usdPrim} / {searchPath} / {forceNotOV}")
rtncode = True
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# Set carb.settings with new MDL search path
add_search_path_to_system_path(searchPath)
# Select a view on the database used for the rtx renderer for.
# It should be fine to use this one always. Hydra will deal with applying the changes to the
# other renderer. It would be possible to use an own space entirely but this would double module loading.
# In the long, we want to load modules only into one scope.
dbScopeName = "rtx_scope"
# create a new transaction
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
try:
stage = mdl_usd.Usd.Stage.Open(usdStage)
except:
rtncode = False
if rtncode:
if usdPrim == None:
try:
# Determine default Prim
usdPrim = stage.GetDefaultPrim().GetPath()
except:
pass
if usdPrim == None:
print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage")
rtncode = False
if rtncode:
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
if not forceNotOV:
context.ov_neuray = ovNeurayLib
inst_name = await mdl_usd.convert_usd_to_mdl(context, usdPrim, None)
rtncode = (inst_name is not None)
# transaction might have changed internally
trans = context.transaction
if not rtncode:
print(f"[omni.mdl.usd_converter] error: Conversion failure")
trans.abort()
trans = None
return rtncode
# test_export_to_mdl(usdStage, usdPrim, searchPath)
# usdStage: Input stage containing the Prim to convert
# usdPrim: Prim to convert (default = not set, use stage default Prim)
# searchPath: MDL search path to be able to load MDL modules referenced by usdPrim (default = not set)
#
async def test_export_to_mdl(usdStage: str, usdPrim: str = None, searchPath: str = None): # pragma: no cover
# Set carb.settings with new MDL search path
add_search_path_to_system_path(searchPath)
stage = None
try:
stage = mdl_usd.Usd.Stage.Open(usdStage)
except:
return False
if usdPrim == None:
try:
# Determine default Prim
usdPrim = stage.GetDefaultPrim().GetPath()
except:
pass
if usdPrim == None:
print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage")
return False
prim = stage.GetPrimAtPath(usdPrim)
path = "c:/temp/new_module.mdl"
return asyncio.ensure_future(export_to_mdl(path, prim))
# export_to_mdl(path, prim)
# path: Output file name
# prim: Prim to convert
#
# Note: The MDL modules referenced by the prim must be in the MDL searchPath
#
async def export_to_mdl(path: str, prim: mdl_usd.Usd.Prim, forceNotOV: bool = False):
if prim == None:
print(f"[omni.mdl.usd_converter] error: No prim specified and no default prim in stage")
return False
# acquire neuray instance from OV
ovNeurayLib = omni.mdl.neuraylib.get_neuraylib()
ovNeurayLibHandle = ovNeurayLib.getNeurayAPI()
# feed the neuray instance into the python binding
neuray: pymdlsdk.INeuray = pymdlsdk.attach_ineuray(ovNeurayLibHandle)
neurayStatus: pymdlsdk.INeuray.Status = neuray.get_status()
print(f"Neuray Status: {neurayStatus}")
# Select a view on the database used for the rtx renderer for.
# It should be fine to use this one always. Hydra will deal with applying the changes to the
# other renderer. It would be possible to use an own space entirely but this would double module loading.
# In the long, we want to load modules only into one scope.
dbScopeName = "rtx_scope"
# create a new transaction
ovTransactionReadHandle = ovNeurayLib.createReadingTransaction(dbScopeName)
trans: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(ovTransactionReadHandle)
print(f"Transaction Open: {trans.is_open()}")
stage = prim.GetStage()
# create context for the conversion of the scene
context = mdl_usd.ConverterContext()
context.set_neuray(neuray)
context.set_transaction(trans)
context.set_stage(stage)
if not forceNotOV:
context.ov_neuray = ovNeurayLib
usd_prim = prim.GetPath()
inst_name = await mdl_usd.convert_usd_to_mdl(context, usd_prim, path)
rtncode = (inst_name is not None)
if rtncode:
print(f"[omni.mdl.usd_converter] Export to MDL success")
else:
print(f"[omni.mdl.usd_converter] Error: Export to MDL failure")
context.transaction.abort()
context.set_transaction(None)
return rtncode
def find_tokens(lines, filter_import_lines = False):
return mdl_usd.find_tokens(lines, filter_import_lines)
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class DiscoveryExtension(omni.ext.IExt): # pragma: no cover
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[omni.mdl.usd_converter] MDL to USD converter startup")
def on_shutdown(self):
print("[omni.mdl.usd_converter] MDL to USD converter shutdown")
| 15,345 | Python | 36.798029 | 123 | 0.676442 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/mdl_usd.py | #*****************************************************************************
# Copyright 2022 NVIDIA Corporation. All rights reserved.
#*****************************************************************************
import sys
import os
import gc
import platform
import traceback
from enum import Enum
from pxr import Usd
from pxr import Plug
from pxr import Sdr
from pxr import Sdf
from pxr import Tf
from pxr import UsdShade
from pxr import Gf
from pxr import UsdGeom
from pxr import Kind
from pxr import UsdUI
import numpy # used to represent Vectors, Matrices, and Colors
import re # For command line args
from copy import deepcopy # Dictionary merging
import tempfile
# load the binding module
print("MDL python binding about to load ...")
####################
# Omniverse code
from omni.mdl import pymdlsdk
from omni.mdl import pymdl
import omni.client
async def copy_async(texture_path, dst_path):
result = await omni.client.copy_async(texture_path, dst_path)
return (result == omni.client.Result.OK)
# Omniverse code
####################
# TODO: loading fails for debug builds of the pymdlsdk.pyd (or pymdlsdk.so on unix) module
print("MDL python binding loaded")
def str2bool(v):
return str(v).lower() in ("true", "1")
def str2MDL_TO_USD_OUTPUT(v):
if v == '1': return OutputType.SHADER
if v == '2': return OutputType.MATERIAL
if v == '3': return OutputType.MATERIAL_AND_GEOMETRY
#--------------------------------------------------------------------------------------------------
# Command line arguments
#--------------------------------------------------------------------------------------------------
class Args: # pragma: no cover
display_usage = False
options = dict()
def __init__(self):
self.options["SEARCH_PATH"] = get_examples_search_path()
self.options["MODULE"] = "::nvidia::sdk_examples::tutorials"
self.options["PRIM"] = "/example_material" # Used for USD to MDL conversion
self.options["STAGE"] = "tutorials.usda"
self.options["OUT"] = "tutorials.usda"
# Set FOR_OV to False if a Material/Shader hierarchy is required in the output USD stage
# SHADER = 1
# MATERIAL = 2
# MATERIAL_AND_GEOMETRY = 3
self.options["MDL_TO_USD_OUTPUT"] = 1
self.options["NESTED_SHADERS"] = False # See mdl_to_usd_output_material_nested_shaders
self.options["MDL_TO_USD"] = True
for a in sys.argv:
if a == "-help" or a == "-h" or a == "-?":
self.display_usage = True
break
match = re.search("(.+)=(.+)", a)
if match:
self.options[match.group(1)] = match.group(2)
# Convert paths
self.options["SEARCH_PATH"] = os.path.abspath(self.options["SEARCH_PATH"])
self.options["OUT"] = os.path.abspath(self.options["OUT"])
# Convert string args to bool
self.options["MDL_TO_USD"] = str2bool(self.options["MDL_TO_USD"])
self.options["NESTED_SHADERS"] = str2bool(self.options["NESTED_SHADERS"])
# Convert string args to int
self.options["MDL_TO_USD_OUTPUT"] = str2MDL_TO_USD_OUTPUT(self.options["MDL_TO_USD_OUTPUT"])
def usage(self):
print("usage: " + os.path.basename(sys.argv[0]) + " [-help|-h|-?] [SEARCH_PATH=<path>] [MODULE=<string>] [PRIM=<string>] [STAGE=<string>] [OUT=<string>] [MDL_TO_USD_OUTPUT=<int>] [NESTED_SHADERS=<bool>] [MDL_TO_USD=<bool>]")
print("\n")
print(" -help|-h|-?:\t Display usage")
print(" SEARCH_PATH:\t Use this as MDL search path (default: {})".format(self.options["SEARCH_PATH"]))
print(" MODULE:\t Module to load (default: {})".format(self.options["MODULE"]))
print(" PRIM:\t\t USD prim to convert to MDL (default: {})".format(self.options["PRIM"]))
print(" STAGE:\t USD stage to load and convert (default: {})".format(self.options["STAGE"]))
print(" OUT:\t\t Output file (default: {})".format(self.options["OUT"]))
print(" MDL_TO_USD_OUTPUT:\t Output either a shader (1) or material (2) or material and geometry (3) (default: {})".format(self.options["MDL_TO_USD_OUTPUT"]))
print(" NESTED_SHADERS:\t Output nested shader tree, vs. flat shader tree (default: {})".format(self.options["NESTED_SHADERS"]))
print(" MDL_TO_USD:\t MDL to USD conversion ortherwise USD to MDL (default: {})".format(self.options["MDL_TO_USD"]))
#--------------------------------------------------------------------------------------------------
# USD and misc utilities
#--------------------------------------------------------------------------------------------------
MdlIValueKindToUSD = {
pymdlsdk.IValue.Kind.VK_BOOL: Sdf.ValueTypeNames.Bool,
pymdlsdk.IValue.Kind.VK_INT : Sdf.ValueTypeNames.Int,
pymdlsdk.IValue.Kind.VK_ENUM : Sdf.ValueTypeNames.Int,
pymdlsdk.IValue.Kind.VK_FLOAT : Sdf.ValueTypeNames.Float,
pymdlsdk.IValue.Kind.VK_DOUBLE : Sdf.ValueTypeNames.Double,
pymdlsdk.IValue.Kind.VK_STRING : Sdf.ValueTypeNames.String,
pymdlsdk.IValue.Kind.VK_COLOR : Sdf.ValueTypeNames.Color3f,
pymdlsdk.IValue.Kind.VK_STRUCT : Sdf.ValueTypeNames.Token,
pymdlsdk.IValue.Kind.VK_TEXTURE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IValue.Kind.VK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IValue.Kind.VK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset
}
MdlITypeKindToUSD = {
pymdlsdk.IType.Kind.TK_BOOL: Sdf.ValueTypeNames.Bool,
pymdlsdk.IType.Kind.TK_INT : Sdf.ValueTypeNames.Int,
pymdlsdk.IType.Kind.TK_ENUM : Sdf.ValueTypeNames.Int,
pymdlsdk.IType.Kind.TK_FLOAT : Sdf.ValueTypeNames.Float,
pymdlsdk.IType.Kind.TK_DOUBLE : Sdf.ValueTypeNames.Double,
pymdlsdk.IType.Kind.TK_STRING : Sdf.ValueTypeNames.String,
pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3f,
pymdlsdk.IType.Kind.TK_STRUCT : Sdf.ValueTypeNames.Token,
pymdlsdk.IType.Kind.TK_TEXTURE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IType.Kind.TK_LIGHT_PROFILE : Sdf.ValueTypeNames.Asset,
pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT : Sdf.ValueTypeNames.Asset
}
# TODO:
# mi::neuraylib::IType::TK_BSDF
# mi::neuraylib::IType::TK_EDF
# mi::neuraylib::IType::TK_VDF
def python_vector_to_usd_type(dtype, size):
if dtype == numpy.int32 or dtype == bool:
if size == 2:
return Sdf.ValueTypeNames.Int2
elif size == 3:
return Sdf.ValueTypeNames.Int3
elif size == 4:
return Sdf.ValueTypeNames.Int4
elif dtype == numpy.float32:
if size == 2:
return Sdf.ValueTypeNames.Float2
elif size == 3:
return Sdf.ValueTypeNames.Float3
elif size == 4:
return Sdf.ValueTypeNames.Float4
elif dtype == numpy.float64:
if size == 2:
return Sdf.ValueTypeNames.Double2
elif size == 3:
return Sdf.ValueTypeNames.Double3
elif size == 4:
return Sdf.ValueTypeNames.Double4
return None
def python_vector_to_usd_value(value):
dtype = value.dtype
size = value.size
out = None
if dtype == numpy.int32 or dtype == bool:
if size == 2:
out = Gf.Vec2i(0)
elif size == 3:
out = Gf.Vec3i(0)
elif size == 4:
out = Gf.Vec4i(0)
if out != None:
for i in range(size):
out[i] = int(value[i][0])
elif dtype == numpy.float32:
if size == 2:
out = Gf.Vec2f(0)
elif size == 3:
out = Gf.Vec3f(0)
elif size == 4:
out = Gf.Vec4f(0)
if out != None:
for i in range(size):
out[i] = float(value[i][0])
elif dtype == numpy.float64:
if size == 2:
out = Gf.Vec2d(0)
elif size == 3:
out = Gf.Vec3d(0)
elif size == 4:
out = Gf.Vec4d(0)
if out != None:
for i in range(size):
out[i] = numpy.float64(value[i][0])
return out
def custom_data_from_python_vector(value):
dtype = value.dtype
out = dict()
if dtype == bool:
size = value.size
out = dict({"mdl":{"type" : "bool{}".format(size)}})
return out
def python_matrix_to_usd_type(dtype, nrow, ncol):
# numpyType Column Row OutType
m = { 'float32' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d,
3 : Sdf.ValueTypeNames.Float3Array,
4 : Sdf.ValueTypeNames.Float4Array},
3 : { 2 : Sdf.ValueTypeNames.Float2Array,
3 : Sdf.ValueTypeNames.Matrix3d,
4 : Sdf.ValueTypeNames.Float4Array},
4 : { 2 : Sdf.ValueTypeNames.Float2Array,
3 : Sdf.ValueTypeNames.Float3Array,
4 : Sdf.ValueTypeNames.Matrix4d }},
'float64' : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2d,
3 : Sdf.ValueTypeNames.Double3Array,
4 : Sdf.ValueTypeNames.Double4Array},
3 : { 2 : Sdf.ValueTypeNames.Double2Array,
3 : Sdf.ValueTypeNames.Matrix3d,
4 : Sdf.ValueTypeNames.Double4Array},
4 : { 2 : Sdf.ValueTypeNames.Double2Array,
3 : Sdf.ValueTypeNames.Double3Array,
4 : Sdf.ValueTypeNames.Matrix4d }}}
return m[dtype.name][ncol][nrow]
def python_matrix_to_usd_value(value):
dtype = value.dtype
nrow = value.shape[0]
ncol = value.shape[1]
out = None
if dtype == numpy.float32:
if ncol == 2:
if nrow == 2:
out = Gf.Matrix2d(0)
out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1])))
out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1])))
elif nrow == 3:
out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1]))]
elif nrow == 4:
out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))]
elif ncol == 3:
if nrow == 2:
out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])),
Gf.Vec2f(float(value[0][1]), float(value[1][1])),
Gf.Vec2f(float(value[0][2]), float(value[1][2]))]
elif nrow == 3:
out = Gf.Matrix3d(0)
out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2])))
out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2])))
out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2])))
elif nrow == 4:
out = [Gf.Vec4f(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4f(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])),
Gf.Vec4f(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))]
elif ncol == 4:
if nrow == 2:
out = [Gf.Vec2f(float(value[0][0]), float(value[1][0])),
Gf.Vec2f(float(value[0][1]), float(value[1][1])),
Gf.Vec2f(float(value[0][2]), float(value[1][2])),
Gf.Vec2f(float(value[0][3]), float(value[1][3]))]
elif nrow == 3:
out = [Gf.Vec3f(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3f(float(value[0][1]), float(value[1][1]), float(value[2][1])),
Gf.Vec3f(float(value[0][2]), float(value[1][2]), float(value[2][2])),
Gf.Vec3f(float(value[0][3]), float(value[1][3]), float(value[2][3]))]
elif nrow == 4:
out = Gf.Matrix4d(0)
out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3])))
out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3])))
out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3])))
out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3])))
elif dtype == numpy.float64:
if ncol == 2:
if nrow == 2:
out = Gf.Matrix2d(0)
out.SetColumn(0, Gf.Vec2d(float(value[0][0]), float(value[0][1])))
out.SetColumn(1, Gf.Vec2d(float(value[1][0]), float(value[1][1])))
elif nrow == 3:
out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1]))]
elif nrow == 4:
out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1]))]
elif ncol == 3:
if nrow == 2:
out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])),
Gf.Vec2d(float(value[0][1]), float(value[1][1])),
Gf.Vec2d(float(value[0][2]), float(value[1][2]))]
elif nrow == 3:
out = Gf.Matrix3d(0)
out.SetColumn(0, Gf.Vec3d(float(value[0][0]), float(value[0][1]), float(value[0][2])))
out.SetColumn(1, Gf.Vec3d(float(value[1][0]), float(value[1][1]), float(value[1][2])))
out.SetColumn(2, Gf.Vec3d(float(value[2][0]), float(value[2][1]), float(value[2][2])))
elif nrow == 4:
out = [Gf.Vec4d(float(value[0][0]), float(value[1][0]), float(value[2][0]), float(value[3][0])),
Gf.Vec4d(float(value[0][1]), float(value[1][1]), float(value[2][1]), float(value[3][1])),
Gf.Vec4d(float(value[0][2]), float(value[1][2]), float(value[2][2]), float(value[3][2]))]
elif ncol == 4:
if nrow == 2:
out = [Gf.Vec2d(float(value[0][0]), float(value[1][0])),
Gf.Vec2d(float(value[0][1]), float(value[1][1])),
Gf.Vec2d(float(value[0][2]), float(value[1][2])),
Gf.Vec2d(float(value[0][3]), float(value[1][3]))]
elif nrow == 3:
out = [Gf.Vec3d(float(value[0][0]), float(value[1][0]), float(value[2][0])),
Gf.Vec3d(float(value[0][1]), float(value[1][1]), float(value[2][1])),
Gf.Vec3d(float(value[0][2]), float(value[1][2]), float(value[2][2])),
Gf.Vec3d(float(value[0][3]), float(value[1][3]), float(value[2][3]))]
elif nrow == 4:
out = Gf.Matrix4d(0)
out.SetColumn(0, Gf.Vec4d(float(value[0][0]), float(value[0][1]), float(value[0][2]), float(value[0][3])))
out.SetColumn(1, Gf.Vec4d(float(value[1][0]), float(value[1][1]), float(value[1][2]), float(value[1][3])))
out.SetColumn(2, Gf.Vec4d(float(value[2][0]), float(value[2][1]), float(value[2][2]), float(value[2][3])))
out.SetColumn(3, Gf.Vec4d(float(value[3][0]), float(value[3][1]), float(value[3][2]), float(value[3][3])))
return out
def python_array_to_usd_type(value):
array_simple_conversion = {
bool : Sdf.ValueTypeNames.BoolArray,
int : Sdf.ValueTypeNames.IntArray,
# TODO: enum?
# AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_ENUM, SdfValueTypeNames->IntArray);
float : Sdf.ValueTypeNames.FloatArray,
# TODO: double ?
# AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_DOUBLE, SdfValueTypeNames->DoubleArray);
str : Sdf.ValueTypeNames.StringArray,
pymdlsdk.IType.Kind.TK_COLOR : Sdf.ValueTypeNames.Color3fArray
# TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_STRUCT, SdfValueTypeNames->TokenArray);
# TODO: AddArrayOfSimpleConversion(mi::neuraylib::IType::TK_TEXTURE, SdfValueTypeNames->AssetArray);
}
array_of_vector_conversion = {
numpy.bool_ : { 2 : Sdf.ValueTypeNames.Int2Array,
3 : Sdf.ValueTypeNames.Int3Array,
4 : Sdf.ValueTypeNames.Int4Array },
numpy.int32 : { 2 : Sdf.ValueTypeNames.Int2Array,
3 : Sdf.ValueTypeNames.Int3Array,
4 : Sdf.ValueTypeNames.Int4Array },
numpy.float32 : { 2 : Sdf.ValueTypeNames.Float2Array,
3 : Sdf.ValueTypeNames.Float3Array,
4 : Sdf.ValueTypeNames.Float4Array },
numpy.float64 : { 2 : Sdf.ValueTypeNames.Double2Array,
3 : Sdf.ValueTypeNames.Double3Array,
4 : Sdf.ValueTypeNames.Double4Array }
}
# // Array of matrix
# numpyType Column Row OutType
array_of_matrix = \
{ numpy.float32 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray,
3 : Sdf.ValueTypeNames.FloatArray,
4 : Sdf.ValueTypeNames.FloatArray},
3 : { 2 : Sdf.ValueTypeNames.FloatArray,
3 : Sdf.ValueTypeNames.Matrix3dArray,
4 : Sdf.ValueTypeNames.FloatArray},
4 : { 2 : Sdf.ValueTypeNames.FloatArray,
3 : Sdf.ValueTypeNames.FloatArray,
4 : Sdf.ValueTypeNames.Matrix4dArray }},
numpy.float64 : { 2 : { 2 : Sdf.ValueTypeNames.Matrix2dArray,
3 : Sdf.ValueTypeNames.DoubleArray,
4 : Sdf.ValueTypeNames.DoubleArray},
3 : { 2 : Sdf.ValueTypeNames.DoubleArray,
3 : Sdf.ValueTypeNames.Matrix3dArray,
4 : Sdf.ValueTypeNames.DoubleArray},
4 : { 2 : Sdf.ValueTypeNames.DoubleArray,
3 : Sdf.ValueTypeNames.DoubleArray,
4 : Sdf.ValueTypeNames.Matrix4dArray }}}
dtype = type(value[0])
if dtype in array_simple_conversion:
return array_simple_conversion[dtype]
elif dtype == numpy.ndarray:
shape = value[0].shape
# Array
if len(shape) > 1 and shape[1] > 1:
# Array of matrices
elemtype = type(value[0][0][0])
if elemtype in array_of_matrix:
if shape[1] in array_of_matrix[elemtype]:
if shape[0] in array_of_matrix[elemtype][shape[1]]:
return array_of_matrix[elemtype][shape[1]][shape[0]]
elif type(value[0][0]) == numpy.ndarray:
# Array of vectors
etype = type(value[0][0][0])
size = len(value[0])
if etype in array_of_vector_conversion:
if size in array_of_vector_conversion[etype]:
return array_of_vector_conversion[etype][size]
else:
print("Array of vector type not supported for type/size: {}/{}".format(etype, size))
elif len(value[0]) == 3:
# Assume this is a color
return array_simple_conversion[pymdlsdk.IType.Kind.TK_COLOR]
else:
print("Array type not supported for type/shape: {}/{}".format(dtype, shape))
else:
print("Type not supported for type: {}".format(dtype))
def python_array_to_usd_value(value):
dtype = type(value[0])
out = None
if dtype == bool or \
dtype == int or \
dtype == float or \
dtype == str:
return value
elif dtype == numpy.ndarray:
# Array
shape = value[0].shape
if len(shape) > 1 and shape[1] > 1:
# Array of matrices
elemtype = type(value[0][0][0])
nrow = shape[0]
ncol = shape[1]
out = None
arraysize = len(value)
if ncol == nrow:
if ncol == 2:
mattype = Gf.Matrix2d
if ncol == 3:
mattype = Gf.Matrix3d
if ncol == 4:
mattype = Gf.Matrix4d
out = []
for i in range(arraysize):
mat = mattype(0)
for c in range(ncol):
row = []
for r in range(nrow):
row.append(float(value[i][c][r]))
mat.SetColumn(c, row)
out.append(mat)
else:
if elemtype == numpy.float32:
otype = float
elif elemtype == numpy.float64:
otype = numpy.float64
out = []
for i in range(arraysize):
for c in range(ncol):
for r in range(nrow):
out.append(otype(value[i][r][c]))
elif type(value[0][0]) == numpy.ndarray:
# Array of vectors
etype = type(value[0][0][0])
size = len(value)
out = []
if etype == numpy.bool_ or \
etype == numpy.int32:
otype = int
elif etype == numpy.float32:
otype = float
elif etype == numpy.float64:
otype = numpy.float64
itemsize = len(value[0])
for i in range(size):
ll = []
for j in range(itemsize):
ll.append(otype(value[i][j]))
out.append(ll)
elif len(value[0]) == 3:
# Assume this is a color
size = len(value)
out = []
for i in range(size):
out.append([value[0][0], value[0][1], value[0][2]])
return out
def custom_data_from_python_array(value):
# type = dict({"mdl":{"type" : "array of matrix"}})
out = dict()
dtype = type(value[0])
arraysize = len(value)
if dtype == numpy.ndarray:
# Array
shape = value[0].shape
if len(shape) > 1 and shape[1] > 1:
# Array of matrices
elemtype = type(value[0][0][0])
nrow = shape[0]
ncol = shape[1]
elemtype = type(value[0][0][0])
if ncol != nrow or elemtype == numpy.float32:
# Non square matrices
typename = ""
if elemtype == numpy.float32:
typename = "float"
elif elemtype == numpy.float64:
typename = "double"
out = dict({"mdl":{"type" : "{}{}x{}[{}]".format(typename, ncol, nrow, arraysize)}})
elif type(value[0][0]) == numpy.ndarray:
# Array of vectors
etype = type(value[0][0][0])
if etype == numpy.bool_:
itemsize = len(value[0])
out = dict({"mdl":{"type" : "bool{}[{}]".format(itemsize, arraysize)}})
return out
def mdl_type_to_usd_type(val : pymdl.ArgumentConstant):
if not val:
return None
kind = val.type.kind
if kind in MdlITypeKindToUSD:
return MdlITypeKindToUSD[kind]
else:
# A bit more work is required to derive the type
if kind == pymdlsdk.IType.Kind.TK_VECTOR:
return python_vector_to_usd_type(val.value.dtype, val.value.size)
elif kind == pymdlsdk.IType.Kind.TK_MATRIX:
return python_matrix_to_usd_type(val.value.dtype, val.value.shape[0], val.value.shape[1])
elif kind == pymdlsdk.IType.Kind.TK_ARRAY:
return python_array_to_usd_type(val.value)
return None
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def top(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
# When converting from MDL to USD user can choose the USD output format
# SHADER: A single shader is output at the root of the USD Stage
# MATERIAL: A single material is output at the root of the USD Stage
# MATERIAL_AND_GEOMETRY: Geometry and Material (bound to the geometry) are output in the USD Stage
class OutputType(Enum):
SHADER = 1
MATERIAL = 2
MATERIAL_AND_GEOMETRY = 3
class ConverterContext():
def __init__(self):
self.neuray = None
self.transaction = None
self.stage = None
self.modules = Stack()
self.usd_materials = Stack()
self.parameter_names = Stack()
self.usd_shaders = Stack()
self.custom_data = Stack()
self.type_annotation = True
self.mdl_to_usd_output = OutputType.SHADER
self.mdl_to_usd_output_material_nested_shaders = False # Nested/deep or flat shader tree
self.ov_neuray = None
GetUniqueNameInStage.s_uniqueID = 0 # Reset the unique name counter to get same output between 2 runs
def enable_type_annotation(self):
self.type_annotation = True
def disable_type_annotation(self):
self.type_annotation = False
def is_type_annotation_enabled(self):
return self.type_annotation == True
def set_neuray(self, neuray):
self.neuray = neuray
def set_transaction(self, transaction):
self.transaction = transaction
def set_stage(self, stage):
self.stage = stage
def push_module(self, module):
self.modules.push(module)
def pop_module(self):
return self.modules.pop()
def current_module(self):
return self.modules.top()
def push_usd_material(self, material):
self.usd_materials.push(material)
def pop_usd_material(self):
return self.usd_materials.pop()
def current_usd_material(self):
return self.usd_materials.top()
def push_parameter_name(self, parm):
self.parameter_names.push(parm)
def pop_parameter_name(self):
return self.parameter_names.pop()
def current_parameter_name(self):
return self.parameter_names.top()
def push_usd_shader(self, shader):
self.usd_shaders.push(shader)
def pop_usd_shader(self):
return self.usd_shaders.pop()
def current_usd_shader(self):
return self.usd_shaders.top()
def push_custom_data(self, custom_data):
self.custom_data.push(custom_data)
def pop_custom_data(self):
return self.custom_data.pop()
def current_custom_data(self):
return self.custom_data.top()
# Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase'
# Return: 'OmniSurface/OmniSurfaceBase.mdl'
def prototype_to_source_asset(prototype):
source_asset = prototype
if source_asset[:5] == "mdl::":
source_asset = source_asset[3:] # Remove leading "mdl"
if source_asset[:2] == "::":
source_asset = source_asset[2:] # Remove leading "::"
ll = source_asset.split("::")
source_asset = '/'.join(ll[0:-1]) # Drop last part which is material name
source_asset = source_asset + ".mdl" # Append ".mdl" extension
return source_asset
def module_mdl_name_to_source_asset(context, module_mdl_name):
# Hack to convert builtin module functions
if module_mdl_name == '::scene' or module_mdl_name == '::state':
return 'nvidia/support_definitions.mdl'
unmangle_helper = UnmangleAndFixMDLSearchPath(context)
(isMangled, wasSuccess, newmodule_mdl_name) = unmangle_helper.unmangle_mdl_module(module_mdl_name)
if wasSuccess and newmodule_mdl_name != module_mdl_name:
return newmodule_mdl_name + '.mdl'
if isMangled and not wasSuccess:
# Better return empty asset than garbage asset
return ''
source_asset = module_mdl_name
if source_asset[:5] == "mdl::":
source_asset = source_asset[3:] # Remove leading "mdl"
if source_asset[:2] == "::":
source_asset = source_asset[2:] # Remove leading "::"
source_asset = source_asset.replace("::", "/") # Replace "::" with "/"
source_asset = source_asset + ".mdl" # Append ".mdl" extension
return source_asset
def source_asset_to_module_name(source_asset, context):
module_name = source_asset
module_name = os.path.normpath(module_name)
if os.path.isabs(module_name):
# Absolute path, try to find a mathing search path and remove it
with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg:
if cfg.is_valid_interface():
for i in range(cfg.get_mdl_paths_length()):
sp = cfg.get_mdl_path(i)
sp = os.path.normpath(sp.get_c_str())
if module_name.find(sp) == 0:
module_name = module_name[len(sp):]
break
# Split path
ll = module_name.split(os.sep)
# Concat path using '::' separator
module_name = "::".join(ll)
if not module_name[0:2] == "::":
# Prepend '::'
module_name = "::" + module_name
if module_name[-4:] == ".mdl":
# Remove '.mdl' extension
module_name = module_name[0:-4]
return module_name
def db_name_to_prim_name(dbname):
name = dbname
name = name.split("(")[0] # Remove arguments
name = name.split("::")[-1] # Remove package, module
name = name.replace(".", "_") # Replace '.'
return name
def mdl_name_to_sub_identifier(mdl_name, fct_call=False):
sub_id = mdl_name
if sub_id[:5] == "mdl::":
sub_id = sub_id[3:] # Remove leading "mdl"
# split the identifier from the arguments
names = sub_id.split("(")
# keep only the last name from the identifier
sub_id = names[0].split("::")[-1]
if fct_call:
# concat with args
if len(names) > 1:
sub_id = sub_id + "(" + names[1]
return sub_id
# Return a unique SdfPath for the current stage
class GetUniqueNameInStage:
s_uniqueID = 0
@staticmethod
def get(stage, path):
unique_path = path
while stage.GetPrimAtPath(unique_path).IsValid():
unique_path = Sdf.Path(str(path) + str(GetUniqueNameInStage.s_uniqueID))
GetUniqueNameInStage.s_uniqueID += 1
return unique_path
class GetUniqueName:
s_uniqueID = 0
@staticmethod
def get(transaction, prefix_in):
prefix = prefix_in
if len(prefix)==0:
prefix = "elt"
if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface():
return prefix
while True:
prefix = prefix_in + "_" + str(GetUniqueName.s_uniqueID)
GetUniqueName.s_uniqueID += 1
if not transaction.access_as(pymdlsdk.IInterface, prefix).is_valid_interface():
return prefix
def create_stage(args):
stageName = args.options["OUT"]
stage = Usd.Stage.CreateNew(stageName)
stage.SetMetadata('comment', 'MDL to USD conversion')
return stage
def load_stage(stageName):
stage = None
try:
stage = Usd.Stage.Open(stageName)
except:
print("Error:\tFailed to load stage: {}".format(stageName))
return stage
def save_stage(stage):
stage.GetRootLayer().Save()
def export_stage(stage, filename):
stage.GetRootLayer().Export(filename)
def material_to_stage_output_material(context, function: pymdl.FunctionDefinition):
return material_to_stage_output_material_and_geo(context, function, want_geometry = False)
def material_to_stage_output_material_and_geo(context, function: pymdl.FunctionDefinition, want_geometry = True):
neuray = context.neuray
transaction = context.transaction
stage = context.stage
db_name = function.dbName
materialName = db_name_to_prim_name(db_name)
# Start at root
rootPath = Sdf.Path('/')
spherePrim = None
if want_geometry:
xform = UsdGeom.Xform.Define(stage,"/World")
# Add geometry
spherePrim = UsdGeom.Sphere.Define(stage, xform.GetPath().AppendChild('Geom'))
model = Usd.ModelAPI(xform)
model.SetKind(Kind.Tokens.component)
# Create Looks scope
# Scope is the simplest grouping primitive...
scope = UsdGeom.Scope.Define(stage, xform.GetPath().AppendChild('Looks'))
rootPath = scope.GetPath()
model = Usd.ModelAPI(scope)
model.SetKind(Kind.Tokens.model)
material = None
# Create material
material = UsdShade.Material.Define(stage, rootPath.AppendChild(materialName))
if spherePrim != None:
# Bind material to geometry
UsdShade.MaterialBindingAPI(spherePrim).Bind(material)
# Create surface shader
surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("Shader"))
# Create surface shader output port
outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token)
# Create material output port
terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token)
# Connect material output to shader output
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
# Determine module asset
module_interface : pymdl.Module
module_interface = context.current_module()
module = module_interface.mdlName
source_asset = module_mdl_name_to_source_asset(context, module)
# Example:
# uniform token info:implementationSource = "sourceAsset"
# uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@
# uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material"
surfaceShader.GetImplementationSourceAttr().Set("sourceAsset")
surfaceShader.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl")
node_identifier = mdl_name_to_sub_identifier(db_name)
surfaceShader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier)
context.stage.SetDefaultPrim(material.GetPrim())
context.push_usd_material(material)
context.push_usd_shader(surfaceShader)
context.push_custom_data(dict())
definition_to_stage(context, function)
# Annotations
anno_dict = get_annotations_dict(context, function)
add_annotations_to_prim(surfaceShader.GetPrim(), anno_dict)
add_annotations_to_node(surfaceShader, anno_dict)
context.pop_custom_data()
context.pop_usd_shader()
context.pop_usd_material()
def material_to_stage_output_shader(context, function: pymdl.FunctionDefinition):
neuray = context.neuray
transaction = context.transaction
stage = context.stage
db_name = function.dbName
materialName = db_name_to_prim_name(db_name)
# Start at root
rootPath = Sdf.Path('/')
material = UsdShade.Shader.Define(stage, rootPath.AppendChild(materialName))
# Create output port
outPort = material.CreateOutput('out', Sdf.ValueTypeNames.Token).SetRenderType("material")
# Determine module asset
module_interface : pymdl.Module
module_interface = context.current_module()
module = module_interface.mdlName
source_asset = module_mdl_name_to_source_asset(context, module)
# Example:
# uniform token info:implementationSource = "sourceAsset"
# uniform asset info:mdl:sourceAsset = @nvidia/core_definitions.mdl@
# uniform token info:mdl:sourceAsset:subIdentifier = "::nvidia::core_definitions::flex_material"
material.GetImplementationSourceAttr().Set("sourceAsset")
material.SetSourceAsset(Sdf.AssetPath(source_asset), "mdl")
node_identifier = mdl_name_to_sub_identifier(db_name)
material.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier)
context.stage.SetDefaultPrim(material.GetPrim())
context.push_usd_material(material)
context.push_usd_shader(material)
context.push_custom_data(dict())
definition_to_stage(context, function)
# Annotations
anno_dict = get_annotations_dict(context, function)
add_annotations_to_prim(material.GetPrim(), anno_dict)
add_annotations_to_node(material, anno_dict)
context.pop_custom_data()
context.pop_usd_shader()
context.pop_usd_material()
def material_to_stage(context, function: pymdl.FunctionDefinition):
if context.mdl_to_usd_output == OutputType.SHADER:
return material_to_stage_output_shader(context, function)
elif context.mdl_to_usd_output == OutputType.MATERIAL:
return material_to_stage_output_material(context, function)
elif context.mdl_to_usd_output == OutputType.MATERIAL_AND_GEOMETRY:
return material_to_stage_output_material_and_geo(context, function)
def module_to_stage(context, module: pymdl.Module):
context.push_module(module)
for simple_name, overloads in module.functions.items():
f: pymdl.FunctionDefinition
for f in overloads:
material_to_stage(context, f)
anno_dict = get_annotations_dict(context, module)
add_annotations_to_stage(context, context.stage, anno_dict)
context.pop_module()
def mdl_prim_to_usd(context : ConverterContext, stage: Usd.Stage, prim: Usd.Prim, createNewMaterial: bool = False):
inst_name = None
mdl_entity = None
mdl_entity_snapshot = None
if context.ov_neuray == None:
return
# Get the shader prim from Material
shader_prim = get_shader_prim(context.stage, prim.GetPath())
mdl_entity = context.ov_neuray.createMdlEntity(shader_prim.GetPath().pathString)
mdl_entity_snapshot = None
if not mdl_entity.getMdlModule() == None:
mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity)
inst_name = mdl_entity_snapshot.dbName
source_asset = Sdf.AssetPath("")
shader = UsdShade.Shader(shader_prim)
if shader:
imp_source = shader.GetImplementationSourceAttr().Get()
if imp_source == "sourceAsset":
# Retrieve module name
source_asset = shader.GetSourceAsset("mdl")
material = UsdShade.Material(prim)
if createNewMaterial:
rootPath = Sdf.Path(prim.GetPath().GetParentPath())
# Create material
materialName = prim.GetName() + "_converted"
# Find unique name
materialName = GetUniqueNameInStage.get(stage, rootPath.AppendChild(materialName))
material = UsdShade.Material.Define(stage, materialName)
# Create surface shader
surfaceShader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild(shader_prim.GetName()))
# Create output port
outPort = surfaceShader.CreateOutput('out', Sdf.ValueTypeNames.Token)
# Create material output port
terminal = material.CreateOutput('mdl:surface', Sdf.ValueTypeNames.Token)
# Connect material output to shader output
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:volume', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
terminal = material.CreateOutput('mdl:displacement', Sdf.ValueTypeNames.Token)
terminal.ConnectToSource(outPort)
context.push_usd_material(material)
context.push_usd_shader(surfaceShader)
context.push_custom_data(dict())
fctCall = pymdl.FunctionCall._fetchFromDb(context.transaction, inst_name)
handle_function_call(context, fctCall)
context.pop_usd_material()
context.pop_usd_shader()
context.pop_custom_data()
if not mdl_entity_snapshot == None:
context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot)
if not mdl_entity == None:
context.ov_neuray.destroyMdlEntity(mdl_entity)
#--------------------------------------------------------------------------------------------------
# Utilities
#--------------------------------------------------------------------------------------------------
def get_examples_search_path():
"""Try to get the example search path or returns 'mdl' sub folder of the current directory if it failed."""
# get the environment variable that is used in all MDL SDK examples
example_sp = os.getenv('MDL_SAMPLES_ROOT')
# fall back to a path relative to this script file
if example_sp == None or not os.path.exists(example_sp):
example_sp = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')
# go down into the mdl folder
example_sp = os.path.join(example_sp, 'mdl')
# fall back to the current folder
if not os.path.exists(example_sp):
example_sp = './mdl'
return os.path.abspath(example_sp)
#--------------------------------------------------------------------------------------------------
# MDL Python Example
#--------------------------------------------------------------------------------------------------
# return usd_value, connection, usd_type
def get_usd_value_and_type(context, val : pymdl.ArgumentConstant):
if not val:
return (None, None, None)
kind = val.type.kind
usd_type = mdl_type_to_usd_type(val)
if usd_type == None:
return (None, None, None)
usd_val = None
connection = None
# -------------------------------- Atomic ---------------------------------
if kind == pymdlsdk.IType.Kind.TK_BOOL or \
kind == pymdlsdk.IType.Kind.TK_INT or \
kind == pymdlsdk.IType.Kind.TK_FLOAT or \
kind == pymdlsdk.IType.Kind.TK_DOUBLE or \
kind == pymdlsdk.IType.Kind.TK_STRING:
usd_val = val.value
elif kind == pymdlsdk.IType.Kind.TK_ENUM:
usd_val = val.value[1]
# -------------------------------- Compound ---------------------------------
elif kind == pymdlsdk.IType.Kind.TK_VECTOR:
usd_val = python_vector_to_usd_value(val.value)
if context.is_type_annotation_enabled():
custom_data = custom_data_from_python_vector(val.value)
context.current_custom_data().update(custom_data)
elif kind == pymdlsdk.IType.Kind.TK_MATRIX:
usd_val = python_matrix_to_usd_value(val.value)
elif kind == pymdlsdk.IType.Kind.TK_COLOR:
usd_val = Gf.Vec3f(val.value[0], val.value[1], val.value[2])
elif kind == pymdlsdk.IType.Kind.TK_ARRAY:
usd_val = python_array_to_usd_value(val.value)
if context.is_type_annotation_enabled():
custom_data = custom_data_from_python_array(val.value)
context.current_custom_data().update(custom_data)
elif kind == pymdlsdk.IType.Kind.TK_STRUCT:
parm_name = context.current_parameter_name()
shader = context.current_usd_shader()
usd_mat = context.current_usd_shader()
new_shader = UsdShade.Shader.Define(context.stage,
GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild("ShaderAttachement_" + parm_name)))
connection = new_shader.CreateOutput('out', Sdf.ValueTypeNames.Token)
context.push_usd_shader(new_shader)
for item in val.value:
field_name = item
context.push_parameter_name(field_name)
context.push_custom_data(dict())
v = val.value[item]
handle_value(context, v)
context.pop_custom_data()
context.pop_parameter_name()
context.pop_usd_shader()
# -------------------------------- Resource ---------------------------------
elif kind == pymdlsdk.IType.Kind.TK_TEXTURE:
ftex = val.value[0]
gamma = val.value[1]
with context.transaction.access_as(pymdlsdk.ITexture, ftex) as text:
if text.is_valid_interface():
with context.transaction.access_as(pymdlsdk.IImage, text.get_image()) as image:
if image.is_valid_interface():
usd_val = image.get_filename(0,0)
elif kind == pymdlsdk.IType.Kind.TK_LIGHT_PROFILE:
v = val.value
with context.transaction.access_as(pymdlsdk.ILightprofile, v) as obj:
if obj.is_valid_interface():
usd_val = obj.get_filename()
elif kind == pymdlsdk.IType.Kind.TK_BSDF_MEASUREMENT:
v = val.value
with context.transaction.access_as(pymdlsdk.IBsdf_measurement, v) as obj:
if obj.is_valid_interface():
usd_val = obj.get_filename()
else:
print("Error: Unknown IValue Kind for parm/kind: {}/{}".format(context.current_parameter_name(), kind))
return (usd_val, connection, usd_type)
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
# Return a dictionary of pair [string, value]
#
def get_annotations_dict(context, val):
main_dict = dict()
# We do not want to collect type annotations during conversion of annotation expressions
# Otherwise the type for the annotations is mized with the parameter annotations
context.disable_type_annotation()
try:
# Handle annotations
if val.annotations:
anno_dict = dict()
# print(f" Annotations:")
anno: pymdl.Annotation
for anno in val.annotations:
# print(f" - Simple Name: {anno.simpleName}")
# print(f" Qualified Name: {anno.name}")
# // Special case of annotations without expressions, e.g. ::anno::hidden()
# // We create a boolean VtValue and set it to true
# // Annotation:
# // ::anno::hidden()
# // becomes:
# // bool "::anno::hidden()" = 1
if len(anno.arguments.items()) == 0:
usd_value = True
usd_type = bool
anno_dict[anno.name] = usd_value
arg: pymdl.val
for arg_name, arg in anno.arguments.items():
# print(f" ({arg.type.kind}) {arg_name}: {arg.value}")
(usd_value, connection, usd_type) = get_usd_value_and_type(context, arg)
# print(f" ({usd_value}) {connection}: {usd_type}")
if usd_value != None and usd_type != None:
anno_dict[anno.name+"::"+arg_name] = usd_value
if len(anno_dict) > 0:
main_dict.update(dict({"mdl" : {"annotations": anno_dict}}))
# Handle special values, concat (possibly empty) context dictionary
main_dict = dict_of_dicts_merge(main_dict, context.current_custom_data())
except Exception as e:
print("Error while retrieving annotations")
finally:
context.enable_type_annotation()
return main_dict
def add_annotations_to_stage(context, stage, anno_dict):
try:
if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]:
stage.SetMetadata('comment', 'Conversion from MDL module: ' + anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"])
else:
if context.current_module() != None:
stage.SetMetadata('comment', 'Conversion from MDL module: ' + context.current_module().mdlName)
# TODO: Add more annotations to Stage as Metadata: version, ...
except:
pass
def add_annotations_to_node(node, anno_dict):
# display name, group and description
#
# sdrMetadata = {
# dictionary ui = {
# string displayGroup = "float2_parm group"
# }
# }
#
if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]:
for anno, key in ( \
("::anno::display_name(string)::name", "ui:displayName"), \
("::anno::in_group(string)::group", "ui:displayGroup"), \
("::anno::in_group(string,string)::group", "ui:displayGroup"), \
("::anno::in_group(string,string,string)::group", "ui:displayGroup"), \
("::anno::description(string)::description", "ui:description")):
if anno in anno_dict["mdl"]["annotations"]:
node.SetSdrMetadataByKey( key, anno_dict["mdl"]["annotations"][anno])
#
# See Also:
#
# ui = Usd.SceneGraphPrimAPI(minput.GetAttr())
# a = ui.CreateDisplayNameAttr()
#
# TODO: Could also use?
#
# minput.GetAttr().SetDisplayName("FOOBAR")
# minput.GetAttr().SetDisplayGroup("GROUP")
try:
if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]:
node.GetAttr().SetDisplayName(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"])
for anno in ( \
"::anno::in_group(string)::group", \
"::anno::in_group(string,string)::group", \
"::anno::in_group(string,string,string)::group" \
):
if anno in anno_dict["mdl"]["annotations"]:
node.GetAttr().SetDisplayGroup(anno_dict["mdl"]["annotations"][anno])
except:
pass
def add_annotations_to_prim(usd_prim, anno_dict):
if len(anno_dict) > 0:
cd = usd_prim.GetCustomData()
cd.update(anno_dict)
usd_prim.SetCustomData(cd)
try:
ui = UsdUI.UsdUIBackdrop(usd_prim)
if "::anno::description(string)::description" in anno_dict["mdl"]["annotations"]:
ui.CreateDescriptionAttr(anno_dict["mdl"]["annotations"]["::anno::description(string)::description"])
except:
pass
try:
ui = UsdUI.SceneGraphPrimAPI(usd_prim)
if "::anno::display_name(string)::name" in anno_dict["mdl"]["annotations"]:
ui.CreateDisplayNameAttr(anno_dict["mdl"]["annotations"]["::anno::display_name(string)::name"])
for anno in ( \
"::anno::in_group(string)::group", \
"::anno::in_group(string,string)::group", \
"::anno::in_group(string,string,string)::group" \
):
if anno in anno_dict["mdl"]["annotations"]:
ui.CreateDisplayGroupAttr(anno_dict["mdl"]["annotations"][anno])
except:
pass
# Hidden
if "mdl" in anno_dict and "annotations" in anno_dict["mdl"]:
if "::anno::hidden()" in anno_dict["mdl"]["annotations"]:
if anno_dict["mdl"]["annotations"]["::anno::hidden()"]:
usd_prim.SetHidden(True)
def handle_value(context, val : pymdl.ArgumentConstant):
if not val:
return
(usd_value, connection, usd_type) = get_usd_value_and_type(context, val)
if (usd_value == None and connection == None) or usd_type == None:
return
parm_name = context.current_parameter_name()
shader = context.current_usd_shader()
minput = shader.CreateInput(parm_name, usd_type)
if usd_value != None:
minput.Set(usd_value)
else:
minput.ConnectToSource(connection)
anno_dict = get_annotations_dict(context, val)
add_annotations_to_prim(minput.GetAttr(), anno_dict)
add_annotations_to_node(minput, anno_dict)
if val.type.kind == pymdlsdk.IType.Kind.TK_ENUM:
minput.SetRenderType(val.type.symbol)
def handle_expression_constant(context, expression_constant : pymdl.ArgumentConstant):
if not expression_constant:
return
handle_value(context, expression_constant)
def handle_function_call(context, function_call : pymdl.FunctionCall):
if not function_call:
return
# print("* Function definition: {}".format(function_call.functionDefinition))
# print("* MDL function definition: {}".format(function_call.mdlFunctionDefinition))
# print("* Parameter count: {}".format(len(function_call.parameters)))
fdef_db_name = function_call.functionDefinition
function_def = pymdl.FunctionDefinition._fetchFromDb(context.transaction, fdef_db_name)
if not function_def:
return
sourceAsset = module_mdl_name_to_source_asset(context, function_def.mdlModuleName)
node_identifier = mdl_name_to_sub_identifier( function_def.mdlName, True )
# Determine if function definition is variant
fctdef = context.transaction.access_as(pymdlsdk.IFunction_definition, function_def.dbName)
prototype = fctdef.get_prototype()
if prototype:
node_identifier = mdl_name_to_sub_identifier(prototype)
sourceAsset = prototype_to_source_asset(prototype)
shader = context.current_usd_shader()
shader.GetImplementationSourceAttr().Set("sourceAsset")
shader.SetSourceAsset(Sdf.AssetPath(sourceAsset), "mdl")
shader.GetPrim().CreateAttribute("info:mdl:sourceAsset:subIdentifier", Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set(node_identifier)
for name, argument in function_call.parameters.items():
# print(f"* Name: {name}")
# print(f" Type: {argument.type.kind}")
# if argument.type.symbol:
# print(f" Type Symbol: {argument.type.symbol}")
# print(f" Value: {argument.value}")
# print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}")
# print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}")
context.push_parameter_name(name)
context.push_custom_data(dict())
handle_expression(context, argument)
context.pop_custom_data()
context.pop_parameter_name()
def handle_material_instance(context, minst):
if not minst.is_valid_interface():
return
pass
def handle_expression_call(context, expression_call : pymdl.ArgumentCall):
if not expression_call:
return
neuray = context.neuray
transaction = context.transaction
# NEW
fcall : pymdl.FunctionCall
fcall = pymdl.FunctionCall._fetchFromDb(transaction, expression_call.value)
if fcall:
handle_function_call(context, fcall)
return
# TODO?
# minst = transaction.access_as(pymdlsdk.IFunction_call, expression_call.get_call())
# if minst.is_valid_interface():
# handle_material_instance(context, minst)
def handle_expression_parameter(context, expression_parameter):
if not expression_parameter.is_valid_interface():
return
pass
def handle_expression_direct_call(context, expression_direct_call):
if not expression_direct_call.is_valid_interface():
return
pass
def handle_expression_temporary(context, expression_temporary):
if not expression_temporary.is_valid_interface():
return
pass
def handle_expression(context, argument : pymdl.Argument):
if not argument:
return
if isinstance(argument, pymdl.ArgumentConstant):
# A constant expression. See #mi::neuraylib::IExpression_constant.
# argument_cst = pymdl.ArgumentConstant(argument) # FAILS
argument_cst : pymdl.ArgumentConstant
argument_cst = argument
handle_expression_constant(context, argument_cst)
elif isinstance(argument, pymdl.ArgumentCall):
# Need to:
# - create a parameter of the given type
# - create a new shader in the current material
# - Connect the parameter to the new shader
# - Evaluate the expression
expression_kind = argument.type.kind
# If the exact return type can not be determined (e.g. vectors, where to get the size?) set the parm type to Token by default
parm_type = Sdf.ValueTypeNames.Token
parm_name = context.current_parameter_name()
if expression_kind in MdlITypeKindToUSD:
parm_type = MdlITypeKindToUSD[expression_kind]
else:
print("Warning: Indirect call expression parm/kind : {}/{}".format(parm_name,argument.type.kind))
# - create a parameter of the given type
usd_shader = context.current_usd_shader()
minput = usd_shader.CreateInput(parm_name, parm_type)
# By default shaders are not nested, they are created immediately under the material
usd_mat = context.current_usd_material()
if context.mdl_to_usd_output_material_nested_shaders == True:
# Nested shaders case, create under current shader
usd_mat = context.current_usd_shader()
# - create a new shader in thecurrent material (or current shader in the nested case)
shName = GetUniqueNameInStage.get(context.stage, usd_mat.GetPath().AppendChild(parm_name))
shader = UsdShade.Shader.Define(context.stage, shName)
outPort = shader.CreateOutput('out', Sdf.ValueTypeNames.Token)
# - Connect the parameter to the new shader
minput.ConnectToSource(outPort)
context.push_usd_shader(shader)
# - Evaluate the expression
argument_call : pymdl.ArgumentCall
argument_call = argument
handle_expression_call(context, argument_call)
# Annotations
anno_dict = get_annotations_dict(context, argument_call)
add_annotations_to_prim(minput.GetAttr(), anno_dict)
add_annotations_to_node(minput, anno_dict)
context.pop_usd_shader()
# TODO
# elif kind == pymdlsdk.IExpression.Kind.EK_PARAMETER:
# # A parameter reference expression. See #mi::neuraylib::IExpression_parameter.
# # handle_expression_parameter(context, expression.get_interface(pymdlsdk.IExpression_parameter))
# pass
# elif kind == pymdlsdk.IExpression.Kind.EK_DIRECT_CALL:
# # A direct call expression. See #mi::neuraylib::IExpression_direct_call.
# # handle_expression_direct_call(context, expression.get_interface(pymdlsdk.IExpression_direct_call))
# pass
# elif kind == pymdlsdk.IExpression.Kind.EK_TEMPORARY:
# # A temporary reference expression. See #mi::neuraylib::IExpression_temporary.
# # handle_expression_temporary(context, expression.get_interface(pymdlsdk.IExpression_temporary))
# pass
def definition_to_stage(context, function: pymdl.FunctionDefinition):
neuray = context.neuray
transaction = context.transaction
argument: pymdl.Argument
for name, argument in function.parameters.items():
# print(f"* Name: {name}")
# print(f" Type: {argument.type.kind}")
# if argument.type.symbol:
# print(f" Type Symbol: {argument.type.symbol}")
# print(f" Value: {argument.value}")
# print(f" Value is Constant: {isinstance(argument, pymdl.ArgumentConstant)}")
# print(f" Value is Attachment: {isinstance(argument, pymdl.ArgumentCall)}")
context.push_parameter_name(name)
context.push_custom_data(dict())
handle_expression(context, argument)
context.pop_custom_data()
context.pop_parameter_name()
def get_db_module_name(neuray, module_mdl_name):
"""Return the db name of the given module."""
module_db_name = None
# When the module is loaded we can access it and all its definitions by accessing the DB
# for that we need to get a the database name of the module using the factory
with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory:
with factory.get_db_module_name(module_mdl_name) as istring:
if istring.is_valid_interface():
module_db_name = istring.get_c_str() # note, even though this name simple and could
# be constructed by string operations, use the
# factory to be save in case of unicode encodings
# and potential upcoming changes in the future
# # shortcut for the function above
# # this chaining is a bit special. In the C++ interface it's not possible without
# # leaking memory. Here we create the smart pointer automatically. However, the IString
# # which is created temporay here is released at the end the `load_module` function, right?
# # This might be unexpected, especially when we rely on the RAII pattern and that
# # objects are disposed at certain points in time (usually before committing a transaction)
# module_db_name_2 = factory.get_db_module_name(module_mdl_name).get_c_str()
# # note, we plan to map compatible types to python. E.g. the IString class may disappear
# return module_db_name_2
return module_db_name
#--------------------------------------------------------------------------------------------------
def get_db_definition_name(neuray, function_mdl_name):
"""Return the db name of the given function definition."""
with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory:
with factory.get_db_definition_name(function_mdl_name) as istring:
if istring.is_valid_interface():
return istring.get_c_str()
return None
#--------------------------------------------------------------------------------------------------
def load_module(context, source_asset):
success = False
module_db_name = ""
if not context.ov_neuray == None:
# We are in OV
if context.transaction:
context.transaction.commit()
context.transaction = None
module_db_name = load_module_from_ov(context.ov_neuray, source_asset.path)
dbScopeName = "rtx_scope"
rtxTransactionReadHandle = context.ov_neuray.createReadingTransaction(dbScopeName)
context.transaction: pymdlsdk.ITransaction = pymdlsdk.attach_itransaction(rtxTransactionReadHandle)
module = pymdl.Module._fetchFromDb(context.transaction, module_db_name)
success = (not module == None)
else:
module_mdl_name = source_asset_to_module_name(source_asset.path, context)
success = load_module_from_neuray(context.neuray, context.transaction, module_mdl_name)
if success:
module_db_name = get_db_module_name(context.neuray, module_mdl_name)
module = pymdl.Module._fetchFromDb(context.transaction, module_db_name)
print(f'Loaded module (from omni.mdl.neuraylib={context.ov_neuray} / source asset={source_asset}): {module.filename}')
return (success, module_db_name)
#--------------------------------------------------------------------------------------------------
def load_module_from_neuray(neuray, transaction, module_mdl_name):
"""Load the module given its name.
Returns true if the module is loaded to database"""
with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp:
with neuray.get_api_component(pymdlsdk.IMdl_factory) as factory:
# for illustation, we don't use a `with` block for the `context`, instead we release manually
context = factory.create_execution_context()
res = imp_exp.load_module(transaction, module_mdl_name, context)
context.release()
return res >= 0
#--------------------------------------------------------------------------------------------------
def load_module_from_ov(rtxneuray, module_path):
"""Load the module given its name.
Returns rtxModule.dbName if the module is loaded to database, otherwise return empty string """
rtxModule = None
try:
rtxModule = rtxneuray.createMdlModule(module_path)
except:
return ""
return rtxModule.dbName
#--------------------------------------------------------------------------------------------------
class ConvertVectorAndArray:
def create_type_or_value(self, usd_type, factory):
if usd_type in (\
Sdf.ValueTypeNames.Float2,\
Sdf.ValueTypeNames.Float2Array,\
Sdf.ValueTypeNames.Float3,\
Sdf.ValueTypeNames.Float3Array,\
Sdf.ValueTypeNames.Float4,\
Sdf.ValueTypeNames.Float4Array,\
Sdf.ValueTypeNames.FloatArray):
return factory.create_float()
elif usd_type in (\
Sdf.ValueTypeNames.Int2,\
Sdf.ValueTypeNames.Int2Array,\
Sdf.ValueTypeNames.Int3,\
Sdf.ValueTypeNames.Int3Array,\
Sdf.ValueTypeNames.Int4,\
Sdf.ValueTypeNames.Int4Array,\
Sdf.ValueTypeNames.IntArray):
return factory.create_int()
elif usd_type in (\
Sdf.ValueTypeNames.Double2,\
Sdf.ValueTypeNames.Double2Array,\
Sdf.ValueTypeNames.Double3,\
Sdf.ValueTypeNames.Double3Array,\
Sdf.ValueTypeNames.Double4,\
Sdf.ValueTypeNames.Double4Array,\
Sdf.ValueTypeNames.DoubleArray,\
Sdf.ValueTypeNames.Matrix2d,\
Sdf.ValueTypeNames.Matrix3d,\
Sdf.ValueTypeNames.Matrix4d):
return factory.create_double()
elif usd_type == Sdf.ValueTypeNames.BoolArray:
return factory.create_bool()
elif usd_type == Sdf.ValueTypeNames.StringArray:
return factory.create_string()
return None
def convert(self, input, usd_type, type_factory, value_factory, expression_factory):
value = input.Get()
if value == None:
return None
if usd_type == Sdf.ValueTypeNames.Color3fArray:
value = input.Get()
array_size = len(value)
vector_size = len(value[0])
assert(vector_size == 3)
atomic_type = type_factory.create_color()
if not atomic_type.is_valid_interface():
return None
array_type = type_factory.create_immediate_sized_array(atomic_type, array_size)
mdl_value_array = value_factory.create_array(array_type)
mdl_value_array.set_size(array_size)
for index in range(array_size):
usd_value = value[index]
atomic_value = value_factory.create_color(usd_value[0],usd_value[1],usd_value[2])
mdl_value_array.set_value(index, atomic_value)
expression = expression_factory.create_constant(mdl_value_array)
return expression
elif usd_type == Sdf.ValueTypeNames.StringArray:
value = input.Get()
array_size = len(value)
atomic_type = type_factory.create_string()
if not atomic_type.is_valid_interface():
return None
array_type = type_factory.create_immediate_sized_array(atomic_type, array_size)
mdl_value_array = value_factory.create_array(array_type)
mdl_value_array.set_size(array_size)
for index in range(array_size):
usd_value = value[index]
atomic_value = value_factory.create_string()
atomic_value.set_value(usd_value)
mdl_value_array.set_value(index, atomic_value)
expression = expression_factory.create_constant(mdl_value_array)
return expression
elif numpy.isscalar(value[0]):
# Vector
vector_size = len(value)
type = self.create_type_or_value(usd_type, type_factory)
if not type.is_valid_interface():
return None
vector_type = type_factory.create_vector(type, vector_size)
if not vector_type.is_valid_interface():
return None
mdl_value_vector = value_factory.create_vector(vector_type)
for index in range(vector_size):
usd_value = value[index]
atomic_value = self.create_type_or_value(usd_type, value_factory)
atomic_value.set_value(usd_value)
mdl_value_vector.set_value(index, atomic_value)
expression = expression_factory.create_constant(mdl_value_vector)
return expression
else:
# Array
value = input.Get()
array_size = len(value)
vector_size = len(value[0])
type = self.create_type_or_value(usd_type, type_factory)
if not type.is_valid_interface():
return None
vector_type = type_factory.create_vector(type, vector_size)
if not vector_type.is_valid_interface():
return None
array_type = type_factory.create_immediate_sized_array(vector_type, array_size)
mdl_value_array = value_factory.create_array(array_type)
mdl_value_array.set_size(array_size)
for index in range(array_size):
mdl_value_vector = value_factory.create_vector(vector_type)
usd_value = value[index]
for index2 in range(vector_size):
atomic_value = self.create_type_or_value(usd_type, value_factory)
atomic_value.set_value(usd_value[index2])
mdl_value_vector.set_value(index2, atomic_value)
mdl_value_array.set_value(index, mdl_value_vector)
expression = expression_factory.create_constant(mdl_value_array)
return expression
#--------------------------------------------------------------------------------------------------
def convert_value(context, input, mdl_type):
neuray = context.neuray
transaction = context.transaction
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
expression_factory = factory.create_expression_factory(transaction)
value_factory = factory.create_value_factory(transaction)
type_factory = factory.create_type_factory(transaction)
name = input.GetBaseName()
type = input.GetTypeName()
# Try to follow the connection
# TODO: not sure this is properly implemented, need further tests
expression = None
if input.HasConnectedSource():
(source, sourceName, sourceType) = input.GetConnectedSource()
if UsdShade.Shader(source):
prim = source.GetPrim()
inst_name = create_material_instance(context, prim.GetPath(), None) # TODO Test None expression_list
if not inst_name == None:
expression = expression_factory.create_call(inst_name)
else:
expression = convert_value(context, UsdShade.Input(input.GetValueProducingAttribute()[0]), mdl_type)
if expression == None:
# No connections
mdlvalue = None
if type == Sdf.ValueTypeNames.Int:
if not input.GetRenderType() == None:
# Handle Enum
tf = factory.create_type_factory(transaction)
if tf and tf.is_valid_interface():
et = tf.create_enum(input.GetRenderType())
if et and et.is_valid_interface():
mdlvalue = value_factory.create_enum(et)
if mdlvalue == None:
# Fallback
mdlvalue = value_factory.create_int()
elif type == Sdf.ValueTypeNames.Float:
mdlvalue = value_factory.create_float()
elif type == Sdf.ValueTypeNames.Bool:
mdlvalue = value_factory.create_bool()
elif type == Sdf.ValueTypeNames.Double:
mdlvalue = value_factory.create_double()
elif type == Sdf.ValueTypeNames.String:
mdlvalue = value_factory.create_string()
elif type == Sdf.ValueTypeNames.Color3f:
value = input.Get()
if value:
mdlvalue = value_factory.create_color(value[0], value[1], value[2])
else:
mdlvalue = value_factory.create_color(0, 0, 0)
expression = expression_factory.create_constant(mdlvalue)
return expression
elif type == Sdf.ValueTypeNames.Asset:
is_texture = mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE
if not is_texture and mdl_type.get_kind() == pymdlsdk.IType.Kind.TK_ALIAS:
type_alias = mdl_type.get_interface(pymdlsdk.IType_alias)
aliased_type = type_alias.get_aliased_type()
is_texture = aliased_type.get_kind() == pymdlsdk.IType.Kind.TK_TEXTURE
if is_texture:
# Shape
# TS_2D = 0,
# TS_3D = 1,
# TS_CUBE = 2,
# TS_PTEX = 3,
# TS_BSDF_DATA = 4,
tt = aliased_type.get_interface(pymdlsdk.IType_texture)
shape = tt.get_shape()
texture_name = GetUniqueName.get(transaction, "texture")
# TODO_PA: Has to specify argc and argv otherwise failure
tex = transaction.create("Texture", 0, None)
transaction.store(tex, texture_name)
value = input.Get()
if value:
texture = transaction.edit_as(pymdlsdk.ITexture, texture_name)
texture.set_image(value.path)
tex_type = type_factory.create_texture(shape)
mdlvalue = value_factory.create_texture(tex_type, texture_name)
if mdlvalue:
expression = expression_factory.create_constant(mdlvalue)
return expression
elif type in (
Sdf.ValueTypeNames.Float2,\
Sdf.ValueTypeNames.Float2Array,\
Sdf.ValueTypeNames.Float3,\
Sdf.ValueTypeNames.Float3Array,\
Sdf.ValueTypeNames.Float4,\
Sdf.ValueTypeNames.Float4Array,\
Sdf.ValueTypeNames.Int2,\
Sdf.ValueTypeNames.Int2Array,\
Sdf.ValueTypeNames.Int3,\
Sdf.ValueTypeNames.Int3Array,\
Sdf.ValueTypeNames.Int4,\
Sdf.ValueTypeNames.Int4Array,\
Sdf.ValueTypeNames.Double2,\
Sdf.ValueTypeNames.Double2Array,\
Sdf.ValueTypeNames.Double3,\
Sdf.ValueTypeNames.Double3Array,\
Sdf.ValueTypeNames.Double4,\
Sdf.ValueTypeNames.Double4Array,\
Sdf.ValueTypeNames.BoolArray,\
Sdf.ValueTypeNames.IntArray,\
Sdf.ValueTypeNames.FloatArray,\
Sdf.ValueTypeNames.DoubleArray,\
Sdf.ValueTypeNames.Color3fArray,\
Sdf.ValueTypeNames.StringArray,\
Sdf.ValueTypeNames.Matrix2d,\
Sdf.ValueTypeNames.Matrix3d,\
Sdf.ValueTypeNames.Matrix4d\
):
converter = ConvertVectorAndArray()
return converter.convert(input, type, type_factory, value_factory, expression_factory)
# TODO Convert structures
# elif type == Sdf.ValueTypeNames.Token:
# pass
else:
print("Error: Unsupported input (parm/type): {}/{}".format(name, type))
if mdlvalue:
value = input.Get()
rtn = 0
if not value == None:
rtn = mdlvalue.set_value(value)
if rtn and not rtn == 0:
print("set_value() error ({}) for (parm/type/value): {}/{}/{}".format(rtn, name, type, value))
expression = expression_factory.create_constant(mdlvalue)
return expression
return expression
#--------------------------------------------------------------------------------------------------
def set_default_value(context, parm_name, definition):
defaults = definition.get_defaults()
i = defaults.get_index(parm_name)
if i != -1:
return defaults.get_expression(i)
return None
#--------------------------------------------------------------------------------------------------
def convert_parameter(context, definition, input):
name = input.GetBaseName()
index = definition.get_parameter_index(name)
if index >= 0:
types = definition.get_parameter_types()
if types:
type = types.get_type(index)
if type:
expression = convert_value(context, input, type)
if expression and expression.is_valid_interface():
return expression
else:
print("Error: Invalid expression for parameter: {}".format(name))
return None
#--------------------------------------------------------------------------------------------------
def edit_instance(transaction, inst_name):
return transaction.edit_as(pymdlsdk.IFunction_call, inst_name)
#--------------------------------------------------------------------------------------------------
def dump_expression_list(expression_list):
print("===== Dump expression list =====")
for index in range(expression_list.get_size()):
name = expression_list.get_name(index)
expr = expression_list.get_expression(index)
print("Expression name/kind/type kind: {} / {} / {}".format(name, expr.get_kind(), expr.get_type().get_kind()))
print("===== End dump expression list =====")
#--------------------------------------------------------------------------------------------------
def dump_parameter_types(fctdef, neuray, transaction):
print("===== Dump parameter types =====")
name = fctdef.get_mdl_simple_name()
print("Function name: {}".format(name))
pt = fctdef.get_parameter_types()
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
type_factory = factory.create_type_factory(transaction)
print(type_factory.dump(pt).get_c_str())
# for i in range(pt.get_size()):
# t = pt.get_type(i)
# k = t.get_kind()
# if k == pymdlsdk.IType.Kind.TK_ALIAS:
# a = t.get_interface(pymdlsdk.IType_alias)
# k = a.get_aliased_type().get_kind()
# pn = fctdef.get_parameter_name(i)
# print("Parameter name/kind: {} / {}".format(pn, k))
print("===== End dump parameter types =====")
#--------------------------------------------------------------------------------------------------
def convert_parameters(context, prim_path):
definition = get_definition(context, prim_path)
if not definition:
return None
stage = context.stage
prim = get_shader_prim(stage, prim_path)
# expression_list = definition.get_defaults()
# expression_list = pymdlsdk.IExpression_list()
neuray = context.neuray
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
transaction = context.transaction
expression_factory = factory.create_expression_factory(transaction)
expression_list = expression_factory.create_expression_list()
if prim:
shader = UsdShade.Shader(prim)
if shader:
inputs = shader.GetInputs()
for input in inputs:
name = input.GetBaseName()
expression = convert_parameter(context, definition, input)
if expression:
rtn = expression_list.add_expression(name, expression)
if rtn != 0:
print("Error")
# dump_expression_list(expression_list)
# Handle parameters which are not set
defaults = definition.get_defaults()
parameter_types = definition.get_parameter_types()
value_factory = factory.create_value_factory(transaction)
for i in range(definition.get_parameter_count()):
name = definition.get_parameter_name(i)
if expression_list.get_index(name) == -1:
type = parameter_types.get_type(i)
value = value_factory.create(type)
expr = expression_factory.create_constant(value)
expression_list.add_expression(name, expr)
return expression_list
#--------------------------------------------------------------------------------------------------
def dump_material_instance(context, inst_name):
transaction = context.transaction
inst = edit_instance(transaction, inst_name)
if not inst.is_valid_interface():
return
print("============ MDL Dump =============")
print(inst_name)
print("")
neuray = context.neuray
factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
expression_factory = factory.create_expression_factory(transaction)
count = inst.get_parameter_count()
arguments = inst.get_arguments()
for index in range(count):
argument = arguments.get_expression(index)
name = inst.get_parameter_name(index)
argument_text = expression_factory.dump(argument, name, 1)
print(argument_text.get_c_str())
print("============ MDL Dump =============")
#--------------------------------------------------------------------------------------------------
# Return a shader prim corresponding to the input prim_path.
# If prim_path is a shader, return the corresponding prim.
# If prim_path is a material, return the first shader found in the list of children.
def get_shader_prim(stage, prim_path):
prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
if UsdShade.Shader(prim):
return prim
if UsdShade.Material(prim):
mat = UsdShade.Material(prim)
if mat.GetOutput("mdl:surface") and mat.GetOutput("mdl:surface").HasConnectedSource():
(src, name, t) = mat.GetOutput("mdl:surface").GetConnectedSource()
if UsdShade.Shader(src):
return src.GetPrim()
for prim in prim.GetChildren():
if UsdShade.Shader(prim):
return prim
if UsdShade.NodeGraph(prim):
ng = UsdShade.NodeGraph(prim)
if ng.GetOutput("out") and ng.GetOutput("out").HasConnectedSource():
(src, name, t) = ng.GetOutput("out").GetConnectedSource()
if UsdShade.Shader(src):
return src.GetPrim()
for prim in prim.GetChildren():
if UsdShade.Shader(prim):
return prim
return None
#--------------------------------------------------------------------------------------------------
def get_sub_identifier_from_prim(prim):
sub_id = prim.GetAttribute("info:mdl:sourceAsset:subIdentifier").Get()
if not sub_id:
sub_id = prim.GetAttribute("info:sourceAsset:subIdentifier").Get()
return sub_id
#--------------------------------------------------------------------------------------------------
def get_definition(context, prim_path):
stage = context.stage
prim = get_shader_prim(stage, prim_path)
if not prim:
print("Error:\tCould not find any shader in prim '{}' from stage '{}'".format(prim_path, stage.GetRootLayer().GetDisplayName()))
else:
shader = UsdShade.Shader(prim)
if shader:
imp_source = shader.GetImplementationSourceAttr().Get()
if imp_source == "sourceAsset":
# Retrieve module name
source_asset = shader.GetSourceAsset("mdl")
neuray = context.neuray
(success, module_db_name) = load_module(context, source_asset)
if not success:
print("Error: Failed to load module: {}".format(source_asset))
else:
sub_id = get_sub_identifier_from_prim(prim)
if sub_id:
transaction = context.transaction
module = pymdl.Module._fetchFromDb(transaction, module_db_name)
if module:
fct = find_function(module, sub_id)
if fct:
fctdef = transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName)
if fctdef.is_valid_interface():
return fctdef
return None
#--------------------------------------------------------------------------------------------------
def list_functions(module: pymdl.Module):
for k in module.functions.keys():
for index in range(len(module.functions[k])):
print(module.functions[k][index].mdlName.split("::")[-1])
#--------------------------------------------------------------------------------------------------
# return (module_name, simple_name, parameters)
# module_name without trailing '::'
# e.g. if sub_id = '::nvidia::foo::bar(float,color)'
# module_name = '::nvidia::foo'
# simple_name = 'bar'
# parameters = 'float,color'
def split_function_name(sub_id: str):
module_name = ""
simple_name = ""
parameters = ""
lf = sub_id.split('(')
name_and_module = lf[0]
lm = name_and_module.split('::')
if len(lm) > 1:
module_name = '::'.join(lm[0:-1])
simple_name = lm[-1]
if len(lf) > 1:
parameters = lf[1].split(')')[0]
return (module_name, simple_name, parameters)
#--------------------------------------------------------------------------------------------------
def find_function(module: pymdl.Module, sub_id: str):
(module_name, simple_name, parameters) = split_function_name(sub_id)
if simple_name in module.functions:
if sub_id == simple_name:
# Exact match, no overload, return the function
return module.functions[simple_name][0]
# Access the function definition, enumerate the overloads
for index in range(len(module.functions[simple_name])):
fct = module.functions[simple_name][index]
(candidate_module_name, candidate_simple_name, candidate_parameters) = split_function_name(fct.mdlName)
if parameters == candidate_parameters:
return module.functions[simple_name][index]
print("Error: Function not found in module (function/module): {} / {}".format(sub_id, module.filename))
# list_functions(module)
return None
#--------------------------------------------------------------------------------------------------
def create_material_instance(context, prim_path, expression_list):
stage = context.stage
prim = get_shader_prim(stage, prim_path)
if prim:
shader = UsdShade.Shader(prim)
if shader:
imp_source = shader.GetImplementationSourceAttr().Get()
if imp_source == "sourceAsset":
# Retrieve module name
source_asset = shader.GetSourceAsset("mdl")
neuray = context.neuray
(success, module_db_name) = load_module(context, source_asset)
if success:
sub_id = get_sub_identifier_from_prim(prim)
if sub_id:
transaction = context.transaction
module = pymdl.Module._fetchFromDb(transaction, module_db_name)
if module:
fct = find_function(module, sub_id)
if fct:
with transaction.access_as(pymdlsdk.IFunction_definition, fct.dbName) as fctdef:
inst = None
if fctdef.is_valid_interface():
if expression_list == None:
expression_list = convert_parameters(context, prim_path)
# dump_parameter_types(fctdef, context.neuray, context.transaction)
(inst, ret) = fctdef.create_function_call_with_ret(expression_list)
fname = "create_material_instance()"
error = {0: "Success.",
-1: "An argument for a non-existing parameter was provided in 'arguments'.",
-2: "The type of an argument in 'arguments' does not have the correct type, see #get_parameter_types().",
-3: "A parameter that has no default was not provided with an argument value.",
-4: "The definition can not be instantiated because it is not exported.",
-5: "A parameter type is uniform, but the corresponding argument has a varying return type.",
-6: "An argument expression is not a constant nor a call.",
-8: "One of the parameter types is uniform, but the corresponding argument or default is a \
call expression and the return type of the called function definition is effectively varying since the \
function definition itself is varying.",
-9: "The function definition is invalid due to a module reload, see #is_valid() for diagnostics."}
if inst:
if inst.is_valid_interface():
(module_name, simple_name, parameters) = split_function_name(fct.dbName)
inst_name = module_name + "::" + simple_name + "::converted"
inst_name = GetUniqueName.get(transaction, inst_name)
transaction.store(inst, inst_name)
return inst_name
else:
print("Error: Invalid instance for function: {}".format(fct.mdlSimpleName))
print("{} error {}: {}".format(fname, ret, error[ret]))
if ret == -2:
dump_parameter_types(fctdef, context.neuray, context.transaction)
return None
#--------------------------------------------------------------------------------------------------
async def convert_usd_to_mdl(context, prim_path, output_filename):
inst_name = None
mdl_entity = None
mdl_entity_snapshot = None
if not context.ov_neuray == None:
# We are in OV
# Get the shader prim from Material
shader_prim_path = get_shader_prim(context.stage, prim_path)
if shader_prim_path == None:
print(f"Error: can not access prim: '{prim_path}'")
return None
mdl_entity = context.ov_neuray.createMdlEntity(shader_prim_path.GetPath().pathString)
mdl_entity_snapshot = None
if not mdl_entity.getMdlModule() == None:
mdl_entity_snapshot = context.ov_neuray.createMdlEntitySnapshot(mdl_entity)
inst_name = mdl_entity_snapshot.dbName
else:
print(f"Error: can not access entity: '{prim_path}'")
else:
# Outside of OV, conversion is done here
expression_list = convert_parameters(context, prim_path)
inst_name = create_material_instance(context, prim_path, expression_list)
if inst_name is not None:
dump_material_instance(context, inst_name)
if output_filename:
# we use a temporary folder for resources from the server
with tempfile.TemporaryDirectory() as temp_dir:
success = await save_instance_to_module(context, inst_name, prim_path, temp_dir, output_filename)
if not success:
inst_name = None
if not context.ov_neuray == None:
# We are in OV
if not mdl_entity_snapshot == None:
context.ov_neuray.destroyMdlEntitySnapshot(mdl_entity_snapshot)
if not mdl_entity == None:
context.ov_neuray.destroyMdlEntity(mdl_entity)
return inst_name
#--------------------------------------------------------------------------------------------------
# Split the input string or list of strings using given the split char
# Return a list of strings
def split_list(list_of_strings, split_char):
res = []
if type(list_of_strings) == list:
for s in list_of_strings:
res += s.split(split_char)
else:
res = list_of_strings.split(split_char)
return res
#--------------------------------------------------------------------------------------------------
# Remove all occurences of element from the list
def remove_all_occurences_of_element_from_list(element, alist):
try:
while True:
alist.remove(element)
except:
pass
finally:
return alist
#--------------------------------------------------------------------------------------------------
# Split the input string or list of strings using all the input split chars
def multi_split_list(list_of_strings, list_of_splits):
res = list_of_strings
for split in list_of_splits:
res = split_list(res, split)
return res
#--------------------------------------------------------------------------------------------------
# Identify a line containing an MD import declaration
# From the MDL 1.7 specs:
# import : import qualified_import {, qualified_import} ;
# | [export] using import_path
# import ( * | simple_name {, simple_name} ) ;
def is_import_line(token_list):
if 'import' in token_list:
if token_list[0] == 'import' or token_list[0] == 'export' or token_list[0] == 'using':
return True
return False
#--------------------------------------------------------------------------------------------------
# Construct a set or strings found in an MDL module
# Split the input strings using several separators (' ',';','(', ')')
# if filter_import_lines is set to True, then only process lines beginning with 'import'
def find_tokens(lines, filter_import_lines = False):
all_ids = set()
input_list = lines
if not type(lines) == list:
input_list = [lines]
for l in input_list:
ids = multi_split_list(l, [' ',';','(', ')'])
remove_all_occurences_of_element_from_list('', ids)
if filter_import_lines:
if not is_import_line(ids):
continue
for id in ids:
if not id.find('::') == -1:
tokens = id.split('::')
for t in tokens:
if len(t) > 0:
all_ids.add(t)
return all_ids
#--------------------------------------------------------------------------------------------------
# Find MDL identifier in this line of text if text is an import statement
def find_import(line):
ids = multi_split_list(line, [' ',';','(', ')'])
remove_all_occurences_of_element_from_list('', ids)
if is_import_line(ids):
for id in ids:
if not id.find('::') == -1:
return id
return ''
#--------------------------------------------------------------------------------------------------
# Find MDL identifier in this line of text
def find_identifiers(line):
rtn_identifiers = set()
ids = multi_split_list(line, [' ', ';', '(', ')', ',', '\n'])
remove_all_occurences_of_element_from_list('', ids)
for id in ids:
if not id.find('::') == -1:
rtn_identifiers.add(id)
return rtn_identifiers
#--------------------------------------------------------------------------------------------------
# Substitute source strings with target strings found in the input table in the input lines
# Input lines is a string or list of strings
def replace_tokens(lines, table):
if type(lines) == list:
for i in range(len(lines)):
for k in table.keys():
lines[i] = lines[i].replace(k, table[k])
return lines
else:
for k in table.keys():
lines = lines.replace(k, table[k])
return lines
#--------------------------------------------------------------------------------------------------
# Helper to perfom unmangling on MDL module files and MDL identifiers
# Un-mangling is only done in the framework of OV if an un-mangling routine exists
class Unmangle:
unmangle_routine = None
def __init__(self, context):
if context.ov_neuray != None:
if "_unmangleMdlModulePath" in dir(context.ov_neuray):
self.unmangle_routine = context.ov_neuray._unmangleMdlModulePath
# Un-mangle a single token
# token should not contain any '::'
def _unmangle_token(self, token):
assert(token.find("::") == -1)
# Un-mangle the input token
# Add prefix otherwise unmangling has not effect
unmangled_token = self.unmangle_routine("::" + token)
# Remove any '.mdl' extension from unmangled token
if len(unmangled_token) > 4 and unmangled_token[-4:] == '.mdl':
unmangled_token = unmangled_token[:-4]
unmangled = (unmangled_token != token)
return (unmangled, unmangled_token)
# Build an un-mangling mapping table from the input list of tokens
def build_mapping_table(self, token_list):
table = dict()
for token in token_list:
(unmangled_flag, unmangled_token) = self._unmangle_token(token)
if unmangled_flag:
table[token] = unmangled_token
return table
# Un-mangled an MDL identifier
# Return a tuple (True if unmagling was done, unmangled value)
def unmangle_mdl_identifier(self, source):
if self.unmangle_routine == None:
return (False, source)
token_list = find_tokens(source)
table = self.build_mapping_table(token_list)
unmangled_str = replace_tokens(source, table)
return (unmangled_str != source, unmangled_str)
# Un-mangle an MDL file and create a new un-mangled output file
def unmangle_mdl_file(self, infile, outfile):
if self.unmangle_routine == None:
return
# Only consider 'import' statements
filter_import_lines = True
with open(infile, 'r') as f_in:
lines = f_in.readlines()
token_list = find_tokens(lines, filter_import_lines)
mapping = self.build_mapping_table(token_list)
lines = replace_tokens(lines, mapping)
with open(outfile, 'w') as f_out:
f_out.writelines(lines)
#--------------------------------------------------------------------------------------------------
def parse_alias(pattern, line):
match = pattern.match(line)
if match == None:
return(False, '', '')
alias = match.group("alias")
path_segment = match.group("value")
# print(f"alias: '{alias}' path_segment: '{path_segment}'")
return(True, alias, path_segment)
#--------------------------------------------------------------------------------------------------
# This unmangling class uses MDL search path to trim down MDL identifiers
# It uses also MDL aliases to perform substitutions in the MDL identifier
class UnmangleAndFixMDLSearchPath(Unmangle):
alias_pattern = None
def __init__(self, context):
# compile pattern only once as it is constant
self.alias_pattern = re.compile(r"""\s*using\s* # whitespace, using, whitespace
(?P<alias>.*?) # alias name
\s*=\s* # whitespace, equal, whitespace
\"(?P<value>.*?)\" # value in quotes,
\s*;""", re.VERBOSE) # semicolon, whitespace
# Build MDL search path list
self.mdl_search_paths = list()
with context.neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg:
if cfg.is_valid_interface():
for i in range(cfg.get_mdl_paths_length()):
sp = cfg.get_mdl_path(i)
sp = os.path.normpath(sp.get_c_str())
self.mdl_search_paths.append(sp)
super(UnmangleAndFixMDLSearchPath, self).__init__(context)
# Determine if this line is defining an alias
def __is_alias(self, line):
(is_alias, alias, path_segment) = parse_alias(self.alias_pattern, line)
if is_alias:
return (True, path_segment, alias)
return (False, '', '')
# Determine if this identifier is mangled
def __is_mangled_identifier(self, id):
token_list = id.split("::")
remove_all_occurences_of_element_from_list('', token_list)
for token in token_list:
(unmangled_flag, unmangled_token) = self._unmangle_token(token)
if unmangled_flag:
return unmangled_flag
return False
# Determine if this string contains a mangled identifier
def __get_mangled_identifiers(self, line):
identifiers = find_identifiers(line)
rtn_identifiers = set()
for id in identifiers:
if len(id) > 0:
if self.__is_mangled_identifier(id):
rtn_identifiers.add(id)
return rtn_identifiers
# Build mapping table for a given mangled identifier
# Using the stored MDL search paths and the MDL aliases
def __build_table_from_mangled_id(self, id, aliases, makeRelativeIfFailure: bool = False):
key = ''
value = ''
# unmangle using _unmangleMdlModulePath
if not id.find('::') == 0:
unmangled_id = self.unmangle_routine("::" + id)
else:
unmangled_id = self.unmangle_routine(id)
unmangled_id = re.sub('^file:/', '', unmangled_id)
# Replace aliases
for alias in aliases.keys():
unmangled_id = unmangled_id.replace(aliases[alias], alias)
unmangled_id = os.path.normpath(unmangled_id)
# Remove MDL seach path
search_path_removed = False
mapping_table = dict()
for sp in self.mdl_search_paths:
temp_id = unmangled_id
temp_sp = sp
if platform.system() == 'Windows':
temp_id = unmangled_id.lower()
temp_sp = sp.lower()
# Remove the search path only when the path is found at the head of id
if temp_id.startswith(temp_sp):
unmangled_id = unmangled_id[len(sp):]
search_path_removed = True
break
# Conversion is done only if we did find search path prefix in the identifier
if search_path_removed:
replaced = unmangled_id
replaced = replaced.replace('\\', '::')
replaced = replaced.replace('.mdl::', '::')
what_to_replace = id
mapping_table[what_to_replace] = replaced
return (True, mapping_table)
else:
if makeRelativeIfFailure:
# Turn absolute path to relative
unmangled_id = os.path.basename(unmangled_id)
replaced = unmangled_id
replaced = replaced.replace('.mdl::', '::')
what_to_replace = id
mapping_table[what_to_replace] = replaced
return (True, mapping_table)
return (False, mapping_table)
# Un-mangle an MDL file and create a new un-mangled output file
def unmangle_mdl_file(self, infile, outfile):
if self.unmangle_routine == None:
return
# Read file
mapping_table = dict()
with open(infile, 'r') as f_in:
input_lines = f_in.readlines()
if not type(input_lines) == list:
# handle single line
input_lines = [input_lines]
# aliases mapping table
aliases = dict()
for line in input_lines:
(alias, key, value) = self.__is_alias(line)
if alias:
aliases[key] = value
continue
ids = self.__get_mangled_identifiers(line)
for id in ids:
(success, new_mapping_table) = self.__build_table_from_mangled_id(id, aliases)
if success:
# Mege new mapping in
mapping_table.update(new_mapping_table)
# Replace in file and write out result
with open(infile, 'r') as f_in:
lines = f_in.readlines()
lines = replace_tokens(lines, mapping_table)
with open(outfile, 'w') as f_out:
f_out.writelines(lines)
# Un-mangle an MDL file and create a new un-mangled output file
# Return (is identifier mangled, demangling and removing search path succeeded, un-mangled module name)
def unmangle_mdl_module(self, module):
if self.unmangle_routine == None:
return (False, True, module)
rtn = module
isMangled = self.__is_mangled_identifier(module)
(success, mapping_table) = self.__build_table_from_mangled_id(module, dict(), makeRelativeIfFailure = True)
if success:
rtn = mapping_table[module]
if rtn.find('::') == 0:
rtn = rtn[2:]
rtn = rtn.replace("::", "/")
return (isMangled, success, rtn)
#--------------------------------------------------------------------------------------------------
def is_reserved_word(name : str):
# there will be an API function for this soon
reserved_words = ['annotation', 'auto', 'bool', 'bool2', 'bool3', 'bool4', 'break', 'bsdf', 'bsdf_measurement',
'case', 'cast', 'color', 'const', 'continue', 'default', 'do', 'double', 'double2', 'double2x2',
'double2x3', 'double3', 'double3x2', 'double3x3', 'double3x4', 'double4', 'double4x3', 'double4x4',
'double4x2', 'double2x4', 'edf', 'else', 'enum', 'export', 'false', 'float', 'float2', 'float2x2',
'float2x3', 'float3', 'float3x2', 'float3x3', 'float3x4', 'float4', 'float4x3', 'float4x4',
'float4x2', 'float2x4', 'for', 'hair_bsdf', 'if', 'import', 'in', 'int', 'int2', 'int3', 'int4',
'intensity_mode', 'intensity_power', 'intensity_radiant_exitance', 'let', 'light_profile', 'material',
'material_emission', 'material_geometry', 'material_surface', 'material_volume', 'mdl', 'module',
'package', 'return', 'string', 'struct', 'switch', 'texture_2d', 'texture_3d', 'texture_cube',
'texture_ptex', 'true', 'typedef', 'uniform', 'using', 'varying', 'vdf', 'while', 'catch', 'char',
'class', 'const_cast', 'delete', 'dynamic_cast', 'explicit', 'extern', 'external', 'foreach',
'friend', 'goto', 'graph', 'half', 'half2', 'half2x2', 'half2x3', 'half3', 'half3x2', 'half3x3',
'half3x4', 'half4', 'half4x3', 'half4x4', 'half4x2', 'half2x4', 'inline', 'inout', 'lambda',
'long', 'mutable', 'namespace', 'native', 'new', 'operator', 'out', 'phenomenon', 'private',
'protected', 'public', 'reinterpret_cast', 'sampler', 'shader', 'short', 'signed', 'sizeof',
'static', 'static_cast', 'technique', 'template', 'this', 'throw', 'try', 'typeid', 'typename',
'union', 'unsigned', 'virtual', 'void', 'volatile', 'wchar_t']
return name in reserved_words
#--------------------------------------------------------------------------------------------------
# the db name of a texture is constructed here:
# rendering\include\rtx\neuraylib\NeurayLibUtils.h
# computeSceneIdentifierTexture
def parse_ov_resource_name(texture_db_name : str):
# drop the db prefix
texture_db_name = texture_db_name[5:]
undescore = texture_db_name.rfind('_')
texture_db_name = texture_db_name[:undescore]
undescore = texture_db_name.rfind('_')
return texture_db_name[:undescore]
async def prepare_resources_for_export(transaction : pymdlsdk.ITransaction, inst_name, temp_dir):
functionCall = pymdl.FunctionCall._fetchFromDb(transaction, inst_name)
for name, param in functionCall.parameters.items():
# name
if param.type.kind == pymdlsdk.IType.Kind.TK_TEXTURE and param.value[0] != None:
# print(f"* Name: {name}")
# print(f" Type Kind: {param.type.kind}")
texture_path = parse_ov_resource_name(param.value[0])
# print(f" texture_path: {texture_path}")
# print(f" db_name: {param.value[0]}")
# print(f" gamma: {param.value[1]}")
# special handling for resources on the server
if texture_path.startswith("omniverse:") or \
texture_path.startswith("file:") or \
texture_path.startswith("ftp:") or \
texture_path.startswith("http:") or \
texture_path.startswith("https:"):
basename = os.path.basename(texture_path)
filename, fileext = os.path.splitext(basename)
id = 0
dst_path = os.path.join(temp_dir, basename)
while (os.path.exists(dst_path)):
dst_path = os.path.join(temp_dir, f"{filename}_{id}{fileext}")
id = id + 1
result = await copy_async(texture_path, dst_path)
if not result:
print(f"Cannot copy from {texture_path} to {dst_path}, error code: {result}.")
continue
else:
print(f"Downloaded resource from {texture_path} to {dst_path}. Will be deleted after export.")
# use the resource in the temp folder
texture_path = dst_path
# create a new image
new_image_db_name = "mdlexp::" + texture_path
with transaction.create("Image", 0, None) as new_interface:
with new_interface.get_interface(pymdlsdk.IImage) as new_image:
new_image.reset_file(texture_path)
transaction.store(new_image, new_image_db_name)
transaction.remove(new_image_db_name) # drop after transaction is closed
# assign the image to the texture
# todo make sure the transaction is aborted, we don't want this change visible to other components
with transaction.edit_as(pymdlsdk.ITexture, param.value[0]) as itexture:
itexture.set_image(new_image_db_name)
itexture.set_gamma(param.value[1]) # TODO check if srgb and linear work with floating precission here
if isinstance(param, pymdl.ArgumentCall):
# print(f"* Name: {name}")
# print(f" Type Kind: {param.type.kind}")
# print(f" dbName: {param.value}")
await prepare_resources_for_export(transaction, param.value, temp_dir)
# ExportHelper: Helps to save files to Nucleus server.
# If we want to export a file to Nucleus, this helper:
# 1- creates a temp folder,
# 2- substitutes the original Nucleus folder with the temp folder,
# 3- files are saved/exported to the temp folder,
# 4- when finalize() is called, the content of the temp folder is saved to Nucleus server
# and temp folder is deleted
class ExportHelper:
def __init__(self, out_filename):
self.original_filename = out_filename
self.out_filename = out_filename
self.temp_dir = None
# If out_filename is on Nucleus, then change it to temp filename
if out_filename.startswith("omniverse:") or \
out_filename.startswith("file:") or \
out_filename.startswith("ftp:"):
# create a temp folder
self.temp_dir = tempfile.TemporaryDirectory()
# substitutes the original Nucleus folder with the temp folder
self.out_filename = os.path.join(self.temp_dir.name, os.path.basename(out_filename))
async def finalize(self, copy_files: bool = True):
# If out_filename is different from the original one, copy all files
# from the temp folder to the Nucleus server
if self.temp_dir != None:
if copy_files:
from_dir = os.path.dirname(self.out_filename)
to_dir = os.path.dirname(self.original_filename)
for ld in os.listdir(from_dir):
f = os.path.basename(ld)
result = await copy_async(os.path.join(from_dir, f), to_dir + '/' + f)
if not result:
print(f"Cannot copy from {f} to {to_dir}, error code: {result}.")
else:
print(f"Copied resource {f} to {to_dir}.")
# Delete temp folder
self.temp_dir.cleanup()
async def save_instance_to_module(context, inst_name, usd_prim, temp_dir, out_filename):
print("============ MDL Save Instance to Module =============")
neuray = context.neuray
transaction = context.transaction
stage = context.stage
# access shader prim
prim = get_shader_prim(stage, usd_prim)
prim_name = usd_prim.pathString.split('/')[-1]
if out_filename == None or os.path.isdir(out_filename) or os.path.splitext(out_filename)[1] != '.mdl':
print(f"Error: output filename is invalid, expected an .mdl file: '{out_filename}'")
return False
# Handle Nucleus: OM-46539 Graph to MDL fails to copy Nucleus textures to local filesystem when exporting
export_helper = ExportHelper(out_filename)
out_filename = export_helper.out_filename
# Sanity checks
with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst:
if inst == None or not inst.is_valid_interface():
print("Error: Invalid instance name (IFunction_call): {}".format(inst_name))
return False
with transaction.access_as(pymdlsdk.IFunction_definition, inst.get_function_definition()) as fd:
if fd == None or not fd.is_valid_interface():
print("Error: Invalid IFunction_definition: {}".format(inst.get_function_definition()))
return False
module = pymdl.Module._fetchFromDb(transaction, fd.get_module())
if module == None:
print("Error: Invalid Module: {}".format(fd.get_module()))
return False
# since resourcse are handled by the renderer we need to pass them to neuray before exporting
await prepare_resources_for_export(transaction, inst_name, temp_dir)
factory: pymdlsdk.IMdl_factory = neuray.get_api_component(pymdlsdk.IMdl_factory)
execution_context = factory.create_execution_context()
# Create the module builder.
module_name = "mdl::new_module_28f8c871b7034e55a0541be81655ffb1"
module_builder = factory.create_module_builder(
transaction,
module_name,
pymdlsdk.MDL_VERSION_1_6, # In order to use aliases
pymdlsdk.MDL_VERSION_LATEST,
execution_context)
if not module_builder.is_valid_interface():
print("Error: Failed to create module builder")
return False
module_builder.clear_module(execution_context)
# Create a variant
success = False
with transaction.access_as(pymdlsdk.IFunction_call, inst_name) as inst, \
factory.create_expression_factory(transaction) as ef, \
ef.create_annotation_block() as empty_anno_block:
if inst.is_valid_interface():
if is_reserved_word(prim_name):
variant_name = "Main"
else:
variant_name = prim_name
result = module_builder.add_variant(
variant_name,
inst.get_function_definition(),
inst.get_arguments(),
empty_anno_block,
empty_anno_block,
True,
execution_context)
if result != 0:
print("Error: Failed to add variant to module builder:\n\t'{}'\n\t'{}'\n\t'{}'".format(prim.GetName(), inst.get_function_definition(), inst.get_arguments()))
for i in range(execution_context.get_messages_count()):
print(execution_context.get_message(i).get_string())
if result == 0:
with neuray.get_api_component(pymdlsdk.IMdl_impexp_api) as imp_exp:
rtn = -1
execution_context.set_option("bundle_resources", True)
rtn = imp_exp.export_module(transaction, module_name, out_filename, execution_context)
if rtn >= 0:
unmangle_helper = UnmangleAndFixMDLSearchPath(context)
unmangle_helper.unmangle_mdl_file(out_filename, out_filename)
print(f"Success: Material '{prim_name}' exported to module '{out_filename}'")
# Copy files to Nucleus if needed
await export_helper.finalize()
success = True
else:
print(f"Failure: Could not export Material '{prim_name}' to module '{out_filename}'")
await export_helper.finalize(copy_files = False)
module_builder.clear_module(execution_context)
return success
| 117,950 | Python | 43.695339 | 232 | 0.568249 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/test_usd_converter.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.mdl.usd_converter
import omni.usd
import shutil
import pathlib
import os
import carb
import carb.settings
# Having a test class derived from omni.kit.test.AsyncTestCase declared on the root of module
# will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCaseFailOnLogError):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._test_data = str(pathlib.Path(__file__).parent.joinpath("data"))
self._test_data_usd = str(pathlib.Path(self._test_data).joinpath("usd"))
self._test_data_mdl = str(pathlib.Path(self._test_data).joinpath("mdl"))
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_mdl_to_usd(self):
# Disable standard path to ensure reproducible results locally and in TC
NO_STD_PATH = "/app/mdl/nostdpath"
settings = carb.settings.get_settings()
settings.set_bool(NO_STD_PATH, True)
filter_import = False
tokens = omni.mdl.usd_converter.find_tokens('mdl::ZA0OmniGlass_2Emdl::OmniGlass::converted_27', filter_import)
result = (tokens == {'ZA0OmniGlass_2Emdl', 'converted_27', 'mdl', 'OmniGlass'})
self.assertEqual(result, True)
filter_import = True
tokens = omni.mdl.usd_converter.find_tokens('import ::state::normal;\n', filter_import)
result = (tokens == {'state', 'normal'})
self.assertEqual(result, True)
filter_import = False
tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import)
result = (tokens == {'anno', 'author'})
self.assertEqual(result, True)
filter_import = True
tokens = omni.mdl.usd_converter.find_tokens(' anno::author("NVIDIA CORPORATION"),\n', filter_import)
result = (len(tokens) == 0)
self.assertEqual(result, True)
with omni.mdl.usd_converter.TemporaryDirectory() as temp_dir:
test_search_path = self._test_data_mdl
fn = "core_definitions.usda"
ADD_MDL_PATH = "/app/mdl/additionalUserPaths"
settings = carb.settings.get_settings()
mdl_custom_paths: List[str] = settings.get(ADD_MDL_PATH) or []
mdl_custom_paths.append(test_search_path)
mdl_custom_paths.append(temp_dir)
mdl_custom_paths = list(set(mdl_custom_paths))
settings.set_string_array(ADD_MDL_PATH, mdl_custom_paths)
result = omni.mdl.usd_converter.mdl_to_usd(
moduleName="nvidia/core_definitions.mdl",
targetFolder=temp_dir,
targetFilename=fn,
output=omni.mdl.usd_converter.mdl_usd.OutputType.MATERIAL_AND_GEOMETRY)
self.assertEqual(result, True)
# fn = "tutorials.usda"
# # WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name
# source_file = str(pathlib.Path(self._test_data_mdl).joinpath('nvidia/sdk_examples/tutorials.mdl'))
# shutil.copy2(source_file, temp_dir)
# module = str(pathlib.Path(temp_dir).joinpath("tutorials.mdl"))
# if os.path.exists(module):
# result = omni.mdl.usd_converter.mdl_to_usd(
# moduleName=module,
# targetFolder=temp_dir,
# targetFilename=fn,
# searchPath=test_search_path)
# self.assertEqual(result, True)
# fn = "test_types.usda"
# WORKAROUND: Copy test file to temp folder, NeurayLib does not handle folder containing '*.mdl.*' in their name
# source_file = str(pathlib.Path(self._test_data_mdl).joinpath('test/test_types.mdl'))
# shutil.copy2(source_file, temp_dir)
# module = str(pathlib.Path(temp_dir).joinpath("test_types.mdl"))
# if os.path.exists(module):
# result = omni.mdl.usd_converter.mdl_to_usd(
# moduleName=module,
# targetFolder=temp_dir,
# targetFilename=fn,
# searchPath=test_search_path)
# self.assertEqual(result, True)
tutorial_scene = str(pathlib.Path(self._test_data_usd).joinpath("tutorials.usda"))
if os.path.exists(tutorial_scene):
result = await omni.mdl.usd_converter.usd_prim_to_mdl(
tutorial_scene,
"/example_material",
test_search_path,
forceNotOV=True)
self.assertEqual(result, True)
result = await omni.mdl.usd_converter.usd_prim_to_mdl(
tutorial_scene,
"/example_modulemdl_material_examples",
test_search_path,
forceNotOV=True)
self.assertEqual(result, True)
result = await omni.mdl.usd_converter.usd_prim_to_mdl(
tutorial_scene,
"/wave_gradient",
test_search_path,
forceNotOV=True)
self.assertEqual(result, True)
omni.mdl.usd_converter.test_mdl_prim_to_usd('/root')
simple_scene = str(pathlib.Path(self._test_data_usd).joinpath("scene.usda"))
if os.path.exists(simple_scene):
test_prim = '/World/Looks/Material'
stage = omni.mdl.usd_converter.mdl_usd.Usd.Stage.Open(simple_scene)
prim = stage.GetPrimAtPath(test_prim)
omni.mdl.usd_converter.mdl_prim_to_usd(stage, prim)
omni.mdl.usd_converter.mdl_usd.get_examples_search_path()
mdl_tmpfile = str(pathlib.Path(temp_dir).joinpath("tmpout.mdl"))
result = await omni.mdl.usd_converter.export_to_mdl(mdl_tmpfile, prim, forceNotOV=True)
self.assertEqual(result, True)
# Example: 'mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase'
# Return: 'OmniSurface/OmniSurfaceBase.mdl'
omni.mdl.usd_converter.mdl_usd.prototype_to_source_asset('mdl::OmniSurface::OmniSurfaceBase::OmniSurfaceBase')
omni.mdl.usd_converter.mdl_usd.parse_ov_resource_name('mdl::resolvedPath_texture_raw')
| 6,881 | Python | 44.576159 | 126 | 0.600203 |
omniverse-code/kit/exts/omni.mdl.usd_converter/omni/mdl/usd_converter/tests/__init__.py | from .test_usd_converter import *
| 34 | Python | 16.499992 | 33 | 0.764706 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/__init__.py | from .file import *
| 20 | Python | 9.499995 | 19 | 0.7 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file_actions.py | import carb
import omni.usd
import omni.kit.window.file
import omni.kit.actions.core
def post_notification(message: str, info: bool = False, duration: int = 3):
try:
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)
except ModuleNotFoundError:
carb.log_warn(message)
def quit(fast: bool = False):
if fast:
carb.settings.get_settings().set("/app/fastShutdown", True)
omni.kit.app.get_app().post_quit()
def open_stage_with_new_edit_layer():
stage = omni.usd.get_context().get_stage()
if not stage:
post_notification(f"Cannot Re-open with New Edit Layer. No valid stage")
return
omni.kit.window.file.open_with_new_edit_layer(stage.GetRootLayer().identifier)
def register_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "File Actions"
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"quit",
lambda: quit(fast=False),
display_name="File->Exit",
description="Exit",
tag=actions_tag,
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"quit_fast",
lambda: quit(fast=True),
display_name="File->Exit Fast",
description="Exit Fast",
tag=actions_tag,
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"open_stage_with_new_edit_layer",
open_stage_with_new_edit_layer,
display_name="File->Open Current Stage With New Edit Layer",
description="Open Stage With New Edit Layer",
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)
| 2,035 | Python | 28.507246 | 82 | 0.653071 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/scripts/file.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 urllib.parse
import carb.input
import omni.client
import omni.ext
import omni.kit.menu.utils
import omni.kit.ui
import omni.usd
from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED
from omni.kit.menu.utils import MenuItemDescription
from .file_actions import register_actions, deregister_actions
from omni.ui import color as cl
from pathlib import Path
_extension_instance = None
_extension_path = None
INTERACTIVE_TEXT = cl.shade(cl("#1A91C5"))
SHARE_ICON_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)).joinpath("data/icons/share.svg")
class FileMenuExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
omni.kit.menu.utils.set_default_menu_proirity("File", -10)
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
global _extension_path
_extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name)
settings = carb.settings.get_settings()
self._max_recent_files = settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10
self._file_menu_list = None
self._recent_menu_list = None
self._build_file_menu()
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self._build_recent_menu())
events = omni.usd.get_context().get_stage_event_stream()
self._stage_event_subscription = events.create_subscription_to_pop(self._on_stage_event, name="omni.kit.menu.file stage watcher")
def on_shutdown(self):
global _extension_instance
deregister_actions(self._ext_name)
_extension_instance = None
self._stage_sub = None
omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File")
omni.kit.menu.utils.remove_menu_items(self._file_menu_list, "File")
self._recent_menu_list = None
self._file_menu_list = None
self._event_sub = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSED):
self._build_file_menu()
def _build_file_menu(self):
# setup menu
self._file_menu_list = [
MenuItemDescription(
name="New",
glyph="file.svg",
onclick_action=("omni.kit.window.file", "new"),
hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.N),
),
MenuItemDescription(
name="Open",
glyph="folder_open.svg",
onclick_action=("omni.kit.window.file", "open"),
hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.O),
),
MenuItemDescription(),
MenuItemDescription(
name="Re-open with New Edit Layer",
glyph="external_link.svg",
# enable_fn=lambda: not FileMenuExtension.is_new_stage(),
onclick_action=("omni.kit.menu.file", "open_stage_with_new_edit_layer")
),
MenuItemDescription(),
MenuItemDescription(
name="Share",
glyph=str(SHARE_ICON_PATH),
enable_fn=FileMenuExtension.can_share,
onclick_action=("omni.kit.window.file", "share")
),
MenuItemDescription(),
MenuItemDescription(
name="Save",
glyph="save.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save"),
hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.S),
),
MenuItemDescription(
name="Save With Options",
glyph="save.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save_with_options"),
hotkey=(
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_ALT,
carb.input.KeyboardInput.S,
),
),
MenuItemDescription(
name="Save As...",
glyph="none.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save_as"),
hotkey=(
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL | carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT,
carb.input.KeyboardInput.S,
),
),
MenuItemDescription(
name="Save Flattened As...",
glyph="none.svg",
# enable_fn=FileMenuExtension.can_close,
onclick_action=("omni.kit.window.file", "save_as_flattened"),
),
MenuItemDescription(),
MenuItemDescription(
name="Add Reference",
glyph="none.svg",
onclick_action=("omni.kit.window.file", "add_reference"),
),
MenuItemDescription(
name="Add Payload",
glyph="none.svg",
onclick_action=("omni.kit.window.file", "add_payload")
),
MenuItemDescription(),
MenuItemDescription(name="Exit", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit")),
]
if not carb.settings.get_settings().get("/app/fastShutdown"):
self._file_menu_list.append(MenuItemDescription(name="Exit Fast (Experimental)", glyph="none.svg", onclick_action=("omni.kit.menu.file", "quit_fast")))
self._build_recent_menu()
omni.kit.menu.utils.add_menu_items(self._file_menu_list, "File", -10)
def _build_recent_menu(self):
if self._recent_menu_list:
omni.kit.menu.utils.remove_menu_items(self._recent_menu_list, "File", rebuild_menus=False)
recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD)
sub_menu = []
# add reopen
stage = omni.usd.get_context().get_stage()
is_anonymous = stage.GetRootLayer().anonymous if stage else False
filename_url = ""
if not is_anonymous:
filename_url = stage.GetRootLayer().identifier if stage else ""
if filename_url:
sub_menu.append(
MenuItemDescription(
name=f"Current stage: {filename_url}",
onclick_action=("omni.kit.window.file", "reopen"),
user={"user_style": {"color": INTERACTIVE_TEXT}}
)
)
elif not recent_files:
sub_menu.append(MenuItemDescription(name="None", enabled=False))
if recent_files:
for recent_file in recent_files:
# NOTE: not compatible with hotkeys as passing URL to open_stage
sub_menu.append(
MenuItemDescription(
name=urllib.parse.unquote(recent_file),
onclick_action=("omni.kit.window.file", "open_stage", recent_file),
)
)
self._recent_menu_list = [
MenuItemDescription(name="Open Recent", glyph="none.svg", appear_after="Open", sub_menu=sub_menu)
]
omni.kit.menu.utils.add_menu_items(self._recent_menu_list, "File")
def is_new_stage():
return omni.usd.get_context().is_new_stage()
def can_open():
stage_state = omni.usd.get_context().get_stage_state()
return stage_state == omni.usd.StageState.OPENED or stage_state == omni.usd.StageState.CLOSED
def can_save():
return (
omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED
and not FileMenuExtension.is_new_stage()
and omni.usd.get_context().is_writable()
)
def can_close():
return omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED
def can_close_and_not_is_new_stage():
return FileMenuExtension.can_close() and not FileMenuExtension.is_new_stage()
def can_share():
return (
omni.usd.get_context() is not None
and omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED
and omni.usd.get_context().get_stage_url().startswith("omniverse://")
)
def get_extension_path(sub_directory):
global _extension_path
path = _extension_path
if sub_directory:
path = os.path.normpath(os.path.join(path, sub_directory))
return path
def get_instance():
global _extension_instance
return _extension_instance
| 9,504 | Python | 39.619658 | 163 | 0.592277 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_recent_menu.py | import carb
import omni.kit.test
import omni.kit.helper.file_utils as file_utils
from omni.kit import ui_test
from .. import get_instance
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
class TestMenuFileRecents(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await omni.usd.get_context().new_stage_async()
file_utils.reset_file_event_queue()
# After running each test
async def tearDown(self):
await omni.usd.get_context().new_stage_async()
file_utils.reset_file_event_queue()
async def _mock_open_stage_async(self, url: str):
# Doesn't actually open a stage but pushes an opened event like that action would. This
# should cause the file event queue to update.
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=url).dict())
await ui_test.human_delay(4)
async def test_file_recent_menu(self):
test_files = [
"omniverse://ov-test/first.usda",
"c:/users/me/second.usda",
"omniverse://ov-test/third.usda",
]
under_test = get_instance()
get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu
# load first.usda file... rebuild_menu == 1
await self._mock_open_stage_async(test_files[0])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 1)
self.assertEqual(recent_list[0].name, test_files[0])
# load second.usda file... rebuild_menu == 2
await self._mock_open_stage_async(test_files[1])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 2)
self.assertEqual(recent_list[0].name, test_files[1])
# load second.usda file again... rebuild_menu still == 2
await self._mock_open_stage_async(test_files[1])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 2)
self.assertEqual(recent_list[0].name, test_files[1])
# load third.usda ... rebuild_menu == 3
await self._mock_open_stage_async(test_files[2])
recent_list = get_recent_list()
self.assertEqual(len(recent_list), 3)
self.assertEqual(recent_list[0].name, test_files[2])
# confirm list order is as expected
expected = test_files[::-1]
self.assertEqual([i.name for i in recent_list], expected)
async def test_file_recent_menu_current_stage(tester, _):
under_test = get_instance()
get_recent_list = lambda: under_test._recent_menu_list[0].sub_menu
# verify recent == "None"
recent_list = get_recent_list()
tester.assertEqual(len(recent_list), 1)
tester.assertTrue(recent_list[0].name.startswith("None"))
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open").click()
await ui_test.human_delay(5)
async with FileImporterTestHelper() as file_import_helper:
dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")
await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda")
await tester.wait_for_stage_event()
await ui_test.human_delay(5)
# verify name of stage
stage = omni.usd.get_context().get_stage()
tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda"))
# verify recent == "Current stage:" and "4Lights.usda"
recent_list = get_recent_list()
tester.assertEqual(len(recent_list), 2)
tester.assertTrue(recent_list[0].name.startswith("Current stage:"))
tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda"))
tester.assertFalse(recent_list[1].name.startswith("Current stage:"))
tester.assertTrue(recent_list[1].name.endswith("data/tests/4Lights.usda"))
await omni.usd.get_context().new_stage_async()
await ui_test.human_delay(5)
# verify recent == "4Lights.usda"
recent_list = get_recent_list()
tester.assertEqual(len(recent_list), 1)
tester.assertFalse(recent_list[0].name.startswith("Current stage:"))
tester.assertTrue(recent_list[0].name.endswith("data/tests/4Lights.usda"))
| 4,420 | Python | 40.317757 | 109 | 0.666968 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/__init__.py | from .file_tests import *
from .test_recent_menu import *
| 58 | Python | 18.66666 | 31 | 0.741379 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_templates.py | import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
async def file_test_func_file_new_from_stage_template_empty(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select empty and wait for stage open
await menu_widget.find_menu("Empty").click()
await tester.wait_for_stage_event()
# verify Empty stage
stage = omni.usd.get_context().get_stage()
tester.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(prim_list == ['/World'])
async def file_test_func_file_new_from_stage_template_sunlight(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select Sunlight and wait for stage open
await menu_widget.find_menu("Sunlight").click()
await tester.wait_for_stage_event()
# verify Sunlight stage
stage = omni.usd.get_context().get_stage()
tester.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight'])
async def file_test_func_file_new_from_stage_template_default_stage(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select Default Stage and wait for stage open
await menu_widget.find_menu("Default Stage").click()
await tester.wait_for_stage_event()
# verify Default Stage
stage = omni.usd.get_context().get_stage()
tester.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertEqual(set(prim_list), set([
'/World', '/Environment', '/Environment/Sky',
'/Environment/DistantLight', '/Environment/Looks',
'/Environment/Looks/Grid', '/Environment/Looks/Grid/Shader',
'/Environment/ground', '/Environment/groundCollider']))
| 3,018 | Python | 42.128571 | 108 | 0.710073 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_media.py | import os
import shutil
import tempfile
import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
async def file_test_func_file_new(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New").click()
await tester.wait_for_stage_event()
# verify its a new layer
tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name)
async def file_test_func_file_open(tester, menu_item: MenuItemDescription):
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open").click()
await ui_test.human_delay(5)
async with FileImporterTestHelper() as file_import_helper:
dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")
await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda")
await tester.wait_for_stage_event()
# verify name of stage
stage = omni.usd.get_context().get_stage()
tester.assertTrue(stage.GetRootLayer().identifier.replace("\\", "/").endswith("data/tests/4Lights.usda"))
async def file_test_func_file_reopen(tester, menu_item: MenuItemDescription):
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open Recent").click()
await menu_widget.find_menu(tester._light_path, ignore_case=True).click()
await tester.wait_for_stage_event()
# verify its a unmodified stage
tester.assertFalse(omni.kit.undo.can_undo())
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# verify its a modified stage
tester.assertTrue(omni.kit.undo.can_undo())
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open Recent").click()
await menu_widget.find_menu("Current stage:", contains_path=True).click()
await tester.wait_for_stage_event()
# verify its a unmodified stage
tester.assertFalse(omni.kit.undo.can_undo())
async def file_test_func_file_re_open_with_new_edit_layer(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Re-open with New Edit Layer").click()
await ui_test.human_delay(50)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights_layer.usda")
await tester.wait_for_stage_event()
# verify its not saved to tmpdir
layer = omni.usd.get_context().get_stage().GetRootLayer()
expected_name = f"{tmpdir}/4Lights_layer.usd".replace("\\", "/")
tester.assertTrue(layer.anonymous)
tester.assertTrue(len(layer.subLayerPaths) == 2)
tester.assertTrue(layer.subLayerPaths[0] == expected_name)
tester.assertTrue(layer.subLayerPaths[1].endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda"))
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save").click()
await ui_test.human_delay(50)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
expected_size = os.path.getsize(expected_name)
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save").click()
await ui_test.human_delay()
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save_with_options(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save With Options").click()
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
expected_size = os.path.getsize(expected_name)
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save").click()
await ui_test.human_delay()
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save_as(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save As...").click()
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_save_flattened_as(tester, menu_item: MenuItemDescription):
# save flattened doesn't send any stage events as it exports not saves
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier.replace("\\", "/") if stage else "None"
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Save Flattened As...").click()
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await ui_test.human_delay(20)
# verify its exported to tmpdir & hasn't changed stage path
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == layer_name)
tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_open_recent_exts_omni_kit_menu_file_data_tests_4lights_usda(tester, menu_item: MenuItemDescription):
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Open Recent").click()
await menu_widget.find_menu(tester._light_path, ignore_case=True).click()
await tester.wait_for_stage_event()
# verify its 4lights
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda"))
async def file_test_func_file_exit(tester, menu_item: MenuItemDescription):
# not sure how to test this without kit exiting...
pass
async def file_test_func_file_exit_fast__experimental(tester, menu_item: MenuItemDescription):
# not sure how to test this without kit exiting...
pass
async def file_test_hotkey_func_file_new(tester, menu_item: MenuItemDescription):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
# emulate hotkey
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await tester.wait_for_stage_event()
# verify its a new layer
tester.assertFalse(omni.usd.get_context().get_stage().GetRootLayer().identifier == layer_name)
async def file_test_hotkey_func_file_open(tester, menu_item: MenuItemDescription):
# emulate hotkey
await tester.reset_stage_event(omni.usd.StageEventType.OPENED)
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileImporterTestHelper() as file_import_helper:
dir_url = carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests")
await file_import_helper.click_apply_async(filename_url=f"{dir_url}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its 4lights
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/").endswith("exts/omni.kit.menu.file/data/tests/4Lights.usda"))
async def file_test_hotkey_func_file_save(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
expected_size = os.path.getsize(expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await ui_test.human_delay()
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.S, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
if save_widget:
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_hotkey_func_file_save_with_options(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usd")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
expected_size = os.path.getsize(expected_name)
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await ui_test.human_delay()
# save again, it should not show dialog....
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
# handle dialog....
save_widget = ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'")
await save_widget.click()
await ui_test.human_delay()
await tester.wait_for_stage_event()
# verify file was saved
tester.assertFalse(os.path.getsize(expected_name) == expected_size)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_hotkey_func_file_save_as(tester, menu_item: MenuItemDescription):
tmpdir = tempfile.mkdtemp()
await file_test_func_file_open(tester, {})
await tester.reset_stage_event(omni.usd.StageEventType.SAVED)
# emulate hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(5)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=f"{tmpdir}/4Lights.usda")
await tester.wait_for_stage_event()
# verify its saved to tmpdir
expected_name = f"{tmpdir}/4Lights.usd".replace("\\", "/")
tester.assertTrue(omni.usd.get_context().get_stage().GetRootLayer().identifier.replace("\\", "/") == expected_name)
# cleanup
shutil.rmtree(tmpdir, ignore_errors=True)
async def file_test_func_file_share(tester, menu_item: MenuItemDescription):
# File->Share will only work on omniverse:// files. Currently there is no way to mock this scenario.
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Share").click()
pass
| 15,830 | Python | 40.012953 | 162 | 0.704991 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/test_func_payload.py | import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
async def file_test_func_file_add_reference(tester, menu_item: MenuItemDescription):
from carb.input import KeyboardInput
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Add Reference").click()
await ui_test.human_delay()
dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'")
await ui_test.human_delay()
await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests"))
await ui_test.human_delay()
await tester.find_content_file("Select File", "sphere.usda").click(double=True)
await ui_test.human_delay(20)
# verify reference was added...
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(len(prim_list) > 0)
async def file_test_func_file_add_payload(tester, menu_item: MenuItemDescription):
from carb.input import KeyboardInput
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("Add Payload").click()
await ui_test.human_delay()
dir_widget = ui_test.find("Select File//Frame/**/StringField[*].identifier=='filepicker_directory_path'")
await ui_test.human_delay()
await dir_widget.input(carb.tokens.acquire_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests"))
await ui_test.human_delay()
await tester.find_content_file("Select File", "sphere.usda").click(double=True)
await ui_test.human_delay(20)
# verify payload was added...
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
tester.assertTrue(len(prim_list) > 0)
| 1,999 | Python | 36.735848 | 119 | 0.710355 |
omniverse-code/kit/exts/omni.kit.menu.file/omni/kit/menu/file/tests/file_tests.py | import sys
import re
import asyncio
import carb
import omni.kit.test
import omni.kit.helper.file_utils as file_utils
from .test_func_media import *
from .test_func_payload import *
from .test_func_templates import *
from .test_recent_menu import test_file_recent_menu_current_stage
class TestMenuFile(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._light_path = carb.tokens.get_tokens_interface().resolve("${kit}/exts/omni.kit.menu.file/data/tests/4Lights.usda")
# load stage so menu shows reopen
await omni.usd.get_context().open_stage_async(self._light_path)
async def tearDown(self):
pass
async def test_file_menus(self):
import omni.kit.material.library
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
menus = omni.kit.menu.utils.get_merged_menus()
prefix = "file_test"
to_test = []
this_module = sys.modules[__name__]
for key in menus.keys():
if key.startswith("File"):
for item in menus[key]['items']:
if item.name != "" and item.has_action():
key_name = re.sub('\W|^(?=\d)','_', key.lower())
func_name = re.sub('\W|^(?=\d)','_', item.name.replace("${kit}/", "").lower())
while key_name and key_name[-1] == "_":
key_name = key_name[:-1]
while func_name and func_name[-1] == "_":
func_name = func_name[:-1]
test_fn = f"{prefix}_func_{key_name}_{func_name}"
if test_fn.startswith("file_test_func_file_open_recent_reopen_current_stage"):
test_fn = "file_test_func_file_reopen"
elif test_fn.startswith("file_test_func_file_open_recent"):
continue
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item))
except AttributeError:
carb.log_error(f"test function \"{test_fn}\" not found")
if item.original_menu_item and item.original_menu_item.hotkey:
test_fn = f"{prefix}_hotkey_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item.original_menu_item))
except AttributeError:
carb.log_error(f"test function \"{test_fn}\" not found")
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file")
# add in any additional tests
test_fn = "test_file_recent_menu_current_stage"
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, None))
for to_call, test_fn, menu_item in to_test:
file_utils.reset_file_event_queue()
carb.settings.get_settings().set("/persistent/app/omniverse/lastOpenDirectory", "")
carb.settings.get_settings().set("/persistent/app/file_exporter/directory", "")
carb.settings.get_settings().set("/persistent/app/file_exporter/filename", "")
carb.settings.get_settings().set("/persistent/app/file_exporter/file_extension", "")
await self.wait_stage_loading()
await omni.usd.get_context().new_stage_async()
await ui_test.human_delay()
print(f"Running test {test_fn}")
await to_call(self, menu_item)
self._stage_event_sub = None
def find_content_file(self, window_name, filename):
for widget in ui_test.find_all(f"{window_name}//Frame/**/TreeView[*]"):
for file_widget in widget.find_all(f"**/Label[*]"):
if file_widget.widget.text==filename:
return file_widget
return None
def _on_stage_event(self, event):
if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done():
self._future_test.set_result(event.type)
async def reset_stage_event(self, stage_event):
self._required_stage_event = stage_event
self._future_test = asyncio.Future()
async def wait_for_stage_event(self):
async def wait_for_event():
await self._future_test
try:
await asyncio.wait_for(wait_for_event(), timeout=30.0)
except asyncio.TimeoutError:
carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}")
self._future_test = None
self._required_stage_event = -1
async def wait_stage_loading(self):
while True:
_, files_loaded, total_files = omni.usd.get_context().get_stage_loading_status()
if files_loaded or total_files:
await ui_test.human_delay()
continue
break
await ui_test.human_delay()
| 5,421 | Python | 42.725806 | 155 | 0.561336 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/stage_mdl_converter_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__ = ["StageMdlConverterExtension"]
from pxr import Sdf
import omni.ext
import omni.usd
import omni.kit.context_menu
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.window.popup_dialog.message_dialog import MessageDialog
import os
import omni.ui as ui
import asyncio
import carb
class AskForOverrideDialog(MessageDialog):
WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE
WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP
WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self._style = self._style.copy()
# self._style["Background"]["background_color"] = ui.color("#00000000")
# self._style["Background"]["border_color"] = ui.color("#00000000")
class WarningDialog(MessageDialog):
WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE
WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP
WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class StageMdlConverterExtension(omni.ext.IExt):
def on_startup(self, ext_id):
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
self._stage_menu = ext_manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_stage_menu(),
on_disable_fn=lambda _: self._unregister_stage_menu(),
ext_name="omni.kit.widget.stage",
hook_name="omni.kit.stage.mdl_converter",
)
self._pick_export_path_dialog = None
self._override_dialog = None
self._warning_dialog = None
self._selected_prim = None
self._current_dir = None
self._current_export_path = None
def on_shutdown(self):
self._unregister_stage_menu()
self._stage_menu = None
self._stage_context_menu_export = None
@staticmethod
def __on_filter_mdl_files(item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
if item and not item.is_folder:
_, ext = os.path.splitext(item.path)
return (ext in [".mdl"])
return True
def __run_export(self):
"""Do the actual export after we have a filename to export to"""
carb.log_info(f"Picked output filename: {self._current_export_path}")
asyncio.ensure_future(omni.mdl.usd_converter.usd_to_mdl(self._current_export_path, self._selected_prim))
def __on_ok_override(self, popup):
"""Called when the the user confirmed to override"""
carb.log_info(f"Confirmed to override selected filename: {self._current_export_path}")
popup.hide()
self.__run_export()
def __on_cancel_override(self, popup):
"""Called when the the user rejected to override"""
carb.log_info(f"Rejected to override selected filename: {self._current_export_path}")
popup.hide()
self._pick_export_path_dialog.refresh_current_directory()
self._pick_export_path_dialog.show(path=self._current_export_path)
def __on_ok_warning(self, popup):
"""Called when the the user closes warning dialog"""
popup.hide()
def __on_apply_filename(self, filename: str, dir: str):
"""Called when the user press "Export" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
# add the file extension if missing
if len(filename) < 5 or filename[-4:] != '.mdl':
filename = filename + '.mdl'
self._current_dir = dir
# add a trailing slash for the client library
if(dir[-1] != os.sep):
dir = dir + os.sep
self._current_export_path = omni.client.combine_urls(dir, filename)
self._pick_export_path_dialog.hide()
# ask for override or run export directly
if os.path.exists(self._current_export_path):
carb.log_info(f"WARNING: selected filename already exists: {self._current_export_path}")
if self._override_dialog != None:
self._override_dialog.destroy()
self._override_dialog = AskForOverrideDialog(
title = "Confirm override...",
message = "The selected file already exists. Do you want to replace it?",
ok_label = "Yes",
cancel_label = "No",
ok_handler = self.__on_ok_override,
cancel_handler = self.__on_cancel_override
)
# self._override_dialog.build_ui()
self._override_dialog.show()
else:
self.__run_export()
def _register_stage_menu(self):
"""Called when "omni.kit.widget.stage" is loaded"""
def on_export(objects: dict):
"""Called from the context menu"""
# keep the selected prim
prims = objects.get("prim_list", None)
if not prims or len(prims) > 1:
return
if len(prims) == 1:
theprim = prims[0]
stage = theprim.GetStage()
(status, message) = omni.mdl.usd_converter.is_shader_resolved(stage, theprim)
if not status:
carb.log_warn(message)
if self._warning_dialog != None:
self._warning_dialog.destroy()
self._warning_dialog = WarningDialog(
title = "Convert Material to MDL",
message = "WARNING: " + message,
disable_cancel_button=True,
ok_handler = self.__on_ok_warning,
)
self._warning_dialog.show()
return
if not omni.mdl.usd_converter.is_material_bound_to_prim(stage, theprim):
# Material not bound, display warning dialog and do not proceed
carb.log_warn(f"Material is not bound to any prim, can not convert")
if self._warning_dialog != None:
self._warning_dialog.destroy()
self._warning_dialog = WarningDialog(
title = "Convert Material to MDL",
message = "WARNING: Material is not bound to any prim, can not convert",
disable_cancel_button=True,
ok_handler = self.__on_ok_warning,
)
self._warning_dialog.show()
return
self._selected_prim = prims[0]
"""Open Pick Folder dialog to add compounds"""
if self._pick_export_path_dialog is None:
self._pick_export_path_dialog = FilePickerDialog(
"Convert Material to MDL and Export As...",
allow_multi_selection=False,
apply_button_label="Export",
click_apply_handler=self.__on_apply_filename,
item_filter_options=["MDL Files (*.mdl)"],
item_filter_fn=self.__on_filter_mdl_files,
# OM-61553: Use the selected material prim name as the default filename
current_filename=self._selected_prim.GetName(),
current_directory=self._current_dir
)
if self._pick_export_path_dialog is not None:
self._pick_export_path_dialog.refresh_current_directory()
self._pick_export_path_dialog.set_filename(self._selected_prim.GetName())
self._pick_export_path_dialog.show(path=self._current_export_path)
# Add context menu to omni.kit.widget.stage
context_menu = omni.kit.context_menu.get_instance()
if context_menu:
menu = {
"name": "Export to MDL",
"glyph": "menu_save.svg",
"show_fn": [context_menu.is_material, context_menu.is_one_prim_selected],
"onclick_fn": on_export,
"appear_after": "Save Selected",
}
self._stage_context_menu_export = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage")
def _unregister_stage_menu(self):
"""Called when "omni.kit.widget.stage" is unloaded"""
if self._pick_export_path_dialog:
self._pick_export_path_dialog.destroy()
self._pick_export_path_dialog = None
if self._override_dialog:
self._override_dialog.destroy()
self._override_dialog = None
if self._warning_dialog:
self._warning_dialog.destroy()
self._warning_dialog = None
self._stage_context_menu_export = None
| 9,267 | Python | 40.375 | 115 | 0.584116 |
omniverse-code/kit/exts/omni.kit.stage.mdl_converter/omni/kit/stage/mdl_converter/tests/test_mdl_converter.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.stage.mdl_converter import *
from pxr import Sdf
from pxr import Usd
from pxr import UsdGeom
import omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
async def test_mdl_converter(self):
"""Testing omni.kit.stage.mdl_converter"""
self.assertEqual(True, True)
| 726 | Python | 37.263156 | 76 | 0.77686 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/capture_progress.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from enum import Enum, IntEnum
import datetime
import subprocess
import carb
import omni.ui as ui
import omni.kit.app
class CaptureStatus(IntEnum):
NONE = 0
CAPTURING = 1
PAUSED = 2
FINISHING = 3
TO_START_ENCODING = 4
ENCODING = 5
CANCELLED = 6
class CaptureProgress:
def __init__(self):
self._init_internal()
def _init_internal(self, time_length=0, time_rate=24):
self._time_length = time_length
self._time_rate = time_rate
self._total_frames = int(self._time_length / self._time_rate)
# at least to capture 1 frame
if self._total_frames < 1:
self._total_frames = 1
self._capture_status = CaptureStatus.NONE
self._elapsed_time = 0.0
self._estimated_time_remaining = 0.0
self._current_frame_time = 0.0
self._average_time_per_frame = 0.0
self._encoding_time = 0.0
self._current_frame = 0
self._first_frame_num = 0
self._got_first_frame = False
self._progress = 0.0
self._current_subframe = -1
self._total_subframes = 1
self._subframe_time = 0.0
self._total_frame_time = 0.0
self._average_time_per_subframe = 0.0
self._total_preroll_frames = 0
self._prerolled_frames = 0
self._path_trace_iteration_num = 0
self._path_trace_subframe_num = 0
@property
def capture_status(self):
return self._capture_status
@capture_status.setter
def capture_status(self, value):
self._capture_status = value
@property
def elapsed_time(self):
return self._get_time_string(self._elapsed_time)
@property
def estimated_time_remaining(self):
return self._get_time_string(self._estimated_time_remaining)
@property
def current_frame_time(self):
return self._get_time_string(self._current_frame_time)
@property
def average_frame_time(self):
return self._get_time_string(self._average_time_per_frame)
@property
def encoding_time(self):
return self._get_time_string(self._encoding_time)
@property
def progress(self):
return self._progress
@property
def current_subframe(self):
return self._current_subframe
@property
def total_subframes(self):
return self._total_subframes
@property
def subframe_time(self):
return self._get_time_string(self._subframe_time)
@property
def average_time_per_subframe(self):
return self._get_time_string(self._average_time_per_subframe)
@property
def total_preroll_frames(self):
return self._total_preroll_frames
@total_preroll_frames.setter
def total_preroll_frames(self, value):
self._total_preroll_frames = value
@property
def prerolled_frames(self):
return self._prerolled_frames
@prerolled_frames.setter
def prerolled_frames(self, value):
self._prerolled_frames = value
@property
def path_trace_iteration_num(self):
return self._path_trace_iteration_num
@path_trace_iteration_num.setter
def path_trace_iteration_num(self, value):
self._path_trace_iteration_num = value
@property
def path_trace_subframe_num(self):
return self._path_trace_subframe_num
@path_trace_subframe_num.setter
def path_trace_subframe_num(self, value):
self._path_trace_subframe_num = value
def start_capturing(self, time_length, time_rate, preroll_frames=0):
self._init_internal(time_length, time_rate)
self._total_preroll_frames = preroll_frames
self._capture_status = CaptureStatus.CAPTURING
def finish_capturing(self):
self._init_internal()
def is_prerolling(self):
return (
(self._capture_status == CaptureStatus.CAPTURING or self._capture_status == CaptureStatus.PAUSED)
and self._total_preroll_frames > 0
and self._total_preroll_frames > self._prerolled_frames
)
def add_encoding_time(self, time):
if self._estimated_time_remaining > 0.0:
self._elapsed_time += self._estimated_time_remaining
self._estimated_time_remaining = 0.0
self._encoding_time += time
def add_frame_time(self, frame, time, pt_subframe_num=0, pt_iteration_num=0):
if not self._got_first_frame:
self._got_first_frame = True
self._first_frame_num = frame
self._current_frame = frame
self._path_trace_subframe_num = pt_subframe_num
self._path_trace_iteration_num = pt_iteration_num
self._elapsed_time += time
if self._current_frame != frame:
frames_captured = self._current_frame - self._first_frame_num + 1
self._average_time_per_frame = self._elapsed_time / frames_captured
self._current_frame = frame
self._current_frame_time = time
else:
self._current_frame_time += time
if frame == self._first_frame_num:
self._estimated_time_remaining = 0.0
self._progress = 0.0
else:
total_frame_time = self._average_time_per_frame * self._total_frames
# if users pause for long times, it's possible that elapsed time will be greater than estimated total time
# if this happens, estimate it again
if self._elapsed_time >= total_frame_time:
total_frame_time += time + self._average_time_per_frame
self._estimated_time_remaining = total_frame_time - self._elapsed_time
self._progress = self._elapsed_time / total_frame_time
def add_single_frame_capture_time(self, subframe, total_subframes, time):
self._total_subframes = total_subframes
self._elapsed_time += time
if self._current_subframe != subframe:
self._subframe_time = time
if self._current_subframe == -1:
self._average_time_per_subframe = self._elapsed_time
else:
self._average_time_per_subframe = self._elapsed_time / subframe
self._total_frame_time = self._average_time_per_subframe * total_subframes
else:
self._subframe_time += time
self._current_subframe = subframe
if self._current_subframe == 0:
self._estimated_time_remaining = 0.0
self._progress = 0.0
else:
if self._elapsed_time >= self._total_frame_time:
self._total_frame_time += time + self._average_time_per_subframe
self._estimated_time_remaining = self._total_frame_time - self._elapsed_time
self._progress = self._elapsed_time / self._total_frame_time
def _get_time_string(self, time_seconds):
hours = int(time_seconds / 3600)
minutes = int((time_seconds - hours*3600) / 60)
seconds = time_seconds - hours*3600 - minutes*60
time_string = ""
if hours > 0:
time_string += '{:d}h '.format(hours)
if minutes > 0:
time_string += '{:d}m '.format(minutes)
else:
if hours > 0:
time_string += "0m "
time_string += '{:.2f}s'.format(seconds)
return time_string
PROGRESS_WINDOW_WIDTH = 360
PROGRESS_WINDOW_HEIGHT = 260
PROGRESS_BAR_WIDTH = 216
PROGRESS_BAR_HEIGHT = 20
PROGRESS_BAR_HALF_HEIGHT = PROGRESS_BAR_HEIGHT / 2
TRIANGLE_WIDTH = 6
TRIANGLE_HEIGHT = 10
TRIANGLE_OFFSET_Y = 10
PROGRESS_WIN_DARK_STYLE = {
"Triangle::progress_marker": {"background_color": 0xFFD1981D},
"Rectangle::progress_bar_background": {
"border_width": 0.5,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"background_color": 0xFF888888,
},
"Rectangle::progress_bar_full": {
"border_width": 0.5,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"background_color": 0xFFD1981D,
},
"Rectangle::progress_bar": {
"background_color": 0xFFD1981D,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"corner_flag": ui.CornerFlag.LEFT,
"alignment": ui.Alignment.LEFT,
},
}
PAUSE_BUTTON_STYLE = {
"NvidiaLight": {
"Button.Label::pause": {"color": 0xFF333333},
"Button.Label::pause:disabled": {"color": 0xFF666666},
},
"NvidiaDark": {
"Button.Label::pause": {"color": 0xFFCCCCCC},
"Button.Label::pause:disabled": {"color": 0xFF666666},
},
}
class CaptureProgressWindow:
def __init__(self):
self._app = omni.kit.app.get_app_interface()
self._update_sub = None
self._window_caption = "Capture Progress"
self._window = None
self._progress = None
self._progress_bar_len = PROGRESS_BAR_HALF_HEIGHT
self._progress_step = 0.5
self._is_single_frame_mode = False
self._show_pt_subframes = False
self._show_pt_iterations = False
self._support_pausing = True
def show(
self,
progress,
single_frame_mode: bool = False,
show_pt_subframes: bool = False,
show_pt_iterations: bool = False,
support_pausing: bool = True,
) -> None:
self._progress = progress
self._is_single_frame_mode = single_frame_mode
self._show_pt_subframes = show_pt_subframes
self._show_pt_iterations = show_pt_iterations
self._support_pausing = support_pausing
self._build_ui()
self._update_sub = self._app.get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.kit.capure progress"
)
def close(self):
self._window = None
self._update_sub = None
def _build_progress_bar(self):
self._progress_bar_area.clear()
self._progress_bar_area.set_style(PROGRESS_WIN_DARK_STYLE)
with self._progress_bar_area:
with ui.Placer(offset_x=self._progress_bar_len - TRIANGLE_WIDTH / 2, offset_y=TRIANGLE_OFFSET_Y):
ui.Triangle(
name="progress_marker",
width=TRIANGLE_WIDTH,
height=TRIANGLE_HEIGHT,
alignment=ui.Alignment.CENTER_BOTTOM,
)
with ui.ZStack():
ui.Rectangle(name="progress_bar_background", width=PROGRESS_BAR_WIDTH, height=PROGRESS_BAR_HEIGHT)
ui.Rectangle(name="progress_bar", width=self._progress_bar_len, height=PROGRESS_BAR_HEIGHT)
def _build_ui_timer(self, text, init_value):
with ui.HStack():
with ui.HStack(width=ui.Percent(50)):
ui.Spacer()
ui.Label(text, width=0)
with ui.HStack(width=ui.Percent(50)):
ui.Spacer(width=15)
timer_label = ui.Label(init_value)
ui.Spacer()
return timer_label
def _build_multi_frames_capture_timers(self):
self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time)
self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining)
self._ui_current_frame_time = self._build_ui_timer("Current frame time", self._progress.current_frame_time)
if self._show_pt_subframes:
subframes_str = f"{self._progress.path_trace_subframe_num}"
self._ui_pt_subframes = self._build_ui_timer("Subframes", subframes_str)
if self._show_pt_iterations:
iter_str = f"{self._progress.path_trace_iteration_num}"
self._ui_pt_iterations = self._build_ui_timer("Iterations", iter_str)
self._ui_ave_frame_time = self._build_ui_timer("Average time per frame", self._progress.average_frame_time)
self._ui_encoding_time = self._build_ui_timer("Encoding", self._progress.encoding_time)
def _build_single_frame_capture_timers(self):
self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time)
self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining)
subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}"
self._ui_subframe_count = self._build_ui_timer("Subframe/Total frames", subframe_count)
self._ui_current_frame_time = self._build_ui_timer("Current subframe time", self._progress.subframe_time)
self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_frame_time)
def _build_preroll_notification(self):
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._preroll_frames_notification = ui.Label("Running preroll frames, please wait...")
ui.Spacer(width=ui.Percent(10))
def _build_ui(self):
if self._window is None:
style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle")
if not style_settings:
style_settings = "NvidiaDark"
self._window = ui.Window(
self._window_caption,
width=PROGRESS_WINDOW_WIDTH,
height=PROGRESS_WINDOW_HEIGHT,
style=PROGRESS_WIN_DARK_STYLE,
)
with self._window.frame:
with ui.VStack():
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._progress_bar_area = ui.VStack()
self._build_progress_bar()
ui.Spacer(width=ui.Percent(20))
ui.Spacer(height=5)
if self._is_single_frame_mode:
self._build_single_frame_capture_timers()
else:
self._build_multi_frames_capture_timers()
self._build_preroll_notification()
with ui.HStack():
with ui.HStack(width=ui.Percent(50)):
ui.Spacer()
self._ui_pause_button = ui.Button(
"Pause",
height=0,
clicked_fn=self._on_pause_clicked,
enabled=self._support_pausing,
style=PAUSE_BUTTON_STYLE[style_settings],
name="pause",
)
with ui.HStack(width=ui.Percent(50)):
ui.Spacer(width=15)
ui.Button("Cancel", height=0, clicked_fn=self._on_cancel_clicked)
ui.Spacer()
ui.Spacer()
self._window.visible = True
self._update_timers()
def _on_pause_clicked(self):
if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause":
self._progress.capture_status = CaptureStatus.PAUSED
self._ui_pause_button.text = "Resume"
elif self._progress.capture_status == CaptureStatus.PAUSED:
self._progress.capture_status = CaptureStatus.CAPTURING
self._ui_pause_button.text = "Pause"
def _on_cancel_clicked(self):
if (
self._progress.capture_status == CaptureStatus.CAPTURING
or self._progress.capture_status == CaptureStatus.PAUSED
):
self._progress.capture_status = CaptureStatus.CANCELLED
def _update_timers(self):
if self._is_single_frame_mode:
self._ui_elapsed_time.text = self._progress.elapsed_time
self._ui_remaining_time.text = self._progress.estimated_time_remaining
subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}"
self._ui_subframe_count.text = subframe_count
self._ui_current_frame_time.text = self._progress.subframe_time
self._ui_ave_frame_time.text = self._progress.average_time_per_subframe
else:
self._ui_elapsed_time.text = self._progress.elapsed_time
self._ui_remaining_time.text = self._progress.estimated_time_remaining
self._ui_current_frame_time.text = self._progress.current_frame_time
if self._show_pt_subframes:
subframes_str = f"{self._progress.path_trace_subframe_num}"
self._ui_pt_subframes.text = subframes_str
if self._show_pt_iterations:
iter_str = f"{self._progress.path_trace_iteration_num}"
self._ui_pt_iterations.text = iter_str
self._ui_ave_frame_time.text = self._progress.average_frame_time
self._ui_encoding_time.text = self._progress.encoding_time
def _update_preroll_frames(self):
if self._progress.is_prerolling():
msg = 'Running preroll frames {}/{}, please wait...'.format(
self._progress.prerolled_frames,
self._progress.total_preroll_frames
)
self._preroll_frames_notification.text = msg
else:
self._preroll_frames_notification.visible = False
def _on_update(self, event):
self._update_preroll_frames()
self._update_timers()
self._progress_bar_len = (
PROGRESS_BAR_WIDTH - PROGRESS_BAR_HEIGHT
) * self._progress.progress + PROGRESS_BAR_HALF_HEIGHT
self._build_progress_bar()
| 17,963 | Python | 38.052174 | 123 | 0.597228 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import math
import time
import datetime
import omni.ext
import carb
import omni.kit.app
import omni.timeline
import omni.usd
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file
from .capture_options import *
from .capture_progress import *
from .video_generation import VideoGenerationHelper
from .helper import get_num_pattern_file_path
VIDEO_FRAMES_DIR_NAME = "frames"
DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO = ".png"
capture_instance = None
class CaptureExtension(omni.ext.IExt):
def on_startup(self):
global capture_instance
capture_instance = self
self._options = CaptureOptions()
self._progress = CaptureProgress()
self._progress_window = CaptureProgressWindow()
self._renderer = None
import omni.renderer_capture
self._renderer = omni.renderer_capture.acquire_renderer_capture_interface()
self._viewport_api = None
self._app = omni.kit.app.get_app_interface()
self._timeline = omni.timeline.get_timeline_interface()
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._settings = carb.settings.get_settings()
self._show_default_progress_window = True
self._progress_update_fn = None
self._forward_one_frame_fn = None
self._capture_finished_fn = None
carb.log_warn("Deprecated notice: Please be noted that omni.kit.capture has been replaced with omni.kit.capture.viewport and will be removed in future releases. " \
"Please update the use of this extension to the new one.")
def on_shutdown(self):
self._progress = None
self._progress_window = None
global capture_instance
capture_instance = None
@property
def options(self):
return self._options
@options.setter
def options(self, value):
self._options = value
@property
def progress(self):
return self._progress
@property
def show_default_progress_window(self):
return self._show_default_progress_window
@show_default_progress_window.setter
def show_default_progress_window(self, value):
self._show_default_progress_window = value
@property
def progress_update_fn(self):
return self._progress_update_fn
@progress_update_fn.setter
def progress_update_fn(self, value):
self._progress_update_fn = value
@property
def forward_one_frame_fn(self):
return self._forward_one_frame_fn
@forward_one_frame_fn.setter
def forward_one_frame_fn(self, value):
self._forward_one_frame_fn = value
@property
def capture_finished_fn(self):
return self._capture_finished_fn
@capture_finished_fn.setter
def capture_finished_fn(self, value):
self._capture_finished_fn = value
def start(self):
self._prepare_folder_and_counters()
self._prepare_viewport()
self._start_internal()
def pause(self):
if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause":
self._progress.capture_status = CaptureStatus.PAUSED
def resume(self):
if self._progress.capture_status == CaptureStatus.PAUSED:
self._progress.capture_status = CaptureStatus.CAPTURING
def cancel(self):
if (
self._progress.capture_status == CaptureStatus.CAPTURING
or self._progress.capture_status == CaptureStatus.PAUSED
):
self._progress.capture_status = CaptureStatus.CANCELLED
def _update_progress_hook(self):
if self._progress_update_fn is not None:
self._progress_update_fn(
self._progress.capture_status,
self._progress.progress,
self._progress.elapsed_time,
self._progress.estimated_time_remaining,
self._progress.current_frame_time,
self._progress.average_frame_time,
self._progress.encoding_time,
self._frame_counter,
self._total_frame_count,
)
def _get_index_for_image(self, dir, file_name, image_suffix):
def is_int(string_val):
try:
v = int(string_val)
return True
except:
return False
images = os.listdir(dir)
name_len = len(file_name)
suffix_len = len(image_suffix)
max_index = 0
for item in images:
if item.startswith(file_name) and item.endswith(image_suffix):
num_part = item[name_len : (len(item) - suffix_len)]
if is_int(num_part):
num = int(num_part)
if max_index < num:
max_index = num
return max_index + 1
def _float_to_time(self, ft):
hour = int(ft)
ft = (ft - hour) * 60
minute = int(ft)
ft = (ft - minute) * 60
second = int(ft)
ft = (ft - second) * 1000000
microsecond = int(ft)
return datetime.time(hour, minute, second, microsecond)
def _is_environment_sunstudy_player(self):
if self._options.sunstudy_player is not None:
return type(self._options.sunstudy_player).__module__ == "omni.kit.environment.core.sunstudy_player.player"
else:
carb.log_warn("Sunstudy player type check is valid only when the player is available.")
return False
def _update_sunstudy_player_time(self):
if self._is_environment_sunstudy_player():
self._options.sunstudy_player.current_time = self._sunstudy_current_time
else:
self._options.sunstudy_player.update_time(self._sunstudy_current_time)
def _set_sunstudy_player_time(self, current_time):
if self._is_environment_sunstudy_player():
self._options.sunstudy_player.current_time = current_time
else:
date_time = self._options.sunstudy_player.get_date_time()
time_to_set = self._float_to_time(current_time)
new_date_time = datetime.datetime(
date_time.year, date_time.month, date_time.day,
time_to_set.hour, time_to_set.minute, time_to_set.second
)
self._options.sunstudy_player.set_date_time(new_date_time)
def _prepare_sunstudy_counters(self):
self._total_frame_count = self._options.fps * self._options.sunstudy_movie_length_in_seconds
duration = self._options.sunstudy_end_time - self._options.sunstudy_start_time
self._sunstudy_iterations_per_frame = self._options.ptmb_subframes_per_frame
self._sunstudy_delta_time_per_iteration = duration / float(self._total_frame_count * self._sunstudy_iterations_per_frame)
self._sunstudy_current_time = self._options.sunstudy_start_time
self._set_sunstudy_player_time(self._sunstudy_current_time)
def _prepare_folder_and_counters(self):
self._workset_dir = self._options.output_folder
if not self._make_sure_directory_existed(self._workset_dir):
carb.log_warn(f"Capture failed due to unable to create folder {self._workset_dir}")
self._finish()
return
if self._options.is_capturing_nth_frames():
if self._options.capture_every_Nth_frames == 1:
frames_folder = self._options.file_name + "_frames"
else:
frames_folder = self._options.file_name + "_" + str(self._options.capture_every_Nth_frames) + "th_frames"
self._nth_frames_dir = os.path.join(self._workset_dir, frames_folder)
if not self._make_sure_directory_existed(self._nth_frames_dir):
carb.log_warn(f"Capture failed due to unable to create folder {self._nth_frames_dir}")
self._finish()
return
if self._options.is_video():
self._frames_dir = os.path.join(self._workset_dir, self._options.file_name + "_" + VIDEO_FRAMES_DIR_NAME)
if not self._make_sure_directory_existed(self._frames_dir):
carb.log_warn(
f"Capture failed due to unable to create folder {self._workset_dir} to save frames of the video."
)
self._finish()
return
self._video_name = self._options.get_full_path()
self._frame_pattern_prefix = os.path.join(self._frames_dir, self._options.file_name)
if self._options.is_capturing_frame():
self._start_time = float(self._options.start_frame) / self._options.fps
self._end_time = float(self._options.end_frame + 1) / self._options.fps
self._time = self._start_time
self._frame = self._options.start_frame
self._start_number = self._frame
self._total_frame_count = round((self._end_time - self._start_time) * self._options.fps)
else:
self._start_time = self._options.start_time
self._end_time = self._options.end_time
self._time = self._options.start_time
self._frame = int(self._options.start_time * self._options.fps)
self._start_number = self._frame
self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._options.fps)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._prepare_sunstudy_counters()
else:
if self._options.is_capturing_nth_frames():
self._frame_pattern_prefix = self._nth_frames_dir
if self._options.is_capturing_frame():
self._start_time = float(self._options.start_frame) / self._options.fps
self._end_time = float(self._options.end_frame + 1) / self._options.fps
self._time = self._start_time
self._frame = self._options.start_frame
self._start_number = self._frame
self._total_frame_count = round((self._end_time - self._start_time) * self._options.fps)
else:
self._start_time = self._options.start_time
self._end_time = self._options.end_time
self._time = self._options.start_time
self._frame = int(self._options.start_time * self._options.fps)
self._start_number = self._frame
self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._options.fps)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._prepare_sunstudy_counters()
else:
index = self._get_index_for_image(self._workset_dir, self._options.file_name, self._options.file_type)
self._frame_pattern_prefix = os.path.join(self._workset_dir, self._options.file_name + str(index))
self._start_time = self._timeline.get_current_time()
self._end_time = self._timeline.get_current_time()
self._time = self._timeline.get_current_time()
self._frame = 1
self._start_number = self._frame
self._total_frame_count = 1
self._subframe = 0
self._sample_count = 0
self._frame_counter = 0
self._real_time_settle_latency_frames_done = 0
self._last_skipped_frame_path = ""
self._path_trace_iterations = 0
self._time_rate = 1.0 / self._options.fps
self._time_subframe_rate = (
self._time_rate * (self._options.ptmb_fsc - self._options.ptmb_fso) / self._options.ptmb_subframes_per_frame
)
def _prepare_viewport(self):
viewport_api = get_active_viewport()
if viewport_api is None:
return False
self._record_current_window_status(viewport_api)
viewport_api.camera_path = self._options.camera
viewport_api.resolution = (self._options.res_width, self._options.res_height)
self._settings.set_bool("/persistent/app/captureFrame/viewport", True)
self._settings.set_bool("/app/captureFrame/setAlphaTo1", not self._options.save_alpha)
if self._options.file_type == ".exr":
self._settings.set_bool("/app/captureFrame/hdr", self._options.hdr_output)
else:
self._settings.set_bool("/app/captureFrame/hdr", False)
if self._options.save_alpha:
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", True)
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/backgroundComposite", False)
self._selection.clear_selected_prim_paths()
if self._options.render_preset == CaptureRenderPreset.RAY_TRACE:
self._switch_renderer = not (self._saved_active_render == "rtx" and self._saved_render_mode == "RaytracedLighting")
if self._switch_renderer:
viewport_api.set_hd_engine("rtx", "RaytracedLighting")
carb.log_info("Switching to RayTracing Mode")
elif self._options.render_preset == CaptureRenderPreset.PATH_TRACE:
self._switch_renderer = not (self._saved_active_render == "rtx" and self._saved_render_mode == "PathTracing")
if self._switch_renderer:
viewport_api.set_hd_engine("rtx", "PathTracing")
carb.log_info("Switching to PathTracing Mode")
elif self._options.render_preset == CaptureRenderPreset.IRAY:
self._switch_renderer = not (self._saved_active_render == "iray" and self._saved_render_mode == "iray")
if self._switch_renderer:
viewport_api.set_hd_engine("iray", "iray")
carb.log_info("Switching to IRay Mode")
else:
self._switch_renderer = False
carb.log_info("Keeping current Render Mode")
if self._options.debug_material_type == CaptureDebugMaterialType.SHADED:
self._settings.set_int("/rtx/debugMaterialType", -1)
elif self._options.debug_material_type == CaptureDebugMaterialType.WHITE:
self._settings.set_int("/rtx/debugMaterialType", 0)
else:
carb.log_info("Keeping current debug mateiral type")
# set it to 0 to ensure we accumulate as many samples as requested even across subframes (for motion blur)
self._settings.set_int("/rtx/pathtracing/totalSpp", 0)
# don't show light and grid during capturing
self._settings.set_int("/persistent/app/viewport/displayOptions", 0)
# disable async rendering for capture, otherwise it won't capture images correctly
self._settings.set_bool("/app/asyncRendering", False)
self._settings.set_bool("/app/asyncRenderingLowLatency", False)
# Rendering to some image buffers additionally require explicitly setting `set_capture_sync(True)`, on top of
# disabling the `/app/asyncRendering` setting. This can otherwise cause images to hold corrupted buffer
# information by erroneously assuming a complete image buffer is available when only a first partial subframe
# has been renderer (as in the case of EXR):
self._renderer.set_capture_sync( self._options.file_type == ".exr" )
# frames to wait for the async settings above to be ready, they will need to be detected by viewport, and
# then viewport will notify the renderer not to do async rendering
self._frames_to_disable_async_rendering = 2
# Normally avoid using a high /rtx/pathtracing/spp setting since it causes GPU
# timeouts for large sample counts. But a value larger than 1 can be useful in Multi-GPU setups
self._settings.set_int(
"/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp)
)
# Setting resetPtAccumOnlyWhenExternalFrameCounterChanges ensures we control accumulation explicitly
# by simpling changing the /rtx/externalFrameCounter value
self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", True)
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._options.path_trace_spp)
# Enable syncLoads in materialDB and Hydra. This is needed to make sure texture updates finish before we start the rendering
self._settings.set("/rtx/materialDb/syncLoads", True)
self._settings.set("/rtx/hydra/materialSyncLoads", True)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", False)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0)
return True
def _show_progress_window(self):
return (
self._options.is_video() or self._options.is_capturing_nth_frames() or (self._options.show_single_frame_progress and self._options.is_capturing_pathtracing_single_frame())
) and self.show_default_progress_window
def _start_internal(self):
# If texture streaming is enabled, set the preroll to at least 1 frame
if self._settings.get("/rtx-transient/resourcemanager/enableTextureStreaming"):
self._options.preroll_frames = max(self._options.preroll_frames, 1)
# set usd time code second to target frame rate
self._saved_timecodes_per_second = self._timeline.get_time_codes_per_seconds()
self._timeline.set_time_codes_per_second(self._options.fps)
# if we want preroll, then set timeline's current time back with the preroll frames' time,
# and rely on timeline to do the preroll using the give timecode
if self._options.preroll_frames > 0:
self._timeline.set_current_time(self._start_time - self._options.preroll_frames / self._options.fps)
self._settings.set("/iray/current_frame_time", self._start_time - self._options.preroll_frames / self._options.fps)
else:
self._timeline.set_current_time(self._start_time)
self._settings.set("/iray/current_frame_time", self._start_time)
# change timeline to be in play state
self._timeline.play()
# disable automatic time update in timeline so that movie capture tool can control time step
self._timeline.set_auto_update(False)
self._update_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update, order=1000000)
)
self._progress.start_capturing(self._end_time - self._start_time, self._time_rate, self._options.preroll_frames)
# always show single frame capture progress for PT mode
self._options.show_single_frame_progress = True
if self._show_progress_window():
self._progress_window.show(
self._progress,
self._options.is_capturing_pathtracing_single_frame(),
show_pt_subframes=self._options.render_preset == CaptureRenderPreset.PATH_TRACE,
show_pt_iterations=self._options.render_preset == CaptureRenderPreset.IRAY
)
def _record_current_window_status(self, viewport_api):
assert viewport_api is not None, "No viewport to record to"
self._viewport_api = viewport_api
self._saved_camera = viewport_api.camera_path
self._saved_hydra_engine = viewport_api.hydra_engine
self._saved_render_mode = viewport_api.render_mode
resolution = viewport_api.resolution
self._saved_resolution_width = int(resolution[0])
self._saved_resolution_height = int(resolution[1])
self._saved_capture_frame_viewport = self._settings.get("/persistent/app/captureFrame/viewport")
self._saved_active_render = self._settings.get("/renderer/active")
self._saved_debug_material_type = self._settings.get("/rtx/debugMaterialType")
self._saved_total_spp = int(self._settings.get("/rtx/pathtracing/totalSpp"))
self._saved_spp = int(self._settings.get("/rtx/pathtracing/spp"))
self._saved_reset_pt_accum_only = self._settings.get("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges")
self._saved_display_options = self._settings.get("/persistent/app/viewport/displayOptions")
self._saved_async_rendering = self._settings.get("/app/asyncRendering")
self._saved_async_renderingLatency = self._settings.get("/app/asyncRenderingLowLatency")
self._saved_background_zero_alpha = self._settings.get("/rtx/post/backgroundZeroAlpha/enabled")
self._saved_background_zero_alpha_comp = self._settings.get("/rtx/post/backgroundZeroAlpha/backgroundComposite")
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._saved_iray_sample_limit = int(self._settings.get("/rtx/iray/progressive_rendering_max_samples"))
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._saved_sunstudy_current_time = self._options.sunstudy_current_time
self._saved_timeline_current_time = self._timeline.get_current_time()
self._saved_rtx_sync_load_setting = self._settings.get("/rtx/materialDb/syncLoads")
self._saved_hydra_sync_load_setting = self._settings.get("/rtx/hydra/materialSyncLoads")
self._saved_async_texture_streaming = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/async")
self._saved_texture_streaming_budget = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB")
def _restore_window_status(self):
viewport_api, self._viewport_api = self._viewport_api, None
assert viewport_api is not None, "No viewport to restore to"
viewport_api.camera_path = self._saved_camera
viewport_api.resolution = (self._saved_resolution_width, self._saved_resolution_height)
if self._switch_renderer:
viewport_api.set_hd_engine(self._saved_hydra_engine, self._saved_render_mode)
self._settings.set_bool("/persistent/app/captureFrame/viewport", self._saved_capture_frame_viewport)
self._settings.set_int("/rtx/debugMaterialType", self._saved_debug_material_type)
self._settings.set_int("/rtx/pathtracing/totalSpp", self._saved_total_spp)
self._settings.set_int("/rtx/pathtracing/spp", self._saved_spp)
self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", self._saved_reset_pt_accum_only)
self._settings.set_int("/persistent/app/viewport/displayOptions", self._saved_display_options)
self._settings.set_bool("/app/asyncRendering", self._saved_async_rendering)
self._settings.set_bool("/app/asyncRenderingLowLatency", self._saved_async_renderingLatency)
self._renderer.set_capture_sync(not self._saved_async_rendering)
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", self._saved_background_zero_alpha)
self._settings.set_bool(
"/rtx/post/backgroundZeroAlpha/backgroundComposite", self._saved_background_zero_alpha_comp
)
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._saved_iray_sample_limit)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._set_sunstudy_player_time(self._saved_sunstudy_current_time)
self._settings.set("/rtx/materialDb/syncLoads", self._saved_rtx_sync_load_setting)
self._settings.set("/rtx/hydra/materialSyncLoads", self._saved_hydra_sync_load_setting)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", self._saved_async_texture_streaming)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", self._saved_texture_streaming_budget)
self._settings.set("/app/captureFrame/hdr", False)
def _clean_pngs_in_directory(self, directory):
self._clean_files_in_directory(directory, ".png")
def _clean_files_in_directory(self, directory, suffix):
images = os.listdir(directory)
for item in images:
if item.endswith(suffix):
os.remove(os.path.join(directory, item))
def _make_sure_directory_existed(self, directory):
if not os.path.exists(directory):
try:
os.makedirs(directory, exist_ok=True)
except OSError as error:
carb.log_warn(f"Directory cannot be created: {dir}")
return False
return True
def _finish(self):
if (
self._progress.capture_status == CaptureStatus.FINISHING
or self._progress.capture_status == CaptureStatus.CANCELLED
):
self._update_sub = None
self._restore_window_status()
self._sample_count = 0
self._start_number = 0
self._frame_counter = 0
self._path_trace_iterations = 0
self._progress.capture_status = CaptureStatus.NONE
# restore timeline settings
# stop timeline, but re-enable auto update
timeline = self._timeline
timeline.set_auto_update(True)
timeline.stop()
timeline.set_time_codes_per_second(self._saved_timecodes_per_second)
self._timeline.set_current_time(self._saved_timeline_current_time)
self._settings.set("/iray/current_frame_time", self._saved_timeline_current_time)
if self._show_progress_window():
self._progress_window.close()
if self._capture_finished_fn is not None:
self._capture_finished_fn()
def _wait_for_image_writing(self):
# wait for the last frame is written to disk
# my tests of scenes of different complexity show a range of 0.2 to 1 seconds wait time
# so 5 second max time should be enough and we can early quit by checking the last
# frame every 0.1 seconds.
SECONDS_TO_WAIT = 5
SECONDS_EACH_TIME = 0.1
seconds_tried = 0.0
carb.log_info("Waiting for frames to be ready for encoding.")
while seconds_tried < SECONDS_TO_WAIT:
if os.path.isfile(self._frame_path) and os.access(self._frame_path, os.R_OK):
break
else:
time.sleep(SECONDS_EACH_TIME)
seconds_tried += SECONDS_EACH_TIME
if seconds_tried >= SECONDS_TO_WAIT:
carb.log_warn(f"Wait time out. To start encoding with images already have.")
def _capture_viewport(self, frame_path: str):
capture_viewport_to_file(self._viewport_api, file_path=frame_path)
carb.log_info(f"Capturing {frame_path}")
def _get_current_frame_output_path(self):
frame_path = ""
if self._options.is_video():
frame_path = get_num_pattern_file_path(
self._frames_dir,
self._options.file_name,
self._options.file_name_num_pattern,
self._frame,
DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO,
self._options.renumber_negative_frame_number_from_0,
abs(self._start_number)
)
else:
if self._options.is_capturing_nth_frames():
if self._frame_counter % self._options.capture_every_Nth_frames == 0:
frame_path = get_num_pattern_file_path(
self._frame_pattern_prefix,
self._options.file_name,
self._options.file_name_num_pattern,
self._frame,
self._options.file_type,
self._options.renumber_negative_frame_number_from_0,
abs(self._start_number)
)
else:
frame_path = self._frame_pattern_prefix + self._options.file_type
return frame_path
def _handle_skipping_frame(self, dt):
if not self._options.overwrite_existing_frames:
if os.path.exists(self._frame_path):
carb.log_warn(f"Frame {self._frame_path} exists, skip it...")
self._settings.set_int("/rtx/pathtracing/spp", 1)
self._subframe = 0
self._sample_count = 0
self._path_trace_iterations = 0
can_continue = True
if self._forward_one_frame_fn is not None:
can_continue = self._forward_one_frame_fn(dt)
elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \
(self._options.is_video() or self._options.is_capturing_nth_frames()):
self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration * self._sunstudy_iterations_per_frame
self._update_sunstudy_player_time()
else: # movie type is SEQUENCE
self._time = self._start_time + (self._frame - self._start_number) * self._time_rate
self._timeline.set_current_time(self._time)
self._settings.set("/iray/current_frame_time", self._time)
self._frame += 1
self._frame_counter += 1
# check if capture ends
if self._forward_one_frame_fn is not None:
if can_continue is False:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
else:
if self._time >= self._end_time or self._frame_counter >= self._total_frame_count:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
return True
else:
if os.path.exists(self._frame_path) and self._last_skipped_frame_path != self._frame_path:
carb.log_warn(f"Frame {self._frame_path} will be overwritten.")
self._last_skipped_frame_path = self._frame_path
return False
def _handle_real_time_capture_settle_latency(self):
if (self._options.render_preset == CaptureRenderPreset.RAY_TRACE
and self._options.real_time_settle_latency_frames > 0):
self._real_time_settle_latency_frames_done += 1
if self._real_time_settle_latency_frames_done > self._options.real_time_settle_latency_frames:
self._real_time_settle_latency_frames_done = 0
return False
else:
self._subframe = 0
self._sample_count = 0
return True
return False
def _on_update(self, e):
dt = e.payload["dt"]
if self._progress.capture_status == CaptureStatus.FINISHING:
self._finish()
self._update_progress_hook()
elif self._progress.capture_status == CaptureStatus.CANCELLED:
# carb.log_warn("video recording cancelled")
self._update_progress_hook()
self._finish()
elif self._progress.capture_status == CaptureStatus.ENCODING:
if VideoGenerationHelper().encoding_done:
self._progress.capture_status = CaptureStatus.FINISHING
self._update_progress_hook()
self._progress.add_encoding_time(dt)
elif self._progress.capture_status == CaptureStatus.TO_START_ENCODING:
if VideoGenerationHelper().is_encoding is False:
self._wait_for_image_writing()
if self._options.renumber_negative_frame_number_from_0 is True and self._start_number < 0:
video_frame_start_num = 0
else:
video_frame_start_num = self._start_number
started = VideoGenerationHelper().generating_video(
self._video_name,
self._frames_dir,
self._options.file_name,
self._options.file_name_num_pattern,
video_frame_start_num,
self._total_frame_count,
self._options.fps,
)
if started:
self._progress.capture_status = CaptureStatus.ENCODING
self._update_progress_hook()
self._progress.add_encoding_time(dt)
else:
carb.log_warn("Movie capture failed to encode the capture images.")
self._progress.capture_status = CaptureStatus.FINISHING
elif self._progress.capture_status == CaptureStatus.CAPTURING:
if self._frames_to_disable_async_rendering >= 0:
self._frames_to_disable_async_rendering -= 1
return
if self._progress.is_prerolling():
self._progress.prerolled_frames += 1
self._settings.set_int("/rtx/pathtracing/spp", 1)
left_preroll_frames = self._options.preroll_frames - self._progress.prerolled_frames
self._timeline.set_current_time(self._start_time - left_preroll_frames / self._options.fps)
self._settings.set("/iray/current_frame_time", self._start_time - left_preroll_frames / self._options.fps)
return
self._frame_path = self._get_current_frame_output_path()
if self._handle_skipping_frame(dt):
return
self._settings.set_int(
"/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp)
)
if self._options.render_preset == CaptureRenderPreset.IRAY:
iterations_done = int(self._settings.get("/iray/progression"))
self._path_trace_iterations = iterations_done
self._sample_count = iterations_done
else:
self._sample_count += self._options.spp_per_iteration
self._timeline.set_prerolling(False)
self._settings.set_int("/rtx/externalFrameCounter", self._frame)
# update progress timers
if self._options.is_capturing_pathtracing_single_frame():
self._progress.add_single_frame_capture_time(self._subframe, self._options.ptmb_subframes_per_frame, dt)
else:
self._progress.add_frame_time(self._frame, dt, self._subframe + 1, self._path_trace_iterations)
self._update_progress_hook()
# capture frame when we reach the sample count for this frame and are rendering the last subframe
# Note _sample_count can go over _samples_per_pixel when 'spp_per_iteration > 1'
if (self._sample_count >= self._options.path_trace_spp) and (
self._subframe == self._options.ptmb_subframes_per_frame - 1
):
if self._handle_real_time_capture_settle_latency():
return
if self._options.is_video():
self._capture_viewport(self._frame_path)
else:
if self._options.is_capturing_nth_frames():
if self._frame_counter % self._options.capture_every_Nth_frames == 0:
self._capture_viewport(self._frame_path)
else:
self._progress.capture_status = CaptureStatus.FINISHING
self._capture_viewport(self._frame_path)
# reset time the *next frame* (since otherwise we capture the first sample)
if self._sample_count >= self._options.path_trace_spp:
self._sample_count = 0
self._path_trace_iterations = 0
self._subframe += 1
if self._subframe == self._options.ptmb_subframes_per_frame:
self._subframe = 0
self._frame += 1
self._frame_counter += 1
self._time = self._start_time + (self._frame - self._start_number) * self._time_rate
can_continue = False
if self._forward_one_frame_fn is not None:
can_continue = self._forward_one_frame_fn(dt)
elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \
(self._options.is_video() or self._options.is_capturing_nth_frames()):
self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration
self._update_sunstudy_player_time()
else:
cur_time = (
self._time + (self._options.ptmb_fso * self._time_rate) + self._time_subframe_rate * self._subframe
)
self._timeline.set_current_time(cur_time)
self._settings.set("/iray/current_frame_time", cur_time)
if self._forward_one_frame_fn is not None:
if can_continue == False:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
else:
if self._time >= self._end_time or self._frame_counter >= self._total_frame_count:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
@staticmethod
def get_instance():
global capture_instance
return capture_instance
| 38,884 | Python | 48.91656 | 183 | 0.610045 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/capture_options.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
from enum import Enum, IntEnum
class CaptureMovieType(IntEnum):
SEQUENCE = 0
SUNSTUDY = 1
PLAYLIST = 2
class CaptureRangeType(IntEnum):
FRAMES = 0
SECONDS = 1
class CaptureRenderPreset(IntEnum):
PATH_TRACE = 0
RAY_TRACE = 1
IRAY = 2
class CaptureDebugMaterialType(IntEnum):
SHADED = 0
WHITE = 1
class CaptureOptions:
""" All Capture options that will be used when capturing.
Note: When adding an attribute make sure it is exposed via the constructor.
Not doing this will cause erorrs when serializing and deserializing this object.
"""
def __init__(
self,
camera="camera",
range_type=CaptureRangeType.FRAMES,
capture_every_nth_frames=-1,
fps="24",
start_frame=1,
end_frame=40,
start_time=0,
end_time=10,
res_width=1920,
res_height=1080,
render_preset=CaptureRenderPreset.PATH_TRACE,
debug_material_type=CaptureDebugMaterialType.SHADED,
spp_per_iteration=1,
path_trace_spp=1,
ptmb_subframes_per_frame=1,
ptmb_fso=0.0,
ptmb_fsc=1.0,
output_folder="",
file_name="Capture",
file_name_num_pattern=".####",
file_type=".tga",
save_alpha=False,
hdr_output=False,
show_pathtracing_single_frame_progress=False,
preroll_frames=0,
overwrite_existing_frames=False,
movie_type=CaptureMovieType.SEQUENCE,
sunstudy_start_time=0.0,
sunstudy_current_time=0.0,
sunstudy_end_time=0.0,
sunstudy_movie_length_in_seconds=0,
sunstudy_player=None,
real_time_settle_latency_frames=0,
renumber_negative_frame_number_from_0=False
):
self._camera = camera
self._range_type = range_type
self._capture_every_nth_frames = capture_every_nth_frames
self._fps = fps
self._start_frame = start_frame
self._end_frame = end_frame
self._start_time = start_time
self._end_time = end_time
self._res_width = res_width
self._res_height = res_height
self._render_preset = render_preset
self._debug_material_type = debug_material_type
self._spp_per_iteration = spp_per_iteration
self._path_trace_spp = path_trace_spp
self._ptmb_subframes_per_frame = ptmb_subframes_per_frame
self._ptmb_fso = ptmb_fso
self._ptmb_fsc = ptmb_fsc
self._output_folder = output_folder
self._file_name = file_name
self._file_name_num_pattern = file_name_num_pattern
self._file_type = file_type
self._save_alpha = save_alpha
self._hdr_output = hdr_output
self._show_pathtracing_single_frame_progress = show_pathtracing_single_frame_progress
self._preroll_frames = preroll_frames
self._overwrite_existing_frames = overwrite_existing_frames
self._movie_type = movie_type
self._sunstudy_start_time = sunstudy_start_time
self._sunstudy_current_time = sunstudy_current_time
self._sunstudy_end_time = sunstudy_end_time
self._sunstudy_movie_length_in_seconds = sunstudy_movie_length_in_seconds
self._sunstudy_player = sunstudy_player
self._real_time_settle_latency_frames = real_time_settle_latency_frames
self._renumber_negative_frame_number_from_0 = renumber_negative_frame_number_from_0
def to_dict(self):
data = vars(self)
return {key.lstrip("_"): value for key, value in data.items()}
@classmethod
def from_dict(cls, options):
return cls(**options)
@property
def camera(self):
return self._camera
@camera.setter
def camera(self, value):
self._camera = value
@property
def range_type(self):
return self._range_type
@range_type.setter
def range_type(self, value):
self._range_type = value
@property
def capture_every_Nth_frames(self):
return self._capture_every_nth_frames
@capture_every_Nth_frames.setter
def capture_every_Nth_frames(self, value):
self._capture_every_nth_frames = value
@property
def fps(self):
return self._fps
@fps.setter
def fps(self, value):
self._fps = value
@property
def start_frame(self):
return self._start_frame
@start_frame.setter
def start_frame(self, value):
self._start_frame = value
@property
def end_frame(self):
return self._end_frame
@end_frame.setter
def end_frame(self, value):
self._end_frame = value
@property
def start_time(self):
return self._start_time
@start_time.setter
def start_time(self, value):
self._start_time = value
@property
def end_time(self):
return self._end_time
@end_time.setter
def end_time(self, value):
self._end_time = value
@property
def res_width(self):
return self._res_width
@res_width.setter
def res_width(self, value):
self._res_width = value
@property
def res_height(self):
return self._res_height
@res_height.setter
def res_height(self, value):
self._res_height = value
@property
def render_preset(self):
return self._render_preset
@render_preset.setter
def render_preset(self, value):
self._render_preset = value
@property
def debug_material_type(self):
return self._debug_material_type
@debug_material_type.setter
def debug_material_type(self, value):
self._debug_material_type = value
@property
def spp_per_iteration(self):
return self._spp_per_iteration
@spp_per_iteration.setter
def spp_per_iteration(self, value):
self._spp_per_iteration = value
@property
def path_trace_spp(self):
return self._path_trace_spp
@path_trace_spp.setter
def path_trace_spp(self, value):
self._path_trace_spp = value
@property
def ptmb_subframes_per_frame(self):
return self._ptmb_subframes_per_frame
@ptmb_subframes_per_frame.setter
def ptmb_subframes_per_frame(self, value):
self._ptmb_subframes_per_frame = value
@property
def ptmb_fso(self):
return self._ptmb_fso
@ptmb_fso.setter
def ptmb_fso(self, value):
self._ptmb_fso = value
@property
def ptmb_fsc(self):
return self._ptmb_fsc
@ptmb_fsc.setter
def ptmb_fsc(self, value):
self._ptmb_fsc = value
@property
def output_folder(self):
return self._output_folder
@output_folder.setter
def output_folder(self, value):
self._output_folder = value
@property
def file_name(self):
return self._file_name
@file_name.setter
def file_name(self, value):
self._file_name = value
@property
def file_name_num_pattern(self):
return self._file_name_num_pattern
@file_name_num_pattern.setter
def file_name_num_pattern(self, value):
self._file_name_num_pattern = value
@property
def file_type(self):
return self._file_type
@file_type.setter
def file_type(self, value):
self._file_type = value
@property
def save_alpha(self):
return self._save_alpha
@save_alpha.setter
def save_alpha(self, value):
self._save_alpha = value
@property
def hdr_output(self):
return self._hdr_output
@hdr_output.setter
def hdr_output(self, value):
self._hdr_output = value
@property
def show_pathtracing_single_frame_progress(self):
return self._show_pathtracing_single_frame_progress
@show_pathtracing_single_frame_progress.setter
def show_pathtracing_single_frame_progress(self, value):
self._show_pathtracing_single_frame_progress = value
@property
def preroll_frames(self):
return self._preroll_frames
@preroll_frames.setter
def preroll_frames(self, value):
self._preroll_frames = value
@property
def overwrite_existing_frames(self):
return self._overwrite_existing_frames
@overwrite_existing_frames.setter
def overwrite_existing_frames(self, value):
self._overwrite_existing_frames = value
@property
def movie_type(self):
return self._movie_type
@movie_type.setter
def movie_type(self, value):
self._movie_type = value
@property
def sunstudy_start_time(self):
return self._sunstudy_start_time
@sunstudy_start_time.setter
def sunstudy_start_time(self, value):
self._sunstudy_start_time = value
@property
def sunstudy_current_time(self):
return self._sunstudy_current_time
@sunstudy_current_time.setter
def sunstudy_current_time(self, value):
self._sunstudy_current_time = value
@property
def sunstudy_end_time(self):
return self._sunstudy_end_time
@sunstudy_end_time.setter
def sunstudy_end_time(self, value):
self._sunstudy_end_time = value
@property
def sunstudy_movie_length_in_seconds(self):
return self._sunstudy_movie_length_in_seconds
@sunstudy_movie_length_in_seconds.setter
def sunstudy_movie_length_in_seconds(self, value):
self._sunstudy_movie_length_in_seconds = value
@property
def sunstudy_player(self):
return self._sunstudy_player
@sunstudy_player.setter
def sunstudy_player(self, value):
self._sunstudy_player = value
@property
def real_time_settle_latency_frames(self):
return self._real_time_settle_latency_frames
@real_time_settle_latency_frames.setter
def real_time_settle_latency_frames(self, value):
self._real_time_settle_latency_frames = value
@property
def renumber_negative_frame_number_from_0(self):
return self._renumber_negative_frame_number_from_0
@renumber_negative_frame_number_from_0.setter
def renumber_negative_frame_number_from_0(self, value):
self._renumber_negative_frame_number_from_0 = value
def is_video(self):
return self.file_type == ".mp4"
def is_capturing_nth_frames(self):
return self._capture_every_nth_frames > 0
def is_capturing_pathtracing_single_frame(self):
return self.is_video() is False and self.is_capturing_nth_frames() is False and self.render_preset == CaptureRenderPreset.PATH_TRACE
def is_capturing_frame(self):
return self._range_type == CaptureRangeType.FRAMES
def get_full_path(self):
return os.path.join(self._output_folder, self._file_name + self._file_type)
| 11,163 | Python | 26.429975 | 140 | 0.642659 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/helper.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
def get_num_pattern_file_path(frames_dir, file_name, num_pattern, frame_num, file_type, renumber_frames=False, renumber_offset=0):
if renumber_frames:
renumbered_frames = frame_num + renumber_offset
else:
renumbered_frames = frame_num
abs_frame_num = abs(renumbered_frames)
padding_length = len(num_pattern.strip(".")[len(str(abs_frame_num)) :])
if renumbered_frames >= 0:
padded_string = "0" * padding_length + str(renumbered_frames)
else:
padded_string = "-" + "0" * padding_length + str(abs_frame_num)
filename = ".".join((file_name, padded_string, file_type.strip(".")))
frame_path = os.path.join(frames_dir, filename)
return frame_path
| 1,154 | Python | 43.423075 | 130 | 0.713172 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/__init__.py | from .test_capture_options import TestCaptureOptions
# from .test_capture_hdr import TestCaptureHdr
| 100 | Python | 32.666656 | 52 | 0.84 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/test_capture_hdr.py | from typing import Type
import os.path
import omni.kit.test
import carb
import carb.settings
import carb.tokens
import pathlib
import omni.kit.capture.capture_options as _capture_options
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file, create_viewport_window
OUTPUTS_DIR = omni.kit.test.get_test_output_path()
class TestCaptureHdr(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
settings = carb.settings.get_settings()
settings.set("/app/asyncRendering", False)
settings.set("/app/asyncRenderingLowLatency", False)
settings.set("/app/captureFrame/hdr", True)
# Setup viewport
self._usd_context = ''
await omni.usd.get_context(self._usd_context).new_stage_async()
async def test_hdr_capture(self):
viewport_api = get_active_viewport(self._usd_context)
if viewport_api is None:
return
# Wait until the viewport has valid resources
await viewport_api.wait_for_rendered_frames()
capture_filename = "capture.hdr_test.exr"
filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename)
capture_viewport_to_file(viewport_api, str(filePath))
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
assert os.path.isfile(str(filePath))
# Make sure we do not crash in the unsupported multi-view case
async def do_test_hdr_multiview_capture(self, test_legacy: bool):
viewport_api = get_active_viewport(self._usd_context)
if viewport_api is None:
return
# Wait until the viewport has valid resources
await viewport_api.wait_for_rendered_frames()
second_vp_window = create_viewport_window('Viewport 2', width=256, height=256)
await second_vp_window.viewport_api.wait_for_rendered_frames()
capture_filename = "capture.hdr_test.multiview.exr"
filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename)
# Multiview HDR output is not yet fully supported, confirm this exits gracefully
capture_viewport_to_file(viewport_api, str(filePath))
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
assert os.path.isfile(str(filePath))
second_vp_window.destroy()
del second_vp_window
async def test_hdr_multiview_capture_legacy(self):
await self.do_test_hdr_multiview_capture(True)
async def test_hdr_multiview_capture(self):
await self.do_test_hdr_multiview_capture(False)
| 2,828 | Python | 36.223684 | 107 | 0.688826 |
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/test_capture_options.py | from typing import Type
import omni.kit.test
import omni.kit.capture.capture_options as _capture_options
class TestCaptureOptions(omni.kit.test.AsyncTestCase):
async def test_capture_options_serialisation(self):
options = _capture_options.CaptureOptions()
data_dict = options.to_dict()
self.assertIsInstance(data_dict, dict)
async def test_capture_options_deserialisation(self):
options = _capture_options.CaptureOptions()
data_dict = options.to_dict()
regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict)
self.assertIsInstance(regenerated_options, _capture_options.CaptureOptions)
async def test_capture_options_values_persisted(self):
options = _capture_options.CaptureOptions(camera="my_camera")
data_dict = options.to_dict()
regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict)
self.assertEqual(regenerated_options.camera, "my_camera")
async def test_adding_random_attribute_fails(self):
""" Test that adding new attributes without making them configurable via the __init__ will raise an exception
"""
options = _capture_options.CaptureOptions()
options._my_new_value = "foo"
data_dict = options.to_dict()
with self.assertRaises(TypeError, msg="__init__() got an unexpected keyword argument 'my_new_value'"):
regnerated = _capture_options.CaptureOptions.from_dict(data_dict) | 1,496 | Python | 40.583332 | 117 | 0.703209 |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/omni/kit/window/splash_close_example/extension.py | import carb
import omni.ext
class SplashCloseExtension(omni.ext.IExt):
def on_startup(self):
try:
import omni.splash
splash_iface = omni.splash.acquire_splash_screen_interface()
except (ImportError, ModuleNotFoundError):
splash_iface = None
if not splash_iface:
return
splash_iface.close_all()
def on_shutdown(self):
pass
| 424 | Python | 19.238094 | 72 | 0.603774 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/light_properties.py | import os
import carb
import omni.ext
from pathlib import Path
from pxr import Sdf, UsdLux, Usd
TEST_DATA_PATH = ""
class LightPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
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")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from .prim_light_widget import LightSchemaAttributesWidget
w = p.get_window()
if w:
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
w.register_widget(
"prim",
"light",
LightSchemaAttributesWidget(
"Light",
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
UsdLux.LightAPI if hasattr(UsdLux, 'LightAPI') else UsdLux.Light,
[
UsdLux.CylinderLight,
UsdLux.DiskLight,
UsdLux.DistantLight,
UsdLux.DomeLight,
UsdLux.GeometryLight,
UsdLux.RectLight,
UsdLux.SphereLight,
UsdLux.ShapingAPI,
UsdLux.ShadowAPI,
UsdLux.LightFilter,
# https://github.com/PixarAnimationStudios/USD/commit/9eda37ec9e1692dd290efd9a26526e0d2c21bb03
UsdLux.PortalLight if hasattr(UsdLux, 'PortalLight') else UsdLux.LightPortal,
UsdLux.ListAPI,
],
[
"color",
"enableColorTemperature",
"colorTemperature",
"intensity",
"exposure",
"normalize",
"angle",
"radius",
"height",
"width",
"radius",
"length",
"texture:file",
"texture:format",
"diffuse",
"specular",
"shaping:focus",
"shaping:focusTint",
"shaping:cone:angle",
"shaping:cone:softness",
"shaping:ies:file",
"shaping:ies:angleScale",
"shaping:ies:normalize",
"collection:shadowLink:expansionRule",
"collection:shadowLink:excludes",
"collection:shadowLink:includes",
"collection:lightLink:expansionRule",
"collection:lightLink:excludes",
"collection:lightLink:includes",
"light:enableCaustics",
"visibleInPrimaryRay",
"disableFogInteraction",
"isProjector",
] \
# https://github.com/PixarAnimationStudios/USD/commit/c8cd344af6be342911e50d2350c228ed329be6b2
# USD v22.08 adds this to LightAPI as an API schema override of CollectionAPI
+ (["collection:lightLink:includeRoot"] if Usd.GetVersion() >= (0,22,8) else []),
[],
),
)
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "light")
self._registered = False
| 4,274 | Python | 37.863636 | 118 | 0.477305 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/__init__.py | from .light_properties import *
| 32 | Python | 15.499992 | 31 | 0.78125 |
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/prim_light_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Set
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import create_primspec_bool
from pxr import Kind, Sdf, Usd, UsdLux
import carb
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class LightSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
self._settings = carb.settings.get_settings()
self._setting_path = PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat"
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self.lux_attributes: Set[str] = set(['inputs:angle', 'inputs:color', 'inputs:temperature', 'inputs:diffuse', 'inputs:specular', 'inputs:enableColorTemperature',
'inputs:exposure', 'inputs:height', 'inputs:width', 'inputs:intensity', 'inputs:length',
'inputs:normalize', 'inputs:radius', 'inputs:shadow:color', 'inputs:shadow:distance', 'inputs:shadow:enable', 'inputs:shadow:falloff',
'inputs:shadow:falloffGamma', 'inputs:shaping:cone:angle', 'inputs:shaping:cone:softness', 'inputs:shaping:focus',
'inputs:shaping:focusTint', 'inputs:shaping:ies:angleScale', 'inputs:shaping:ies:file', 'inputs:shaping:ies:normalize', 'inputs:texture:format'])
# custom attributes
def is_prim_light_primary_visible_supported(prim):
return (
prim.IsA(UsdLux.DomeLight)
or prim.IsA(UsdLux.DiskLight)
or prim.IsA(UsdLux.RectLight)
or prim.IsA(UsdLux.SphereLight)
or prim.IsA(UsdLux.CylinderLight)
or prim.IsA(UsdLux.DistantLight)
)
def is_prim_light_disable_fog_interaction_supported(prim):
return (
prim.IsA(UsdLux.DomeLight)
or prim.IsA(UsdLux.DiskLight)
or prim.IsA(UsdLux.RectLight)
or prim.IsA(UsdLux.SphereLight)
or prim.IsA(UsdLux.CylinderLight)
or prim.IsA(UsdLux.DistantLight)
)
def is_prim_light_caustics_supported(prim):
return prim.IsA(UsdLux.DiskLight) or prim.IsA(UsdLux.RectLight) or prim.IsA(UsdLux.SphereLight)
def is_prim_light_is_projector_supported(prim):
return prim.IsA(UsdLux.RectLight)
def add_vipr(attribute_name, value_dict):
anchor_prim = self._get_prim(self._payload[-1])
if anchor_prim and (anchor_prim.IsA(UsdLux.DomeLight) or anchor_prim.IsA(UsdLux.DistantLight)):
return UsdPropertyUiEntry("visibleInPrimaryRay", "", create_primspec_bool(True), Usd.Attribute)
else:
return UsdPropertyUiEntry("visibleInPrimaryRay", "", create_primspec_bool(False), Usd.Attribute)
self.add_custom_schema_attribute("visibleInPrimaryRay", is_prim_light_primary_visible_supported, add_vipr, "", {})
self.add_custom_schema_attribute("disableFogInteraction", is_prim_light_disable_fog_interaction_supported, None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("light:enableCaustics", is_prim_light_caustics_supported, None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("isProjector", is_prim_light_is_projector_supported, None, "", create_primspec_bool(False))
def _on_change(self, item, event_type):
self.request_rebuild()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
if self._schema().IsTyped() and not prim.IsA(self._schema):
return False
if self._schema().IsAPISchema() and not prim.HasAPI(self._schema):
return False
used += [attr for attr in prim.GetAttributes() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
if self.is_custom_schema_attribute_used(prim):
used.append(None)
return used
def has_authored_inputs_attr(self, prim):
attrs = set([a.GetName() for a in prim.GetAuthoredAttributes()])
any_authored = attrs.intersection(self.lux_attributes)
return any_authored
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
self.add_custom_schema_attributes_to_props(attrs)
frame = CustomLayoutFrame(hide_extra=False)
anchor_prim = self._get_prim(self._payload[-1])
# TODO -
# add shadow values (Shadow Enable, Shadow Include, Shadow Exclude, Shadow Color, Shadow Distance, Shadow Falloff, Shadow Falloff Gamma)
# add UsdLux.DomeLight portals (see UsdLux.DomeLight GetPortalsRel)
# add filters (see UsdLux.Light / UsdLux.LightAPI GetFiltersRel)
self.usdLuxUnprefixedCompat = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat")
has_authored_inputs = self.has_authored_inputs_attr(anchor_prim)
with frame:
with CustomLayoutGroup("Main"):
self._create_property("color", "Color", anchor_prim, has_authored_inputs)
self._create_property("enableColorTemperature", "Enable Color Temperature", anchor_prim, has_authored_inputs)
self._create_property("colorTemperature", "Color Temperature", anchor_prim, has_authored_inputs)
self._create_property("intensity", "Intensity", anchor_prim, has_authored_inputs)
self._create_property("exposure", "Exposure", anchor_prim, has_authored_inputs)
self._create_property("normalize", "Normalize Power", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.DistantLight):
self._create_property("angle", "Angle", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.DiskLight):
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.RectLight):
self._create_property("height", "Height", anchor_prim, has_authored_inputs)
self._create_property("width", "Width", anchor_prim, has_authored_inputs)
self._create_property("texture:file", "Texture File", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.SphereLight):
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
CustomLayoutProperty("treatAsPoint", "Treat As Point")
if anchor_prim and anchor_prim.IsA(UsdLux.CylinderLight):
self._create_property("length", "Length", anchor_prim, has_authored_inputs)
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
CustomLayoutProperty("treatAsLine", "Treat As Line")
if anchor_prim and anchor_prim.IsA(UsdLux.DomeLight):
self._create_property("texture:file", "Texture File", anchor_prim, has_authored_inputs)
self._create_property("texture:format", "Texture Format", anchor_prim, has_authored_inputs)
self._create_property("diffuse", "Diffuse Multiplier", anchor_prim, has_authored_inputs)
self._create_property("specular", "Specular Multiplier", anchor_prim, has_authored_inputs)
CustomLayoutProperty("visibleInPrimaryRay", "Visible In Primary Ray")
CustomLayoutProperty("disableFogInteraction", "Disable Fog Interaction")
CustomLayoutProperty("light:enableCaustics", "Enable Caustics")
CustomLayoutProperty("isProjector", "Projector light type")
with CustomLayoutGroup("Shaping", collapsed=True):
self._create_property("shaping:focus", "Focus", anchor_prim, has_authored_inputs)
self._create_property("shaping:focusTint", "Focus Tint", anchor_prim, has_authored_inputs)
self._create_property("shaping:cone:angle", "Cone Angle", anchor_prim, has_authored_inputs)
self._create_property("shaping:cone:softness", "Cone Softness", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:file", "File", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:angleScale", "AngleScale", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:normalize", "Normalize", anchor_prim, has_authored_inputs)
with CustomLayoutGroup("Light Link"):
CustomLayoutProperty("collection:lightLink:includeRoot", "Light Link Include Root")
CustomLayoutProperty("collection:lightLink:expansionRule", "Light Link Expansion Rule")
CustomLayoutProperty("collection:lightLink:includes", "Light Link Includes")
CustomLayoutProperty("collection:lightLink:excludes", "Light Link Excludes")
with CustomLayoutGroup("Shadow Link"):
CustomLayoutProperty("collection:shadowLink:includeRoot", "Shadow Link Include Root")
CustomLayoutProperty("collection:shadowLink:expansionRule", "Shadow Link Expansion Rule")
CustomLayoutProperty("collection:shadowLink:includes", "Shadow Link Includes")
CustomLayoutProperty("collection:shadowLink:excludes", "Shadow Link Excludes")
return frame.apply(attrs)
def _create_property(self, name: str, display_name: str, prim, has_authored_inputs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutProperty
)
if has_authored_inputs or not self.usdLuxUnprefixedCompat or not prim.HasAttribute(name):
prefixed_name = "inputs:" + name
return CustomLayoutProperty(prefixed_name, display_name)
return CustomLayoutProperty(name, display_name)
| 11,860 | Python | 54.167442 | 168 | 0.649494 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/__init__.py | """
This module contains bindings to the C++ omni::audio::IAudioDeviceEnum
interface. This provides functionality for enumerating available audio devices
and collecting some basic information on each one.
Sound devices attached to the system may change at any point due to user
activity (ie: connecting or unplugging a USB audio device). When enumerating
devices, it is important to collect all device information directly instead
of caching it.
The device information is suitable to be used to display to a user in a menu
to allow them to choose a device to use by name.
"""
from ._audiodeviceenum import *
# Cached audio device enumerator instance pointer
def get_audio_device_enum_interface() -> IAudioDeviceEnum:
"""
helper method to retrieve a cached version of the IAudioDeviceEnum interface.
Returns:
The cached :class:`omni.kit.audiodeviceenum.IAudioDeviceEnum` interface. This will
only be retrieved on the first call. All subsequent calls will return the cached
interface object.
"""
if not hasattr(get_audio_device_enum_interface, "audio_device_enum"):
get_audio_device_enum_interface.audio_device_enum = acquire_audio_device_enum_interface()
return get_audio_device_enum_interface.audio_device_enum
| 1,351 | Python | 39.969696 | 97 | 0.720207 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/tests/test_device.py | import omni.kit.test
import omni.kit.audiodeviceenum
def get_name_from_sample_type(sample_type): # pragma: no cover
if sample_type == omni.kit.audiodeviceenum.SampleType.UNKNOWN:
return "UNKNOWN"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_SIGNED_INTEGER:
return "INT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_UNSIGNED_INTEGER:
return "UINT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_FLOAT:
return "FLOAT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.COMPRESSED:
return "COMPRESSED"
class TestAudio(omni.kit.test.AsyncTestCase): # pragma: no cover
async def test_audio_device(self):
audio = omni.kit.audiodeviceenum.get_audio_device_enum_interface()
self.assertIsNotNone(audio)
count = audio.get_device_count(omni.kit.audiodeviceenum.Direction.PLAYBACK)
self.assertGreaterEqual(count, 0)
printDevices = 0
if printDevices != 0:
print("Found ", count, " Available Playback Devices:")
if count > 0:
for i in range(0, count):
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(uniqueId)
if not audio.is_direct_hardware_backend():
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
if printDevices != 0:
str_desc = " found the device '" + name + "' "
str_desc += "{" + str(channel_count) + " channels "
str_desc += "@ " + str(frame_rate) + "Hz "
str_desc += str(sample_size) + "-bit " + get_name_from_sample_type(sample_type)
print(str_desc)
print(" " + desc)
else:
if printDevices != 0:
print(" found the device '" + name + "' ")
print(" " + desc)
# make sure out of range values fail.
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(uniqueId)
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(sample_type, omni.kit.audiodeviceenum.SampleType.UNKNOWN)
count = audio.get_device_count(omni.kit.audiodeviceenum.Direction.CAPTURE)
self.assertGreaterEqual(count, 0)
if printDevices != 0:
print("\nFound ", count, " Available Capture Devices:")
if count > 0:
for i in range(0, count):
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(uniqueId)
if not audio.is_direct_hardware_backend():
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
if printDevices != 0:
str_desc = " found the device '" + name + "' "
str_desc += "{" + str(channel_count) + " channels "
str_desc += "@ " + str(frame_rate) + "Hz "
str_desc += str(sample_size) + "-bit " + get_name_from_sample_type(sample_type)
print(str_desc)
print(" " + desc)
else:
if printDevices != 0:
print(" found the device '" + name + "' ")
print(" " + desc)
# make sure out of range values fail.
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(uniqueId)
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(sample_type, omni.kit.audiodeviceenum.SampleType.UNKNOWN)
| 6,979 | Python | 47.137931 | 114 | 0.60854 |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/tests/__init__.py | from .test_device import * # pragma: no cover
| 48 | Python | 15.333328 | 46 | 0.6875 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/cursor.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
from carb import windowing, log_warn
import omni.ext
import weakref
EXTEND_CURSOR_GRAB_OPEN = "Grab_open"
EXTEND_CURSOR_GRAB_CLOSE = "Grab_close"
EXTEND_CURSOR_PAN_FILE = "cursorPan.png"
EXTEND_CURSOR_PAN_CLOSE_FILE = "cursorPanClosed.png"
main_window_cursor = None
def get_main_window_cursor():
return main_window_cursor
def get_icon_path(path: str):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
icon_path = Path(extension_path).joinpath("data").joinpath("icons").joinpath(path)
return str(icon_path)
class WindowCursor(omni.ext.IExt):
def __init__(self):
self._imgui_renderer = None
self._app_window = None
super().__init__()
def on_startup(self, ext_id):
global main_window_cursor
main_window_cursor = weakref.proxy(self)
try:
import omni.kit.imgui_renderer
import omni.appwindow
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
self._app_window = omni.appwindow.get_default_app_window()
except Exception:
# Currently need both of these for further API usage, which can't happen now; so clear them both out
self._imgui_renderer, self._app_window = None, None
log_warn("omni.kit.window.cursor failed to initialize properly, changing cursor with it will not work")
import traceback
log_warn(f"{traceback.format_exc()}")
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._on_app_ready,
)
def on_shutdown(self):
if self._imgui_renderer:
self._imgui_renderer.unregister_cursor_shape_extend(EXTEND_CURSOR_GRAB_OPEN)
self._imgui_renderer.unregister_cursor_shape_extend(EXTEND_CURSOR_GRAB_CLOSE)
global main_window_cursor
main_window_cursor = None
self._imgui_renderer = None
self._app_window = None
self._app_ready_sub = None
def _on_app_ready(self, event):
if self._imgui_renderer:
self._imgui_renderer.register_cursor_shape_extend(EXTEND_CURSOR_GRAB_OPEN, get_icon_path(EXTEND_CURSOR_PAN_FILE))
self._imgui_renderer.register_cursor_shape_extend(EXTEND_CURSOR_GRAB_CLOSE, get_icon_path(EXTEND_CURSOR_PAN_CLOSE_FILE))
def override_cursor_shape_extend(self, shape_name: str):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.set_cursor_shape_override_extend(self._app_window, shape_name)
return True
return False
def override_cursor_shape(self, shape: windowing.CursorStandardShape):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.set_cursor_shape_override(self._app_window, shape)
return True
return False
def clear_overridden_cursor_shape(self):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.clear_cursor_shape_override(self._app_window)
return True
return False
def get_cursor_shape_override_extend(self):
if self._app_window and self._imgui_renderer:
return self._imgui_renderer.get_cursor_shape_override_extend(self._app_window)
return None
def get_cursor_shape_override(self):
if self._app_window and self._imgui_renderer:
return self._imgui_renderer.get_cursor_shape_override(self._app_window)
return None
| 4,062 | Python | 37.695238 | 132 | 0.674545 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/__init__.py | from .cursor import *
| 22 | Python | 10.499995 | 21 | 0.727273 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/tests/tests.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.imgui
import carb.input
import carb.windowing
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.kit.window.cursor
import omni.kit.imgui_renderer
import omni.ui as ui
class TestCursorShape(omni.kit.test.AsyncTestCase):
async def setUp(self):
app_window = omni.appwindow.get_default_app_window()
self._mouse = app_window.get_mouse()
self._app = omni.kit.app.get_app()
self._cursor = omni.kit.window.cursor.get_main_window_cursor()
self._input_provider = carb.input.acquire_input_provider()
self._imgui = carb.imgui.acquire_imgui()
self._windowing = carb.windowing.acquire_windowing_interface()
self._os_window = app_window.get_window()
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
await self._build_test_windows()
async def tearDown(self):
self._os_window = None
self._windowing = None
self._imgui = None
self._window = None
self._dock_window_1 = None
self._dock_window_2 = None
self._imgui_renderer = None
async def test_cursor_shape(self):
main_dockspace = ui.Workspace.get_window("DockSpace")
width = main_dockspace.width
height = main_dockspace.height
await self._wait()
await self._move_and_test_cursor_shape((width / 2, 1), carb.imgui.MouseCursor.ARROW)
# Put on StringField and test IBeam shape
await self._move_and_test_cursor_shape((width / 2, height / 4), carb.imgui.MouseCursor.TEXT_INPUT)
# Put on vertical split and test HORIZONTAL_RESIZE
await self._move_and_test_cursor_shape(
(width / 2 + 1, height * 3 / 4),
carb.imgui.MouseCursor.RESIZE_EW,
)
# Put on horizontal split and test VERTICAL_RESIZE
await self._move_and_test_cursor_shape(
(width * 3 / 4, height / 2 + 1),
carb.imgui.MouseCursor.RESIZE_NS,
)
await self._wait()
# test override_cursor_shape_extend and get_cursor_shape_override_extend
test_extend_shapes = [
"IBeam",
"Grab_close",
"Crosshair",
"Grab_open",
]
for cursor_shape in test_extend_shapes:
self._cursor.override_cursor_shape_extend(cursor_shape)
await self._wait(100)
cur_cursor = self._cursor.get_cursor_shape_override_extend()
self.assertEqual(cur_cursor, cursor_shape)
# test override_cursor_shape and get_cursor_shape_override
test_shapes = [
carb.windowing.CursorStandardShape.CROSSHAIR,
carb.windowing.CursorStandardShape.IBEAM,
]
for cursor_shape in test_shapes:
self._cursor.override_cursor_shape(cursor_shape)
await self._wait(100)
cur_cursor = self._cursor.get_cursor_shape_override()
self.assertEqual(cur_cursor, cursor_shape)
all_shapes = self._imgui_renderer.get_all_cursor_shape_names()
print(all_shapes)
self._cursor.clear_overridden_cursor_shape()
await self._wait()
async def _move_and_test_cursor_shape(self, pos, cursor: carb.imgui.MouseCursor):
# Available options:
# carb.imgui.MouseCursor.ARROW: carb.windowing.CursorStandardShape.ARROW,
# carb.imgui.MouseCursor.TEXT_INPUT: carb.windowing.CursorStandardShape.IBEAM,
# carb.imgui.MouseCursor.RESIZE_NS: carb.windowing.CursorStandardShape.VERTICAL_RESIZE,
# carb.imgui.MouseCursor.RESIZE_EW: carb.windowing.CursorStandardShape.HORIZONTAL_RESIZE,
# carb.imgui.MouseCursor.HAND: carb.windowing.CursorStandardShape.HAND,
# carb.imgui.MouseCursor.CROSSHAIR: carb.windowing.CursorStandardShape.CROSSHAIR,
self._input_provider.buffer_mouse_event(self._mouse, carb.input.MouseEventType.MOVE, pos, 0, pos)
self._windowing.set_cursor_position(self._os_window, carb.Int2(*[int(p) for p in pos]))
await self._wait()
imgui_cursor = self._imgui.get_mouse_cursor()
self.assertEqual(cursor, imgui_cursor, f"Expect {cursor} but got {imgui_cursor}")
# build a dockspace with windows/widgets to test various cursor shape from imgui
async def _build_test_windows(self):
import omni.ui as ui
self._window = ui.Window("CursorShapeTest")
with self._window.frame:
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=10):
ui.StringField()
self._dock_window_1 = ui.Window("DockWindow1")
self._dock_window_2 = ui.Window("DockWindow2")
await self._app.next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window_handle = ui.Workspace.get_window("CursorShapeTest")
dock_window_handle1 = ui.Workspace.get_window("DockWindow1")
dock_window_handle2 = ui.Workspace.get_window("DockWindow2")
window_handle.dock_in(main_dockspace, ui.DockPosition.SAME)
dock_window_handle1.dock_in(window_handle, ui.DockPosition.BOTTOM, 0.5)
dock_window_handle2.dock_in(dock_window_handle1, ui.DockPosition.RIGHT, 0.5)
async def _wait(self, num=8):
for i in range(num):
await self._app.next_update_async() | 5,770 | Python | 38.8 | 106 | 0.656672 |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/tests/__init__.py | from .tests import *
| 21 | Python | 9.999995 | 20 | 0.714286 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.usd
import omni.ext
import omni.kit.app
from .live_state_menu import LiveStateMenu
from .icons import Icons
from .style import Styles
class OmniLiveWidgetExtension(omni.ext.IExt):
def on_startup(self, ext_id):
extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
Icons.on_startup(extension_path)
Styles.on_startup()
usd_context = omni.usd.get_context()
self._live_state_menu = LiveStateMenu(usd_context)
self._live_state_menu.register_menu_widgets()
def on_shutdown(self):
self._live_state_menu.unregister_menu_widgets()
Icons.on_shutdown()
| 1,112 | Python | 33.781249 | 108 | 0.739209 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/live_state_menu.py | import carb
import omni.usd
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.widget.live_session_management as lsm
from functools import partial
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni.ui import color as cl
from typing import Union
from .style import Styles
class LiveStateDelegate(ui.MenuDelegate):
def __init__(self, layers_interface, **kwargs):
super().__init__(**kwargs)
self._layers = layers_interface
self._live_syncing = layers_interface.get_live_syncing()
self._usd_context = self._live_syncing.usd_context
self._live_background = None
self._drop_down_background = None
self._live_button = None
self._drop_down_button = None
self._live_session_user_list_widget = None
self._layers_event_subs = []
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
]:
layers_event_sub = self._layers.get_event_stream().create_subscription_to_pop_by_type(
event, self._on_layer_event, name=f"omni.kit.widget.live {str(event)}"
)
self._layers_event_subs.append(layers_event_sub)
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.kit.widget.live stage event"
)
def destroy(self):
if self._live_button:
self._live_button.set_clicked_fn(None)
self._live_button = None
if self._drop_down_button:
self._drop_down_button.set_clicked_fn(None)
self._drop_down_button = None
if self._live_session_user_list_widget:
self._live_session_user_list_widget.destroy()
self._live_session_user_list_widget = None
self._live_syncing = None
self._layers_event_subs = []
self._stage_event_sub = None
def _on_layer_event(self, event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if not payload:
return
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self.__update_live_state()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self.__update_live_tooltip()
def _on_stage_event(self, event: carb.events.IEvent):
if event.type == int(omni.usd.StageEventType.OPENED):
if self._live_session_user_list_widget:
self._live_session_user_list_widget.track_layer(self._usd_context.get_stage_url())
def _on_live_widget_button_clicked(self, button, show_options):
menu_widget = lsm.stop_or_show_live_session_widget(
self._live_syncing.usd_context,
not show_options,
False,
show_options
)
if not menu_widget:
return
# Try to align it with the button.
drop_down_x = button.screen_position_x
drop_down_y = button.screen_position_y
drop_down_height = button.computed_height
# FIXME: The width of context menu cannot be got. Using fixed width here.
menu_widget.show_at(
drop_down_x - 94,
drop_down_y + drop_down_height + 2
)
def build_item(self, item: ui.MenuHelper):
margin = 2
with ui.HStack(width=0, style={"margin" : 0}):
with ui.HStack(content_clipping=1, width=0, style=Styles.LIVE_STATE_ITEM_STYLE):
with ui.VStack():
ui.Spacer(height=margin)
self.__build_user_list()
ui.Spacer(height=margin)
ui.Spacer(width=2 * margin)
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
self._live_background = ui.Rectangle(width=50, name="offline")
with ui.HStack(width=50):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="lightning")
ui.Spacer()
ui.Spacer(width=margin)
ui.Label("LIVE", width=0)
ui.Spacer()
self._live_button = ui.InvisibleButton(width=50, identifier="live_button")
self._live_button.set_clicked_fn(
partial(self._on_live_widget_button_clicked, self._live_button, False)
)
ui.Spacer(height=margin)
ui.Spacer(width=margin)
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
self._drop_down_background = ui.Rectangle(width=16, name="offline")
with ui.HStack(width=16):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="arrow_down")
ui.Spacer()
ui.Spacer()
self._drop_down_button = ui.InvisibleButton(width=16, identifier="drop_down_button")
self._drop_down_button.set_clicked_fn(
partial(self._on_live_widget_button_clicked, self._drop_down_button, True)
)
ui.Spacer(height=margin)
ui.Spacer(width=8)
self.__update_live_state()
def get_menu_alignment(self):
return MenuAlignment.RIGHT
def update_menu_item(self, menu_item: Union[ui.Menu, ui.MenuItem], menu_refresh: bool):
if isinstance(menu_item, ui.MenuItem):
menu_item.visible = False
def __update_live_tooltip(self):
current_session = self._live_syncing.get_current_live_session()
if current_session:
peer_users_count = len(current_session.peer_users)
if peer_users_count > 0:
self._live_background.set_tooltip(
f"Leave Session {current_session.name}\n{peer_users_count + 1} Total Users in Session"
)
else:
self._live_background.set_tooltip(
f"Leave Session {current_session.name}"
)
def __update_live_state(self):
if self._live_background:
current_session = self._live_syncing.get_current_live_session()
if current_session:
self._live_background.name = "live"
self.__update_live_tooltip()
self._drop_down_background.name = "live"
else:
self._live_background.name = "offline"
self._live_background.set_tooltip("Start Session")
self._drop_down_background.name = "offline"
def __build_user_list(self):
def is_follow_enabled():
settings = carb.settings.get_settings()
enabled = settings.get(f"/app/liveSession/enableMenuFollowUser")
if enabled == True or enabled == False:
return enabled
return True
stage_url = self._usd_context.get_stage_url()
self._live_session_user_list_widget = lsm.LiveSessionUserList(
self._usd_context, stage_url,
follow_user_with_double_click=is_follow_enabled(),
allow_timeline_settings=True,
maximum_users=10
)
class LiveStateMenu:
def __init__(self, usd_context):
self._live_menu_name = "Live State Widget"
self._menu_list = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
self._usd_context = usd_context
self._layers = layers.get_layers(self._usd_context)
self._layer_state_delegate = None
def register_menu_widgets(self):
self._layer_state_delegate = LiveStateDelegate(self._layers)
omni.kit.menu.utils.add_menu_items(self._menu_list, name=self._live_menu_name, delegate=self._layer_state_delegate)
def unregister_menu_widgets(self):
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._live_menu_name)
self._menu_list = None
if self._layer_state_delegate:
self._layer_state_delegate.destroy()
self._layer_state_delegate = None
self._layers = None
self._usd_context = None
| 9,094 | Python | 39.066079 | 123 | 0.55905 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/__init__.py | from .extension import OmniLiveWidgetExtension | 46 | Python | 45.999954 | 46 | 0.913043 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/base.py | import carb
def enable_server_tests():
settings = carb.settings.get_settings()
return settings.get_as_bool("/exts/omni.kit.widget.live/enable_server_tests")
| 168 | Python | 20.124997 | 81 | 0.72619 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/test_live_widget.py | import omni.kit.test
from pathlib import Path
import omni.usd
import omni.client
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.clipboard
from omni.ui.tests.test_base import OmniUiTest
from pxr import Usd, Sdf
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data")
class TestLiveWidget(OmniUiTest):
# Before running each test
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
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 = self.layers.get_live_syncing()
await omni.usd.get_context().new_stage_async()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self.simulated_user_names = []
self.simulated_user_ids = []
self.test_session_name = "test"
self.stage_url = "omniverse://__faked_omniverse_server__/test/live_session.usd"
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def __create_simulated_users(self, count=2):
for i in range(count):
user_name = f"test{i}"
user_id = user_name
self.simulated_user_names.append(user_name)
self.simulated_user_ids.append(user_id)
join_new_simulated_user(user_name, user_id)
await self.wait(2)
async def test_menu_setup(self):
import omni.kit.ui_test as ui_test
await self.usd_context.new_stage_async()
menu_widget = ui_test.get_menubar()
menu = menu_widget.find_menu("Live State Widget")
self.assertTrue(menu)
async def __create_fake_stage(self, join_test_session=True):
format = Sdf.FileFormat.FindByExtension(".usd")
# Sdf.Layer.New will not save layer so it won't fail.
# This can be used to test layer identifier with omniverse sheme without
# touching real server.
layer = Sdf.Layer.New(format, self.stage_url)
stage = Usd.Stage.Open(layer.identifier)
session = self.live_syncing.create_live_session(self.test_session_name, layer_identifier=layer.identifier)
self.assertTrue(session)
if join_test_session:
await self.usd_context.attach_stage_async(stage)
self.live_syncing.join_live_session(session)
return stage, layer
@MockLiveSyncingApi
async def test_open_stage_with_live_session(self):
import omni.kit.ui_test as ui_test
await self.usd_context.new_stage_async()
_, layer = await self.__create_fake_stage(False)
menu_widget = ui_test.get_menubar()
menu = menu_widget.find_menu("Live State Widget")
self.assertTrue(menu)
await menu.bring_to_front()
await menu.click(menu.center + ui_test.Vec2(50, 0), False, 10)
# hard code the position of click point, as the menu positon changes after running test_join_live_session_users
# don't know why the menu positon changes after running test_join_live_session_users
# await menu.click(ui_test.Vec2(1426, 5), False, 10)
await ui_test.human_delay(100)
await ui_test.select_context_menu("Join With Session Link")
stage_url_with_session = f"{layer.identifier}?live_session_name=test"
omni.kit.clipboard.copy(stage_url_with_session)
window = ui_test.find("JOIN LIVE SESSION WITH LINK")
self.assertTrue(window is not None)
input_field = window.find("**/StringField[*].name=='new_session_link_field'")
self.assertTrue(input_field)
confirm_button = window.find("**/Button[*].name=='confirm_button'")
self.assertTrue(confirm_button)
cancel_button = window.find("**/Button[*].name=='cancel_button'")
self.assertTrue(cancel_button)
# Invalid session name will fail to join
await ui_test.human_delay(100)
input_field.model.set_value("111111")
await confirm_button.click()
await ui_test.human_delay(100)
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertTrue(window.window.visible)
input_field.model.set_value("")
await confirm_button.click()
await ui_test.human_delay(100)
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertTrue(window.window.visible)
await cancel_button.click()
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertFalse(window.window.visible)
window.window.visible = True
await self.wait()
# Valid session link
paste_button = window.find("**/ToolButton[*].name=='paste_button'")
self.assertTrue(paste_button)
await paste_button.click()
self.assertEqual(input_field.model.get_value_as_string(), stage_url_with_session)
await confirm_button.click()
self.assertFalse(window.window.visible)
await ui_test.human_delay(300)
self.assertTrue(self.live_syncing.is_stage_in_live_session())
await menu.click(menu.center + ui_test.Vec2(70, 0), False, 10)
await ui_test.human_delay(100)
# Copy session link
omni.kit.clipboard.copy("unkonwn")
await ui_test.select_context_menu("Share Session Link")
window = ui_test.find("SHARE LIVE SESSION LINK")
self.assertTrue(window is not None)
confirm_button = window.find("**/InvisibleButton[*].name=='confirm_button'")
self.assertTrue(confirm_button)
await confirm_button.click()
stage_url_with_session = f"{layer.identifier}?live_session_name=test"
live_session_link = omni.kit.clipboard.paste()
self.assertTrue(live_session_link, stage_url_with_session)
self.assertFalse(window.window.visible)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_join_live_session_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users()
await self.wait()
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
hide_menu_bar = False,
threshold=1e-4
)
self.live_syncing.stop_all_live_sessions()
await self.wait()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_leave_live_session_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users()
await self.wait()
quit_simulated_user(self.simulated_user_ids[0])
await self.wait()
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
hide_menu_bar=False,
threshold=1e-4
)
self.live_syncing.stop_all_live_sessions()
await self.wait()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_join_live_session_over_max_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users(26)
await self.wait()
await self.finalize_test(golden_img_dir=self._golden_img_dir, hide_menu_bar=False)
self.live_syncing.stop_all_live_sessions()
await self.wait()
| 7,798 | Python | 36.676328 | 119 | 0.645037 |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/__init__.py | from .test_live_widget import TestLiveWidget | 44 | Python | 43.999956 | 44 | 0.863636 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ext
import omni.kit.app
import carb
class ViewportReadyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.__vp_ready = None
self.__vp_extension_hooks = None
# Create a default ready-delegate when exts/omni.kit.viewport.ready/startup/enabled is set
if carb.settings.get_settings().get("exts/omni.kit.viewport.ready/startup/enabled"):
manager = omni.kit.app.get_app().get_extension_manager()
self.__vp_extension_hooks = (
manager.subscribe_to_extension_enable(
self._create_viewport_ready,
self._remove_viewport_ready,
ext_name="omni.kit.window.viewport",
hook_name="omni.kit.viewport.ready.LoadListener-1",
),
manager.subscribe_to_extension_enable(
self._create_viewport_ready,
self._remove_viewport_ready,
ext_name="omni.kit.viewport.window",
hook_name="omni.kit.viewport.ready.LoadListener-2",
)
)
def on_shutdown(self):
self._remove_viewport_ready()
def _create_viewport_ready(self, *args):
async def viewport_ready_ui():
# Honor setting to force this message to only ever show once in a session if requested.
# This needs to happen in the async loop as subscribe_to_extension_enable can call _create_viewport_ready
# before it has returned and assigend hooks to self.__vp_extension_hooks
settings = carb.settings.get_settings()
show_once = bool(settings.get("exts/omni.kit.viewport.ready/startup/show_once"))
if show_once:
self.__vp_extension_hooks = None
import omni.ui
from .viewport_ready import ViewportReady, ViewportReadyDelegate
max_wait = 100
viewport_name = settings.get("exts/omni.kit.viewport.ready/startup/viewport") or "Viewport"
viewport_window = omni.ui.Workspace.get_window(viewport_name)
while viewport_window is None and max_wait:
await omni.kit.app.get_app().next_update_async()
viewport_window = omni.ui.Workspace.get_window(viewport_name)
max_wait = max_wait - 1
# Create a simple delegate that responds to on_complete and clears the objects created
class DefaultDelegate(ViewportReadyDelegate):
def on_complete(delegate_self):
# self is ViewportReadyExtension instance
self.__vp_ready = None
super().on_complete()
self.__vp_ready = ViewportReady(DefaultDelegate())
import asyncio
asyncio.ensure_future(viewport_ready_ui())
def _remove_viewport_ready(self, *args):
self.__vp_ready = None
self.__vp_extension_hooks = None
| 3,381 | Python | 44.093333 | 117 | 0.623188 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/__init__.py | from .extension import ViewportReadyExtension
| 46 | Python | 22.499989 | 45 | 0.891304 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/viewport_ready.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__ = ['ViewportReadyProgressDelegate', 'ViewportReadyDelegate', 'ViewportReady']
import omni.ui
import omni.usd
import carb
class ViewportReadyProgressDelegate:
def __init__(self, settings: carb.settings.ISettings):
self.__progress = None
self.__label = None
self.__shader_count = None
self.__enabled_mask_id = None
self.setup_updates(settings)
def __del__(self):
self.destroy()
def setup_updates(self, settings: carb.settings.ISettings):
"""Setup the ViewportReadyProgressDelegate to get progress updates"""
try:
import re
import omni.activity.core
import omni.activity.profiler
self.__re_matcher = re.compile("^.*\.hlsl \(UID: [0-9]+\)")
persisted_shader_count = settings.get("/persistent/exts/omni.kit.viewport.ready/shader_count")
# Guard against divide by 0 error in activity_event which shouldn't happen but did once somehow.
self.__shader_count = (0, persisted_shader_count if persisted_shader_count else 1)
profiler = omni.activity.profiler.get_activity_profiler()
if profiler:
self.__enabled_mask_id = profiler.enable_capture_mask(omni.activity.profiler.CAPTURE_MASK_STARTUP)
activity = omni.activity.core.get_instance()
self.__activity = (activity, activity.create_callback_to_pop(self.activity_event))
except (ImportError, RuntimeError):
required_exts = "omni.activity.profiler and omni.activity.pump"
carb.log_error(f"{required_exts} must be enabled with /exts/omni.kit.viewport.ready/activity_progress=true")
def destroy(self):
self.__activity = None
progress, self.__progress = self.__progress, None
if progress:
progress.destroy()
label, self.__label = self.__label, None
if label:
label.destroy()
# Save the total number of shaders processed as the progress max hint for the next launch
if self.__shader_count:
carb.settings.get_settings().set("/persistent/exts/omni.kit.viewport.ready/shader_count", self.__shader_count[0])
# Restore the profile mask to whatever it was before
enabled_mask_id, self.__enabled_mask_id = self.__enabled_mask_id, None
if enabled_mask_id is not None:
profiler = omni.activity.profiler.get_activity_profiler()
profiler.disable_capture_mask(enabled_mask_id)
def activity_event(self, node, root_node: bool = True):
"""Event handler for omni.activity messages"""
# This is a rather delicate method relying on strings being constant to filter properly
node_name = node.name or ""
if not root_node:
if self.__re_matcher.search(node_name) is not None:
self.__shader_count = self.__shader_count[0] + 1, self.__shader_count[1]
self.set_progress(self.__shader_count[0] / self.__shader_count[1], f"Compiling: {node_name}")
elif node_name == "Ray Tracing Pipeline":
for node_id in range(node.child_count):
self.activity_event(node.get_child(node_id), False)
def set_progress(self, amount: float, message: str):
if self.__progress:
self.__progress.model.set_value(amount)
if self.__label:
self.__label.text = message
def build_ui(self, settings: carb.settings.ISettings, font_size: float, color: omni.ui.color):
"""Build the progress ui with font and color style hints"""
margin = settings.get("/exts/omni.kit.viewport.ready/activity_progress/margin")
margin = omni.ui.Percent(20 if margin is None else margin)
omni.ui.Spacer(width=margin)
with omni.ui.VStack():
omni.ui.Spacer(height=5)
self.__progress = omni.ui.ProgressBar(height=5,
alignment=omni.ui.Alignment.CENTER_BOTTOM,
style={"border_width": 2, "border_radius": 5,
"color": color})
omni.ui.Spacer(height=5)
self.__label = omni.ui.Label("", alignment=omni.ui.Alignment.CENTER_TOP, style={"font_size": font_size})
omni.ui.Spacer(width=margin)
class ViewportReadyDelegate:
def __init__(self, viewport_name: str = 'Viewport', usd_context_name: str = '', viewport_handle: int = None):
self.__viewport_name = viewport_name
self.__usd_context_name = usd_context_name
self.__viewport_handle = viewport_handle
self.__frame = None
# The signal RTX sends that first frame is ready could actually come before omni.ui has called the ui build fn
self.__destroyed = False
# Fill in some default based on carb.settings
settings = carb.settings.get_settings()
self.__message = settings.get("/exts/omni.kit.viewport.ready/message") or "RTX Loading"
self.__font_size = settings.get("/exts/omni.kit.viewport.ready/font_size") or 72
if settings.get("/exts/omni.kit.viewport.ready/activity_progress/enabled"):
self.__progress = ViewportReadyProgressDelegate(settings)
else:
self.__progress = None
@property
def message(self) -> str:
'''Return the string for the default omni.ui.Label.'''
if self.__message == "RTX Loading":
active = {
"rtx": "RTX",
"iray": "Iray",
"pxr": "Storm",
"index": "Index"
}.get(carb.settings.get_settings().get("/renderer/active"), None)
if active:
return f"{active} Loading"
return self.__message
@property
def font_size(self) -> float:
'''Return the font-size for the default omni.ui.Label.'''
return self.__font_size
@property
def usd_context_name(self) -> str:
'''Return the omni.usd.UsdContext name this delegate is waiting for completion on.'''
return self.__usd_context_name
@property
def viewport_name(self) -> str:
'''Return the name of the omni.ui.Window this delegate is waiting for completion on.'''
return self.__viewport_name
@property
def viewport_handle(self) -> int:
'''Return the ViewportHandle this delegate is waiting for completion on or None for any Viewport.'''
return self.__viewport_handle
def on_complete(self):
'''Callback function invoked when first rendered frame is delivered'''
# Make sure to always call destroy if any exception is thrown during log_complete
try:
self.log_complete()
finally:
self.destroy()
def log_complete(self, msg: str = None, prefix_time_since_start: bool = True):
'''Callback function that will log to info (and stdout if /app/enableStdoutOutput is enabled)'''
if msg is None:
msg = 'RTX ready'
if prefix_time_since_start:
import omni.kit.app
seconds = omni.kit.app.get_app().get_time_since_start_s()
msg = "[{0:.3f}s] ".format(seconds) + msg
if carb.settings.get_settings().get('/app/enableStdoutOutput'):
# Going to sys.stdout directly is cleaner when launched with -info
import sys
sys.stdout.write(msg + '\n')
else:
carb.log_info(msg)
def build_label(self) -> omni.ui.Widget:
'''Simple method to override the basic label showing progress.'''
return omni.ui.Label(self.message, alignment=omni.ui.Alignment.CENTER, style={"font_size": self.font_size})
def build_progress(self) -> None:
settings = carb.settings.get_settings()
color = settings.get("/exts/omni.kit.viewport.ready/activity_progress/color")
color = omni.ui.color("#76b900" if color is None else color)
font_size = settings.get("/exts/omni.kit.viewport.ready/activity_progress/font_size")
if font_size is None:
font_size = self.__font_size / 6
omni.ui.Spacer(height=5)
with omni.ui.HStack():
self.__progress.build_ui(settings, font_size, color)
def build_frame(self) -> None:
'''Method to override the basic frame showing progress.'''
# If RTX is ready before omni.ui is calling the build function, then do nothing
if self.__destroyed:
return
self.__frame = omni.ui.ZStack()
with self.__frame:
bg_color = carb.settings.get_settings().get('/exts/omni.kit.viewport.ready/background_color')
if bg_color:
omni.ui.Rectangle(style={"background_color": bg_color})
with omni.ui.VStack():
kwargs = {}
if self.__progress:
kwargs = {"height": omni.ui.Percent(35)}
omni.ui.Spacer(**kwargs)
self.build_label()
if self.__progress:
self.build_progress()
omni.ui.Spacer()
def build_ui(self) -> None:
'''Method to build the progress/info state in the Viewport window.'''
# If RTX is ready before build_ui is called then do nothing
if self.__destroyed:
return
if self.__frame is None:
viewport_window = omni.ui.Workspace.get_window(self.viewport_name)
if viewport_window:
frame = None
if hasattr(viewport_window, 'get_frame'):
frame = viewport_window.get_frame('omni.kit.viewport.ready.ViewportReadyDelegate')
else:
# TODO: Use omni.kit.viewport.utility get_viewport_window to manage omni.ui Wrapper on legacy viewport
if hasattr(viewport_window, 'frame'):
frame = viewport_window.frame
if frame:
frame.set_build_fn(self.build_frame)
def __del__(self):
self.destroy()
def destroy(self):
self.__destroyed = True
progress, self.__progress = self.__progress, None
if progress:
progress.destroy()
if self.__frame:
self.__frame.visible = False
if hasattr(self.__frame, 'clear'):
self.__frame.clear()
self.__frame.destroy()
self.__frame = None
class ViewportReady:
def __init__(self, viewport_ready: ViewportReadyDelegate = None):
self.__viewport_ready = viewport_ready if viewport_ready else ViewportReadyDelegate()
usd_context_name = self.__viewport_ready.usd_context_name
usd_context = omni.usd.get_context(usd_context_name)
if usd_context:
# Build the UI objects now
self.__viewport_ready.build_ui()
# Subscribe to the eent to wait for frame delivery
self.__new_frame_sub = usd_context.get_rendering_event_stream().create_subscription_to_push_by_type(
int(omni.usd.StageRenderingEventType.NEW_FRAME),
self.__on_event,
name=f"omni.kit.viewport.ready.ViewportReady"
)
else:
raise RuntimeError(f'No omni.usd.UsdContext found with name "{usd_context_name}"')
def __del__(self):
self.destroy()
def destroy(self):
self.__new_frame_sub = None
self.__viewport_ready = None
def __on_event(self, e: carb.events.IEvent):
waiting_for = self.__viewport_ready.viewport_handle
if (waiting_for is None) or (waiting_for == e.payload["viewport_handle"]):
if self.__viewport_complete():
# Avoid wrapping callback in try/catch by storing it first, destroying, then calling it
viewport_ready, self.__viewport_ready = self.__viewport_ready, None
self.destroy()
viewport_ready.on_complete()
del viewport_ready
def __viewport_complete(self):
usd_context_name = self.__viewport_ready.usd_context_name
window_name = self.__viewport_ready.viewport_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(usd_context_name):
if window.title == window_name:
return window.viewport_api.frame_info.get('viewport_handle', None) is not None
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:
return bool(vp_window.get_drawable_ldr_resource() or vp_window.get_drawable_hdr_resource())
except ImportError:
pass
return False
| 13,578 | Python | 42.107936 | 125 | 0.602887 |
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/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.
##
__all__ = ['TestViewportReady']
import omni.kit.test
from ..viewport_ready import ViewportReadyDelegate, ViewportReady
import omni.usd
import omni.ui
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
EXTENSION_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.ready}")).resolve().absolute()
TEST_PATH = EXTENSION_PATH.joinpath("data", "tests")
WIDTH, HEIGHT = 512, 512
class TestViewportReady(OmniUiTest):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
@staticmethod
def __test_image_name(base_name: str):
settings = carb.settings.get_settings()
if settings.get("/exts/omni.kit.viewport.ready/activity_progress/enabled"):
base_name += "_progress"
if settings.get("/exts/omni.kit.viewport.window/startup/windowName"):
base_name += "_viewport"
return base_name + ".png"
async def test_ready_delegate_begin(self):
'''Test the Viewport readys status message is placed inside a ui.Window named Viewport'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
delegate = ViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_begin"))
async def test_ready_delegate_end(self):
'''Test the Viewport readys status message is removed from the Viewport'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
delegate = ViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
delegate.on_complete()
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_end"))
async def test_settings(self):
'''Test carb.settings usage for default delegate'''
# Make sure the values being set aren't the defaults!
delegate = ViewportReadyDelegate()
self.assertNotEqual(delegate.message, 'TEST MESSAGE')
self.assertNotEqual(delegate.font_size, 128)
import carb
settings = carb.settings.get_settings()
# Save all the defaults for restoration for later tests
preferences = [
'/exts/omni.kit.viewport.ready/message',
'/exts/omni.kit.viewport.ready/font_size',
]
defaults = {k: settings.get(k) for k in preferences}
try:
settings.set('/exts/omni.kit.viewport.ready/message', 'TEST MESSAGE')
settings.set('/exts/omni.kit.viewport.ready/font_size', 128)
delegate = ViewportReadyDelegate(viewport_name='Not a Viewport', usd_context_name='Not a UsdContext')
self.assertEqual(delegate.message, 'TEST MESSAGE')
self.assertEqual(delegate.font_size, 128)
self.assertEqual(delegate.viewport_name, 'Not a Viewport')
self.assertEqual(delegate.usd_context_name, 'Not a UsdContext')
except Exception as e:
raise e
finally:
# Restore the defaults
for k, v in defaults.items():
settings.set(k, v)
async def test_throw_in_log_message(self):
'''Test the Viewport readys status message is removed from the Viewport when log_message throws an Exception'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
log_complete_threw = False
class LocalExpection(RuntimeError):
pass
class ThrowingViewportReadyDelegate(ViewportReadyDelegate):
def log_complete(self):
nonlocal log_complete_threw
log_complete_threw = True
raise LocalExpection("Expected to throw")
try:
delegate = ThrowingViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
await self.capture_and_compare(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_threw_begin"))
delegate.on_complete()
except LocalExpection:
pass
self.assertTrue(log_complete_threw)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_threw_end"))
| 5,879 | Python | 38.463087 | 143 | 0.647899 |
omniverse-code/kit/exts/omni.volume_nodes/omni/volume_nodes/ogn/SaveVDBDatabase.py | """Support for simplified access to data on nodes of type omni.volume.SaveVDB
Saves a VDB from file and puts it in a memory buffer.
"""
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 SaveVDBDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.volume.SaveVDB
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.assetPath
inputs.compressionMode
inputs.data
inputs.execIn
Outputs:
outputs.execOut
Predefined Tokens:
tokens.none
tokens.blosc
tokens.zip
"""
# 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:assetPath', 'token', 0, None, 'Path to VDB file to save.', {}, True, "", False, ''),
('inputs:compressionMode', 'token', 0, None, 'The compression mode to use when encoding', {ogn.MetadataKeys.ALLOWED_TOKENS: 'None,Blosc,Zip', 'default': 'None', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"none": "None", "blosc": "Blosc", "zip": "Zip"}'}, False, None, False, ''),
('inputs:data', 'uint[]', 0, None, 'Data to save to file in NanoVDB or OpenVDB memory format.', {}, True, [], False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, None, 'Output execution', {}, True, None, False, ''),
])
class tokens:
none = "None"
blosc = "Blosc"
zip = "Zip"
@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.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 assetPath(self):
data_view = og.AttributeValueHelper(self._attributes.assetPath)
return data_view.get()
@assetPath.setter
def assetPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.assetPath)
data_view = og.AttributeValueHelper(self._attributes.assetPath)
data_view.set(value)
@property
def compressionMode(self):
data_view = og.AttributeValueHelper(self._attributes.compressionMode)
return data_view.get()
@compressionMode.setter
def compressionMode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.compressionMode)
data_view = og.AttributeValueHelper(self._attributes.compressionMode)
data_view.set(value)
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get()
@data.setter
def data(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.data)
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value)
self.data_size = data_view.get_array_size()
@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 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)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = SaveVDBDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = SaveVDBDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = SaveVDBDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,422 | Python | 42.409356 | 283 | 0.644301 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/audio_properties.py | import os
import carb
import omni.ext
from pathlib import Path
from .audio_settings_widget import AudioSettingsWidget
from pxr import Sdf, OmniAudioSchema, UsdMedia
TEST_DATA_PATH = ""
class AudioPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
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")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget, MultiSchemaPropertiesWidget
w = p.get_window()
if w:
w.register_widget("prim", "media", SchemaPropertiesWidget("Media", UsdMedia.SpatialAudio, False))
w.register_widget("prim", "audio_sound", SchemaPropertiesWidget("Sound", OmniAudioSchema.OmniSound, False))
w.register_widget("prim", "audio_listener", SchemaPropertiesWidget("Listener", OmniAudioSchema.OmniListener, False))
w.register_widget("layers", "audio_settings", AudioSettingsWidget())
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "media")
w.unregister_widget("prim", "audio_sound")
w.unregister_widget("prim", "audio_listener")
w.unregister_widget("layers", "audio_settings")
self._registered = False
| 1,899 | Python | 36.999999 | 128 | 0.657188 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/__init__.py | from .audio_properties import *
| 32 | Python | 15.499992 | 31 | 0.78125 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/audio_settings_widget.py | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.app
import omni.kit.ui
import omni.ui as ui
from pxr import Usd
import omni.usd
import omni.usd.audio
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import SimplePropertyWidget
class AudioSettingsWidget(SimplePropertyWidget):
def __init__(self):
super().__init__(title="Audio Settings", collapsed=False)
self._stage = None
self._audio = omni.usd.audio.get_stage_audio_interface()
self._listener_setting_model = None
self._events = self._audio.get_metadata_change_stream()
if self._events is not None:
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_metadata_event, name="audio settings window"
)
self._doppler_setting = None
self._distance_delay_setting = None
self._interaural_delay_setting = None
self._concurrent_voices_setting = None
self._speed_of_sound_setting = None
self._doppler_scale_setting = None
self._doppler_limit_setting = None
self._spatial_timescale_setting = None
self._nonspatial_timescale_setting = None
def __del__(self):
self._stage_event_sub = None
self._events = None
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
# stage is not part of LayerItem payload
self.set_stage(omni.usd.get_context().get_stage())
return payload is not None
class ListenerComboBoxNotifier(omni.ui.AbstractItemModel):
class MinimalItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
def __init__(self, refresh_items_callback, set_callback):
super().__init__()
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._changed_model)
self._set_callback = set_callback
self._refresh_items_callback = refresh_items_callback
self._options = []
self.refresh_items()
self._path = ""
def get_value_as_string(self):
return self._path
def refresh_items(self):
self._options = ["Active Camera"]
self._options.extend(self._refresh_items_callback())
self._items = [
AudioSettingsWidget.ListenerComboBoxNotifier.MinimalItem(text) for text in self._options
]
return self._items
def _changed_model(self, model):
self._set_callback(model.as_int - 1)
self._item_changed(None)
def set_value(self, value):
# item 0 will always be "Active Camera" => handle 'None' or an empty string specially
# as if it were that value.
if value is None or value == "":
self._current_index.as_int = 0
self._path = ""
return
for i in range(0, len(self._options)):
if self._options[i] == value:
self._current_index.as_int = i
break
self._path = value
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
class DefaultsComboBoxNotifier(omni.ui.AbstractItemModel):
class MinimalItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
def __init__(self, set_callback):
super().__init__()
self._options = [
["on", omni.usd.audio.FeatureDefault.ON],
["off", omni.usd.audio.FeatureDefault.OFF],
["force on", omni.usd.audio.FeatureDefault.FORCE_ON],
["force off", omni.usd.audio.FeatureDefault.FORCE_OFF],
]
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._changed_model)
self._set_callback = set_callback
self._items = [
AudioSettingsWidget.DefaultsComboBoxNotifier.MinimalItem(text) for (text, value) in self._options
]
def _changed_model(self, model):
self._set_callback(self._options[model.as_int][1])
self._item_changed(None)
def set_value(self, value):
for i in range(0, len(self._options) - 1):
if self._options[i][1] == value:
self._current_index.as_int = i
break
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
class ChangeNotifier(omni.ui.AbstractValueModel):
def __init__(self, update_callback):
super(AudioSettingsWidget.ChangeNotifier, self).__init__()
self._update_callback = update_callback
self._value = 0
def get_value_as_string(self):
return str(self._value)
def get_value_as_int(self):
return int(self._value)
def get_value_as_float(self):
return float(self._value)
def begin_edit(self):
pass
class SlowChangeNotifier(ChangeNotifier):
def __init__(self, update_callback):
super(AudioSettingsWidget.SlowChangeNotifier, self).__init__(update_callback)
def set_value(self, value):
self._value = value
self._value_changed()
def end_edit(self):
self._update_callback(self._value)
pass
class FastChangeNotifier(ChangeNotifier):
def __init__(self, update_callback):
super(AudioSettingsWidget.FastChangeNotifier, self).__init__(update_callback)
def set_value(self, value):
self._value = value
self._value_changed()
self._update_callback(self._value)
def end_edit(self):
pass
def set_stage(self, stage: Usd.Stage):
self._stage = stage
def _caption(self, text, width=150):
"""Create a formated heading"""
with omni.ui.ZStack():
omni.ui.Rectangle(name="caption", width=width, style={"background_color": 0x454545})
omni.ui.Label(text, name="caption")
def _create_tooltip(self, text):
"""Create a tooltip in a fixed style"""
with omni.ui.VStack(width=400, style={"Label": {"color": 0xFF3B494B}}):
omni.ui.Label(text, word_wrap=True)
def _refresh_active_listener(self):
if not self._listener_setting_model:
return
active_listener = self._audio.get_active_listener()
if active_listener is None:
self._listener_setting_model.set_value(None)
else:
self._listener_setting_model.set_value(str(active_listener.GetPath()))
def _refresh(self):
self._refresh_active_listener()
if not self._listener_setting_model:
return
if self._doppler_setting:
self._doppler_setting.model.set_value(self._audio.get_doppler_default())
if self._distance_delay_setting:
self._distance_delay_setting.model.set_value(self._audio.get_distance_delay_default())
if self._interaural_delay_setting:
self._interaural_delay_setting.model.set_value(self._audio.get_interaural_delay_default())
if self._concurrent_voices_setting:
self._concurrent_voices_setting.model.set_value(self._audio.get_concurrent_voices())
if self._speed_of_sound_setting:
self._speed_of_sound_setting.model.set_value(self._audio.get_speed_of_sound())
if self._doppler_scale_setting:
self._doppler_scale_setting.model.set_value(self._audio.get_doppler_scale())
if self._doppler_limit_setting:
self._doppler_limit_setting.model.set_value(self._audio.get_doppler_limit())
if self._spatial_timescale_setting:
self._spatial_timescale_setting.model.set_value(self._audio.get_spatial_time_scale())
if self._nonspatial_timescale_setting:
self._nonspatial_timescale_setting.model.set_value(self._audio.get_nonspatial_time_scale())
def _on_metadata_event(self, event):
if event.type == int(omni.usd.audio.EventType.METADATA_CHANGE):
self._refresh()
elif event.type == int(omni.usd.audio.EventType.LISTENER_LIST_CHANGE):
if self._listener_setting_model is not None:
self._listener_setting_model.refresh_items()
elif event.type == int(omni.usd.audio.EventType.ACTIVE_LISTENER_CHANGE):
self._refresh_active_listener()
def _refresh_listeners(self):
list = []
count = self._audio.get_listener_count()
for i in range(0, count):
list.append(str(self._audio.get_listener_by_index(i).GetPath()))
return list
def _set_active_listener(self, index):
# a negative index means the active camera should be used as the listener.
if index < 0:
self._audio.set_active_listener(None)
# all other indices are assumed to be an index into the listener list.
else:
prim = self._audio.get_listener_by_index(index)
if prim is None:
return
self._audio.set_active_listener(prim)
def _add_label(self, label: str):
filter_text = self._filter.name
UsdPropertiesWidgetBuilder._create_label(label, {}, {"highlight": filter_text})
self._any_item_visible = True
def build_items(self):
def item_visible(label: str) -> bool:
return not self._filter or self._filter.matches(label)
with omni.ui.VStack(height=0, spacing=8):
if item_visible("Active Listener"):
with ui.HStack():
self._add_label("Active Listener")
self._listener_setting_model = AudioSettingsWidget.ListenerComboBoxNotifier(
self._refresh_listeners, self._set_active_listener
)
self._listener_setting = omni.ui.ComboBox(
self._listener_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The path to the active Listener prim in the current USD scene. "
+ "Spatial audio calculations use the active listener as the position "
+ "(and optionally orientation) in 3D space, where the audio is heard "
+ "from. This value must be set to a valid Listener prim if 'Use "
+ "active camera as listener' is unchecked."
),
)
if item_visible("Doppler default"):
with ui.HStack():
self._add_label("Doppler default")
self._doppler_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_doppler_default
)
self._doppler_setting = omni.ui.ComboBox(
self._doppler_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"This sets the value that Sound prims will use for enableDoppler "
+ "when that parameter is set to 'default'. This also allows the "
+ "setting to be forced on or off on all prims for testing purposes, "
+ "using the 'force on' and 'force off' values"
),
)
if item_visible("Distance delay default"):
with ui.HStack():
self._add_label("Distance delay default")
self._distance_delay_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_distance_delay_default
)
self._distance_delay_setting = omni.ui.ComboBox(
self._distance_delay_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The value that Sound prims will use for enableDistanceDelay when "
+ "that parameter is set to 'default'. This also allows the setting "
+ "to be forced on or off on all prims for testing purposes, using "
+ "the 'force on' and 'force off' values"
),
)
if item_visible("Interaural delay default"):
with ui.HStack():
self._add_label("Interaural delay default")
self._interaural_delay_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_interaural_delay_default
)
self._interaural_delay_setting = omni.ui.ComboBox(
self._interaural_delay_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The value that Sound prims will use for enableInterauralDelay when "
+ "that parameter is set to 'default'. This also allows the setting "
+ "to be forced on or off on all prims for testing purposes, using "
+ "the 'force on' and 'force off' values"
),
)
if item_visible("Concurrent voices"):
with ui.HStack():
self._add_label("Concurrent voices")
self._concurrent_voices_setting_notifier = AudioSettingsWidget.SlowChangeNotifier(
self._audio.set_concurrent_voices
)
self._concurrent_voices_setting = omni.ui.IntDrag(
self._concurrent_voices_setting_notifier,
min=2,
max=4096,
tooltip_fn=lambda: self._create_tooltip(
"The number of sounds in a scene that can be played concurrently. "
+ "In a scene where there this is set to N and N + 1 sounds are "
+ "played concurrently, the N + 1th sound will be simulated instead "
+ "of playing on the audio device and instead simulate that voice. "
+ "The simulated voice will begin playing again when fewer than N "
+ "voices are playing"
),
)
if item_visible("Speed of sound"):
with ui.HStack():
self._add_label("Speed of sound")
self._speed_of_sound_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_speed_of_sound
)
self._speed_of_sound_setting = omni.ui.FloatDrag(
self._speed_of_sound_setting_notifier,
min=0.0001,
max=float("inf"),
step=1.0,
tooltip_fn=lambda: self._create_tooltip(
"Sets the speed of sound in the medium surrounding the listener "
+ "(typically air). This is measured in meters per second. This would "
+ "typically be adjusted when doing an underwater scene (as an "
+ "example). The speed of sound in dry air at sea level is "
+ "approximately 340.0m/s."
),
)
if item_visible("Doppler scale"):
with ui.HStack():
self._add_label("Doppler scale")
self._doppler_scale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_doppler_scale
)
self._doppler_scale_setting = omni.ui.FloatDrag(
self._doppler_scale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The scaler that can exaggerate or lessen the Doppler effect. Setting "
+ "this above 1.0 will exaggerate the Doppler effect. Setting this "
+ "below 1.0 will lessen the Doppler effect."
),
)
if item_visible("Doppler limit"):
with ui.HStack():
self._add_label("Doppler limit")
self._doppler_limit_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_doppler_limit
)
self._doppler_limit_setting = omni.ui.FloatDrag(
self._doppler_limit_setting_notifier,
min=1.0,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"A Limit on the maximum Doppler pitch shift that can be applied to "
+ "a playing voice. Since supersonic spatial audio is not handled, a "
+ "maximum frequency shift must be set for prims that move toward the "
+ "listener at or faster than the speed of sound."
),
)
if item_visible("Spatial time scale"):
with ui.HStack():
self._add_label("Spatial time scale")
self._spatial_timescale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_spatial_time_scale
)
self._spatial_timescale_setting = omni.ui.FloatDrag(
self._spatial_timescale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The timescale modifier for all spatial voices. Each spatial Sound "
+ "prim multiplies its timeScale attribute by this value. For "
+ "example, setting this to 0.5 will play all spatial sounds at half "
+ "speed and setting this to 2.0 will play all spatial sounds at "
+ "double speed. This affects delay times for the distance delay "
+ "effect. This feature is intended to allow time-dilation to be "
+ "performed with the sound effects in the scene without affecting "
+ "non-spatial elements like the background music."
),
)
if item_visible("Non-spatial time scale"):
with ui.HStack():
self._add_label("Non-spatial time scale")
self._nonspatial_timescale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_nonspatial_time_scale
)
self._nonspatial_timescale_setting = omni.ui.FloatDrag(
self._nonspatial_timescale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The timescale modifier for all non-spatial voices. Each non-spatial "
+ "Sound prim multiplies its timeScale attribute by this value. For "
+ "example, setting this to 0.5 will play all non-spatial sounds at "
+ "half speed and setting this to 2.0 will play all non-spatial "
+ "sounds at double speed."
),
)
self._refresh()
| 21,187 | Python | 44.176972 | 113 | 0.539576 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/__init__.py | from .test_audio import *
from .test_layer_audio import *
| 58 | Python | 18.66666 | 31 | 0.741379 |
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/test_layer_audio.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class TestLayerAudioWidget(OmniUiTest): # pragma: no cover
# Before running each test
async def setUp(self):
await super().setUp()
await arrange_windows("Layer")
from omni.kit.property.audio.scripts.audio_properties import TEST_DATA_PATH
self._usd_path = TEST_DATA_PATH.absolute()
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
usd_context.open_stage(str(test_file_path))
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_layer_sound_ui(self):
await ui_test.find("Layer").focus()
await ui_test.find("Layer//Frame/**/TreeView[*]").find(f"**/Label[*].text=='Root Layer (Authoring Layer)'").click()
await ui_test.human_delay(50)
| 1,565 | Python | 39.153845 | 123 | 0.714377 |
omniverse-code/kit/exts/omni.kit.test_async_rendering/omni/kit/test_async_rendering/__init__.py | from .test_async_rendering import *
| 36 | Python | 17.499991 | 35 | 0.777778 |
omniverse-code/kit/exts/omni.kit.test_async_rendering/omni/kit/test_async_rendering/test_async_rendering.py | import pathlib
import asyncio
import carb
import carb.settings
import carb.tokens
import omni.kit.app
import omni.kit.test
import omni.hydratexture
import omni.usd
from typing import Callable
# FIXME: omni.ui.ImageProvider holds the carb.Format conversion routine
import omni.ui
EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
DATA_DIR = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class AsyncRenderingTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._hydra_texture_factory = omni.hydratexture.acquire_hydra_texture_factory_interface()
self._usd_context_name = ''
self._usd_context = omni.usd.get_context(self._usd_context_name)
await self._usd_context.new_stage_async()
async def tearDown(self):
print("Tearing down..")
self._usd_context.close_stage()
omni.usd.release_all_hydra_engines(self._usd_context)
self._hydra_texture_factory = None
self._settings = None
wait_iterations = 6
for i in range(wait_iterations):
await omni.kit.app.get_app().next_update_async()
async def test_1_simple_context_attach(self):
renderer = "rtx"
if renderer not in self._usd_context.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(renderer, self._usd_context)
test_usd_asset = DATA_DIR.joinpath("simple_cubes_mat.usda")
print("Opening '%s'" % (test_usd_asset))
await self._usd_context.open_stage_async(str(test_usd_asset))
app = omni.kit.app.get_app()
self._update_counter = 0
self._render_counter = 0
self._asset_loaded = False
def on_update(event):
self._update_counter += 1
self._app_update_sub = app.get_update_event_stream().create_subscription_to_pop(on_update, name='async rendering test update')
is_async = self._settings.get("/app/asyncRendering")
print("Async is %s" % (is_async))
self._hydra_texture = self._hydra_texture_factory.create_hydra_texture(
"test_viewport",
1280,
720,
self._usd_context_name,
"/test_cam",
renderer,
is_async=is_async
)
def _on_stage_event(event):
ASSETS_LOADED = int(omni.usd.StageEventType.ASSETS_LOADED)
if (self._asset_loaded == False) and (event.type is ASSETS_LOADED):
self._asset_loaded = True
print("Assets loaded. UI frame: %d" % (self._update_counter))
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(_on_stage_event, name="stage events")
def on_drawable_changed(event: carb.events.IEvent):
# Renderer counter should start after usd assets are completely loaded in async mode
if self._asset_loaded or (is_async == False):
# +1 because the frame number is zero-based.
self._render_counter = self._hydra_texture.get_frame_info(event.payload['result_handle']).get('frame_number') + 1
print("Rendered %d frames (UI frames drawn: %d)" % (self._render_counter, self._update_counter))
self._drawable_changed_sub = self._hydra_texture.get_event_stream().create_subscription_to_push_by_type(
omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED,
on_drawable_changed,
name='async rendering test drawable update',
)
print("Waiting the RTX renderer to load and start draw pictures")
MAX_WAIT_FRAMES_INIT = 50000
wait_frames_left = MAX_WAIT_FRAMES_INIT
while True:
await app.next_update_async()
if self._render_counter > 0 or wait_frames_left <= 0:
break
wait_frames_left -= 1
print("Waited %d frames before renderer initialized" % (MAX_WAIT_FRAMES_INIT - wait_frames_left))
# Set render mode and settings
self._settings.set("/rtx/rendermode", "PathTracing")
self._settings.set("/rtx/pathtracing/totalSpp", 0)
self._settings.set("/rtx/pathtracing/spp", 256)
self._settings.set("/rtx/pathtracing/clampSpp", 256)
print("Starting render loop")
test_updates_before = self._update_counter
test_renders_before = self._render_counter
wait_frames_left = 10000
while True:
await app.next_update_async()
if self._render_counter - test_renders_before > 10 or wait_frames_left <= 0:
break
wait_frames_left -= 1
self.assertTrue(self._render_counter > 10)
test_updates_delta = self._update_counter - test_updates_before
test_renders_delta = self._render_counter - test_renders_before
updates_renders_ratio = test_updates_delta / test_renders_delta
updates_renders_difference = test_updates_delta - test_renders_delta
print("Updates: %d, renders: %d, difference %d, ratio %3.2f" % (test_updates_delta, test_renders_delta, updates_renders_difference, updates_renders_ratio))
# Verify results, this depends on the Async mode
if is_async:
# When Async is On - we expect much more UI updates than render delegate renders
# R525+ drivers showing 3X+ UI draws than 10X+ in comparison to R470.
# OM-78715: lowering threshold even further since it occasionally fails on IPP agents.
self.assertTrue(updates_renders_ratio > 2.3)
else:
# When Async is Off - we expect UI updates come in a lockstep with render delegate renders
# Add some leeway for potential frame offsetting
self.assertTrue(updates_renders_ratio < 1.9)
NUM_FRAMES_IN_FLIGHT = 3
# The UI should be no more than NUM_FRAMES_IN_FLIGHT + 1 frames ahead of the renderer.
self.assertTrue(0 <= updates_renders_difference and updates_renders_difference <= NUM_FRAMES_IN_FLIGHT + 1)
self._drawable_changed_sub = None
self._hydra_texture = None
self._app_update_sub = None
self._stage_event_sub = None
| 6,284 | Python | 41.181208 | 163 | 0.635742 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/__init__.py | """
This module contains bindings to the C++ omni::audio::IAudioPlayer interface.
This provides functionality for playing sound assets. This is intended only
as a basic audio player interface for previewing assets. This is not intended
to play sounds in a USD stage or in the Kit UI. For sounds in the USD stage,
the omni.usd.audio interface should be used instead. For UI sounds, the
omni.kit.uiaudio interface should be used.
Sound files may be in RIFF/WAV, Ogg, or FLAC format.
Data in the sound files may use 8, 16, 24, or 32 bit integer samples,
or 32 bit floating point samples. Channel counts may be from 1 to 64
If more channels of data are provided than the audio device can play,
some channels will be blended together automatically.
"""
from ._audioplayer import *
| 872 | Python | 47.499997 | 86 | 0.694954 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/tests/__init__.py | from .test_audio_player import * # pragma: no cover
| 54 | Python | 17.333328 | 52 | 0.703704 |
omniverse-code/kit/exts/omni.audioplayer/omni/audioplayer/tests/test_audio_player.py | import pathlib
import time
import pathlib
from PIL import Image
import carb.tokens
import omni.audioplayer
import os
import omni.kit.test
import omni.kit.test_helpers_gfx.compare_utils
OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path())
# This test needs to come first alphabetically since the bug this tests didn't
# trigger if the plugin was already loaded and carb plugins don't ever unload
# during normal kit operations.
class Test0AudioPlayerHang(omni.kit.test.AsyncTestCase): # pragma: no cover
def setUp(self):
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.audioplayer}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._player = omni.audioplayer.create_audio_player()
self.assertIsNotNone(self._player)
def tearDown(self):
# if you don't do this, the player never gets destroyed until plugin unload
self._player = None
def test_unload_during_load(self):
self._player.load_sound(str(self._test_path.joinpath("long.oga")))
# Finish the test so the player will close and the plugin will unload.
# At one point, this caused a GIL deadlock in ~AudioPlayer().
# This test should verify that this deadlock no longer happens.
class TestAudioPlayer(omni.kit.test.AsyncTestCase): # pragma: no cover
def setUp(self):
self._player = omni.audioplayer.create_audio_player()
self.assertIsNotNone(self._player)
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.audioplayer}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._golden_path = self._test_path.joinpath("golden")
def tearDown(self):
self._player = None
def test_basic(self):
events = []
expected_load_result = True
def event_callback(event):
nonlocal events
nonlocal expected_load_result
events.append(event.type)
if event.type == int(omni.audioplayer.CallbackType.LOADED):
self.assertEqual(event.payload["success"], expected_load_result)
sub = self._player.get_event_stream().create_subscription_to_pop(event_callback)
# load the sound and verify that a loaded event shows up
last = len(events)
self._player.load_sound(str(self._test_path.joinpath("long.oga")))
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# check that get_sound_length() works
self.assertLess(abs(self._player.get_sound_length() - 120.0), 0.001)
# play the sound and verify that a load event is sent
last = len(events)
self._player.play_sound(str(self._test_path.joinpath("long.oga")))
# it should load quickly since it's already been loaded once
time.sleep(1)
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# pause and unpause it a few times
last = len(events)
self._player.pause_sound()
time.sleep(1)
self._player.unpause_sound()
time.sleep(1)
self._player.pause_sound()
time.sleep(1)
# nothing should have been sent
self.assertEqual(len(events), last)
self.assertGreater(self._player.get_play_cursor(), 0.0)
# modify the play cursor, this should send an ended then loaded event
last = len(events)
self._player.set_play_cursor(60.0)
i = 0
while len(events) <= last + 1:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 2)
self.assertEqual(events[-2], int(omni.audioplayer.CallbackType.ENDED))
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
self.assertGreaterEqual(self._player.get_play_cursor(), 60.0)
# stop it and verify that the ended event is sent
last = len(events)
self._player.stop_sound()
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.ENDED))
# play the same sound again and see if events are sent
last = len(events)
self._player.play_sound(str(self._test_path.joinpath("long.oga")))
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# play again to see the ended and loaded event
last = len(events)
self._player.play_sound(str(self._test_path.joinpath("long.oga")))
i = 0
while len(events) <= last + 1:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 2)
self.assertEqual(events[-2], int(omni.audioplayer.CallbackType.ENDED))
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# Note: there is no test for callbacks with play_sound() 2 times back to back
# because whether callbacks for both calls are sent is dependent on timing.
# The less recent sound playback may just be cancelled.
def test_draw_waveform(self):
# toggle in case you want to regenerate waveforms
GENERATE_GOLDEN_IMAGES = False
W = 256
H = 256
loaded = False
def event_callback(event):
if event.type == int(omni.audioplayer.CallbackType.LOADED):
nonlocal loaded
loaded = True
sub = self._player.get_event_stream().create_subscription_to_pop(event_callback)
self._player.load_sound(str(self._test_path.joinpath("short-2ch.oga")))
i = 0
while not loaded:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self._player.draw_waveform_to_file(str(OUTPUTS_DIR.joinpath("waveform.png")), W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.png"),
self._golden_path.joinpath("waveform.png"),
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.png.diff.png")),
0.1)
raw = self._player.draw_waveform(W, H, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(OUTPUTS_DIR.joinpath("waveform.raw.png")))
if not GENERATE_GOLDEN_IMAGES:
# this image is slightly different than the original and this compare
# helper function cannot handle even a slight difference, so we need to
# have a separate golden image for this
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.raw.png"),
self._golden_path.joinpath("waveform.raw.png"),
pathlib.Path(OUTPUTS_DIR).joinpath("waveform.raw.png.diff.png")),
0.1)
def _load_and_play_data_in_memory(self, filename, frame_rate, channels, format, flags = 0, expected_length = 2.0):
events = []
expected_load_result = True
def event_callback(event):
nonlocal events
nonlocal expected_load_result
events.append(event.type)
if event.type == int(omni.audioplayer.CallbackType.LOADED):
self.assertEqual(event.payload["success"], expected_load_result)
# subscribe to events from the player.
sub = self._player.get_event_stream().create_subscription_to_pop(event_callback)
# load the test file into a bytes object.
file_data = pathlib.Path(self._test_path.joinpath(filename)).read_bytes()
# load the sound and verify that a 'loaded' event shows up.
last = len(events)
self._player.load_sound_in_memory(filename, file_data, frame_rate, channels, format, flags)
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# check that get_sound_length() works.
self.assertLess(abs(self._player.get_sound_length() - expected_length), 0.001)
# play the sound and verify that a load event is sent.
last = len(events)
self._player.play_sound_in_memory(filename, file_data, frame_rate, channels, format, 0.0, flags)
# it should load quickly since it's already been loaded once.
time.sleep(1)
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.LOADED))
# stop it and verify that the ended event is sent.
last = len(events)
self._player.stop_sound()
i = 0
while len(events) == last:
time.sleep(0.001)
if i > 30000:
raise Exception("hang while loading a test asset")
i += 1
self.assertEqual(len(events), last + 1)
self.assertEqual(events[-1], int(omni.audioplayer.CallbackType.ENDED))
# clean up.
sub = None
def test_data_in_memory(self):
self._load_and_play_data_in_memory("tone-440-8.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_8)
self._load_and_play_data_in_memory("tone-440-16.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_16)
self._load_and_play_data_in_memory("tone-440-32.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_32)
self._load_and_play_data_in_memory("tone-440-float.wav", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_FLOAT)
def test_raw_data_in_memory(self):
self._load_and_play_data_in_memory("tone-440-8.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_8, omni.audioplayer.FLAG_RAW_DATA)
self._load_and_play_data_in_memory("tone-440-16.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_16, omni.audioplayer.FLAG_RAW_DATA)
self._load_and_play_data_in_memory("tone-440-32.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_32, omni.audioplayer.FLAG_RAW_DATA)
self._load_and_play_data_in_memory("tone-440-float.raw", 44100, 1, omni.audioplayer.RawPcmFormat.PCM_FLOAT, omni.audioplayer.FLAG_RAW_DATA)
| 11,500 | Python | 39.354386 | 147 | 0.61913 |
omniverse-code/kit/exts/omni.rtx.shadercache.d3d12/omni/rtx/shadercache/d3d12/__init__.py | from .shadercache_d3d12 import ShaderCacheConfig
| 49 | Python | 23.999988 | 48 | 0.877551 |
omniverse-code/kit/exts/omni.kit.clipboard/omni/kit/clipboard/__init__.py |
def _clipboard_prep():
import omni.appwindow
import carb.windowing
_app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
_app_window = _app_window_factory.get_default_window()
_carb_window = _app_window.get_window()
_windowing = carb.windowing.acquire_windowing_interface()
return _windowing, _carb_window
def copy(value_str):
"""
Platform-independent copy functionality.
Args:
value_str (str): String to put in the clipboard.
"""
_windowing, _carb_window = _clipboard_prep()
_windowing.set_clipboard(_carb_window, value_str)
def paste():
"""
Platform-independent paste functionality.
Returns:
str: Value pulled from the clipboard.
"""
_windowing, _carb_window = _clipboard_prep()
value_str = _windowing.get_clipboard(_carb_window)
return value_str
| 877 | Python | 23.388888 | 79 | 0.667047 |
omniverse-code/kit/exts/omni.kit.clipboard/omni/kit/clipboard/tests/__init__.py | from .test_clipboard import *
| 30 | Python | 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.clipboard/omni/kit/clipboard/tests/test_clipboard.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.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from .. import copy, paste
class ClipboardTest(OmniUiTest):
async def test_clipboard(self):
await self.create_test_window(width=400, height=40)
human_delay_speed = 2
await ui_test.wait_n_updates(human_delay_speed)
str_to_copy = "Testing, testing, 1, 2, 3."
copy(str_to_copy)
pasted_str = paste()
self.assertEqual(str_to_copy, pasted_str)
| 917 | Python | 31.785713 | 77 | 0.720829 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/style.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 Dict
from omni.ui import color as cl
COLOR_X = 0xFF6060AA
COLOR_Y = 0xFF76A371
COLOR_Z = 0xFFA07D4F
COLOR_SCREEN = 0x8AFEF68E
COLOR_FREE = 0x40404040
COLOR_FOCAL = 0xE6CCCCCC
def get_default_style():
return {
"Translate.Axis::x": {"color": COLOR_X},
"Translate.Axis::y": {"color": COLOR_Y},
"Translate.Axis::z": {"color": COLOR_Z},
"Translate.Plane::x_y": {"color": COLOR_Z},
"Translate.Plane::y_z": {"color": COLOR_X},
"Translate.Plane::z_x": {"color": COLOR_Y},
"Translate.Point": {"color": COLOR_SCREEN, "type": "point"},
"Translate.Focal": {"color": COLOR_FOCAL, "visible": False},
"Rotate.Arc::x": {"color": COLOR_X},
"Rotate.Arc::y": {"color": COLOR_Y},
"Rotate.Arc::z": {"color": COLOR_Z},
"Rotate.Arc::screen": {"color": COLOR_SCREEN},
"Rotate.Arc::free": {"color": COLOR_FREE},
"Scale.Axis::x": {"color": COLOR_X},
"Scale.Axis::y": {"color": COLOR_Y},
"Scale.Axis::z": {"color": COLOR_Z},
"Scale.Plane::x_y": {"color": COLOR_Z},
"Scale.Plane::y_z": {"color": COLOR_X},
"Scale.Plane::z_x": {"color": COLOR_Y},
"Scale.Point": {"color": COLOR_SCREEN},
}
def get_default_toolbar_style():
return {
"CollapsableFrame": {
"background_color": 0x00,
"secondary_color": 0x00,
"border_color": 0x0,
"border_width": 0,
"padding": 0,
"margin_height": 5,
"margin_width": 0,
},
"CollapsableFrame:hovered": {"secondary_color": 0x00},
"CollapsableFrame:pressed": {"secondary_color": 0x00},
"Line": {"color": 0xFFA1A1A1, "border_width": 2},
"Rectangle": {"background_color": 0x8F000000},
}
def abgr_to_color(abgr: int) -> cl:
# cl in rgba order
return cl((abgr & 0xFF) / 255, (abgr >> 8 & 0xFF) / 255, (abgr >> 16 & 0xFF) / 255, (abgr >> 24 & 0xFF) / 255)
# style is nested dict, can't simply call to_style.update(from_style)
def update_style(to_style: Dict, from_style: Dict):
if from_style:
for k, v in from_style.items():
if isinstance(v, dict):
to_style[k] = update_style(to_style.get(k, {}), v)
else:
to_style[k] = v
return to_style
| 2,774 | Python | 34.126582 | 114 | 0.583273 |
omniverse-code/kit/exts/omni.kit.manipulator.transform/omni/kit/manipulator/transform/extension.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ext
from .style import get_default_style
SHOW_EXAMPLE = False
class TransformManipulatorExt(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
if SHOW_EXAMPLE:
from .example import SimpleManipulatorExample
self._example = SimpleManipulatorExample()
def on_shutdown(self):
if SHOW_EXAMPLE:
self._example.destroy()
self._example = None
| 1,015 | Python | 32.866666 | 119 | 0.733005 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.