file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_actiongraph.py
"""Basic tests of the action graph""" import omni.client import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.kit.commands import execute from pxr import Gf, Sdf, Vt # ====================================================================== class TestActionGraphIntegration(ogts.OmniGraphTestCase): """Integration tests for Action Graph""" TEST_GRAPH_PATH = "/World/TestGraph" async def setUp(self): """Set up test environment, to be torn down when done""" self._var_index = 0 await super().setUp() og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) # ---------------------------------------------------------------------- async def test_path_attribute(self): """Check that AG properly handles USD prim paths being changed at runtime""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() (_, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { "create_nodes": [ ("OnTick", "omni.graph.action.OnTick"), ("Set", "omni.graph.action.SetPrimActive"), ("Query", "omni.graph.nodes.IsPrimActive"), ("PrimPath", "omni.graph.nodes.ConstantPath"), ("BoolNot", "omni.graph.nodes.BooleanNot"), ("Simple", "omni.graph.tutorials.SimpleData"), ], "create_prims": [("Test", {}), ("Test/Child", {}), ("Dummy", {}), ("Dummy/Child", {})], "connect": [ ("OnTick.outputs:tick", "Set.inputs:execIn"), ("Query.outputs:active", "BoolNot.inputs:valueIn"), ("BoolNot.outputs:valueOut", "Set.inputs:active"), ("PrimPath.inputs:value", "Simple.inputs:a_path"), ("Simple.outputs:a_path", "Query.inputs:prim"), ], "set_values": [ ("Set.inputs:prim", "/Test/Child"), ("PrimPath.inputs:value", "/Test"), ("OnTick.inputs:onlyPlayback", False), ], }, ) # Move the prim. execute("MovePrim", path_from="/Test", path_to="/Test1") test = stage.GetPrimAtPath("/Test1/Child") # Graph should still work. First run should deactivate the prim. await controller.evaluate() self.assertFalse(test.IsActive()) # Second run should make it active again. await controller.evaluate() self.assertTrue(test.IsActive()) # Make sure that if we change the value, it can reconnect correctly to the path. # First change to an unrelated target. controller.edit( self.TEST_GRAPH_PATH, {"set_values": [("Set.inputs:prim", "/Dummy"), ("PrimPath.inputs:value", "/Dummy")]} ) # Disconnected form the prim => evaluation shouldn't change a thing. self.assertTrue(test.IsActive()) await controller.evaluate() self.assertTrue(test.IsActive()) # Now reset to proper name. controller.edit( self.TEST_GRAPH_PATH, {"set_values": [("Set.inputs:prim", "/Test1/Child"), ("PrimPath.inputs:value", "/Test1")]}, ) # Graph should work. First run should deactivate the prim. await controller.evaluate() self.assertFalse(test.IsActive()) # Second run should make it active again. await controller.evaluate() self.assertTrue(test.IsActive()) # Move again the prim. execute("MovePrim", path_from="/Test1", path_to="/Test2") test = stage.GetPrimAtPath("/Test2/Child") # Graph should still work. First run should deactivate the prim. await controller.evaluate() self.assertFalse(test.IsActive()) # Second run should make it active again. await controller.evaluate() self.assertTrue(test.IsActive()) # ---------------------------------------------------------------------- async def test_path_on_property(self): """Another test to check AG properly handles USD prim paths being changed at runtime""" # Query--------->BoolNot-----+ # ^ | # | v # Simple----+ OnObjectChange-> Set # | ^ # +-------------------------------+ usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() (_, _, prims, _) = controller.edit( self.TEST_GRAPH_PATH, { "create_nodes": [ ("OnObjectChange", "omni.graph.action.OnObjectChange"), ("Set", "omni.graph.action.SetPrimActive"), ("Query", "omni.graph.nodes.IsPrimActive"), ("BoolNot", "omni.graph.nodes.BooleanNot"), ("Simple", "omni.graph.tutorials.SimpleData"), ], "create_prims": [("Test", {}), ("Test/Child", {"myfloat": ("float", 0)})], "connect": [ ("OnObjectChange.outputs:changed", "Set.inputs:execIn"), ("Simple.outputs:a_path", "Set.inputs:prim"), ("Simple.outputs:a_path", "Query.inputs:prim"), ("Query.outputs:active", "BoolNot.inputs:valueIn"), ("BoolNot.outputs:valueOut", "Set.inputs:active"), ], "set_values": [ ("Simple.inputs:a_path", "/Test"), ("OnObjectChange.inputs:onlyPlayback", False), ("OnObjectChange.inputs:path", "/Test/Child.myfloat"), ], }, ) test = prims[1] attr = test.GetAttribute("myfloat") # First evaluation should do nothing. self.assertTrue(test.IsActive()) await controller.evaluate() self.assertTrue(test.IsActive()) # Modify the trigger value, should activate the graph. attr.Set(1) self.assertTrue(test.IsActive()) await controller.evaluate() self.assertFalse(test.IsActive()) # Moving the parent prim should keep everything working. execute("MovePrim", path_from="/Test", path_to="/Test1") test = stage.GetPrimAtPath("/Test1/Child") attr = test.GetAttribute("myfloat") # => first, the move shouldn't have triggered a changed. self.assertFalse(test.IsActive()) await controller.evaluate() self.assertFalse(test.IsActive()) # => then, graph is executed again if value is changed. attr.Set(2) self.assertFalse(test.IsActive()) await controller.evaluate() self.assertTrue(test.IsActive()) # ---------------------------------------------------------------------- async def test_writeprimattribute_scaler(self): """Exercise WritePrimAttribute for scalar value""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, _, prims, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: ("/World/Float", {"myfloat": ("float", 0)}), keys.CONNECT: ("OnTick.outputs:tick", "Set.inputs:execIn"), keys.SET_VALUES: [ ("Set.inputs:name", "myfloat"), ("Set.inputs:primPath", "/World/Float"), ("Set.inputs:usePath", True), ("Set.inputs:value", 42.0, "float"), ("OnTick.inputs:onlyPlayback", False), ], }, ) await controller.evaluate(graph) self.assertEqual(prims[0].GetAttribute("myfloat").Get(), 42.0) # Same test but with bundle input stage.GetPrimAtPath(f"{self.TEST_GRAPH_PATH}/Set").GetRelationship("inputs:prim").SetTargets( [Sdf.Path("/World/Float")] ) controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ("Set.inputs:usePath", False), ("Set.inputs:value", 0.0, "float"), ] }, ) await controller.evaluate(graph) self.assertEqual(prims[0].GetAttribute("myfloat").Get(), 0.0) # ---------------------------------------------------------------------- async def test_writeprimattribute_noexist(self): """Test WritePrimAttribute can handle attribute that exists in USD but not in FC""" controller = og.Controller() keys = og.Controller.Keys (graph, _, prims, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: ("/World/Cube", "Cube"), keys.CONNECT: ("OnTick.outputs:tick", "Set.inputs:execIn"), keys.SET_VALUES: [ ("Set.inputs:name", "visibility"), ("Set.inputs:primPath", "/World/Cube"), ("Set.inputs:usePath", True), ("Set.inputs:value", "invisible", "token"), ("OnTick.inputs:onlyPlayback", False), ], }, ) await controller.evaluate(graph) await controller.evaluate(graph) self.assertEqual(prims[0].GetAttribute("visibility").Get(), "invisible") # ---------------------------------------------------------------------- async def test_readwrite_primattribute_primvar(self): """Test WritePrimAttribute and ReadPrimAttribute can handle primvars""" # The idea is to Read the primvar that exists, but does not have a value. It should resolve to the correct type # of float[3][] because the primvar is defined. Then take that value and append a color and feed that into # WritePrimAttribute to write it to a different prim which requires authoring the primvar and copying the value. # controller = og.Controller() keys = og.Controller.Keys (graph, _, prims, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_PRIMS: [("/World/Cube1", "Cube"), ("/World/Cube2", "Cube")]} ) self.assertIsNone(prims[0].GetAttribute("primvars:displayColor").Get()) controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ("Get", "omni.graph.nodes.ReadPrimAttribute"), ("ArraySetIndex", "omni.graph.nodes.ArraySetIndex"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Set.inputs:execIn"), ("Get.outputs:value", "ArraySetIndex.inputs:array"), ("ArraySetIndex.outputs:array", "Set.inputs:value"), ], keys.SET_VALUES: [ ("Set.inputs:name", "primvars:displayColor"), ("Set.inputs:primPath", "/World/Cube2"), ("Set.inputs:usePath", True), ("Get.inputs:name", "primvars:displayColor"), ("Get.inputs:primPath", "/World/Cube1"), ("Get.inputs:usePath", True), ("ArraySetIndex.inputs:resizeToFit", True), ("ArraySetIndex.inputs:index", 0), ("ArraySetIndex.inputs:value", (1, 0, 0), "float[3]"), ("OnTick.inputs:onlyPlayback", False), ], }, ) await controller.evaluate(graph) await controller.evaluate(graph) self.assertEqual(list(prims[1].GetAttribute("primvars:displayColor").Get()), [(1, 0, 0)]) # ---------------------------------------------------------------------- async def _test_writeprimattribute_tuple(self): """Exercise WritePrimAttribute for a tuple value""" controller = og.Controller() keys = og.Controller.Keys (graph, _, prims, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: ("/World/Double3", {"mydouble3": ("double[3]", Gf.Vec3d(0, 0, 0))}), keys.CONNECT: ("OnTick.outputs:tick", "Set.inputs:execIn"), keys.SET_VALUES: [ ("Set.inputs:name", "mydouble3"), ("Set.inputs:primPath", "/World/Double3"), ("Set.inputs:usePath", True), ("Set.inputs:value", Gf.Vec3d(42.0, 42.0, 42.0), "double[3]"), ("OnTick.inputs:onlyPlayback", False), ], }, ) await controller.evaluate(graph) self.assertEqual(prims[0].GetAttribute("mydouble3").Get(), Gf.Vec3d(42.0, 42.0, 42.0)) # ---------------------------------------------------------------------- async def test_writeprimattribute_array(self): """Exercise WritePrimAttribute for an array value""" controller = og.Controller() keys = og.Controller.Keys big_array = Vt.IntArray(1000, [0 for _ in range(1000)]) (graph, _, prims, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: ("/World/IntArray", {"myintarray": ("int[]", [0xFF for _ in range(10)])}), keys.CONNECT: ("OnTick.outputs:tick", "Set.inputs:execIn"), keys.SET_VALUES: [ ("Set.inputs:name", "myintarray"), ("Set.inputs:primPath", "/World/IntArray"), ("Set.inputs:usePath", True), ("Set.inputs:value", big_array, "int[]"), ("OnTick.inputs:onlyPlayback", False), ], }, ) await controller.evaluate(graph) self.assertEqual(prims[0].GetAttribute("myintarray").Get(), big_array) async def test_resync_handling(self): """Test that resyncing a path only resets OG state when expected""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube = stage.DefinePrim("/World/scope1/cube", "Cube") controller = og.Controller() keys = og.Controller.Keys (graph, (on_impulse, _, counter, extra), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnImpulse", "omni.graph.action.OnImpulseEvent"), ("TickN", "omni.graph.action.Countdown"), ("Counter0", "omni.graph.action.Counter"), ("OnImpulseExtra", "omni.graph.action.OnImpulseEvent"), ], keys.CONNECT: [ ("OnImpulse.outputs:execOut", "TickN.inputs:execIn"), ("TickN.outputs:finished", "Counter0.inputs:execIn"), ], keys.SET_VALUES: [ ("OnImpulse.inputs:onlyPlayback", False), ("TickN.inputs:duration", 3), ("OnImpulse.state:enableImpulse", True), ], }, ) count_attrib = og.Controller.attribute("outputs:count", counter) # tick 0 (setup) await controller.evaluate(graph) # tick 1 await controller.evaluate(graph) # Removing the prim will trigger resync handling, we will verify that this doesn't # interrupt the latent node stage.RemovePrim(cube.GetPath()) # tick 2 await omni.kit.app.get_app().next_update_async() self.assertEqual(og.Controller.get(count_attrib), 0) # tick 3 (last tick in duration) await controller.evaluate(graph) self.assertEqual(og.Controller.get(count_attrib), 0) # tick 5 (finished triggers counter) await controller.evaluate(graph) self.assertEqual(og.Controller.get(count_attrib), 1) # Now check that removing a node prim does reset the state og.Controller.set(og.Controller.attribute("state:enableImpulse", on_impulse), True) # tick 0 (setup) await controller.evaluate(graph) # tick 1 await controller.evaluate(graph) # Removing the prim will trigger resync handling, we will verify that this doesn't # interrupt the latent node stage.RemovePrim(extra.get_prim_path()) # tick ( nothing ) await omni.kit.app.get_app().next_update_async() self.assertEqual(og.Controller.get(count_attrib), 1) # tick 3 (nothing) await controller.evaluate(graph) self.assertEqual(og.Controller.get(count_attrib), 1) # tick 5 (nothing) await controller.evaluate(graph) self.assertEqual(og.Controller.get(count_attrib), 1)
17,967
Python
41.277647
120
0.512551
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_autonode.py
""" Contains support for testing methods in ../autonode/autonode.py """ import enum import random import sys import unittest from typing import Tuple import omni.graph.core as og import omni.graph.core.autonode as oga import omni.graph.core.tests as ogts # Test warp integration # Detect the testing environment and use the Kit Async testing framework if it is available try: import omni.kit.test TestBaseClass = omni.kit.test.AsyncTestCase except ImportError: TestBaseClass = unittest.TestCase @oga.AutoClass(module_name="__test__") class TestClass: """Simple AutoClass test with four attributes""" test_visible_str_property: str = "test visible str property" test_visible_int_property: int = 42 test_visible_float_property: float = 3.141 test_uninitialized_property: str _test_hidden_state = 0 def __init__(self): raise RuntimeError("This is a test singleton class") @classmethod def _get_instance(cls): if not hasattr(cls, "_instance") or cls._instance is None: cls._instance = cls.__new__(cls) return cls._instance def test_visible_method(self, is_input: bool = False) -> int: self._test_hidden_state ^= int(is_input) return self._test_hidden_state @oga.AutoFunc(module_name="__test__") def get_test_class_instance() -> TestClass: return TestClass._get_instance() # noqa: PLW0212 class TestEnum(enum.Enum): VAL0 = 0 VAL1 = 1 VAL2 = 2 def get_test_enum(input_value: int) -> TestEnum: i = input_value % 3 return TestEnum(i) @oga.AutoFunc(module_name="__test__", pure=True) def pack(v: og.Float3, c: og.Color3f) -> og.Bundle: bundle = og.Bundle("return", False) bundle.create_attribute("vec", og.Float3).value = v bundle.create_attribute("col", og.Color3f).value = c return bundle @oga.AutoFunc(module_name="__test__", pure=True) def unpack_vector(bundle: og.Bundle) -> og.Float3: vec = bundle.attribute_by_name("vec") if vec: return vec.value return (0, 0, 0) @oga.AutoFunc(module_name="__test__", pure=True) def identity_float3(input_value: og.Float3) -> og.Float3: return input_value @oga.AutoFunc(module_name="__test__", pure=True) def identity_tuple(input_value_1: str, input_value_2: int) -> Tuple[int, str]: return (input_value_1, input_value_2) def dbl_to_matd(input_value: og.Double3) -> og.Matrix4d: pass ################################################################################ class TestAutographNodes(ogts.OmniGraphTestCase): TEST_GRAPH_PATH = "/World/TestGraph" async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) # -------------------------------------------------------------------------------- async def _property_test(self, property_name, test_value, *, almost_equal=False): """exercise a basic network of execution nodes""" controller = og.Controller() keys = og.Controller.Keys gci_name = "GetClassInstance" getter_name = "Getter" setter_name = "Setter" (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Ticker", "omni.graph.action.OnTick"), (f"{gci_name}01", "__test__.get_test_class_instance"), (getter_name, f"__test__.TestClass__PROP__{property_name}__GET"), ], keys.CONNECT: [ ("Ticker.outputs:tick", f"{gci_name}01.inputs:exec"), (f"{gci_name}01.outputs:exec", f"{getter_name}.inputs:exec"), (f"{gci_name}01.outputs:out_0", f"{getter_name}.inputs:target"), ], keys.SET_VALUES: [("Ticker.inputs:onlyPlayback", False)], }, ) await controller.evaluate(graph) (_, _, getter_node) = nodes if almost_equal: self.assertAlmostEqual( og.Controller.get(controller.attribute("outputs:out_0", getter_node)), getattr(TestClass._get_instance(), property_name), # noqa: PLW0212 places=3, ) else: self.assertEqual( og.Controller.get(controller.attribute("outputs:out_0", getter_node)), getattr(TestClass._get_instance(), property_name), # noqa: PLW0212 ) self.assertEqual( og.Controller.get(controller.attribute("outputs:exec", getter_node)), og.ExecutionAttributeState.ENABLED ) (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ (f"{gci_name}02", "__test__.get_test_class_instance"), (setter_name, f"__test__.TestClass__PROP__{property_name}__SET"), ], keys.CONNECT: [ ("Ticker.outputs:tick", f"{gci_name}02.inputs:exec"), (f"{gci_name}02.outputs:exec", f"{setter_name}.inputs:exec"), (f"{gci_name}02.outputs:out_0", f"{setter_name}.inputs:target"), ], keys.DISCONNECT: ("Ticker.outputs:tick", f"{gci_name}01.inputs:exec"), keys.SET_VALUES: (f"{setter_name}.inputs:value", test_value), }, ) await controller.evaluate(graph) (_, setter_node) = nodes if almost_equal: self.assertAlmostEqual( getattr(TestClass._get_instance(), property_name), test_value, places=3 # noqa: PLW0212 ) else: self.assertEqual(getattr(TestClass._get_instance(), property_name), test_value) # noqa: PLW0212 self.assertEqual( og.Controller.get(controller.attribute("outputs:exec", setter_node)), og.ExecutionAttributeState.ENABLED ) # -------------------------------------------------------------------------------- async def test_property_string(self): """Test to see strings can be get and set""" property_name = "test_visible_str_property" test_value = "test_value!" await self._property_test(property_name, test_value) # -------------------------------------------------------------------------------- async def test_property_int(self): """Test to see ints can be get and set""" property_name = "test_visible_int_property" test_value = random.randint(0, sys.maxsize >> 32) await self._property_test(property_name, test_value) # -------------------------------------------------------------------------------- async def test_property_float(self): """Test to see floats can be get and set""" property_name = "test_visible_float_property" test_value = random.random() await self._property_test(property_name, test_value, almost_equal=True) # -------------------------------------------------------------------------------- async def test_enum(self): """Test switching on enums""" oga.AutoClass(module_name="__test__")(TestEnum) oga.AutoFunc(module_name="__test__")(get_test_enum) test_enum_sanitized_name = TestEnum.__qualname__.replace(".", "__NSP__") controller = og.Controller() keys = og.Controller.Keys (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Ticker", "omni.graph.action.OnTick"), ("Generator", "__test__.get_test_enum"), ("Switch", f"__test__.{test_enum_sanitized_name}"), ], keys.CONNECT: [ ("Ticker.outputs:tick", "Generator.inputs:exec"), ("Generator.outputs:exec", "Switch.inputs:exec"), ("Generator.outputs:out_0", "Switch.inputs:enum"), ], keys.SET_VALUES: [("Ticker.inputs:onlyPlayback", False), ("Generator.inputs:input_value", 1)], }, ) await controller.evaluate(graph) (_, _, switch_node) = nodes self.assertEqual( og.Controller.get(controller.attribute("outputs:VAL0", switch_node)), og.ExecutionAttributeState.DISABLED ) self.assertEqual( og.Controller.get(controller.attribute("outputs:VAL1", switch_node)), og.ExecutionAttributeState.ENABLED ) self.assertEqual( og.Controller.get(controller.attribute("outputs:VAL2", switch_node)), og.ExecutionAttributeState.DISABLED ) controller.edit( self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Generator.inputs:input_value", 2), ("Switch.outputs:VAL1", False)]}, ) await controller.evaluate(graph) self.assertEqual( og.Controller.get(controller.attribute("outputs:VAL0", switch_node)), og.ExecutionAttributeState.DISABLED ) self.assertEqual( og.Controller.get(controller.attribute("outputs:VAL1", switch_node)), og.ExecutionAttributeState.DISABLED ) self.assertEqual( og.Controller.get(controller.attribute("outputs:VAL2", switch_node)), og.ExecutionAttributeState.ENABLED ) # -------------------------------------------------------------------------------- class TestAutographPureNodes(ogts.OmniGraphTestCase): TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def tuple_test(self): """Test multiple outputs""" def switch_io(input1: str, input2: int) -> Tuple[int, str]: return (input2, input1) oga.AutoFunc(module_name="__test__", pure=True)(switch_io) # ---------------------------------------------------------------------- async def test_tuple(self): """Test multiple outputs""" test_input1 = "test" test_input2 = 42 controller = og.Controller() keys = og.Controller.Keys (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [("Identity1", "__test__.identity_tuple"), ("Identity2", "__test__.identity_tuple")], keys.CONNECT: [ ("Identity1.outputs:out_0", "Identity2.inputs:input_value_1"), ("Identity1.outputs:out_1", "Identity2.inputs:input_value_2"), ], keys.SET_VALUES: [ ("Identity1.inputs:input_value_1", test_input1), ("Identity1.inputs:input_value_2", test_input2), ], }, ) await controller.evaluate(graph) (identity1_node, _) = nodes self.assertEqual(og.Controller.get(controller.attribute("outputs:out_0", identity1_node)), test_input1) self.assertEqual(og.Controller.get(controller.attribute("outputs:out_1", identity1_node)), test_input2) # -------------------------------------------------------------------------------- async def test_bundle(self): """Test switching on bundles""" test_input_1 = (random.random(), random.random(), random.random()) test_input_2 = (0, 0.5, 1) oga.AutoFunc(module_name="__test__", pure=True)(unpack_vector) controller = og.Controller() keys = og.Controller.Keys (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Pack", "__test__.pack"), ("UnpackVector", "__test__.unpack_vector"), ("Id", "__test__.identity_float3"), ], keys.CONNECT: [ # outputs_out_0 instead of outputs:out_0 due to the way bundles are implemented ("Pack.outputs_out_0", "UnpackVector.inputs:bundle"), ("UnpackVector.outputs:out_0", "Id.inputs:input_value"), ], keys.SET_VALUES: [("Pack.inputs:v", test_input_1), ("Pack.inputs:c", test_input_2)], }, ) await controller.evaluate(graph) (_, unpack_vector_node, _) = nodes out_0 = og.Controller.get(controller.attribute("outputs:out_0", unpack_vector_node)) self.assertAlmostEqual(out_0[0], test_input_1[0], places=3) self.assertAlmostEqual(out_0[1], test_input_1[1], places=3) self.assertAlmostEqual(out_0[2], test_input_1[2], places=3) # -------------------------------------------------------------------------------- async def test_type(self): """Tests creating nodes based on functions from many types.""" oga.AutoFunc(module_name="__test__")(dbl_to_matd)
13,001
Python
35.318436
120
0.535497
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_general.py
# noqa: PLC0302 """Basic tests of the compute graph""" import os import tempfile import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands from pxr import Gf, OmniGraphSchemaTools, Sdf # ====================================================================== class SimpleGraph: def __init__(self): self.graph = None self.input_prim = None self.simple_node = None self.cube_prim = None # ====================================================================== def create_simple_graph(stage): """Create a scene containing an Xform prim, a Cube, and a PushGraph with a SimpleNode.""" scene = SimpleGraph() # create nodes path = omni.usd.get_stage_next_free_path(stage, "/" + "InputPrim", True) scene.input_prim = stage.DefinePrim(path, "Xform") scene.input_prim.CreateAttribute("value", Sdf.ValueTypeNames.Float).Set(0.5) (scene.graph, nodes, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [("SimpleNode", "omni.graph.examples.cpp.Simple")], og.Controller.Keys.SET_VALUES: [("SimpleNode.inputs:multiplier", 3.0), ("SimpleNode.inputs:value", 1.0)], }, ) scene.simple_node = og.Controller.prim(nodes[0]) path = omni.usd.get_stage_next_free_path(stage, "/" + "Cube", True) scene.cube_prim = stage.DefinePrim(path, "Cube") scene.cube_prim.CreateAttribute("size", Sdf.ValueTypeNames.Double).Set(2.0) return scene class TestOmniGraphGeneral(ogts.OmniGraphTestCase): # ---------------------------------------------------------------------- async def test_graph_load(self): """Test state after a simple graph is loaded from a file""" await og.load_example_file("ExampleCube.usda") # These nodes are known to be in the file self.assertFalse(ogts.verify_node_existence(["/World/graph/NoOp"])) # ---------------------------------------------------------------------- async def test_graph_creation(self): """Test state after manually creating a simple graph""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() scene = create_simple_graph(stage) self.assertIsNotNone(scene, "Failed to create a simple graph") self.assertIsNotNone(scene.input_prim, "Failed to create input primitive in simple graph") self.assertIsNotNone(scene.simple_node, "Failed to create simple node in simple graph") self.assertIsNotNone(scene.cube_prim, "Failed to create cube primitive in simple graph") await omni.kit.app.get_app().next_update_async() ogts.dump_graph() # Verify that the simple_node prim belongs to an actual OG node in the graph. node_prims = [og.Controller.prim(node) for node in scene.graph.get_nodes()] self.assertTrue(scene.simple_node in node_prims) # ---------------------------------------------------------------------- async def test_graph_disable(self): """Exercise disabling a graph""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() scene = create_simple_graph(stage) controller = og.Controller() graph = scene.graph simple_node = og.get_node_by_path(scene.simple_node.GetPath().pathString) multiplier_attr = simple_node.get_attribute("inputs:multiplier") in_value_attr = simple_node.get_attribute("inputs:value") out_value_attr = simple_node.get_attribute("outputs:value") # set some values on simple node multiplier_attr.set(2) in_value_attr.set(3) # test the graph works await controller.evaluate() self.assertEqual(out_value_attr.get(), 6) # test the graph works with an update multiplier_attr.set(3) await controller.evaluate() self.assertEqual(out_value_attr.get(), 9) # disable the graph graph.set_disabled(True) # test the graph stopped taking into account updates multiplier_attr.set(4) await controller.evaluate() self.assertEqual(out_value_attr.get(), 9) # re-enable the graph graph.set_disabled(False) # value should now update await controller.evaluate() self.assertEqual(out_value_attr.get(), 12) # ---------------------------------------------------------------------- async def test_usd_update_settings(self): """ Basic idea of test: here we test the USD write back policy of OmniGraph under normal circumstances. We get the USD prim that is backing an intermediate node, and test all possible settings against it to make sure it is updating only when expected. """ (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) usd_context = omni.usd.get_context() stage = usd_context.get_stage() subtract_node_prim = stage.GetPrimAtPath("/World/moveX/subtract") output_usd_attr = subtract_node_prim.GetAttribute("outputs:out") # test that there is no change in the intermediate USD value: # ------------------------------------------ t0 = output_usd_attr.Get() await omni.kit.app.get_app().next_update_async() t1 = output_usd_attr.Get() diff = abs(t1 - t0) self.assertAlmostEqual(diff, 0.0, places=3) # ---------------------------------------------------------------------- async def test_reload_from_stage(self): # The basic idea of the test is as follows: # We load up the TestTranslatingCube.usda file, which has a cube # that continually moves in X. We make sure first the # node is working, and then we reload the graph from the stage. Once we do # that, we make sure that the graph is still working - make sure the cube still moves (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) usd_context = omni.usd.get_context() stage = usd_context.get_stage() # make sure the box and the attribute we expect are there. graph = og.get_graph_by_path("/World/moveX") cube_prim = stage.GetPrimAtPath("/World/Cube") translate_attr = cube_prim.GetAttribute("xformOp:translate") self.assertTrue(translate_attr.IsValid()) # get the initial position of the cube translate = translate_attr.Get() t0 = translate[0] # wait 1 frame await omni.kit.app.get_app().next_update_async() # get the updated cube position and make sure it moved translate = translate_attr.Get() t1 = translate[0] diff = abs(t1 - t0) self.assertGreater(diff, 0.1) # subtract_node = graph.get_node("/World/moveX/subtract") # node_handle = subtract_node.get_handle() # now reload the graph and make sure the node has a new handle (showing that it's been deleted and recreated) # and that everything still works. graph.reload_from_stage() # Note that we have to re-fetch a lot of the constructs, as those would have been destroyed and recreated during # the graph reload process: # subtract_node = graph.get_node("/World/moveX/subtract") # new_node_handle = subtract_node.get_handle() # Almost certainly the new handle will not be the same as the old one, but we're not doing the check here # because it possibly could be the same, and that could lead to flaky test. # self.assertTrue(new_node_handle != node_handle) cube_prim = stage.GetPrimAtPath("/World/Cube") translate_attr = cube_prim.GetAttribute("xformOp:translate") self.assertTrue(translate_attr.IsValid()) # get the initial position of the cube translate = translate_attr.Get() t0 = translate[0] # wait 1 frame await omni.kit.app.get_app().next_update_async() # get the updated cube position and make sure it moved translate = translate_attr.Get() t1 = translate[0] diff = abs(t1 - t0) self.assertGreater(diff, 0.1) # ---------------------------------------------------------------------- async def test_reload_from_stage_retains_instances(self): """Validates that the reload from stage call will retain any instances that may be referencing the node""" graph_path = "/World/Graph" num_instances = 3 controller = og.Controller(update_usd=True) keys = controller.Keys # Simple graph that increments a counter attribute on the graph target # [ReadPrim]->[Add 1]->[WritePrim] (graph, _, _, nodes) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadPrim", "omni.graph.nodes.ReadPrimAttribute"), ("WritePrim", "omni.graph.nodes.WritePrimAttribute"), ("Add", "omni.graph.nodes.Add"), ("Constant", "omni.graph.nodes.ConstantDouble"), ("GraphTarget", "omni.graph.nodes.GetGraphTargetPrim"), ], keys.SET_VALUES: [ ("Constant.inputs:value", 1.0), ("ReadPrim.inputs:name", "counter"), ("WritePrim.inputs:name", "counter"), ], keys.CONNECT: [ ("GraphTarget.outputs:prim", "ReadPrim.inputs:prim"), ("GraphTarget.outputs:prim", "WritePrim.inputs:prim"), ("ReadPrim.outputs:value", "Add.inputs:a"), ("Constant.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "WritePrim.inputs:value"), ], }, ) # create instances for i in range(0, num_instances): prim_name = f"/World/Prim_{i}" prim = omni.usd.get_context().get_stage().DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(omni.usd.get_context().get_stage(), prim_name, graph_path) prim.CreateAttribute("counter", Sdf.ValueTypeNames.Int).Set(0) await controller.evaluate() await omni.kit.app.get_app().next_update_async() # capture the existing values attr = nodes["Add"].get_attribute("outputs:sum") values = [] for i in range(0, num_instances): values.append(attr.get(instance=i)) attr_path = attr.get_path() # reload the graph here. Note this will invalidate any handles to og objects (except the graph) graph.reload_from_stage() # reevaluate await controller.evaluate() await omni.kit.app.get_app().next_update_async() attr = og.Controller.attribute(attr_path) # validate the values have been updated for i in range(0, num_instances): self.assertGreater(attr.get(instance=i), values[i]) # ---------------------------------------------------------------------- async def test_invalid_graph_objects(self): # The basic idea of the test is as follows: # Often the graph constructs like node, attribute, graph etc. will outlive their python wrapers. # Accessing these deleted things will lead to a crash. We have put in measures to prevent things # from crashing, even if the underlying objects have been destroyed. This test tries out these # scenarios. This test also tests the deletion of global graphs, by deleting the corresponding # wrapper node in the orchestration graph (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = og.Controller.graph("/World/moveX") # make sure the box and the attribute we expect are there. context = graph.get_default_graph_context() subtract_node = graph.get_node("/World/moveX/subtract") output_attr = subtract_node.get_attribute("outputs:out") self.assertTrue(output_attr.is_valid()) self.assertTrue(subtract_node.is_valid()) graph.destroy_node("/World/moveX/subtract", True) self.assertFalse(subtract_node.is_valid()) self.assertFalse(output_attr.is_valid()) self.assertTrue(context.is_valid()) self.assertTrue(graph.is_valid()) orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage( og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION ) self.assertEqual(len(orchestration_graphs), 1) orchestration_graph = orchestration_graphs[0] global_graph_nodes = orchestration_graph.get_nodes() self.assertTrue(len(global_graph_nodes) == 1) global_implicit_graph_node = global_graph_nodes[0] orchestration_graph.destroy_node(global_graph_nodes[0].get_prim_path(), False) self.assertFalse(global_implicit_graph_node.is_valid()) self.assertFalse(context.is_valid()) self.assertFalse(graph.is_valid()) # Do not use something like new stage to destroy the objects and assert invalidity. This can cause # a race condition where the destruction of the existing stuff on the stage is not complete when # the new stage is ready # await omni.usd.get_context().new_stage_async() # self.assertFalse(context.is_valid()) # self.assertFalse(graph.is_valid()) # self.assertFalse(output_attr.is_valid()) # ---------------------------------------------------------------------- async def test_memory_type_and_optional_keywords(self): """Test the persistence of the memoryType and optional keyword values in .ogn nodes""" controller = og.Controller() keys = og.Controller.Keys # Create some nodes with known memoryType and optional values # # C++ Nodes # omni.graph.tutorials.CpuGpuData # node memory type = any # inputs:is_gpu memory type = cpu # inputs:a memory type = any (inherited from node) # omni.graph.tutorials.CudaData # node memory type = cuda # inputs:a memory type = cuda (inherited from node) # inputs:multiplier memory type = cpu # omni.graph.nodes.CopyAttr # inputs:fullData optional = false # inputs:partialData optional = true # # Python Nodes # omni.graph.tutorials.CpuGpuExtendedPy # node memory type = cpu # inputs:cpuData memory type = any # inputs:gpu memory type = cpu (inherited from node) # omni.graph.test.PerturbPointsGpu # node memory type = cuda # inputs:percentModified memory type = cpu # inputs:minimum memory type = cuda (inherited from node) # omni.graph.tutorials.TutorialSimpleDataPy # inputs:a_bool optional = true # inputs:a_half optional = false ( _, ( cpu_gpu_node, cuda_node, optional_node, cpu_gpu_py_node, cuda_py_node, optional_py_node, ), _, _, ) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("CpuGpu", "omni.graph.tutorials.CpuGpuData"), ("Cuda", "omni.graph.tutorials.CudaData"), ("Optional", "omni.graph.nodes.CopyAttribute"), ("CpuGpuPy", "omni.graph.tutorials.CpuGpuBundlesPy"), ("CudaPy", "omni.graph.test.PerturbPointsGpu"), ("OptionalPy", "omni.graph.tutorials.SimpleDataPy"), ] }, ) memory_type_key = ogn.MetadataKeys.MEMORY_TYPE self.assertEqual(cpu_gpu_node.get_node_type().get_metadata(memory_type_key), ogn.MemoryTypeValues.ANY) is_gpu_attr = cpu_gpu_node.get_attribute("inputs:is_gpu") self.assertEqual(is_gpu_attr.get_metadata(memory_type_key), ogn.MemoryTypeValues.CPU) a_attr = cpu_gpu_node.get_attribute("inputs:a") self.assertEqual(a_attr.get_metadata(memory_type_key), None) self.assertEqual(cuda_node.get_node_type().get_metadata(memory_type_key), ogn.MemoryTypeValues.CUDA) multiplier_attr = cuda_node.get_attribute("inputs:multiplier") self.assertEqual(multiplier_attr.get_metadata(memory_type_key), ogn.MemoryTypeValues.CPU) a_attr = cuda_node.get_attribute("inputs:a") self.assertEqual(a_attr.get_metadata(memory_type_key), None) self.assertEqual(optional_node.get_node_type().get_metadata(memory_type_key), None) full_data_attr = optional_node.get_attribute("inputs:fullData") self.assertFalse(full_data_attr.is_optional_for_compute) partial_data_attr = optional_node.get_attribute("inputs:partialData") self.assertTrue(partial_data_attr.is_optional_for_compute) self.assertEqual(cpu_gpu_py_node.get_node_type().get_metadata(memory_type_key), None) gpu_attr = cpu_gpu_py_node.get_attribute("inputs:cpuBundle") self.assertEqual(gpu_attr.get_metadata(memory_type_key), None) cpu_data_attr = cpu_gpu_py_node.get_attribute("inputs:gpuBundle") self.assertEqual(cpu_data_attr.get_metadata(memory_type_key), ogn.MemoryTypeValues.CUDA) cpu_data_attr = cpu_gpu_py_node.get_attribute("outputs_cpuGpuBundle") self.assertEqual(cpu_data_attr.get_metadata(memory_type_key), ogn.MemoryTypeValues.ANY) self.assertEqual(cuda_py_node.get_node_type().get_metadata(memory_type_key), ogn.MemoryTypeValues.CUDA) percent_attr = cuda_py_node.get_attribute("inputs:percentModified") self.assertEqual(percent_attr.get_metadata(memory_type_key), ogn.MemoryTypeValues.CPU) minimum_attr = cuda_py_node.get_attribute("inputs:minimum") self.assertEqual(minimum_attr.get_metadata(memory_type_key), None) self.assertEqual(optional_py_node.get_node_type().get_metadata(memory_type_key), None) a_half_attr = optional_py_node.get_attribute("inputs:a_half") self.assertEqual(a_half_attr.is_optional_for_compute, False) a_bool_attr = optional_py_node.get_attribute("inputs:a_bool") self.assertEqual(a_bool_attr.is_optional_for_compute, True) # Check that the three methods of getting Cpu pointers to Gpu data give the same answer # Method 1: Directly from the attribute value helper data_view = og.AttributeValueHelper(cuda_node.get_attribute("outputs:points")) data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU data_view_data = data_view.get(on_gpu=True) # Method 2: From the controller class get() method controller_data = og.Controller.get( cuda_node.get_attribute("outputs:points"), on_gpu=True, gpu_ptr_kind=og.PtrToPtrKind.CPU ) self.assertEqual(data_view_data.memory, controller_data.memory) # Method 3: From the controller object get() method controller = og.Controller(cuda_node.get_attribute("outputs:points")) controller.gpu_ptr_kind = og.PtrToPtrKind.CPU controller_data = controller.get(on_gpu=True) self.assertEqual(data_view_data.memory, controller_data.memory) # ---------------------------------------------------------------------- async def test_equality_comparisons(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() scene = create_simple_graph(stage) graph = scene.graph # Nodes simple_node = og.get_node_by_path(scene.simple_node.GetPath().pathString) self.assertEqual(simple_node, simple_node) self.assertNotEqual(simple_node, None) simple_node2 = graph.get_node(simple_node.get_prim_path()) self.assertEqual(simple_node, simple_node2) cube_node = og.get_node_by_path(scene.cube_prim.GetPath().pathString) self.assertNotEqual(simple_node, cube_node) # TODO: These emit intentional error messages which the build # framework picks up as test failures. Need to find another # way to test this. # # bad_node = graph.get_node('bad_node') # bad_node2 = graph.get_node('bad_node2') # self.assertNotEqual(simple_node, bad_node) # self.assertEqual(bad_node, bad_node2) # Graphs self.assertEqual(graph, graph) self.assertNotEqual(graph, None) graph2 = simple_node.get_graph() self.assertEqual(graph, graph2) # TODO: These emit intentional error messages which the build # framework picks up as test failures. Need to find another # way to test this. # # bad_graph = bad_node.get_graph() # bad_graph2 = bad_node2.get_graph() # self.assertNotEqual(graph, bad_graph) # self.assertEqual(bad_graph, bad_graph2) # Attributes multiplier_attr = simple_node.get_attribute("inputs:multiplier") self.assertEqual(multiplier_attr, multiplier_attr) self.assertNotEqual(multiplier_attr, None) multiplier_attr2 = simple_node.get_attribute("inputs:multiplier") self.assertEqual(multiplier_attr, multiplier_attr2) value_attr = simple_node.get_attribute("inputs:value") self.assertNotEqual(multiplier_attr, value_attr) # TODO: These emit intentional error messages which the build # framework picks up as test failures. Need to find another # way to test this. # # bad_attr = bad_node.get_attribute('bad_attr') # bad_attr2 = bad_node.get_attribute('bad_attr2') # self.assertNotEqual(multiplier_attr, bad_attr) # self.assertEqual(bad_attr, bad_attr2) # AttributeData mult_data = multiplier_attr.get_attribute_data() self.assertEqual(mult_data, mult_data) self.assertNotEqual(mult_data, None) mult_data2 = multiplier_attr.get_attribute_data() self.assertEqual(mult_data, mult_data2) value_data = value_attr.get_attribute_data() self.assertNotEqual(mult_data, value_data) # Types t1 = og.Type(og.INT, 2, 1, og.COLOR) same_as_t1 = og.Type(og.INT, 2, 1, og.COLOR) t2 = og.Type(og.FLOAT, 2, 1, og.COLOR) t3 = og.Type(og.INT, 3, 1, og.COLOR) t4 = og.Type(og.INT, 2, 0, og.COLOR) t5 = og.Type(og.INT, 2, 1, og.POSITION) self.assertEqual(t1, t1) self.assertNotEqual(t1, None) self.assertEqual(t1, same_as_t1) self.assertNotEqual(t1, t2) self.assertNotEqual(t1, t3) self.assertNotEqual(t1, t4) self.assertNotEqual(t1, t5) # ---------------------------------------------------------------------- async def test_hashability(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() scene = create_simple_graph(stage) graph = scene.graph # Nodes simple_node = og.get_node_by_path(scene.simple_node.GetPath().pathString) simple_node2 = graph.get_node(simple_node.get_prim_path()) cube_node = og.get_node_by_path(scene.cube_prim.GetPath().pathString) d = {simple_node: 1, cube_node: 2, simple_node2: 3} self.assertEqual(len(d), 2) self.assertEqual(d[simple_node], 3) # Graphs graph2 = simple_node.get_graph() d = {graph: -3, graph2: -17} self.assertEqual(len(d), 1) self.assertEqual(d[graph], -17) # Attributes multiplier_attr = simple_node.get_attribute("inputs:multiplier") multiplier_attr2 = simple_node.get_attribute("inputs:multiplier") value_attr = simple_node.get_attribute("inputs:value") d = {multiplier_attr: 5, value_attr: 6, multiplier_attr2: 7} self.assertEqual(len(d), 2) self.assertEqual(d[multiplier_attr], 7) # AttributeData mult_data = multiplier_attr.get_attribute_data() mult_data2 = multiplier_attr.get_attribute_data() value_data = value_attr.get_attribute_data() d = {mult_data: 8, value_data: 9, mult_data2: 10} self.assertEqual(len(d), 2) self.assertEqual(d[mult_data], 10) # Types t1 = og.Type(og.INT, 2, 1, og.COLOR) same_as_t1 = og.Type(og.INT, 2, 1, og.COLOR) t2 = og.Type(og.FLOAT, 2, 1, og.COLOR) t3 = og.Type(og.INT, 3, 1, og.COLOR) t4 = og.Type(og.INT, 2, 0, og.COLOR) t5 = og.Type(og.INT, 2, 1, og.POSITION) d = {t1: 1, t2: 2, t3: 3, t4: 5, t5: 6, same_as_t1: 4} self.assertEqual(len(d), 5) self.assertEqual(d[t1], 4) # ---------------------------------------------------------------------- async def test_dirty_push_time_change(self): """Test that dirty_push evaluator dirties the time node when time changes""" controller = og.Controller() (_, (read_time, sub), _, _) = controller.edit( {"graph_path": "/World/TestGraph", "evaluator_name": "dirty_push"}, { og.Controller.Keys.CREATE_NODES: [ ("ReadTime", "omni.graph.nodes.ReadTime"), ("Sub", "omni.graph.test.SubtractDoubleC"), ], og.Controller.Keys.CONNECT: [ ("ReadTime.outputs:frame", "Sub.inputs:a"), ("ReadTime.outputs:frame", "Sub.inputs:b"), ], }, ) await controller.evaluate() # Verify when anim time does not change, the downstream node does not compute cc_0 = sub.get_compute_count() await omni.kit.app.get_app().next_update_async() cc_1 = sub.get_compute_count() # FIXME: OM-45551: Assert fails due to a bug in the lazy evaluator # self.assertEqual(cc_0, cc_1) # Verify when anim time DOES change, the downstream node DOES compute time_out = controller.attribute("outputs:time", read_time) # Start playback timeline = omni.timeline.get_timeline_interface() timeline.set_start_time(1.0) timeline.set_end_time(10.0) timeline.set_target_framerate(timeline.get_time_codes_per_seconds()) timeline.play() # One update and record start values await omni.kit.app.get_app().next_update_async() cc_0 = sub.get_compute_count() t_0 = og.Controller.get(time_out) self.assertAlmostEqual(t_0, 1.0, places=1) # One update and compare values await omni.kit.app.get_app().next_update_async() cc_1 = sub.get_compute_count() t_1 = og.Controller.get(time_out) self.assertGreater(t_1, t_0) self.assertEqual(cc_1, cc_0 + 1) # ---------------------------------------------------------------------- async def test_attribute_deprecation(self): """Test the attribute deprecation API.""" controller = og.Controller() (_, nodes, _, _) = controller.edit( {"graph_path": "/World/TestGraph", "evaluator_name": "dirty_push"}, { og.Controller.Keys.CREATE_NODES: [ ("cpp_node1", "omni.graph.test.ComputeErrorCpp"), ("cpp_node2", "omni.graph.test.ComputeErrorCpp"), ("py_node1", "omni.graph.test.ComputeErrorPy"), ("py_node2", "omni.graph.test.ComputeErrorPy"), ] }, ) for node in nodes: deprecated_in_ogn = node.get_attribute("inputs:deprecatedInOgn") self.assertTrue(deprecated_in_ogn.is_deprecated()) self.assertEqual(deprecated_in_ogn.deprecation_message(), "Use 'dummyIn' instead.") deprecated_in_init = node.get_attribute("inputs:deprecatedInInit") self.assertTrue(deprecated_in_init.is_deprecated()) self.assertEqual(deprecated_in_init.deprecation_message(), "Use 'dummyIn' instead.") dummy_in = node.get_attribute("inputs:dummyIn") self.assertFalse(dummy_in.is_deprecated()) self.assertEqual(dummy_in.deprecation_message(), "") # Deprecate the dummyIn attr. og._internal.deprecate_attribute(dummy_in, "Deprecated on the fly.") # noqa: PLW0212 self.assertTrue(dummy_in.is_deprecated()) self.assertEqual(dummy_in.deprecation_message(), "Deprecated on the fly.") # ---------------------------------------------------------------------- async def test_minimal_population(self): """Test that when fabric minimal population is enabled, that we still initialize graphs properly. See OM-108844 for more details""" controller = og.Controller() (_, nodes, _, _) = controller.edit( {"graph_path": "/World/TestGraph"}, { og.Controller.Keys.CREATE_NODES: [ ("find_prims", "omni.graph.nodes.FindPrims"), ] }, ) await controller.evaluate() self.assertEqual(nodes[0].get_attribute("inputs:type").get(), "*") with tempfile.TemporaryDirectory() as test_directory: # Need to set the default prim, otherwise creating a reference/payload to this file will cause an error stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.GetPrimAtPath("/World")) tmp_file_path = os.path.join(test_directory, "tmp_test_minimal_population.usda") await omni.usd.get_context().save_as_stage_async(tmp_file_path) # Run a usdrt query to ensure that fabric minimal population is enabled from usdrt import Usd as UsdRtUsd usdrt_stage = UsdRtUsd.Stage.Attach(omni.usd.get_context().get_stage_id()) self.assertEqual(usdrt_stage.GetPrimsWithTypeName("OmniGraph"), ["/World/TestGraph"]) # Test adding as payload await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() # Run a usdrt query to ensure that fabric minimal population is enabled from usdrt import Usd as UsdRtUsd usdrt_stage = UsdRtUsd.Stage.Attach(omni.usd.get_context().get_stage_id()) self.assertEqual(usdrt_stage.GetPrimsWithTypeName("OmniGraph"), []) stage = omni.usd.get_context().get_stage() payload = stage.DefinePrim("/payload") payload.GetPayloads().AddPayload(tmp_file_path) await omni.kit.app.get_app().next_update_async() node = controller.node("/payload/TestGraph/find_prims") self.assertEqual(node.get_attribute("inputs:type").get(), "*") # Test adding as reference await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() stage = omni.usd.get_context().get_stage() ref = stage.DefinePrim("/ref") ref.GetReferences().AddReference(tmp_file_path) await omni.kit.app.get_app().next_update_async() node = controller.node("/ref/TestGraph/find_prims") self.assertEqual(node.get_attribute("inputs:type").get(), "*") # =================================================================== class TestOmniGraphSimpleMisc(ogts.OmniGraphTestCase): """Misc tests that issue expected errors functionality""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__cb_count = 0 self.__error_node = None async def test_compute_messages(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() scene = create_simple_graph(stage) graph = scene.graph graph.set_disabled(True) # to ensure "compute" messages are managed only by hand in the first tests node = og.get_node_by_path(scene.simple_node.GetPath().pathString) # A new node should start with no messages. self.assertEqual(len(node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(node.get_compute_messages(og.WARNING)), 0) self.assertEqual(len(node.get_compute_messages(og.ERROR)), 0) # Check counts. msg1 = "Ignore this error/warning message #1" msg2 = "Ignore this error/warning message #2" msg3 = "Ignore this error/warning message #3" node.log_compute_message(og.INFO, msg1) node.log_compute_message(og.WARNING, msg1) node.log_compute_message(og.WARNING, msg2) self.assertEqual(len(node.get_compute_messages(og.INFO)), 1) self.assertEqual(len(node.get_compute_messages(og.WARNING)), 2) # Check that logging detects duplicates. self.assertFalse(node.log_compute_message(og.ERROR, msg2)) self.assertFalse(node.log_compute_message(og.ERROR, msg1)) self.assertTrue(node.log_compute_message(og.ERROR, msg2)) # Check that duplicates are only recorded once per severity level. msgs = node.get_compute_messages(og.ERROR) self.assertEqual(len(msgs), 2) # Check message retrieval. Note that while the current implementation # does preserve the order in which the messages were issued, that's # not a requirement, so we only test that we get each message back once. counts = {msg1: 0, msg2: 0} for msg in msgs: # The logging ABI adds context information to the message so we can't # do an exact comparison with our original, only that the logged message # contains our original. if msg.find(msg1) != -1: counts[msg1] += 1 elif msg.find(msg2) != -1: counts[msg2] += 1 self.assertEqual(list(counts.values()).count(1), 2) # Repeat a message at a new compute count and make sure the message # count hasn't changed. await omni.kit.app.get_app().next_update_async() self.assertTrue(node.log_compute_message(og.ERROR, msg1)) self.assertEqual(len(node.get_compute_messages(og.ERROR)), 2) # Add a new (non-repeated) message at the new compute count. self.assertFalse(node.log_compute_message(og.ERROR, msg3)) # If we clear old messages all but the one we just repeated and # the one just added should be removed. self.assertEqual(node.clear_old_compute_messages(), 4) self.assertEqual(len(node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(node.get_compute_messages(og.WARNING)), 0) self.assertEqual(len(node.get_compute_messages(og.ERROR)), 2) # Clear everything. await omni.kit.app.get_app().next_update_async() self.assertEqual(node.clear_old_compute_messages(), 2) self.assertEqual(len(node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(node.get_compute_messages(og.WARNING)), 0) self.assertEqual(len(node.get_compute_messages(og.ERROR)), 0) # Ensure it still all works after clearing. self.assertFalse(node.log_compute_message(og.ERROR, msg1)) self.assertEqual(len(node.get_compute_messages(og.ERROR)), 1) self.assertTrue(node.get_compute_messages(og.ERROR)[0].find(msg1) != -1) # Test with nodes which will generate messages during compute. graph.set_disabled(False) for node_name, node_type in [ ("CppErrorNode", "omni.graph.test.ComputeErrorCpp"), ("PyErrorNode", "omni.graph.test.ComputeErrorPy"), ]: (_, nodes, _, _) = og.Controller.edit(graph, {og.Controller.Keys.CREATE_NODES: [(node_name, node_type)]}) self.assertEqual(len(nodes), 1) self.__error_node = nodes[0] # It should start with no messages. self.assertEqual(len(self.__error_node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.WARNING)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.ERROR)), 0) # Set it to generate a warning. severity_attr = self.__error_node.get_attribute("inputs:severity") message_attr = self.__error_node.get_attribute("inputs:message") msg4 = "Ignore this error/warning message #4" message_attr.set(msg4) severity_attr.set("warning") # There should be no warning yet since the node has not evaluated. self.assertEqual(len(self.__error_node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.WARNING)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.ERROR)), 0) # Evaluate the graph and check again. await omni.kit.app.get_app().next_update_async() self.assertEqual(len(self.__error_node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.ERROR)), 0) msgs = self.__error_node.get_compute_messages(og.WARNING) self.assertEqual(len(msgs), 1) self.assertTrue(msgs[0].find(msg4) != -1) # Have it issue a different error message. After evaluation we should only # have the error not the warning. msg5 = "Ignore this error/warning message #5" message_attr.set(msg5) severity_attr.set("error") await omni.kit.app.get_app().next_update_async() self.assertEqual(len(self.__error_node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.WARNING)), 0) msgs = self.__error_node.get_compute_messages(og.ERROR) self.assertEqual(len(msgs), 1) self.assertTrue(msgs[0].find(msg5) != -1) # Stop the node generating errors. After the next evaluate there # should be no messages. severity_attr.set("none") await omni.kit.app.get_app().next_update_async() self.assertEqual(len(self.__error_node.get_compute_messages(og.INFO)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.WARNING)), 0) self.assertEqual(len(self.__error_node.get_compute_messages(og.ERROR)), 0) # Set up a callback for changes in the node's error status. self.__cb_count = 0 def error_status_changed(nodes, graph): self.assertEqual(len(nodes), 1) self.assertEqual(nodes[0], self.__error_node) self.__cb_count += 1 cb = graph.register_error_status_change_callback(error_status_changed) # There are currently no errors so the callback should not get # called. await omni.kit.app.get_app().next_update_async() self.assertEqual(self.__cb_count, 0) # Setting a warning message should call the callback. message_attr.set(msg4) severity_attr.set("warning") await omni.kit.app.get_app().next_update_async() self.assertEqual(self.__cb_count, 1) # Converting the warning to an error should call the callback. severity_attr.set("error") await omni.kit.app.get_app().next_update_async() self.assertEqual(self.__cb_count, 2) # Setting the same message again should not call the callback. await omni.kit.app.get_app().next_update_async() self.assertEqual(self.__cb_count, 2) # A clean compute should clear the message and call the callback. severity_attr.set("none") await omni.kit.app.get_app().next_update_async() self.assertEqual(self.__cb_count, 3) # No more messages so further evaluations should not call the callback. await omni.kit.app.get_app().next_update_async() self.assertEqual(self.__cb_count, 3) graph.deregister_error_status_change_callback(cb) async def test_write_to_backing(self): """Test the GraphContext.write_to_backing functionality""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() (graph, (constant_string,), _, path_to_object_map) = og.Controller.edit( "/Root", { og.Controller.Keys.CREATE_NODES: [ ("ConstantString", "omni.graph.nodes.ConstantString"), ], }, ) controller = og.Controller(path_to_object_map=path_to_object_map, update_usd=False) (graph, _, _, _) = controller.edit( graph, { og.Controller.Keys.SET_VALUES: [ ("ConstantString.inputs:value", "foo"), ], }, ) string_attrib = controller.attribute("inputs:value", constant_string) string_usd_attrib = stage.GetAttributeAtPath(string_attrib.get_path()) self.assertEqual("foo", controller.get(string_attrib)) self.assertEqual(None, string_usd_attrib.Get()) # flush to USD and verify the USD attrib value has changed bucket_id = constant_string.get_backing_bucket_id() graph.get_default_graph_context().write_bucket_to_backing(bucket_id) self.assertEqual("foo", string_usd_attrib.Get()) # Verify changing OG attribute does not change USD attrib string_attrib.set("bar") await controller.evaluate() self.assertEqual("bar", controller.get(string_attrib)) self.assertEqual("foo", string_usd_attrib.Get()) # flush to USD and verify the USD attrib value has changed graph.get_default_graph_context().write_bucket_to_backing(bucket_id) self.assertEqual("bar", controller.get(string_attrib)) self.assertEqual("bar", string_usd_attrib.Get()) # verify invalid bucket raises # FC issues: getNamesAndTypes, bucketId 42 not found with ogts.ExpectedError(): with self.assertRaises(ValueError): bad_bucket_id = og.BucketId(42) graph.get_default_graph_context().write_bucket_to_backing(bad_bucket_id) controller.edit("/Root", {og.Controller.Keys.DELETE_NODES: "ConstantString"}) with self.assertRaises(ValueError): constant_string.get_backing_bucket_id() async def test_ogn_defaults(self): # tests that overriden attributes values persists after serialization # tests that non-overriden attributes values are set to OGN defaults, even after serialization stage = omni.usd.get_context().get_stage() (_, (data_node), _, _) = og.Controller.edit( "/World/Graph", {og.Controller.Keys.CREATE_NODES: [("TupleData", "omni.tutorials.TupleData")]} ) self.assertTrue((data_node[0].get_attribute("inputs:a_double3").get() == [1.1, 2.2, 3.3]).all()) # we don't have any value in USD node_prim = stage.GetPrimAtPath("/World/Graph/TupleData") usd_attrib = node_prim.GetAttribute("inputs:a_double3").Get() self.assertTrue(usd_attrib is None) # set runtime only data_node[0].get_attribute("inputs:a_double3").set([16.0, 17.0, 18.0]) self.assertTrue((data_node[0].get_attribute("inputs:a_double3").get() == [16.0, 17.0, 18.0]).all()) # does not affect USD usd_attrib = node_prim.GetAttribute("inputs:a_double3").Get() self.assertTrue(usd_attrib is None) # save and reload with tempfile.TemporaryDirectory() as test_directory: tmp_file_path = os.path.join(test_directory, "tmp_test_ogn_defaults.usda") (result, error, _) = await omni.usd.get_context().save_as_stage_async(str(tmp_file_path)) self.assertTrue(result, error) (result, error) = await omni.usd.get_context().open_stage_async(tmp_file_path) self.assertTrue(result, error) stage = omni.usd.get_context().get_stage() node_prim = stage.GetPrimAtPath("/World/Graph/TupleData") # still no usd value usd_attrib = node_prim.GetAttribute("inputs:a_double3").Get() self.assertTrue(usd_attrib is None) # we have the default OGN values in OG attr = og.Controller.attribute("/World/Graph/TupleData/inputs:a_double3") self.assertTrue((attr.get() == [1.1, 2.2, 3.3]).all()) # replace the node with something else in order to test a different default interface = ogu.get_node_type_forwarding_interface() try: self.assertTrue( interface.define_forward( "omni.tutorials.TupleData", 1, "omni.tests.FakeTupleData", 1, "omni.graph.test" ) ) # save and reload with tempfile.TemporaryDirectory() as test_directory: tmp_file_path = os.path.join(test_directory, "tmp_test_ogn_defaults.usda") (result, error, _) = await omni.usd.get_context().save_as_stage_async(str(tmp_file_path)) self.assertTrue(result, error) (result, error) = await omni.usd.get_context().open_stage_async(tmp_file_path) self.assertTrue(result, error) stage = omni.usd.get_context().get_stage() node_prim = stage.GetPrimAtPath("/World/Graph/TupleData") # still no usd value usd_attrib = node_prim.GetAttribute("inputs:a_double3").Get() self.assertTrue(usd_attrib is None) # we have now the new "fake" default OGN values in OG attr = og.Controller.attribute("/World/Graph/TupleData/inputs:a_double3") self.assertTrue((attr.get() == [4.5, 6.7, 8.9]).all()) # set USD node_prim.GetAttribute("inputs:a_double3").Set(Gf.Vec3f(6.0, 7.0, 8.0)) self.assertTrue((attr.get() == [6.0, 7.0, 8.0]).all()) # save and reload with tempfile.TemporaryDirectory() as test_directory: tmp_file_path = os.path.join(test_directory, "tmp_test_ogn_defaults.usda") (result, error, _) = await omni.usd.get_context().save_as_stage_async(str(tmp_file_path)) self.assertTrue(result, error) (result, error) = await omni.usd.get_context().open_stage_async(tmp_file_path) self.assertTrue(result, error) # it should has now persisted stage = omni.usd.get_context().get_stage() node_prim = stage.GetPrimAtPath("/World/Graph/TupleData") self.assertTrue(node_prim.GetAttribute("inputs:a_double3").Get() == [6.0, 7.0, 8.0]) # ...and proper OG values attr = og.Controller.attribute("/World/Graph/TupleData/inputs:a_double3") self.assertTrue((attr.get() == [6.0, 7.0, 8.0]).all()) finally: interface.remove_forwarded_type("omni.tests.FakeTupleData", 1) # ====================================================================== class TestOmniGraphSimpleSchema(ogts.OmniGraphTestCaseNoClear): """Test basic schema-based graph functionality""" # ---------------------------------------------------------------------- async def test_node_duplication(self): """Test that duplication of an OmniGraph node copies the values correctly""" controller = og.Controller() (_, (node, py_node), _, _) = controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: [ ("SimpleData", "omni.graph.tutorials.SimpleData"), ("SimpleDataPy", "omni.graph.tutorials.SimpleDataPy"), ], og.Controller.Keys.SET_VALUES: [ ("SimpleData.inputs:a_string", "Not The Default"), ("SimpleData.inputs:a_constant_input", 17), ("SimpleData.inputs:a_double", 3.25), ("SimpleDataPy.inputs:a_string", "Not The Default"), ("SimpleDataPy.inputs:a_constant_input", 17), ("SimpleDataPy.inputs:a_double", 3.25), ], }, ) await controller.evaluate() # Confirm that the value being set made it to USD stage = omni.usd.get_context().get_stage() original_prim = stage.GetPrimAtPath("/TestGraph/SimpleData") value = original_prim.GetAttribute("inputs:a_string").Get() self.assertEqual(value, og.Controller(("inputs:a_string", node)).get()) # Check that the original nodes have their values set properly self.assertEqual("Not The Default", og.Controller(("inputs:a_string", node)).get()) self.assertEqual(17, og.Controller(("inputs:a_constant_input", node)).get()) self.assertEqual(3.25, og.Controller(("inputs:a_double", node)).get()) self.assertEqual(True, og.Controller(("inputs:a_bool", node)).get()) self.assertEqual(0, og.Controller(("inputs:a_int", node)).get()) self.assertEqual("Not The Default", og.Controller(("inputs:a_string", py_node)).get()) self.assertEqual(17, og.Controller(("inputs:a_constant_input", py_node)).get()) self.assertEqual(3.25, og.Controller(("inputs:a_double", py_node)).get()) self.assertEqual(True, og.Controller(("inputs:a_bool", py_node)).get()) self.assertEqual(0, og.Controller(("inputs:a_int", py_node)).get()) # Duplicate the node omni.kit.commands.execute( "CopyPrims", paths_from=[str(node.get_prim_path()), str(py_node.get_prim_path())], paths_to=["/TestGraph/Duplicate", "/TestGraph/DuplicatePy"], ) await omni.kit.app.get_app().next_update_async() # Check that the duplicate has its values set to the ones supplied by the original node duplicate_node = controller.node("/TestGraph/Duplicate") self.assertIsNotNone(duplicate_node) self.assertTrue(duplicate_node.is_valid()) self.assertEqual("Not The Default", og.Controller(("inputs:a_string", duplicate_node)).get()) self.assertEqual(17, og.Controller(("inputs:a_constant_input", duplicate_node)).get()) self.assertEqual(3.25, og.Controller(("inputs:a_double", duplicate_node)).get()) self.assertEqual(True, og.Controller(("inputs:a_bool", duplicate_node)).get()) self.assertEqual(0, og.Controller(("inputs:a_int", duplicate_node)).get()) duplicate_py_node = controller.node("/TestGraph/DuplicatePy") self.assertIsNotNone(duplicate_py_node) self.assertTrue(duplicate_py_node.is_valid()) self.assertEqual("Not The Default", og.Controller(("inputs:a_string", duplicate_py_node)).get()) self.assertEqual(17, og.Controller(("inputs:a_constant_input", duplicate_py_node)).get()) self.assertEqual(3.25, og.Controller(("inputs:a_double", duplicate_py_node)).get()) self.assertEqual(True, og.Controller(("inputs:a_bool", duplicate_py_node)).get()) self.assertEqual(0, og.Controller(("inputs:a_int", duplicate_py_node)).get())
51,888
Python
45.082593
120
0.599715
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_instancing.py
""" Tests for omnigraph instancing """ import os import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from pxr import OmniGraphSchemaTools, Sdf # ====================================================================== class TestInstancing(ogts.OmniGraphTestCase): _graph_path = "/World/TestGraph" async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() timeline.set_fast_mode(True) # ---------------------------------------------------------------------- async def tick(self): timeline = omni.timeline.get_timeline_interface() timeline.play() await og.Controller.evaluate() timeline.stop() # ---------------------------------------------------------------------- async def test_instances_read_variables_from_instances(self): """Tests that variable instances are correctly read from the graph when evaluate_targets is called""" controller = og.Controller() keys = og.Controller.Keys # +---------------+ # | WritePrimAttr | # +------------+ | | # |ReadVariable|=======>|value | # +------------+ | | # | | # +------------+ | | # |ReadVariable|=======>|primPath | # +------------+ +---------------+ (_, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("ReadPrimName", "omni.graph.core.ReadVariable"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "WritePrimAttr.inputs:value"), ("ReadPrimName.outputs:value", "WritePrimAttr.inputs:primPath"), ], keys.CREATE_VARIABLES: [ ("float_var", og.Type(og.BaseDataType.FLOAT)), ("prim_name", og.Type(og.BaseDataType.TOKEN)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "float_var"), ("ReadPrimName.inputs:variableName", "prim_name"), ("WritePrimAttr.inputs:usePath", True), ("WritePrimAttr.inputs:name", "graph_output"), ], }, ) int_range = range(1, 100) stage = omni.usd.get_context().get_stage() for i in int_range: prim_name = f"/World/Prim_{i}" prim = stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self._graph_path) prim.CreateAttribute("graph:variable:float_var", Sdf.ValueTypeNames.Float).Set(float(i)) prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Float).Set(float(0)) prim.CreateAttribute("graph:variable:prim_name", Sdf.ValueTypeNames.Token).Set(prim_name) await self.tick() for i in int_range: prim_path = f"/World/Prim_{i}" val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get() self.assertEqual(val, i) # ---------------------------------------------------------------------- async def test_instancing_reports_graph_target(self): """Tests that graphs containing a node that uses the graph target reports the correct value """ controller = og.Controller() keys = og.Controller.Keys stage = omni.usd.get_context().get_stage() prims = [stage.DefinePrim(f"/prim_{i}") for i in range(1, 100)] for prim in prims: prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Token) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim.GetPath(), self._graph_path) # +----------------+ # +--------+===>|primPath | # | self | | writePrimAttr | # +--------+===>|value | # +----------------+ (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("GraphTarget", "omni.graph.nodes.GraphTarget"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("GraphTarget.outputs:primPath", "WritePrimAttr.inputs:value"), ("GraphTarget.outputs:primPath", "WritePrimAttr.inputs:primPath"), ], keys.SET_VALUES: [ ("WritePrimAttr.inputs:usePath", True), ("WritePrimAttr.inputs:name", "graph_output"), ], }, ) graph_prim = stage.GetPrimAtPath(self._graph_path) graph_prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Token) # validate calling get_graph_target outside of execution gives the graph path self.assertEqual(graph.get_default_graph_context().get_graph_target(), self._graph_path) # evaluate the graph, validate it returns the correct prim graph.evaluate() # evaluate the prims, validate the output write their own prim path await self.tick() for prim in prims: self.assertEqual(prim.GetAttribute("graph_output").Get(), str(prim.GetPath())) # ---------------------------------------------------------------------- async def test_instances_edits_apply(self): """Tests that changes to variable instances (USD) are applied to the graph immediately""" controller = og.Controller() keys = og.Controller.Keys int_range = range(1, 100) # +---------------+ # | WritePrimAttr | # +------------+ | | # |ReadVariable|=======>|value | # +------------+ | | # | | # +------------+ | | # |GraphTarget |=======>|primPath | # +------------+ +---------------+ with ogts.ExpectedError(): (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("GraphTarget", "omni.graph.nodes.GraphTarget"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "WritePrimAttr.inputs:value"), ("GraphTarget.outputs:primPath", "WritePrimAttr.inputs:primPath"), ], keys.CREATE_VARIABLES: [ ("float_var", og.Type(og.BaseDataType.FLOAT)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "float_var"), ("WritePrimAttr.inputs:usePath", True), ("WritePrimAttr.inputs:name", "graph_output"), ], }, ) stage = omni.usd.get_context().get_stage() # avoid an error because the graph gets run as well stage.GetPrimAtPath(self._graph_path).CreateAttribute("graph_output", Sdf.ValueTypeNames.Float).Set(float(0)) # create the instances, avoid the override for i in int_range: prim_name = f"/World/Prim_{i}" prim = stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self._graph_path) prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Float).Set(float(0)) # set the variable default value var = graph.find_variable("float_var") og.Controller.set_variable_default_value(var, 10.0) await self.tick() # validate all prims read the default value for i in int_range: prim = stage.GetPrimAtPath(f"/World/Prim_{i}") self.assertEqual(prim.GetAttribute("graph_output").Get(), 10.0) # create an override attribute on each prim, set it with an unique value for i in int_range: prim = stage.GetPrimAtPath(f"/World/Prim_{i}") prim.CreateAttribute("graph:variable:float_var", Sdf.ValueTypeNames.Float).Set(float(i)) await self.tick() # update the attribute for i in int_range: stage.GetPrimAtPath(f"/World/Prim_{i}").GetAttribute("graph:variable:float_var").Set(float(i * i)) await self.tick() # validate the updated output was read in the graph for i in int_range: prim_path = f"/World/Prim_{i}" val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get() self.assertEqual(val, float(i * i)) async def test_instances_run_from_references(self): """OM-48547 - tests instances run when added as references""" num_prims = 4 for frame_rate in [24, 25, 30]: with self.subTest(frame_rate=frame_rate): timeline = omni.timeline.get_timeline_interface() timeline.set_time_codes_per_second(frame_rate) file_path = os.path.join(os.path.dirname(__file__), "data", "TestReferenceInstance.usda") stage = omni.usd.get_context().get_stage() # Add references to a file that contains a graph and a graph instance. # The graph increments an attribute on the instance called 'count' each frame for i in range(0, num_prims): prim = stage.DefinePrim(f"/World/Root{i}") prim.GetReferences().AddReference(file_path) await omni.kit.app.get_app().next_update_async() counts = [] for i in range(0, num_prims): # validate a graph was properly created attr = stage.GetAttributeAtPath(f"/World/Root{i}/Instance.count") self.assertTrue(attr.IsValid()) counts.append(attr.Get()) timeline.play() await omni.kit.app.get_app().next_update_async() # validate that every graph instance was executed for i in range(0, num_prims): attr = stage.GetAttributeAtPath(f"/World/Root{i}/Instance.count") self.assertGreater(attr.Get(), counts[i]) counts[i] = attr.Get() # remove a prim along with its instances. Validates no errors are thrown # with the next update stage.RemovePrim(f"/World/Root{num_prims-1}") await omni.kit.app.get_app().next_update_async() # validate the remaining update for i in range(0, num_prims - 1): attr = stage.GetAttributeAtPath(f"/World/Root{i}/Instance.count") self.assertGreater(attr.Get(), counts[i]) timeline.stop() await omni.usd.get_context().new_stage_async() # ---------------------------------------------------------------------- async def test_instances_can_be_duplicated(self): """Test that valdiates that an OmniGraph instance can be duplicated""" controller = og.Controller() keys = og.Controller.Keys # +------------+ +---------------+ # |GraphTarget |=======>|WriteVariable | # +------------+ +---------------+ (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("GraphTarget", "omni.graph.nodes.GraphTarget"), ("WriteVar", "omni.graph.core.WriteVariable"), ], keys.CONNECT: [ ("GraphTarget.outputs:primPath", "WriteVar.inputs:value"), ], keys.CREATE_VARIABLES: [ ("path", og.Type(og.BaseDataType.TOKEN)), ], keys.SET_VALUES: [ ("WriteVar.inputs:variableName", "path"), ], }, ) # create an instance, and duplicate it stage = omni.usd.get_context().get_stage() prim0 = stage.DefinePrim("/World/Prim0") OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim0.GetPath(), self._graph_path) omni.kit.commands.execute("CopyPrim", path_from=prim0.GetPath(), path_to="/World/Prim1", exclusive_select=False) await omni.kit.app.get_app().next_update_async() # validate both instances ran by checking the variable was written variable = graph.find_variable("path") context = graph.get_default_graph_context() self.assertEquals(variable.get(context, "/World/Prim0"), "/World/Prim0") self.assertEquals(variable.get(context, "/World/Prim1"), "/World/Prim1") # ---------------------------------------------------------------------- async def test_instances_python(self): """ Tests that python nodes reads correctly their internal state when used in instantiated graphs The test creates 2 instances, the first one that use override, the other not We check that the 2 instances behaves differently. Then we swith instances "override", and we check that each has its own internal state """ controller = og.Controller() keys = og.Controller.Keys override_value = -1 # +--------------------+ # | OgnTutorialStatePy | # +------------+ | | +---------------+ # |Constant |=======>|overrideValue | | WritePrimAttr | # +------------+ | | | | # | monotonic |=======>|value | # +------------+ | | | | # |ReadVariable|=======>|override | | | # +------------+ +--------------------+ | | # +------------+ | | # |GraphTarget |=======>|primPath | # +------------+ +---------------+ # (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_PRIMS: [ ("/World/Inst1", {"graph_output": ("Int64", -2)}), ("/World/Inst2", {"graph_output": ("Int64", -2)}), ], keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("OgnTutorialStatePy", "omni.graph.tutorials.StatePy"), ("Const", "omni.graph.nodes.ConstantInt64"), ("GraphTarget", "omni.graph.nodes.GraphTarget"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "OgnTutorialStatePy.inputs:override"), ("Const.inputs:value", "OgnTutorialStatePy.inputs:overrideValue"), ("GraphTarget.outputs:primPath", "WritePrimAttr.inputs:primPath"), ("OgnTutorialStatePy.outputs:monotonic", "WritePrimAttr.inputs:value"), ], keys.CREATE_VARIABLES: [ ("var_override", og.Type(og.BaseDataType.BOOL)), ], keys.SET_VALUES: [ ("Const.inputs:value", override_value), ("ReadVariable.inputs:variableName", "var_override"), ("WritePrimAttr.inputs:usePath", True), ("WritePrimAttr.inputs:name", "graph_output"), ], }, ) # create the instances stage = omni.usd.get_context().get_stage() prim1 = stage.GetPrimAtPath("/World/Inst1") OmniGraphSchemaTools.applyOmniGraphAPI(stage, "/World/Inst1", self._graph_path) prim2 = stage.GetPrimAtPath("/World/Inst2") OmniGraphSchemaTools.applyOmniGraphAPI(stage, "/World/Inst2", self._graph_path) # set the variable default value var = graph.find_variable("var_override") og.Controller.set_variable_default_value(var, False) # change the value of the variable on prim1 prim1.CreateAttribute("graph:variable:var_override", Sdf.ValueTypeNames.Bool).Set(True) # run a frame await self.tick() prim1_out = prim1.GetAttribute("graph_output") prim2_out = prim2.GetAttribute("graph_output") # prim1 should have the overriden value self.assertEqual(prim1_out.Get(), override_value) # prim2 should have the internal initial state value self.assertEqual(prim2_out.Get(), 0) # run a frame await self.tick() # prim1 should still have the overriden value self.assertEqual(prim1_out.Get(), override_value) # prim2 should have the internal state value incremented step2 = prim2_out.Get() self.assertNotEqual(step2, override_value) # turn off override on prim 1 prim1.GetAttribute("graph:variable:var_override").Set(False) # run a frame await self.tick() # prim1 should now have a fresh internal state initial value self.assertEqual(prim1_out.Get(), 0) # prim2 should have the internal state value incremented self.assertEqual(prim2_out.Get(), 2 * step2) # run a frame await self.tick() # prim1 should have the internal state value incremented step1 = prim1_out.Get() self.assertNotEqual(step1, override_value) # the new step should be an increment of the previous one self.assertEqual(step1, step2 + 1) # prim2 should have the internal state value incremented self.assertEqual(prim2_out.Get(), 3 * step2) # change the value of the variable on prim2 prim2.CreateAttribute("graph:variable:var_override", Sdf.ValueTypeNames.Bool).Set(True) # run a frame await self.tick() # prim1 should have the internal state value incremented self.assertEqual(prim1_out.Get(), 2 * step1) # prim2 should have overriden value self.assertEqual(prim2_out.Get(), override_value) # now check that deleting an instance deletes as well its internal state stage.RemovePrim("/World/Inst1") # run a frame to apply the removal await self.tick() # re-create a fresh prim prim1 = stage.DefinePrim("/World/Inst1") OmniGraphSchemaTools.applyOmniGraphAPI(stage, "/World/Inst1", self._graph_path) prim1.CreateAttribute("graph_output", Sdf.ValueTypeNames.Int64).Set(-2) prim1_out = prim1.GetAttribute("graph_output") # run a frame await self.tick() # prim1 should be back to the initial state self.assertEqual(prim1_out.Get(), 0) # prim2 should have overriden value self.assertEqual(prim2_out.Get(), override_value) # run a frame await self.tick() # prim1 should have the internal state value incremented new_step = prim1_out.Get() self.assertNotEqual(new_step, override_value) self.assertEqual(new_step, step1 + 1) # prim2 should have overriden value self.assertEqual(prim2_out.Get(), override_value) # run a frame await self.tick() # prim1 should have the internal state value incremented self.assertEqual(prim1_out.Get(), 2 * new_step) # ------------------------------------------------------------------------- async def test_instance_variables_values_persist(self): """ Tests that instance variables value persist even if the backing values are removed from fabric """ controller = og.Controller() keys = og.Controller.Keys # Create a simple graph that reads a variable and passes it through the graph (graph, (read_var, to_str), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("ToString", "omni.graph.nodes.ToString"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "ToString.inputs:value"), ], keys.CREATE_VARIABLES: [ ("var_str", og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "var_str"), ], }, ) # Create instances with unique values per instance num_prims = 3 stage = omni.usd.get_context().get_stage() variable = graph.find_variable("var_str") output_attr = to_str.get_attribute("outputs:converted") context = graph.get_default_graph_context() for i in range(0, num_prims): prim_name = f"/World/Prim_{i}" stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self._graph_path) attr = stage.GetPrimAtPath(f"/World/Prim_{i}").CreateAttribute( "graph:variable:var_str", Sdf.ValueTypeNames.String ) attr.Set(str(i)) await self.tick() read_var_count = read_var.get_compute_count() to_str_count = to_str.get_compute_count() for i in range(0, num_prims): expected_value = str(i) self.assertEqual(variable.get(context, instance_path=f"/World/Prim_{i}"), expected_value) self.assertEqual(output_attr.get(instance=i), expected_value) # if USDRT is available use that to remove the backing properties from Fabric. # otherwise, use USD. usdrt_stage = stage try: import usdrt usdrt_stage = usdrt.Usd.Stage.Attach(omni.usd.get_context().get_stage_id()) except ImportError: pass # Update the values in Fabric for i in range(0, num_prims): variable.set(context, str(i + 10), instance_path=f"/World/Prim_{i}") await self.tick() # validate the nodes updated self.assertGreater(read_var.get_compute_count(), read_var_count) self.assertGreater(to_str.get_compute_count(), to_str_count) read_var_count = read_var.get_compute_count() to_str_count = to_str.get_compute_count() # Remove the backing properties for i in range(0, num_prims): prim = usdrt_stage.GetPrimAtPath(f"/World/Prim_{i}") prim.RemoveProperty("graph:variable:var_str") await self.tick() self.assertGreater(read_var.get_compute_count(), read_var_count) self.assertGreater(to_str.get_compute_count(), to_str_count) # validate the values still exist as expected for i in range(0, num_prims): expected_value = str(i + 10) self.assertEqual(variable.get(context, instance_path=f"/World/Prim_{i}"), expected_value) self.assertEqual(output_attr.get(instance=i), expected_value) # ------------------------------------------------------------------------- async def test_instance_author_existing_graph(self): """ Tests that an instanced graph can be authored """ controller = og.Controller() keys = og.Controller.Keys # Create a simple graph that reads a variable and passes it through the graph # we need an action graph here to prevent vectorization and exercise the one-by-one code path # this can be revisited with a push graph when we'll be able to controll the instance batch size per node # (and removing the artificially added action node that forces execution) controller.create_graph({"graph_path": self._graph_path, "evaluator_name": "execution"}) (graph, (_, to_str, _, _), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("ToString", "omni.graph.nodes.ToString"), ("ForceExec", "omni.graph.test.TestAllDataTypes"), ("OnTick", "omni.graph.action.OnTick"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "ToString.inputs:value"), ("OnTick.outputs:tick", "ForceExec.inputs:a_execution"), ("ToString.outputs:converted", "ForceExec.inputs:a_string"), ], keys.CREATE_VARIABLES: [ ("var_str", og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "var_str"), ("OnTick.inputs:onlyPlayback", False), ], }, ) # Create instances with unique values per instance num_prims = 3 stage = omni.usd.get_context().get_stage() variable = graph.find_variable("var_str") output_attr = to_str.get_attribute("outputs:converted") context = graph.get_default_graph_context() for i in range(0, num_prims): prim_name = f"/World/Prim_{i}" stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self._graph_path) attr = stage.GetPrimAtPath(f"/World/Prim_{i}").CreateAttribute( "graph:variable:var_str", Sdf.ValueTypeNames.String ) attr.Set(str(i)) await self.tick() for i in range(0, num_prims): expected_value = str(i) self.assertEqual(variable.get(context, instance_path=f"/World/Prim_{i}"), expected_value) self.assertEqual(output_attr.get(instance=i), expected_value) (_, (append), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [("Append", "omni.graph.nodes.AppendString")], keys.CONNECT: [ ("ToString.outputs:converted", "Append.inputs:value"), ("Append.outputs:value", "ForceExec.inputs:a_string"), ], keys.SET_VALUES: [ ("Append.inputs:suffix", {"value": "_suffix", "type": "string"}), ], }, ) await self.tick() output_attr = append[0].get_attribute("outputs:value") for i in range(0, num_prims): expected_value = str(i) + "_suffix" self.assertEqual(output_attr.get(instance=i), expected_value)
27,675
Python
41.709876
120
0.518374
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_compound_node_type_api.py
"""Tests related to the CompoundNodeType python APIs""" import carb import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.kit.test import omni.usd class TestCompoundNodesAPI(ogts.OmniGraphTestCase): """Tests that validate the ICompoundNodeType + python wrapper""" @classmethod def setUpClass(cls): # this is required when running a single test to make expectedError work correctly...not sure why carb.log_warn("This class expects error. This preflushes to avoid problems with ExpectedError") async def test_default_compound_node_type_folder(self): """Tests the default folder commmand of the compound node type""" # with no default prim, "/World" is used await omni.usd.get_context().new_stage_async() self.assertEquals(ogu.get_default_compound_node_type_folder(), "/World/Compounds") # if there is a default set, the compounds folder is off of that. stage = omni.usd.get_context().get_stage() prim = stage.DefinePrim("/MyDefault") stage.SetDefaultPrim(prim) self.assertEquals(ogu.get_default_compound_node_type_folder(), "/MyDefault/Compounds") async def test_compound_nodes_cannot_add_state(self): """API test for compound nodes that verifies set state calls have no effect.""" compound = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") with ogts.ExpectedError(): compound.node_type.add_state("state", "int", True) with ogts.ExpectedError(): compound.node_type.add_extended_state( "extended", "numerics", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) self.assertFalse(compound.node_type.has_state()) async def test_get_compound_node_type(self): """API test for get_compound_node_type""" (result, error) = await ogts.load_test_file("TestCompoundGraph.usda", use_caller_subdirectory=True) self.assertTrue(result, error) compound_type = og.get_node_type("local.nodes.Compounds") self.assertFalse(ogu.get_compound_node_type(compound_type).is_valid()) non_compound_type = og.get_node_type("omni.graph.nodes.Add") self.assertFalse(ogu.get_compound_node_type(non_compound_type).is_valid()) async def test_find_compound_node_type_by_path(self): """API test for find_compound_node_type_by_path""" self.assertFalse(ogu.find_compound_node_type_by_path("/World/Compounds/Compound").is_valid()) (result, error) = await ogts.load_test_file("TestCompoundGraph.usda", use_caller_subdirectory=True) self.assertTrue(result, error) self.assertTrue(ogu.find_compound_node_type_by_path("/World/Compounds/Compound").is_valid()) self.assertFalse(ogu.find_compound_node_type_by_path("/World/Compounds/Compound1").is_valid()) self.assertFalse(ogu.find_compound_node_type_by_path("").is_valid()) async def test_create_compound_node_type(self): """API test for create compound node type""" def expect_fail(compound_name, graph_name, namespace=None, folder=None): with ogts.ExpectedError(): self.assertFalse(ogu.create_compound_node_type(compound_name, graph_name, namespace, folder).is_valid()) self.assertTrue(ogu.create_compound_node_type("ValidCompound_01", "Graph").is_valid()) self.assertTrue(ogu.create_compound_node_type("ValidCompound_02", "Graph", "other.namespace").is_valid()) self.assertTrue( ogu.create_compound_node_type( "ValidCompound_03", "Graph", "other.namespace", "/World/OtherCompounds" ).is_valid() ) expect_fail("/INVALID_COMPOUND_NAME", "ValidGraphName") expect_fail("ValidCompoundName", "//!@#INVALID_GRAPH_NAME") expect_fail("ValidCompoundName", "ValidGraphName", "valid.namespace", "#@#$#$#INVALID_FOLDER##$@!#$") expect_fail("ValidCompound_01", "Graph") # same namespace & path expect_fail("ValidCompound_01", "Graph", "local.nodes", "/World/Compounds2") async def test_as_node_type(self): """Test conversion between compound node type and node type""" ogu.create_compound_node_type("TestType", "Graph", "test.nodes") node_type = og.get_node_type("test.nodes.TestType") self.assertTrue(node_type.is_valid()) compound_node_type = ogu.get_compound_node_type(node_type) self.assertTrue(compound_node_type.is_valid()) add_type = og.get_node_type("omni.graph.nodes.Add") self.assertTrue(add_type.is_valid()) self.assertFalse(ogu.get_compound_node_type(add_type).is_valid()) async def test_node_type_add_attributes(self): """Tests that attributes added through the INodeType ABI update compound node types correctly""" stage = omni.usd.get_context().get_stage() # create the compound compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") self.assertTrue(compound_node_type.is_valid()) prim = stage.GetPrimAtPath("/World/Compounds/TestType") self.assertTrue(prim.IsValid()) # downcast to the given node type node_type = compound_node_type.node_type self.assertTrue(node_type.is_valid()) def validate_input(input_name, type_name, expect_typed_data): input_attr = compound_node_type.find_input(input_name) self.assertTrue(input_attr.is_valid()) self.assertEqual(input_attr.name, f"inputs:{input_name}") self.assertEqual(input_attr.type_name, type_name) path = prim.GetPath().AppendProperty(f"omni:graph:input:{input_name}") rel = stage.GetRelationshipAtPath(path) self.assertTrue(rel.IsValid(), f"Failed to get input at {path}") if expect_typed_data: self.assertIsNotNone(rel.GetCustomDataByKey("omni:graph:type")) # add regular input node_type.add_input("input_a", "int", True) validate_input("input_a", "int", True) # add an any input node_type.add_extended_input("input_b", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) validate_input("input_b", "token", False) # add a union input node_type.add_extended_input("input_c", "int, int2", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) validate_input("input_c", "token", True) def validate_output(output_name, type_name, expect_typed_data): output = compound_node_type.find_output(output_name) self.assertTrue(output.is_valid()) self.assertEqual(output.name, f"outputs:{output_name}") self.assertEqual(output.type_name, type_name) path = prim.GetPath().AppendProperty(f"omni:graph:output:{output_name}") rel = stage.GetRelationshipAtPath(path) self.assertTrue(rel.IsValid(), f"Failed to get output at {path}") if expect_typed_data: self.assertIsNotNone(rel.GetCustomDataByKey("omni:graph:type")) # add regular output node_type.add_output("output_a", "int", True) validate_output("output_a", "int", True) # add an any output node_type.add_extended_output("output_b", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) validate_output("output_b", "token", False) # add a union output node_type.add_extended_output("output_c", "int, int2", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) validate_output("output_c", "token", True) async def test_add_attributes_with_default_data(self): """Tests that compound nodes can handle adding attributes that use default data""" stage = omni.usd.get_context().get_stage() compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") self.assertTrue(compound_node_type.is_valid()) prim = stage.GetPrimAtPath("/World/Compounds/TestType") self.assertTrue(prim.IsValid()) prim_path = prim.GetPath() def validate_typed_attributes(attr_name, attr_type, is_required, var_value): compound_node_type.add_input(attr_name, attr_type, is_required, var_value) compound_node_type.add_output(attr_name, attr_type, is_required, var_value) input_rel = stage.GetRelationshipAtPath(prim_path.AppendProperty(f"omni:graph:input:{attr_name}")) output_rel = stage.GetRelationshipAtPath(prim_path.AppendProperty(f"omni:graph:output:{attr_name}")) self.assertTrue(input_rel.IsValid()) self.assertTrue(output_rel.IsValid()) input_data = input_rel.GetCustomDataByKey("omni:graph:default") self.assertIsNotNone(input_data) output_data = output_rel.GetCustomDataByKey("omni:graph:default") self.assertIsNotNone(output_data) # token[] rearranges quotes and quat4 is out of order (input takes w first) if attr_type != "token[]" and "quat" not in attr_type: var_value_as_string = str(var_value).replace(" ", "") input_data_as_string = str(input_data).replace(" ", "") output_data_as_string = str(output_data).replace(" ", "") self.assertEqual(var_value_as_string, input_data_as_string) self.assertEqual(var_value_as_string, output_data_as_string) validate_typed_attributes("a_bool", "bool", True, True) validate_typed_attributes("a_bool_array", "bool[]", True, [0, 1]) validate_typed_attributes("a_colord_3", "colord[3]", True, (0.01625, 0.14125, 0.26625)) validate_typed_attributes( "a_colord_3_array", "colord[3][]", True, [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] ) validate_typed_attributes("a_colord_4", "colord[4]", True, (0.01625, 0.14125, 0.26625, 0.39125)) validate_typed_attributes( "a_colord_4_array", "colord[4][]", True, [(0.01625, 0.14125, 0.26625, 0.39125), (0.39125, 0.26625, 0.14125, 0.01625)], ) validate_typed_attributes("a_colorf_3", "colorf[3]", True, (0.125, 0.25, 0.375)) validate_typed_attributes("a_colorf_3_array", "colorf[3][]", True, [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)]) validate_typed_attributes("a_colorf_4", "colorf[4]", True, (0.125, 0.25, 0.375, 0.5)) validate_typed_attributes( "a_colorf_4_array", "colorf[4][]", True, [(0.125, 0.25, 0.375, 0.5), (0.5, 0.375, 0.25, 0.125)] ) validate_typed_attributes("a_colorh_3", "colorh[3]", True, (0.5, 0.625, 0.75)) validate_typed_attributes("a_colorh_3_array", "colorh[3][]", True, [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)]) validate_typed_attributes("a_colorh_4", "colorh[4]", True, (0.5, 0.625, 0.75, 0.875)) validate_typed_attributes( "a_colorh_4_array", "colorh[4][]", True, [(0.5, 0.625, 0.75, 0.875), (0.875, 0.75, 0.625, 0.5)] ) validate_typed_attributes("a_double", "double", True, 4.125) validate_typed_attributes("a_double_2", "double[2]", True, (4.125, 4.25)) validate_typed_attributes("a_double_2_array", "double[2][]", True, [(4.125, 4.25), (2.125, 2.25)]) validate_typed_attributes("a_double_3", "double[3]", True, (4.125, 4.25, 4.375)) validate_typed_attributes("a_double_3_array", "double[3][]", True, [(4.125, 4.25, 4.375), (2.125, 2.25, 2.375)]) validate_typed_attributes("a_double_4", "double[4]", True, (4.125, 4.25, 4.375, 4.5)) validate_typed_attributes( "a_double_4_array", "double[4][]", True, [(4.125, 4.25, 4.375, 4.5), (2.125, 2.25, 2.375, 2.5)] ) validate_typed_attributes("a_double_array", "double[]", True, [4.125, 2.125]) validate_typed_attributes("a_execution", "execution", True, 0) validate_typed_attributes("a_float", "float", True, 4.5) validate_typed_attributes("a_float_2", "float[2]", True, (4.5, 4.625)) validate_typed_attributes("a_float_2_array", "float[2][]", True, [(4.5, 4.625), (2.5, 2.625)]) validate_typed_attributes("a_float_3", "float[3]", True, (4.5, 4.625, 4.75)) validate_typed_attributes("a_float_3_array", "float[3][]", True, [(4.5, 4.625, 4.75), (2.5, 2.625, 2.75)]) validate_typed_attributes("a_float_4", "float[4]", True, (4.5, 4.625, 4.75, 4.875)) validate_typed_attributes( "a_float_4_array", "float[4][]", True, [(4.5, 4.625, 4.75, 4.875), (2.5, 2.625, 2.75, 2.875)] ) validate_typed_attributes("a_float_array", "float[]", True, [4.5, 2.5]) validate_typed_attributes( "a_frame_4", "frame[4]", True, ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)) ) validate_typed_attributes( "a_frame_4_array", "frame[4][]", True, [ ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)), ((2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2)), ], ) validate_typed_attributes("a_half", "half", True, 2.5) validate_typed_attributes("a_half_2", "half[2]", True, (2.5, 2.625)) validate_typed_attributes("a_half_2_array", "half[2][]", True, [(2.5, 2.625), (4.5, 4.625)]) validate_typed_attributes("a_half_3", "half[3]", True, (2.5, 2.625, 2.75)) validate_typed_attributes("a_half_3_array", "half[3][]", True, [(2.5, 2.625, 2.75), (4.5, 4.625, 4.75)]) validate_typed_attributes("a_half_4", "half[4]", True, (2.5, 2.625, 2.75, 2.875)) validate_typed_attributes( "a_half_4_array", "half[4][]", True, [(2.5, 2.625, 2.75, 2.875), (4.5, 4.625, 4.75, 4.875)] ) validate_typed_attributes("a_half_array", "half[]", True, [2.5, 4.5]) validate_typed_attributes("a_int", "int", True, -32) validate_typed_attributes("a_int64", "int64", True, -46) validate_typed_attributes("a_int64_array", "int64[]", True, [-46, -64]) validate_typed_attributes("a_int_2", "int[2]", True, (-32, -31)) validate_typed_attributes("a_int_2_array", "int[2][]", True, [(-32, -31), (-23, -22)]) validate_typed_attributes("a_int_3", "int[3]", True, (-32, -31, -30)) validate_typed_attributes("a_int_3_array", "int[3][]", True, [(-32, -31, -30), (-23, -22, -21)]) validate_typed_attributes("a_int_4", "int[4]", True, (-32, -31, -30, -29)) validate_typed_attributes("a_int_4_array", "int[4][]", True, [(-32, -31, -30, -29), (-23, -22, -21, -20)]) validate_typed_attributes("a_int_array", "int[]", True, [-32, -23]) validate_typed_attributes("a_matrixd_2", "matrixd[2]", True, ((1, 0), (0, 1))) validate_typed_attributes("a_matrixd_2_array", "matrixd[2][]", True, [((1, 0), (0, 1)), ((2, 3), (3, 2))]) validate_typed_attributes("a_matrixd_3", "matrixd[3]", True, ((1, 0, 0), (0, 1, 0), (0, 0, 1))) validate_typed_attributes( "a_matrixd_3_array", "matrixd[3][]", True, [((1, 0, 0), (0, 1, 0), (0, 0, 1)), ((2, 3, 3), (3, 2, 3), (3, 3, 2))], ) validate_typed_attributes( "a_matrixd_4", "matrixd[4]", True, ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)) ) validate_typed_attributes( "a_matrixd_4_array", "matrixd[4][]", True, [ ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)), ((2, 3, 3, 3), (3, 2, 3, 3), (3, 3, 2, 3), (3, 3, 3, 2)), ], ) validate_typed_attributes("a_normald_3", "normald[3]", True, (0.01625, 0.14125, 0.26625)) validate_typed_attributes( "a_normald_3_array", "normald[3][]", True, [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] ) validate_typed_attributes("a_normalf_3", "normalf[3]", True, (0.125, 0.25, 0.375)) validate_typed_attributes( "a_normalf_3_array", "normalf[3][]", True, [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] ) validate_typed_attributes("a_normalh_3", "normalh[3]", True, (0.5, 0.625, 0.75)) validate_typed_attributes("a_normalh_3_array", "normalh[3][]", True, [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)]) validate_typed_attributes("a_objectId", "objectId", True, 46) validate_typed_attributes("a_objectId_array", "objectId[]", True, [46, 64]) validate_typed_attributes("a_path", "path", True, "/This/Is") validate_typed_attributes("a_pointd_3", "pointd[3]", True, (0.01625, 0.14125, 0.26625)) validate_typed_attributes( "a_pointd_3_array", "pointd[3][]", True, [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] ) validate_typed_attributes("a_pointf_3", "pointf[3]", True, (0.125, 0.25, 0.375)) validate_typed_attributes("a_pointf_3_array", "pointf[3][]", True, [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)]) validate_typed_attributes("a_pointh_3", "pointh[3]", True, (0.5, 0.625, 0.75)) validate_typed_attributes("a_pointh_3_array", "pointh[3][]", True, [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)]) validate_typed_attributes("a_quatd_4", "quatd[4]", True, (0.78, 0.01625, 0.14125, 0.26625)) validate_typed_attributes( "a_quatd_4_array", "quatd[4][]", True, [(0.78, 0.01625, 0.14125, 0.26625), (0.51625, 0.14125, 0.26625, 0.39125)], ) validate_typed_attributes("a_quatf_4", "quatf[4]", True, (0.5, 0.125, 0.25, 0.375)) validate_typed_attributes( "a_quatf_4_array", "quatf[4][]", True, [(0.5, 0.125, 0.25, 0.375), (0.625, 0.25, 0.375, 0.5)] ) validate_typed_attributes("a_quath_4", "quath[4]", True, (0.75, 0, 0.25, 0.5)) validate_typed_attributes( "a_quath_4_array", "quath[4][]", True, [(0.75, 0, 0.25, 0.5), (0.875, 0.125, 0.375, 0.625)] ) validate_typed_attributes("a_string", "string", True, "Anakin") validate_typed_attributes("a_texcoordd_2", "texcoordd[2]", True, (0.01625, 0.14125)) validate_typed_attributes( "a_texcoordd_2_array", "texcoordd[2][]", True, [(0.01625, 0.14125), (0.14125, 0.01625)] ) validate_typed_attributes("a_texcoordd_3", "texcoordd[3]", True, (0.01625, 0.14125, 0.26625)) validate_typed_attributes( "a_texcoordd_3_array", "texcoordd[3][]", True, [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] ) validate_typed_attributes("a_texcoordf_2", "texcoordf[2]", True, (0.125, 0.25)) validate_typed_attributes("a_texcoordf_2_array", "texcoordf[2][]", True, [(0.125, 0.25), (0.25, 0.125)]) validate_typed_attributes("a_texcoordf_3", "texcoordf[3]", True, (0.125, 0.25, 0.375)) validate_typed_attributes( "a_texcoordf_3_array", "texcoordf[3][]", True, [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] ) validate_typed_attributes("a_texcoordh_2", "texcoordh[2]", True, (0.5, 0.625)) validate_typed_attributes("a_texcoordh_2_array", "texcoordh[2][]", True, [(0.5, 0.625), (0.625, 0.5)]) validate_typed_attributes("a_texcoordh_3", "texcoordh[3]", True, (0.5, 0.625, 0.75)) validate_typed_attributes( "a_texcoordh_3_array", "texcoordh[3][]", True, [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)] ) validate_typed_attributes("a_timecode", "timecode", True, 5) validate_typed_attributes("a_timecode_array", "timecode[]", True, [5, 6]) validate_typed_attributes("a_token", "token", True, "Ahsoka") validate_typed_attributes("a_token_array", "token[]", True, ["Ahsoka", "Tano"]) validate_typed_attributes("a_uchar", "uchar", True, 12) validate_typed_attributes("a_uchar_array", "uchar[]", True, [12, 8]) validate_typed_attributes("a_uint", "uint", True, 32) validate_typed_attributes("a_uint64", "uint64", True, 46) validate_typed_attributes("a_uint64_array", "uint64[]", True, [46, 64]) validate_typed_attributes("a_uint_array", "uint[]", True, [32, 23]) validate_typed_attributes("a_vectord_3", "vectord[3]", True, (0.01625, 0.14125, 0.26625)) validate_typed_attributes( "a_vectord_3_array", "vectord[3][]", True, [(0.01625, 0.14125, 0.26625), (0.26625, 0.14125, 0.01625)] ) validate_typed_attributes("a_vectorf_3", "vectorf[3]", True, (0.125, 0.25, 0.375)) validate_typed_attributes( "a_vectorf_3_array", "vectorf[3][]", True, [(0.125, 0.25, 0.375), (0.375, 0.25, 0.125)] ) validate_typed_attributes("a_vectorh_3", "vectorh[3]", True, (0.5, 0.625, 0.75)) validate_typed_attributes("a_vectorh_3_array", "vectorh[3][]", True, [(0.5, 0.625, 0.75), (0.75, 0.625, 0.5)]) async def test_remove_attribute_commands(self): """Validates the API/ABI commands to remove attributes function as expected""" stage = omni.usd.get_context().get_stage() compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") self.assertTrue(compound_node_type.is_valid()) prim = stage.GetPrimAtPath("/World/Compounds/TestType") self.assertTrue(prim.IsValid()) for i in range(1, 20): compound_node_type.add_input(f"input_{i}", "int", True) compound_node_type.add_output(f"output_{i}", "float", True) self.assertTrue(prim.GetRelationship(f"omni:graph:input:input_{i}").IsValid()) self.assertTrue(prim.GetRelationship(f"omni:graph:output:output_{i}").IsValid()) for i in range(1, 20, 2): compound_node_type.remove_input_by_name(f"input_{i}") compound_node_type.remove_output_by_name(f"output_{i}") for i in range(1, 20): input_attr = compound_node_type.find_input(f"input_{i}") output_attr = compound_node_type.find_output(f"output_{i}") valid = (i % 2) == 0 self.assertEqual(input_attr.is_valid(), valid) self.assertEqual(output_attr.is_valid(), valid) self.assertEqual(prim.GetRelationship(f"omni:graph:input:input_{i}").IsValid(), valid) self.assertEqual(prim.GetRelationship(f"omni:graph:output:output_{i}").IsValid(), valid) async def test_get_attributes_commands(self): """Validates the methods to get inputs and outputs""" compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") for i in range(1, 20): compound_node_type.add_input(f"input_{i}", "int", True) compound_node_type.add_output(f"output_{i}", "float", True) compound_node_type.add_output("output_20", "bool", True) self.assertEquals(compound_node_type.input_count, 19) self.assertEquals(compound_node_type.output_count, 20) inputs = compound_node_type.get_inputs() input_names = [input_attr.name for input_attr in inputs] outputs = compound_node_type.get_outputs() output_names = [output.name for output in outputs] for i in range(1, 20): self.assertTrue(f"inputs:input_{i}" in input_names) for i in range(1, 21): self.assertTrue(f"outputs:output_{i}" in output_names) async def test_find_attribute_commands(self): """Validates the find input and find output commands""" compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") # create some without prefix for i in range(1, 20): compound_node_type.add_input(f"input_{i}", "int", True) compound_node_type.add_output(f"output_{i}", "float", True) # some with prefix for i in range(20, 40): compound_node_type.add_input(f"inputs:input_{i}", "int", True) compound_node_type.add_output(f"outputs:output_{i}", "float", True) # validate that the prefix is optional for i in range(1, 40): self.assertTrue(compound_node_type.find_input(f"inputs:input_{i}").is_valid()) self.assertTrue(compound_node_type.find_input(f"input_{i}").is_valid()) self.assertEqual( compound_node_type.find_input(f"inputs:input_{i}"), compound_node_type.find_input(f"input_{i}") ) self.assertTrue(compound_node_type.find_output(f"outputs:output_{i}").is_valid()) self.assertTrue(compound_node_type.find_output(f"output_{i}").is_valid()) self.assertEqual( compound_node_type.find_output(f"outputs:output_{i}"), compound_node_type.find_output(f"output_{i}") )
24,934
Python
54.782998
120
0.593286
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_scheduling_types.py
"""Tests related to the scheduling information feature""" import omni.graph.core as og import omni.graph.core.tests as og_tests # ============================================================================================================== class TestSchedulingHints(og_tests.OmniGraphTestCase): """Testing to ensure scheduling information work""" # ---------------------------------------------------------------------- async def test_scheduling_hints(self): """Test the scheduling information embedded in .ogn files""" controller = og.Controller() keys = og.Controller.Keys (_, (list_node, string_node), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("AsList", "omni.graph.test.TestSchedulingHintsList"), ("AsString", "omni.graph.test.TestSchedulingHintsString"), ] }, ) scheduling_hints = list_node.get_node_type().get_scheduling_hints() scheduling_hints_2 = og.ISchedulingHints2(scheduling_hints) self.assertEqual(og.eThreadSafety.E_SAFE, scheduling_hints.thread_safety) self.assertEqual(og.eAccessType.E_NONE, scheduling_hints.get_data_access(og.eAccessLocation.E_GLOBAL)) self.assertEqual(og.eAccessType.E_NONE, scheduling_hints.get_data_access(og.eAccessLocation.E_STATIC)) self.assertEqual(og.eAccessType.E_NONE, scheduling_hints.get_data_access(og.eAccessLocation.E_TOPOLOGY)) self.assertEqual(og.eAccessType.E_NONE, scheduling_hints.get_data_access(og.eAccessLocation.E_USD)) self.assertEqual(og.eComputeRule.E_DEFAULT, scheduling_hints.compute_rule) if scheduling_hints_2: self.assertEqual(og.ePurityStatus.E_IMPURE, scheduling_hints_2.purity_status) scheduling_hints.thread_safety = og.eThreadSafety.E_UNKNOWN list_node.get_node_type().set_scheduling_hints(scheduling_hints) self.assertEqual(og.eThreadSafety.E_UNKNOWN, scheduling_hints.thread_safety) scheduling_hints.compute_rule = og.eComputeRule.E_ON_REQUEST list_node.get_node_type().set_scheduling_hints(scheduling_hints) self.assertEqual(og.eComputeRule.E_ON_REQUEST, scheduling_hints.compute_rule) # restore the node to its default values scheduling_hints.thread_safety = og.eThreadSafety.E_SAFE scheduling_hints.compute_rule = og.eComputeRule.E_DEFAULT list_node.get_node_type().set_scheduling_hints(scheduling_hints) scheduling_hints = string_node.get_node_type().get_scheduling_hints() scheduling_hints_2 = og.ISchedulingHints2(scheduling_hints) self.assertEqual(og.eThreadSafety.E_UNSAFE, scheduling_hints.thread_safety) self.assertEqual(og.eAccessType.E_READ, scheduling_hints.get_data_access(og.eAccessLocation.E_GLOBAL)) self.assertEqual(og.eAccessType.E_READ_WRITE, scheduling_hints.get_data_access(og.eAccessLocation.E_STATIC)) self.assertEqual(og.eAccessType.E_WRITE, scheduling_hints.get_data_access(og.eAccessLocation.E_TOPOLOGY)) self.assertEqual(og.eAccessType.E_READ_WRITE, scheduling_hints.get_data_access(og.eAccessLocation.E_USD)) self.assertEqual(og.eComputeRule.E_ON_REQUEST, scheduling_hints.compute_rule) if scheduling_hints_2: self.assertEqual(og.ePurityStatus.E_IMPURE, scheduling_hints_2.purity_status) scheduling_hints.set_data_access(og.eAccessLocation.E_GLOBAL, og.eAccessType.E_WRITE) scheduling_hints.set_data_access(og.eAccessLocation.E_STATIC, og.eAccessType.E_NONE) scheduling_hints.set_data_access(og.eAccessLocation.E_TOPOLOGY, og.eAccessType.E_READ_WRITE) scheduling_hints.set_data_access(og.eAccessLocation.E_USD, og.eAccessType.E_READ) scheduling_hints.compute_rule = og.eComputeRule.E_DEFAULT if scheduling_hints_2: scheduling_hints_2.purity_status = og.ePurityStatus.E_PURE string_node.get_node_type().set_scheduling_hints(scheduling_hints) self.assertEqual(og.eAccessType.E_WRITE, scheduling_hints.get_data_access(og.eAccessLocation.E_GLOBAL)) self.assertEqual(og.eAccessType.E_NONE, scheduling_hints.get_data_access(og.eAccessLocation.E_STATIC)) self.assertEqual(og.eAccessType.E_READ_WRITE, scheduling_hints.get_data_access(og.eAccessLocation.E_TOPOLOGY)) self.assertEqual(og.eAccessType.E_READ, scheduling_hints.get_data_access(og.eAccessLocation.E_USD)) self.assertEqual(og.eComputeRule.E_DEFAULT, scheduling_hints.compute_rule) if scheduling_hints_2: self.assertEqual(og.ePurityStatus.E_PURE, scheduling_hints_2.purity_status) # restore to default values scheduling_hints.set_data_access(og.eAccessLocation.E_GLOBAL, og.eAccessType.E_READ) scheduling_hints.set_data_access(og.eAccessLocation.E_STATIC, og.eAccessType.E_READ_WRITE) scheduling_hints.set_data_access(og.eAccessLocation.E_TOPOLOGY, og.eAccessType.E_WRITE) scheduling_hints.set_data_access(og.eAccessLocation.E_USD, og.eAccessType.E_READ_WRITE) scheduling_hints.compute_rule = og.eComputeRule.E_ON_REQUEST if scheduling_hints_2: scheduling_hints_2.purity_status = og.ePurityStatus.E_IMPURE string_node.get_node_type().set_scheduling_hints(scheduling_hints)
5,374
Python
62.235293
118
0.689617
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_target_type.py
import omni.graph.core as og import omni.graph.core.tests as ogts import omni.usd from pxr import OmniGraphSchemaTools GRAPH_TARGET_PRIM = og.INSTANCING_GRAPH_TARGET_PATH class TestTargetType(ogts.OmniGraphTestCase): """Tests related to using the target attribute type""" _graph_path = "/World/TestGraph" # ------------------------------------------------------------------------- async def test_target_path_substitution(self): """Test that the target accepts target path substitutions""" # Create the graph controller = og.Controller() keys = og.Controller.Keys (graph, (prim_node,), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [("GetPrimsPaths", "omni.graph.nodes.GetPrimPaths")], keys.SET_VALUES: [("GetPrimsPaths.inputs:prims", [GRAPH_TARGET_PRIM])], }, ) await og.Controller.evaluate(graph) actual_result = controller.get(("outputs:primPaths", prim_node)) self.assertEqual(self._graph_path, actual_result[0]) # Change the graph path and verify the changes get picked up correctly controller.edit( self._graph_path, {keys.SET_VALUES: [("GetPrimsPaths.inputs:prims", f"{GRAPH_TARGET_PRIM}/Child")]} ) await og.Controller.evaluate(graph) actual_result = controller.get(("outputs:primPaths", prim_node)) self.assertEqual(f"{self._graph_path}/Child", actual_result[0]) # ------------------------------------------------------------------------- async def test_target_path_substitution_on_instances(self): """Tests that target paths substitution works as expected on instances""" controller = og.Controller() keys = og.Controller.Keys (graph, (prim_node,), prims, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [("GetPrimsPaths", "omni.graph.nodes.GetPrimPaths")], keys.SET_VALUES: [("GetPrimsPaths.inputs:prims", GRAPH_TARGET_PRIM)], keys.CREATE_PRIMS: [ ("/World/Instance1", "Xform"), ("/World/Instance2", "Xform"), ("/World/Instance3", "Xform"), ("/World/Instance4", "Xform"), ("/World/Instance5", "Xform"), ], }, ) context = graph.get_default_graph_context() # Create the instances stage = omni.usd.get_context().get_stage() for p in prims: OmniGraphSchemaTools.applyOmniGraphAPI(stage, p.GetPath(), self._graph_path) await og.Controller.evaluate(graph) for i in range(0, len(prims)): actual_result = controller.get(("outputs:primPaths", prim_node), instance=i) self.assertEqual(str(actual_result[0]), str(context.get_graph_target(i))) # Change the path and verify the changes propagate correctly controller.edit( self._graph_path, {keys.SET_VALUES: [("GetPrimsPaths.inputs:prims", f"{GRAPH_TARGET_PRIM}/Child")]} ) await og.Controller.evaluate(graph) for i in range(0, len(prims)): actual_result = controller.get(("outputs:primPaths", prim_node), instance=i) self.assertEqual(str(actual_result[0]), f"{context.get_graph_target(i)}/Child") # ------------------------------------------------------------------------- async def test_target_types_substitution_with_multiple_target_paths(self): """Test that the target accepts multiple target path substitutions""" # Create the graph controller = og.Controller() keys = og.Controller.Keys (graph, (prim_node,), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [("GetPrimsPaths", "omni.graph.nodes.GetPrimPaths")], keys.SET_VALUES: [ ("GetPrimsPaths.inputs:prims", [GRAPH_TARGET_PRIM, "/World/Other", f"{GRAPH_TARGET_PRIM}/Child"]) ], }, ) await og.Controller.evaluate(graph) actual_result = controller.get(("outputs:primPaths", prim_node)) expected_result = [self._graph_path, "/World/Other", f"{self._graph_path}/Child"] self.assertEqual(expected_result, actual_result) # ------------------------------------------------------------------------- async def test_target_types_substitution_in_connected_graphs(self): """Tests that the graph target replacements propagate through the graph""" # Create the graph controller = og.Controller() keys = og.Controller.Keys (graph, (_const_node, prim_node,), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ConstantPrims", "omni.graph.nodes.ConstantPrims"), ("GetPrimPaths", "omni.graph.nodes.GetPrimPaths"), ], keys.SET_VALUES: [("ConstantPrims.inputs:value", [GRAPH_TARGET_PRIM])], keys.CONNECT: [("ConstantPrims.inputs:value", "GetPrimPaths.inputs:prims")], }, ) # test the single evaluation case await og.Controller.evaluate(graph) actual_result = controller.get(("outputs:primPaths", prim_node)) self.assertEqual(self._graph_path, actual_result[0]) # create and instances and test the instanced case num_instances = 5 stage = omni.usd.get_context().get_stage() for i in range(0, num_instances): p = stage.DefinePrim(f"/World/Instance{i}", "Xform") OmniGraphSchemaTools.applyOmniGraphAPI(stage, p.GetPath(), self._graph_path) await og.Controller.evaluate(graph) context = graph.get_default_graph_context() for i in range(0, num_instances): actual_result = controller.get(("outputs:primPaths", prim_node), instance=i) self.assertEqual(str(actual_result[0]), context.get_graph_target(i)) # ------------------------------------------------------------------------- async def test_target_types_substitution_in_referenced_graphs(self): # Create the graph controller = og.Controller() keys = og.Controller.Keys (_, (_, _,), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ConstantPrims", "omni.graph.nodes.ConstantPrims"), ("GetPrimPaths", "omni.graph.nodes.GetPrimPaths"), ], keys.SET_VALUES: [("ConstantPrims.inputs:value", [GRAPH_TARGET_PRIM])], keys.CONNECT: [("ConstantPrims.inputs:value", "GetPrimPaths.inputs:prims")], }, ) instance_path = "/World/Instance" stage = omni.usd.get_context().get_stage() prim = stage.DefinePrim(instance_path) prim.GetReferences().AddInternalReference(self._graph_path) await og.Controller.evaluate() instance_graph = og.Controller.graph(instance_path) self.assertTrue(instance_graph.is_valid()) await og.Controller.evaluate(instance_graph) attr = og.Controller.attribute(f"{instance_path}/GetPrimPaths.outputs:primPaths") self.assertTrue(attr.is_valid()) self.assertEqual([instance_path], og.Controller.get(attr))
7,481
Python
41.754285
117
0.562625
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_variables.py
# pylint: disable=too-many-lines """ Tests for omnigraph variables """ import os import string import tempfile from typing import List, Optional, Set import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.kit.usd.layers import LayerUtils from pxr import OmniGraphSchemaTools ALL_USD_TYPES = ogts.DataTypeHelper.all_attribute_types() # ===================================================================== # Helper method to create a flat list item, list, tuples, for easy comparison def flatten(item): def _internal_flatten(item, flattened_list): if hasattr(item, "__iter__") and not isinstance(item, str): for i in item: flattened_list = _internal_flatten(i, flattened_list) else: flattened_list.append(item) return flattened_list return _internal_flatten(item, []) # ====================================================================== class TestVariables(ogts.OmniGraphTestCase): _graph_path = "/World/TestGraph" async def setUp(self): self._var_index = 0 await super().setUp() # ---------------------------------------------------------------------- def create_variable( self, graph, name, var_type, display_name: Optional[str] = None, category: Optional[str] = None, tooltip: Optional[str] = None, scope: Optional[og.eVariableScope] = None, ): """Helper method to create and validate a variable in a graph""" var = graph.create_variable(name, var_type) self.assertNotEquals(var, None) self.assertEquals(var.source_path, self._graph_path + ".graph:variable:" + name) self.assertEquals(var.name, name) self.assertEquals(var.type, var_type) if display_name: var.display_name = display_name self.assertEquals(var.display_name, display_name) if category: var.category = category self.assertEquals(var.category, category) if tooltip: var.tooltip = tooltip self.assertEquals(var.tooltip, tooltip) if scope: var.scope = scope self.assertEquals(var.scope, scope) return var # ---------------------------------------------------------------------- def create_simple_graph(self): (graph, _, _, _) = og.Controller.edit( self._graph_path, { og.Controller.Keys.CREATE_NODES: [("SimpleNode", "omni.graph.examples.cpp.Simple")], }, ) return graph # ---------------------------------------------------------------------- def next_variable_name(self): """Returns a unique variable name each time it is called""" variable_name = "variable" index = self._var_index while index >= 0: variable_name += chr(ord("a") + index % 26) index -= 26 self._var_index += 1 return variable_name # ---------------------------------------------------------------------- def get_variables_from_types(self): """Returns a list of variables of all supported types in the form (name, Og.Type, data) """ return [ ( self.next_variable_name(), og.AttributeType.type_from_sdf_type_name(entry), ogts.DataTypeHelper.test_input_value(entry), ) for entry in ALL_USD_TYPES ] # ------------------------------------------------------------------------- async def test_graph_variables_return_expected_value(self): """ Simple test that checks the API returns expected values from a loaded file """ # load the graph (result, error) = await ogts.load_test_file("TestGraphVariables.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = omni.graph.core.get_graph_by_path("/World/ComputeGraph") # put the variables in a dictionary variables = {var.source_path: var for var in graph.get_variables()} self.assertEquals(len(variables), 103) # walk through the usd types and validate they all load as variables # and return expected values for usd_type in ALL_USD_TYPES: var_name = usd_type.lower().replace("[]", "_array") key = "/World/ComputeGraph.graph:variable:var_" + var_name self.assertTrue(key in variables, key) self.assertEquals(variables[key].name, "var_" + var_name) is_array = "_array" in key or usd_type == "string" var_type = variables[key].type if is_array: self.assertNotEqual(var_type.array_depth, 0, key) else: self.assertEqual(var_type.array_depth, 0, key) async def test_variables_get_and_set_oncontext(self): """ Validates variable values can be written and retrieved through the API """ # turn off global graphs, as the test file doesn't use them (result, error) = await ogts.load_test_file("TestGraphVariables.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = omni.graph.core.get_graph_by_path("/World/ComputeGraph") context = graph.get_default_graph_context() variables = {var.source_path: var for var in graph.get_variables()} for entry in ogts.DataTypeHelper.all_attribute_types(): var_name = entry.lower().replace("[]", "_array") key = "/World/ComputeGraph.graph:variable:var_" + var_name variable = variables[key] # grab the reference value, set it, read it back and validate they are the same ref_value = ogts.DataTypeHelper.test_input_value(entry) variable.set(context, ref_value) if "_array" in key: value = variable.get_array(context, False, 0) else: value = variable.get(context) # use almostEqual to deal with numerical imprecision # that occurs with some floating point precisions for a, b in zip(flatten(value), flatten(ref_value)): self.assertAlmostEqual(a, b, places=1) async def test_variables_can_be_created_and_removed(self): """Validates variables are correctly created and removed""" graph = self.create_simple_graph() # validate variables can be created var1 = self.create_variable(graph, "var_float", og.Type(og.BaseDataType.FLOAT)) var2 = self.create_variable(graph, "var_int", og.Type(og.BaseDataType.INT)) var3 = self.create_variable(graph, "var_float_array", og.Type(og.BaseDataType.FLOAT, 3, 0)) var4 = self.create_variable(graph, "var_int_tuple", og.Type(og.BaseDataType.INT, 2, 0)) # check they are all valid, using both valid property and __bool__ override self.assertTrue(var1.valid) self.assertTrue(var2.valid) self.assertTrue(var3.valid) self.assertTrue(var4.valid) self.assertTrue(bool(var1)) self.assertTrue(bool(var2)) self.assertTrue(bool(var3)) self.assertTrue(bool(var4)) # check that the list is created as expected variables = graph.get_variables() self.assertEquals(len(variables), 4) self.assertIn(var1, variables) self.assertIn(var2, variables) self.assertIn(var3, variables) self.assertIn(var4, variables) # validate nodes that already exist (same type, different type) are ignored with ogts.ExpectedError(): var_x = graph.create_variable("var_float", og.Type(og.BaseDataType.FLOAT)) self.assertEquals(var_x, None) with ogts.ExpectedError(): var_x = graph.create_variable("var_float", og.Type(og.BaseDataType.INT)) self.assertEquals(var_x, None) # remove a variable, then again to verify it fails self.assertTrue(graph.remove_variable(var3)) with ogts.ExpectedError(): self.assertFalse(graph.remove_variable(var3)) self.assertEquals(len(graph.get_variables()), 3) self.assertNotIn(var3, graph.get_variables()) self.assertFalse(var3.valid) self.assertFalse(bool(var3)) async def test_find_variable(self): """Tests that variables can be correctly searched for by name""" graph = self.create_simple_graph() # create a set of variables for a in string.ascii_lowercase: self.create_variable(graph, "var_" + a, og.Type(og.BaseDataType.FLOAT)) # validate they are correctly found for a in string.ascii_lowercase: var = graph.find_variable("var_" + a) self.assertIsNotNone(var) self.assertEquals(var.name, "var_" + a) self.assertIsNone(graph.find_variable("not_var_" + a)) async def test_variable_metadata(self): """Validates the metadata for the variables can and retreived as expected.""" graph = self.create_simple_graph() var = graph.create_variable("var", og.Type(og.BaseDataType.FLOAT)) self.assertTrue(var.valid) # validate default values self.assertEquals(var.display_name, "var") self.assertEquals(var.category, "") self.assertEquals(var.tooltip, "") self.assertEquals(var.scope, og.eVariableScope.E_PRIVATE) # set valid values var.display_name = "VAR1" var.category = "New Category" var.tooltip = "Tooltip" var.scope = og.eVariableScope.E_READ_ONLY self.assertEquals(var.display_name, "VAR1") self.assertEquals(var.category, "New Category") self.assertEquals(var.tooltip, "Tooltip") self.assertEquals(var.scope, og.eVariableScope.E_READ_ONLY) # set special and/or secondary values var.display_name = "" var.category = "" var.tooltip = "" var.scope = og.eVariableScope.E_PUBLIC self.assertEquals(var.display_name, "var") # "" resets to default value self.assertEquals(var.category, "") self.assertEquals(var.tooltip, "") self.assertEquals(var.scope, og.eVariableScope.E_PUBLIC) var.category = "New Category" var.tooltip = "Tooltip" # validate that removed attribute specify empty/default values graph.remove_variable(var) self.assertFalse(var.valid) self.assertEquals(var.display_name, "") self.assertEquals(var.category, "") self.assertEquals(var.tooltip, "") self.assertEquals(var.scope, og.eVariableScope.E_PRIVATE) async def test_variables_save_and_load(self): """Verifies that variables are correctly saved and restored from serialization""" type_list = [og.BaseDataType.FLOAT, og.BaseDataType.INT, og.BaseDataType.HALF] graph = self.create_simple_graph() for x in type_list: type_name = str(x).replace(".", "_") self.create_variable( graph, str(type_name).lower(), og.Type(x), display_name=str(type_name).upper(), category=str(type_name).swapcase(), scope=og.eVariableScope.E_PUBLIC, tooltip=str(type_name).title(), ) with tempfile.TemporaryDirectory() as tmpdirname: # save the file tmp_file_path = os.path.join(tmpdirname, "tmp.usda") result = omni.usd.get_context().save_as_stage(tmp_file_path) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(tmp_file_path) self.assertTrue(result, error) graph = omni.graph.core.get_graph_by_path(self._graph_path) self.assertTrue(graph.is_valid) self.assertEquals(len(graph.get_variables()), len(type_list)) for x in type_list: type_name = str(x).replace(".", "_") var = graph.find_variable(str(type_name).lower()) self.assertEquals(var.type, og.Type(x)) self.assertEquals(var.scope, og.eVariableScope.E_PUBLIC) self.assertEquals(var.display_name, str(type_name).upper()) self.assertEquals(var.category, str(type_name).swapcase()) self.assertEquals(var.tooltip, str(type_name).title()) # ---------------------------------------------------------------------- async def test_write_variable_node(self): """Tests WriteVariable Nodes that variable data is correctly written for all variable types""" # +-------+ +-------------+ # |OnTick |-->|WriteVariable| # +-------+ +-------------+ # C++ node, Python equivalent for write_node in ["omni.graph.core.WriteVariable", "omni.graph.test.TestWriteVariablePy"]: with self.subTest(write_node=write_node): controller = og.Controller() keys = og.Controller.Keys variables = self.get_variables_from_types() # Create a graph that writes the give variable (graph, (_, write_variable_node), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("WriteVariable", write_node), ], keys.CONNECT: [ ("OnTick.outputs:tick", "WriteVariable.inputs:execIn"), ], keys.CREATE_VARIABLES: [(var_name, var_type) for (var_name, var_type, _) in variables], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ], }, ) for (var_name, og_type, ref_value) in variables: variable = graph.find_variable(var_name) # First write the variable type, then the value. The value field needs to resolve first, # based on the type of variable that is set variable_name_attr = write_variable_node.get_attribute("inputs:variableName") variable_value_attr = write_variable_node.get_attribute("inputs:value") og.Controller.set(variable_name_attr, var_name) og.Controller.set(variable_value_attr, ref_value) # Evaluate the graph, which writes the value await controller.evaluate(graph) # fetch the data from variable node variable_output_attr = write_variable_node.get_attribute("outputs:value") # retrieve the value from the graph variable, and the output port if og_type.array_depth >= 1: value = variable.get_array(graph.get_default_graph_context(), False, 0) output_value = variable_output_attr.get_array(False, False, 0) else: value = variable.get(graph.get_default_graph_context()) output_value = variable_output_attr.get() # unpack and compare the elements for a, b, c in zip(flatten(value), flatten(ref_value), flatten(output_value)): self.assertAlmostEqual(a, b, places=1, msg=f"{var_name} {og_type}") self.assertAlmostEqual(a, c, places=1, msg=f"{var_name} {og_type}") # reset the stage, so the next iteration starts clean await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() # ---------------------------------------------------------------------- async def test_variable_graph_type_resolution(self): """Tests output port resolution for built""" controller = og.Controller() keys = og.Controller.Keys # [ReadVariable]->+------------+ # [ConstantString]->[WriteVariable]->|AppendString|->[WriteVariable] # +------------+ (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("WriteVariable", "omni.graph.core.WriteVariable"), ("AppendString", "omni.graph.nodes.AppendString"), ("WriteVariable2", "omni.graph.core.WriteVariable"), ("ConstantToken", "omni.graph.nodes.ConstantToken"), ], keys.CREATE_VARIABLES: [ ("var_float", og.Type(og.BaseDataType.FLOAT)), ("var_str", og.Type(og.BaseDataType.TOKEN)), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "AppendString.inputs:value"), ("WriteVariable.outputs:value", "AppendString.inputs:suffix"), ("AppendString.outputs:value", "WriteVariable2.inputs:value"), ("ConstantToken.inputs:value", "WriteVariable.inputs:value"), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "var_str"), ("WriteVariable.inputs:variableName", "var_str"), ("WriteVariable2.inputs:variableName", "var_str"), ("ConstantToken.inputs:value", "_A_"), ], }, ) await omni.kit.app.get_app().next_update_async() # Helper to verify the base data type of an attribute def assert_attrib_is(attrib, node, base_type): attrib = controller.attribute(attrib, node, graph) self.assertEqual(attrib.get_resolved_type().base_type, base_type) # validate the output types assert_attrib_is("outputs:value", "ReadVariable", og.BaseDataType.TOKEN) assert_attrib_is("outputs:value", "WriteVariable", og.BaseDataType.TOKEN) assert_attrib_is("inputs:value", "WriteVariable", og.BaseDataType.TOKEN) assert_attrib_is("inputs:value", "WriteVariable2", og.BaseDataType.TOKEN) # disconnect the input controller.edit( graph, { keys.DISCONNECT: [ ("ReadVariable.outputs:value", "AppendString.inputs:value"), ("WriteVariable.outputs:value", "AppendString.inputs:suffix"), ("ConstantToken.inputs:value", "WriteVariable.inputs:value"), ] }, ) await omni.kit.app.get_app().next_update_async() # resolution types assert_attrib_is("outputs:value", "ReadVariable", og.BaseDataType.TOKEN) assert_attrib_is("outputs:value", "WriteVariable", og.BaseDataType.TOKEN) assert_attrib_is("inputs:value", "WriteVariable", og.BaseDataType.TOKEN) assert_attrib_is("inputs:value", "AppendString", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:suffix", "AppendString", og.BaseDataType.UNKNOWN) # change the variable type one at a time controller.edit( graph, { keys.SET_VALUES: [ ("WriteVariable.inputs:variableName", "var_float"), ("ReadVariable.inputs:variableName", "var_float"), ], }, ) await omni.kit.app.get_app().next_update_async() # validate the updated resolution - outputs change, inputs unresolve assert_attrib_is("outputs:value", "ReadVariable", og.BaseDataType.FLOAT) assert_attrib_is("outputs:value", "WriteVariable", og.BaseDataType.FLOAT) assert_attrib_is("inputs:value", "WriteVariable", og.BaseDataType.FLOAT) # 'unset' the variable name controller.edit( graph, { keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", ""), ("WriteVariable.inputs:variableName", ""), ] }, ) await omni.kit.app.get_app().next_update_async() assert_attrib_is("outputs:value", "ReadVariable", og.BaseDataType.UNKNOWN) assert_attrib_is("outputs:value", "WriteVariable", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:value", "WriteVariable", og.BaseDataType.UNKNOWN) # ---------------------------------------------------------------------- async def test_read_variable_node(self): """Tests ReadVariable Nodes that variable data is properly read for all variable types""" # C++ node, Python equivalent for read_node in ["omni.graph.core.ReadVariable", "omni.graph.test.TestReadVariablePy"]: with self.subTest(read_node=read_node): controller = og.Controller() keys = og.Controller.Keys variables = self.get_variables_from_types() # Create a graph that writes the give variable (graph, nodes, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", read_node), ], keys.CREATE_VARIABLES: [(var_name, var_type) for (var_name, var_type, _) in variables], }, ) context = graph.get_default_graph_context() for (var_name, var_type, ref_value) in variables: # set the value on the variable variable = graph.find_variable(var_name) variable.set(context, ref_value) # set the node to use the appropriate variable variable_name_attr = nodes[0].get_attribute("inputs:variableName") og.Controller.set(variable_name_attr, var_name) # Evaluate the graph and read the output of the node await controller.evaluate(graph) value = og.Controller.get(nodes[0].get_attribute("outputs:value")) # unpack and compare the elements for a, b in zip(flatten(value), flatten(ref_value)): self.assertAlmostEqual(a, b, places=1, msg=f"{var_name} : {var_type}") # reset the stage, so the next iteration starts clean await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() # ---------------------------------------------------------------------- async def test_variable_graph_events(self): """Tests that variable related graph events trigger and are caught by built-in variable nodes""" controller = og.Controller() keys = og.Controller.Keys (graph, (read_var_node, write_var_node), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("WriteVariable", "omni.graph.core.WriteVariable"), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "test_var"), ("WriteVariable.inputs:variableName", "test_var"), ], }, ) create_counter = 0 remove_counter = 0 last_var_name = "" def on_graph_event(event): nonlocal create_counter nonlocal remove_counter nonlocal last_var_name if event.type == int(og.GraphEvent.CREATE_VARIABLE): create_counter += 1 if event.type == int(og.GraphEvent.REMOVE_VARIABLE): remove_counter += 1 last_var_name = event.payload["variable"] sub = graph.get_event_stream().create_subscription_to_pop(on_graph_event) var = graph.create_variable("test_var", og.Type(og.BaseDataType.FLOAT)) # check the callback has been hit, and that the resolved type has been updated self.assertEquals(create_counter, 1) self.assertEquals( read_var_node.get_attribute("outputs:value").get_resolved_type(), og.Type(og.BaseDataType.FLOAT) ) self.assertEquals( write_var_node.get_attribute("inputs:value").get_resolved_type(), og.Type(og.BaseDataType.FLOAT) ) self.assertEquals(last_var_name, "test_var") last_var_name = "" # remove the variable, it should unresolve graph.remove_variable(var) self.assertEquals(remove_counter, 1) self.assertEquals( read_var_node.get_attribute("outputs:value").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertEquals( write_var_node.get_attribute("inputs:value").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertEquals(last_var_name, "test_var") # add, remove a variety of variables, including the listened one (with a different type) graph.create_variable("test_var", og.Type(og.BaseDataType.BOOL)) for i in range(1, 10): var_n = graph.create_variable(f"test_var{i}", og.Type(og.BaseDataType.INT)) self.assertEquals(last_var_name, f"test_var{i}") if i % 2 == 0: graph.remove_variable(var_n) self.assertEquals(create_counter, 11) self.assertEquals(remove_counter, 5) self.assertEquals( read_var_node.get_attribute("outputs:value").get_resolved_type(), og.Type(og.BaseDataType.BOOL) ) self.assertEquals( write_var_node.get_attribute("inputs:value").get_resolved_type(), og.Type(og.BaseDataType.BOOL) ) del sub def assert_almost_equal(self, a_val, b_val): flat_a = flatten(a_val) flat_b = flatten(b_val) self.assertEqual(len(flat_a), len(flat_b)) for a, b in zip(flatten(a_val), flatten(b_val)): self.assertAlmostEqual(a, b, places=1, msg=f"{a_val} != {b_val}") # ---------------------------------------------------------------------- async def test_variables_load_default_values(self): """Tests variables are initialized with attribute default values""" (result, error) = await ogts.load_test_file("TestGraphVariables.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = omni.graph.core.get_graph_by_path("/World/ComputeGraph") ctxt = graph.get_default_graph_context() self.assert_almost_equal(graph.find_variable("var_bool").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_bool_array").get_array(ctxt), [1, 0, 1]) self.assert_almost_equal(graph.find_variable("var_color3d").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_color3d_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_color3f").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_color3f_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_color3h").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_color3h_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_color4d").get(ctxt), (1, 2, 3, 4)) self.assert_almost_equal( graph.find_variable("var_color4d_array").get_array(ctxt), [(1, 2, 3, 4), (11, 12, 13, 14)] ) self.assert_almost_equal(graph.find_variable("var_color4f").get(ctxt), (1, 2, 3, 4)) self.assert_almost_equal( graph.find_variable("var_color4f_array").get_array(ctxt), [(1, 2, 3, 4), (11, 12, 13, 14)] ) self.assert_almost_equal(graph.find_variable("var_color4h").get(ctxt), (1, 2, 3, 4)) self.assert_almost_equal( graph.find_variable("var_color4h_array").get_array(ctxt), [(1, 2, 3, 4), (11, 12, 13, 14)] ) self.assert_almost_equal(graph.find_variable("var_double").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_double2").get(ctxt), (1, 2)) self.assert_almost_equal(graph.find_variable("var_double2_array").get_array(ctxt), [(1, 2), (11, 12)]) self.assert_almost_equal(graph.find_variable("var_double3").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_double3_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_double4").get(ctxt), (1, 2, 3, 4)) self.assert_almost_equal( graph.find_variable("var_double4_array").get_array(ctxt), [(1, 2, 3, 4), (11, 12, 13, 14)] ) self.assert_almost_equal(graph.find_variable("var_double_array").get_array(ctxt), [1, 2]) self.assert_almost_equal(graph.find_variable("var_float").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_float2").get(ctxt), (1, 2)) self.assert_almost_equal(graph.find_variable("var_float2_array").get_array(ctxt), [(1, 2), (11, 12)]) self.assert_almost_equal(graph.find_variable("var_float3").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_float3_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_float4").get(ctxt), (1, 2, 3, 4)) self.assert_almost_equal( graph.find_variable("var_float4_array").get_array(ctxt), [(1, 2, 3, 4), (11, 12, 13, 14)] ) self.assert_almost_equal(graph.find_variable("var_float_array").get_array(ctxt), [1, 2]) self.assert_almost_equal( graph.find_variable("var_frame4d").get(ctxt), ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)), ) self.assert_almost_equal( graph.find_variable("var_frame4d_array").get_array(ctxt), [ ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)), ((11, 12, 13, 14), (15, 16, 17, 18), (19, 20, 21, 22), (23, 24, 25, 26)), ], ) self.assert_almost_equal(graph.find_variable("var_half").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_half2").get(ctxt), (1, 2)) self.assert_almost_equal(graph.find_variable("var_half2_array").get_array(ctxt), [(1, 2), (11, 12)]) self.assert_almost_equal(graph.find_variable("var_half3").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_half3_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_half4").get(ctxt), (1, 2, 3, 4)) self.assert_almost_equal( graph.find_variable("var_half4_array").get_array(ctxt), [(1, 2, 3, 4), (11, 12, 13, 14)] ) self.assert_almost_equal(graph.find_variable("var_half_array").get_array(ctxt), [1, 2]) self.assert_almost_equal(graph.find_variable("var_int").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_int2").get(ctxt), (1, 2)) self.assert_almost_equal(graph.find_variable("var_int2_array").get_array(ctxt), [(1, 2), (3, 4)]) self.assert_almost_equal(graph.find_variable("var_int3").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_int3_array").get_array(ctxt), [(1, 2, 3), (4, 5, 6)]) self.assert_almost_equal(graph.find_variable("var_int4").get(ctxt), (1, 2, 3, 4)) self.assert_almost_equal(graph.find_variable("var_int4_array").get_array(ctxt), [(1, 2, 3, 4), (5, 6, 7, 8)]) self.assert_almost_equal(graph.find_variable("var_int64").get(ctxt), 12345) self.assert_almost_equal(graph.find_variable("var_int64_array").get_array(ctxt), [12345, 23456]) self.assert_almost_equal(graph.find_variable("var_int_array").get_array(ctxt), [1, 2]) self.assert_almost_equal(graph.find_variable("var_matrix2d").get(ctxt), ((1, 2), (3, 4))) self.assert_almost_equal( graph.find_variable("var_matrix2d_array").get_array(ctxt), [((1, 2), (3, 4)), ((11, 12), (13, 14))] ) self.assert_almost_equal(graph.find_variable("var_matrix3d").get(ctxt), ((1, 2, 3), (4, 5, 6), (7, 8, 9))) self.assert_almost_equal( graph.find_variable("var_matrix3d_array").get_array(ctxt), [((1, 2, 3), (4, 5, 6), (7, 8, 9)), ((11, 12, 13), (14, 15, 16), (17, 18, 19))], ) self.assert_almost_equal( graph.find_variable("var_matrix4d").get(ctxt), ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)), ) self.assert_almost_equal( graph.find_variable("var_matrix4d_array").get_array(ctxt), [ ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)), ((11, 12, 13, 14), (15, 16, 17, 18), (19, 20, 21, 22), (23, 24, 25, 26)), ], ) self.assert_almost_equal(graph.find_variable("var_normal3d").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_normal3d_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_normal3f").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_normal3f_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_normal3h").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_normal3h_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_point3d").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_point3d_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_point3f").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_point3f_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_point3h").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_point3h_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) # note the reordering of the quaternion layout self.assert_almost_equal(graph.find_variable("var_quatd").get(ctxt), (2, 3, 4, 1)) self.assert_almost_equal( graph.find_variable("var_quatd_array").get_array(ctxt), [(2, 3, 4, 1), (12, 13, 14, 11)] ) self.assert_almost_equal(graph.find_variable("var_quatf").get(ctxt), (2, 3, 4, 1)) self.assert_almost_equal( graph.find_variable("var_quatf_array").get_array(ctxt), [(2, 3, 4, 1), (12, 13, 14, 11)] ) self.assert_almost_equal(graph.find_variable("var_quath").get(ctxt), (2, 3, 4, 1)) self.assert_almost_equal( graph.find_variable("var_quath_array").get_array(ctxt), [(2, 3, 4, 1), (12, 13, 14, 11)] ) # strings use get_array, not get self.assertEqual(graph.find_variable("var_string").get_array(ctxt), "Rey") self.assert_almost_equal(graph.find_variable("var_texcoord2d").get(ctxt), (1, 2)) self.assert_almost_equal(graph.find_variable("var_texcoord2d_array").get_array(ctxt), [(1, 2), (11, 12)]) self.assert_almost_equal(graph.find_variable("var_texcoord2f").get(ctxt), (1, 2)) self.assert_almost_equal(graph.find_variable("var_texcoord2f_array").get_array(ctxt), [(1, 2), (11, 12)]) self.assert_almost_equal(graph.find_variable("var_texcoord2h").get(ctxt), (1, 2)) self.assert_almost_equal(graph.find_variable("var_texcoord2h_array").get_array(ctxt), [(1, 2), (11, 12)]) self.assert_almost_equal(graph.find_variable("var_texcoord3d").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_texcoord3d_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_texcoord3f").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_texcoord3f_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_texcoord3h").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_texcoord3h_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_timecode").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_timecode_array").get_array(ctxt), [1, 2]) self.assert_almost_equal(graph.find_variable("var_token").get(ctxt), "Sith") self.assert_almost_equal(graph.find_variable("var_token_array").get_array(ctxt), ["Kylo", "Ren"]) self.assert_almost_equal(graph.find_variable("var_uchar").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_uchar_array").get_array(ctxt), [1, 2]) self.assert_almost_equal(graph.find_variable("var_uint").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_uint64").get(ctxt), 1) self.assert_almost_equal(graph.find_variable("var_uint64_array").get_array(ctxt), [1, 2]) self.assert_almost_equal(graph.find_variable("var_uint_array").get_array(ctxt), [1, 2]) self.assert_almost_equal(graph.find_variable("var_vector3d").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_vector3d_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_vector3f").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_vector3f_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) self.assert_almost_equal(graph.find_variable("var_vector3h").get(ctxt), (1, 2, 3)) self.assert_almost_equal(graph.find_variable("var_vector3h_array").get_array(ctxt), [(1, 2, 3), (11, 12, 13)]) # ------------------------------------------------------------------------- async def test_variables_create_remove_stress_test(self): """Stress test the creation, removal and query of variables""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ], }, ) context = graph.get_default_graph_context() # get/set the active variable (FC) def active_set(var, val): nonlocal context var.set(context, val) def active_get(var): nonlocal context return var.get(context) # get/set the default value def default_set(var, val): og.Controller.set_variable_default_value(var, val) def default_get(var): return og.Controller.get_variable_default_value(var) # include setting the default value and getting the active value func_list = [(active_get, active_set), (default_get, default_set), (active_get, default_set)] # loop through default and active get, set values methods for (getter, setter) in func_list: for i in range(1, 10): variable = graph.create_variable("TestVariable", og.Type(og.BaseDataType.FLOAT)) setter(variable, float(i)) self.assertEqual(getter(variable), float(i)) graph.remove_variable(variable) self.assertFalse(bool(variable)) self.assertIsNone(graph.find_variable("TestVariable")) # ------------------------------------------------------------------------- async def test_variables_write_update_on_graph(self): """Tests that the updating of variables occurs as expected""" # Create a graph that writes the give variable controller = og.Controller() keys = og.Controller.Keys # [OnTick] --> [WriteVariable(2)] (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("WriteVariable", "omni.graph.core.WriteVariable"), ("ConstInt", "omni.graph.nodes.ConstantInt"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "WriteVariable.inputs:execIn"), ("ConstInt.inputs:value", "WriteVariable.inputs:value"), ], keys.CREATE_VARIABLES: [("TestVariable", og.Type(og.BaseDataType.INT))], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("ConstInt.inputs:value", 2), ("WriteVariable.inputs:variableName", "TestVariable"), ], }, ) variable = graph.find_variable("TestVariable") og.Controller.set_variable_default_value(variable, 1) await controller.evaluate(graph) # USD value remains at 1 self.assertEqual(og.Controller.get_variable_default_value(variable), 1) # Fabric value remains at 2 self.assertEqual(variable.get(graph.get_default_graph_context()), 2) # change default value - variable value should change og.Controller.set_variable_default_value(variable, 3) self.assertEqual(og.Controller.get_variable_default_value(variable), 3) self.assertEqual(variable.get(graph.get_default_graph_context()), 3) await controller.evaluate(graph) # FC value should change again self.assertEqual(og.Controller.get_variable_default_value(variable), 3) self.assertEqual(variable.get(graph.get_default_graph_context()), 2) # ------------------------------------------------------------------------- async def __create_instances(self, graph_path: str, prim_names: List[str]): """Helper method to create graph instances""" stage = omni.usd.get_context().get_stage() for prim_name in prim_names: prim = stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, graph_path) self.assertTrue(prim.GetRelationship("omniGraphs").IsValid()) # need to wait a frame for USD changes to apply. This could use an immediate # python API. await omni.kit.app.get_app().next_update_async() # ------------------------------------------------------------------------- async def test_get_set_variable_instance_values(self): """Tests for retrieving and setting variable instance values""" # create the graph controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_VARIABLES: [ ("float_var", og.Type(og.BaseDataType.FLOAT)), ("token_var", og.Type(og.BaseDataType.TOKEN)), ("array_var", og.Type(og.BaseDataType.INT, array_depth=1)), ("tuple_var", og.Type(og.BaseDataType.FLOAT, 3, 0)), ], }, ) # create the instances prim_names = [f"/World/Prim_{i}" for i in range(1, 10)] await self.__create_instances(self._graph_path, prim_names) context = graph.get_default_graph_context() float_var = graph.find_variable("float_var") token_var = graph.find_variable("token_var") array_var = graph.find_variable("array_var") tuple_var = graph.find_variable("tuple_var") # set the default variable values. This should be promoted to each instance og.Controller.set_variable_default_value(float_var, -1.0) og.Controller.set_variable_default_value(token_var, "token_var") og.Controller.set_variable_default_value(array_var, [1.0, 1.0, 1.0, 1.0]) og.Controller.set_variable_default_value(tuple_var, (1.0, 1.0, 1.0)) # validate all the instances have the default value for prim_name in prim_names: self.assertEquals(float_var.get(context, instance_path=prim_name), -1.0) self.assertEquals(token_var.get(context, instance_path=prim_name), "token_var") self.assert_almost_equal(array_var.get_array(context, instance_path=prim_name), [1.0, 1.0, 1.0, 1.0]) self.assert_almost_equal(tuple_var.get(context, instance_path=prim_name), (1.0, 1.0, 1.0)) # set the variables i = 0 for prim_name in prim_names: float_var.set(context, instance_path=prim_name, value=float(i)) token_var.set(context, instance_path=prim_name, value=prim_name) array_var.set(context, instance_path=prim_name, value=[i, i + 1, i + 2, i + 3]) tuple_var.set(context, instance_path=prim_name, value=(float(i), float(i + 1), float(i + 2))) i = i + 1 # retrieve the variables i = 0 for prim_name in prim_names: self.assertEquals(float_var.get(context, instance_path=prim_name), float(i)) self.assertEquals(token_var.get(context, instance_path=prim_name), prim_name) self.assert_almost_equal(array_var.get_array(context, instance_path=prim_name), [i, i + 1, i + 2, i + 3]) self.assert_almost_equal( tuple_var.get(context, instance_path=prim_name), (float(i), float(i + 1), float(i + 2)) ) i = i + 1 # ------------------------------------------------------------------------- async def test_invalid_variable_access_throws(self): """Tests that invalid variable access throws errors""" # create the graph controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_VARIABLES: [ ("float_var", og.Type(og.BaseDataType.FLOAT)), ("array_var", og.Type(og.BaseDataType.FLOAT, array_depth=1)), ("invalid_var", og.Type(og.BaseDataType.FLOAT)), ] }, ) # create an instance context = graph.get_default_graph_context() valid_prim_name = "/World/ValidInstance" invalid_instance_name = "/World/InvalidInstance" await self.__create_instances(self._graph_path, [valid_prim_name]) float_var = graph.find_variable("float_var") array_var = graph.find_variable("array_var") invalid_var = graph.find_variable("invalid_var") graph.remove_variable(invalid_var) og.Controller.set_variable_default_value(float_var, 1.0) self.assertEquals(float_var.get(context), 1.0) self.assertEquals(float_var.get(context, instance_path=valid_prim_name), 1.0) # invalid variable with self.assertRaises(TypeError): invalid_var.get(context) # invalid variable and instance with self.assertRaises(TypeError): invalid_var.get(context, instance_path=invalid_instance_name) # invalid instance, valid variable with self.assertRaises(TypeError): float_var.get(context, instance_path=invalid_instance_name) # invalid instance with array variable with self.assertRaises(TypeError): array_var.get(context, instance_path=invalid_instance_name) # ------------------------------------------------------------------------- def _get_ogtypes_for_testing(self) -> Set[og.Type]: """Get a list of types to be used for testing.""" numerics = og.AttributeType.get_unions()["numerics"] type_set = {og.AttributeType.type_from_ogn_type_name(n_type) for n_type in numerics}.union( { og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT), og.Type(og.BaseDataType.TOKEN, 1, 0, og.AttributeRole.NONE), } ) # transform converts to matrix when used in a variable type_set.remove(og.Type(og.BaseDataType.DOUBLE, 16, 1, og.AttributeRole.TRANSFORM)) type_set.remove(og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.TRANSFORM)) return type_set # ------------------------------------------------------------------------- async def test_changevariabletype_command(self): """ Validates the ChangeVariableType Command property changes the type of the variable """ controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_VARIABLES: [ ("var", og.Type(og.BaseDataType.FLOAT)), ] }, ) types = self._get_ogtypes_for_testing() variable = graph.find_variable("var") for og_type in types: og.cmds.ChangeVariableType(variable=variable, variable_type=og_type) self.assertEqual(variable.type, og_type) # ------------------------------------------------------------------------- async def test_changevariabletype_command_undo_redo(self): """ Validates the change variable type command applies and restores default values as expected with undo and redo """ controller = og.Controller() keys = og.Controller.Keys original_type = og.Type(og.BaseDataType.FLOAT) (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_VARIABLES: [ ("var", original_type), ] }, ) types = self._get_ogtypes_for_testing() types.remove(original_type) variable = graph.find_variable("var") default_value = 5.0 og.Controller.set_variable_default_value(variable, default_value) # validate not changing type doesn't erase the default value og.cmds.ChangeVariableType(variable=variable, variable_type=original_type) self.assertEqual(variable.type, original_type) self.assertEqual(og.Controller.get_variable_default_value(variable), default_value) for og_type in types: og.cmds.ChangeVariableType(variable=variable, variable_type=og_type) self.assertEqual(variable.type, og_type) self.assertIsNone(og.Controller.get_variable_default_value(variable)) # on undo, when the type changes, the default value is removed omni.kit.undo.undo() self.assertEqual(variable.type, original_type) self.assertEqual(og.Controller.get_variable_default_value(variable), default_value) # on redo, the type and default value are restored omni.kit.undo.redo() self.assertEqual(variable.type, og_type) self.assertIsNone(og.Controller.get_variable_default_value(variable)) omni.kit.undo.undo() # ------------------------------------------------------------------------- async def test_changevariabletype_command_on_separate_layer(self): """ Validates the behaviour of change variable type command on different layers """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() root_layer = stage.GetRootLayer() identifier1 = LayerUtils.create_sublayer(root_layer, 0, "").identifier identifier2 = LayerUtils.create_sublayer(root_layer, 1, "").identifier identifier3 = LayerUtils.create_sublayer(root_layer, 2, "").identifier LayerUtils.set_edit_target(stage, identifier2) # create a graph on the middle layer controller = og.Controller() keys = og.Controller.Keys original_type = og.Type(og.BaseDataType.FLOAT) (graph, _, _, _) = controller.edit( self._graph_path, { keys.CREATE_VARIABLES: [ ("var", original_type), ] }, ) # validate the type can be changed variable = graph.find_variable("var") og_type = og.Type(og.BaseDataType.INT) og.cmds.ChangeVariableType(variable=variable, variable_type=og_type) self.assertEqual(variable.type, og_type) # change the edit layer to a type with a stronger opinion and validate the change still works LayerUtils.set_edit_target(stage, identifier1) variable = graph.find_variable("var") og_type = og.Type(og.BaseDataType.DOUBLE) og.cmds.ChangeVariableType(variable=variable, variable_type=og_type) self.assertEqual(variable.type, og_type) # change the edit layer to a type with a weaker opinion and validate the change fails LayerUtils.set_edit_target(stage, identifier3) variable = graph.find_variable("var") og_type = og.Type(og.BaseDataType.INT, 2) omni.kit.commands.set_logging_enabled(False) (_, succeeded) = og.cmds.ChangeVariableType(variable=variable, variable_type=og_type) omni.kit.commands.set_logging_enabled(True) self.assertFalse(succeeded) # ----------------------------------------------------------------------------------------- async def test_changevariabletype_changes_resolution(self): """ Validate that changing a variable type changes the resolution of node types """ controller = og.Controller() keys = og.Controller.Keys original_type = og.Type(og.BaseDataType.FLOAT) (graph, nodes, _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ], keys.CREATE_VARIABLES: [ ("var", original_type), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "var"), ], }, ) node = nodes[0] variable = graph.find_variable("var") await og.Controller.evaluate(graph) self.assertEqual(node.get_attribute("outputs:value").get_resolved_type(), original_type) og_type = og.Type(og.BaseDataType.INT, 2) omni.kit.commands.set_logging_enabled(False) await og.Controller.evaluate(graph) og.cmds.ChangeVariableType(variable=variable, variable_type=og_type) self.assertEqual(node.get_attribute("outputs:value").get_resolved_type(), og_type)
55,299
Python
46.34589
120
0.569468
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.test as ogtest from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphTestApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ogtest, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogtest.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(ogtest, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212 _check_public_api_contents(ogtest.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
936
Python
48.315787
110
0.65812
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_topology_commands.py
# noqa: PLC0302 """Tests for the various OmniGraph commands""" from typing import List, Tuple import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.usd from pxr import OmniGraphSchemaTools, Usd class TestTopologyCommands(ogts.OmniGraphTestCase): # ---------------------------------------------------------------------- async def test_create_graph_global(self): """ test the CreateGraphAsNodeCommand with global graphs """ # This is the main command we'll use # to create new graphs for users going forward. These graphs are top level graphs, and are wrapped by nodes # in an overall global container graph # We also leverage this setup to test the creation of dynamic attributes with USD backing orchestration_graphs = og.get_global_orchestration_graphs() # 4, because we have 3 separate pipeline stages currently (simulation, pre-render, post-render, on-demand) self.assertEqual(len(orchestration_graphs), 4) orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage( og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER ) self.assertEqual(len(orchestration_graphs), 1) self.assertEqual(orchestration_graphs[0].get_path_to_graph(), "/__postRenderRootGraph") self.assertEqual( orchestration_graphs[0].get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER ) self.assertEqual(orchestration_graphs[0].get_graph_backing_type(), og.GraphBackingType.GRAPH_BACKING_TYPE_NONE) self.assertEqual( orchestration_graphs[0].evaluation_mode, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC ) orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage( og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION ) self.assertEqual(len(orchestration_graphs), 1) orchestration_graph = orchestration_graphs[0] (result, wrapper_node) = og.cmds.CreateGraphAsNode( graph=orchestration_graph, node_name="my_push_graph", graph_path="/World/my_push_graph", evaluator_name="push", is_global_graph=True, backed_by_usd=True, fc_backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE, ) self.assertTrue(result) self.assertTrue(wrapper_node.is_valid()) self.assertEqual(wrapper_node.get_prim_path(), "/__simulationRootGraph/_World_my_push_graph") wrapped_graph = wrapper_node.get_wrapped_graph() self.assertTrue(wrapped_graph.is_valid()) self.assertEqual(wrapped_graph.get_path_to_graph(), "/World/my_push_graph") self.assertEqual(wrapped_graph.get_graph_backing_type(), og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED) self.assertEqual(wrapped_graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) self.assertEqual(wrapped_graph.evaluation_mode, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE) (_, (_, counter_node), _, _) = og.Controller.edit( wrapped_graph, { og.Controller.Keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Counter", "omni.graph.action.Counter"), ], og.Controller.Keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)], og.Controller.Keys.CONNECT: [ ("OnTick.outputs:tick", "Counter.inputs:execIn"), ], }, ) # What we should see in response is that the counter is incrementing await og.Controller.evaluate(wrapped_graph) outputs_attr_value1 = og.Controller.get(counter_node.get_attribute("outputs:count")) await og.Controller.evaluate(wrapped_graph) outputs_attr_value2 = og.Controller.get(counter_node.get_attribute("outputs:count")) self.assertGreater(outputs_attr_value2, outputs_attr_value1) # test dynamic attribute creation, with USD backing: # try setting a simple value and retrieving it counter_node.create_attribute( "inputs:test_create1", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "", ) test_create1_attr = counter_node.get_attribute("inputs:test_create1") self.assertTrue(test_create1_attr.is_valid()) self.assertTrue(test_create1_attr.is_dynamic()) og.cmds.SetAttr(attr=test_create1_attr, value=123) test_create1_attr_value = og.Controller.get(test_create1_attr) self.assertEqual(test_create1_attr_value, 123) self.assertEqual(test_create1_attr.get_port_type(), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) # try setting a tuple value and retrieving it counter_node.create_attribute( "inputs:test_create2", og.Type(og.BaseDataType.INT, 3), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "", ) test_create2_attr = counter_node.get_attribute("inputs:test_create2") self.assertTrue(test_create2_attr.is_valid()) og.cmds.SetAttr(attr=test_create2_attr, value=(1, 2, 3)) test_create2_attr_value = og.Controller.get(test_create2_attr) self.assertEqual(test_create2_attr_value[0], 1) self.assertEqual(test_create2_attr_value[1], 2) self.assertEqual(test_create2_attr_value[2], 3) # try setting a tuple array value and retrieving it counter_node.create_attribute( "inputs:test_create3", og.Type(og.BaseDataType.INT, 3, 1), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "", ) test_create3_attr = counter_node.get_attribute("inputs:test_create3") self.assertTrue(test_create3_attr.is_valid()) og.cmds.SetAttr(attr=test_create3_attr, value=[[1, 2, 3], [4, 5, 6]]) test_create3_attr_value = og.Controller.get(test_create3_attr) v1 = test_create3_attr_value[1] self.assertEqual(v1[0], 4) self.assertEqual(v1[1], 5) self.assertEqual(v1[2], 6) # try creating an execution attribute counter_node.create_attribute( "inputs:test_create4", og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "", ) test_create4_attr = counter_node.get_attribute("inputs:test_create4") self.assertTrue(test_create4_attr.is_valid()) # ---------------------------------------------------------------------- async def test_undo_redo_connection(self): """Test undo and redo of node creation and connection""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit("/TestGraph") async def create_and_connect(ix): controller.edit( graph, { keys.CREATE_NODES: [ (f"SimpleA{ix}", "omni.graph.tutorials.SimpleData"), (f"SimpleB{ix}", "omni.graph.tutorials.SimpleData"), ] }, ) await controller.evaluate(graph) controller.edit(graph, {keys.CONNECT: (f"SimpleA{ix}.outputs:a_float", f"SimpleB{ix}.inputs:a_float")}) await controller.evaluate(graph) await create_and_connect(1) # undo the connection omni.kit.undo.undo() # undo the node creation omni.kit.undo.undo() # redo node creation omni.kit.undo.redo() # redo connection omni.kit.undo.redo() # undo the connection omni.kit.undo.undo() # undo the node creation omni.kit.undo.undo() # -------------------------------------------------------------------------------------------------------------- def __confirm_connection_counts(self, attribute: og.Attribute, upstream_count: int, downstream_count: int): """Check that the given attribute has the proscribed number of upstream and downstream connections""" self.assertEqual(attribute.get_upstream_connection_count(), upstream_count) self.assertEqual(attribute.get_downstream_connection_count(), downstream_count) # ---------------------------------------------------------------------- async def test_disconnect_all_attrs(self): """ Test the DisconnectAllAttrsCommand. This command takes a single attribute as parameter and disconnects all incoming and outgoing connections on it. """ controller = og.Controller() keys = og.Controller.Keys # # Source --> Sink --> InOut # \ \ / # \ -----/ # --> FanOut (graph, (source_node, sink_node, fanout_node, inout_node), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("Source", "omni.graph.tutorials.SimpleData"), ("Sink", "omni.graph.tutorials.SimpleData"), ("FanOut", "omni.graph.tutorials.SimpleData"), ("InOut", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("Source.outputs:a_bool", "Sink.inputs:a_bool"), ("Source.outputs:a_bool", "FanOut.inputs:a_bool"), ("Sink.inputs:a_bool", "InOut.inputs:a_bool"), ], }, ) def _get_attributes(): return ( og.Controller.attribute("outputs:a_bool", ("Source", graph)), og.Controller.attribute("inputs:a_bool", ("Sink", graph)), og.Controller.attribute("inputs:a_bool", ("FanOut", graph)), og.Controller.attribute("inputs:a_bool", ("InOut", graph)), ) source_output, sink_input, fanout_input, inout_input = _get_attributes() # The sequence tests successful restoration when everything is deleted and restored in groups; # DisconnectAll(Source.outputs:a_bool) # Removes Source->Sink and Source->FanOut # DisconnectAll(Sink.inputs:a_bool) # Removes Sink->InOut # Delete Source, Sink, InOut, FanOut # undo deletes # undo second disconnect # Restores Sink->InOut # undo first disconnect # Restores Source->Sink and Source->FanOut # redo and undo to go the beginning and get back here again # DisconnectAll(Sink.inputs:a_bool) # Removes Sink->InOut and Source->Sink # undo og.cmds.DisconnectAllAttrs(attr=source_output, modify_usd=True) self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 1) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 1, 0) og.cmds.DisconnectAllAttrs(attr=sink_input, modify_usd=True) self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 0) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 0, 0) og.cmds.DeleteNode(graph=graph, node_path=source_node.get_prim_path(), modify_usd=True) og.cmds.DeleteNode(graph=graph, node_path=sink_node.get_prim_path(), modify_usd=True) og.cmds.DeleteNode(graph=graph, node_path=fanout_node.get_prim_path(), modify_usd=True) og.cmds.DeleteNode(graph=graph, node_path=inout_node.get_prim_path(), modify_usd=True) omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() # May have lost the objects through the undo process so get them again source_output, sink_input, fanout_input, inout_input = _get_attributes() self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 1) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 1, 0) omni.kit.undo.undo() self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) omni.kit.undo.redo() omni.kit.undo.redo() omni.kit.undo.redo() omni.kit.undo.redo() omni.kit.undo.redo() omni.kit.undo.redo() omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() # May have lost the objects through the undo process so get them again source_output, sink_input, fanout_input, inout_input = _get_attributes() self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) og.cmds.DisconnectAllAttrs(attr=sink_input, modify_usd=True) self.__confirm_connection_counts(source_output, 0, 1) self.__confirm_connection_counts(sink_input, 0, 0) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 0, 0) omni.kit.undo.undo() self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) # ---------------------------------------------------------------------- async def test_change_pipeline_stage_invalid(self): """ Test the ChangePipelineStageCommand when given an invalid pipeline stage """ controller = og.Controller() (graph, _, _, _) = controller.edit("/World/TestGraph") self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) # Check that we are not allowed to set pipeline stage to unknown og.cmds.ChangePipelineStage(graph=graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_UNKNOWN) self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) # Check that setting the same pipeline stage does nothing og.cmds.ChangePipelineStage( graph=graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION ) self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) # ------------------------------------------------------------------------- async def next_frame(self, node) -> bool: """Helper method that ticks the next frame, returning how many times the node was ticked""" start_count = node.get_compute_count() await omni.kit.app.get_app().next_update_async() end_count = node.get_compute_count() return end_count - start_count # ------------------------------------------------------------------------- async def test_evaluation_modes_command(self): """Test evaluation modes using instanced and non-instanced graphs""" _graph_path = "/World/TestGraph" __graph_count = 0 def create_simple_graph(path) -> Tuple[og.Graph, List[og.Node]]: nonlocal __graph_count controller = og.Controller() keys = og.Controller.Keys (graph, nodes, _, _) = controller.edit( f"{path}_{__graph_count}", { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ] }, ) __graph_count += 1 return (graph, nodes) def create_graph_instance(name: str, graph: og.Graph) -> Usd.Prim: """Creates an instance of the given graph""" stage = omni.usd.get_context().get_stage() prim = stage.DefinePrim(name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim.GetPath(), graph.get_path_to_graph()) return prim stage = omni.usd.get_context().get_stage() (graph, nodes) = create_simple_graph(_graph_path) timeline = omni.timeline.get_timeline_interface() timeline.set_target_framerate(timeline.get_time_codes_per_seconds()) timeline.set_start_time(0) timeline.set_end_time(1000) timeline.play() node = nodes[0] self.assertEquals(graph.evaluation_mode, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC) # in standalone mode, the node should tick ticks = await self.next_frame(node) self.assertEquals(ticks, 1) # in asset mode it should not og.cmds.SetEvaluationMode( graph=graph, new_evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED ) ticks = await self.next_frame(node) self.assertEquals(ticks, 0) # create graph instances prims = [create_graph_instance(f"/World/Prim{i}", graph) for i in range(0, 2)] # automatic mode reference mode should evaluate once (vectorized) for all instances # the returned compute count should be equal to the number of instances though expected_instanced_ticks = 2 ticks = await self.next_frame(node) self.assertEquals(ticks, expected_instanced_ticks) og.cmds.SetEvaluationMode( graph=graph, new_evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC ) ticks = await self.next_frame(node) self.assertEquals(ticks, expected_instanced_ticks) # standalone mode should run itself and not the prims og.cmds.SetEvaluationMode( graph=graph, new_evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE ) ticks = await self.next_frame(node) self.assertEquals(ticks, 1) # delete the prims, standalone should now run for p in prims: stage.RemovePrim(p.GetPath()) ticks = await self.next_frame(node) self.assertEquals(ticks, 1) omni.timeline.get_timeline_interface().stop() # ---------------------------------------------------------------------- async def test_evaluation_modes_command_undo_redo(self): """Tests the evaluation mode command has the correct value when undo and redo are applied""" controller = og.Controller() (graph, _, _, _) = controller.edit("/TestGraph") # validate the correct default default_value = og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC self.assertEquals(graph.evaluation_mode, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC) for value in [ og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED, ]: og.cmds.SetEvaluationMode(graph=graph, new_evaluation_mode=value) self.assertEquals(graph.evaluation_mode, value) omni.kit.undo.undo() self.assertEquals(graph.evaluation_mode, default_value) omni.kit.undo.redo() self.assertEquals(graph.evaluation_mode, value) omni.kit.undo.undo() self.assertEquals(graph.evaluation_mode, default_value) # ---------------------------------------------------------------------- async def test_variable_commands(self): controller = og.Controller() (graph, _, _, _) = controller.edit("/TestGraph") variable_name = "TestVariable" og.cmds.CreateVariable( graph=graph, variable_name=variable_name, variable_type=og.Type(og.BaseDataType.INT), graph_context=graph.get_default_graph_context(), variable_value=5, ) variable = graph.find_variable(variable_name) self.assertTrue(variable is not None) self.assertTrue(variable.valid) self.assertEqual(variable.type, og.Type(og.BaseDataType.INT)) self.assertEqual(og.Controller.get_variable_default_value(variable), 5) # undo the command and verify that the variable is no longer in the graph omni.kit.undo.undo() variable = graph.find_variable(variable_name) self.assertTrue(variable is None) # redo the command and verify that the variable has been restored in the graph omni.kit.undo.redo() variable = graph.find_variable(variable_name) self.assertTrue(variable is not None) self.assertTrue(variable.valid) self.assertEqual(variable.type, og.Type(og.BaseDataType.INT)) self.assertEqual(og.Controller.get_variable_default_value(variable), 5) test_tooltip = "test tooltip" og.cmds.SetVariableTooltip(variable=variable, tooltip=test_tooltip) self.assertEqual(variable.tooltip, test_tooltip) # undo the command and verify that the variable tooltip is cleared omni.kit.undo.undo() self.assertEqual(variable.tooltip, "") # redo the command and verify that the variable tooltip is restored omni.kit.undo.redo() self.assertEqual(variable.tooltip, test_tooltip) og.cmds.RemoveVariable(graph=graph, variable=variable, graph_context=graph.get_default_graph_context()) variable = graph.find_variable(variable_name) self.assertTrue(variable is None) # undo the command and verify that the variable has been restored in the graph omni.kit.undo.undo() variable = graph.find_variable(variable_name) self.assertTrue(variable is not None) self.assertTrue(variable.valid) self.assertEqual(variable.type, og.Type(og.BaseDataType.INT)) self.assertEqual(og.Controller.get_variable_default_value(variable), 5) # redo the command and verify that the variable is no longer in the graph omni.kit.undo.redo() variable = graph.find_variable(variable_name) self.assertTrue(variable is None) # ---------------------------------------------------------------------- async def test_change_pipeline_stage(self): """ Test the ChangePipelineStageCommand """ controller = og.Controller() keys = og.Controller.Keys (graph, create_nodes, _, _) = controller.edit( "/World/TestGraph", { keys.EXPOSE_PRIMS: [ (og.Controller.PrimExposureType.AS_WRITABLE, "/World/Cube", "Write"), ], keys.CREATE_PRIMS: [ ("/World/Cube", {"size": ("int", 1)}), ], keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ("Read", "omni.graph.nodes.ReadPrimsBundle"), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ], keys.SET_VALUES: [("ExtractPrim.inputs:primPath", "/World/Cube")], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractPrim.inputs:prims"), ("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], }, ) stage = omni.usd.get_context().get_stage() input_prim_prop = stage.GetPropertyAtPath("/World/TestGraph/Read.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube") await controller.evaluate(graph) # check the correctness of the output bundles read_node = create_nodes[1] extract_prim = create_nodes[2] extract_node = create_nodes[3] # IBundle2 factory factory = og.IBundleFactory.create() # Read Prim outputs multiple primitives in bundle read_bundle = graph.get_default_graph_context().get_output_bundle(read_node, "outputs_primsBundle") self.assertTrue(read_bundle.is_valid()) read_bundle2 = factory.get_bundle(graph.get_default_graph_context(), read_bundle) self.assertTrue(read_bundle2.valid) # check number of children from Read Prim self.assertEqual(read_bundle2.get_child_bundle_count(), 1) # Extract Bundle gets content of the child bundle from Read Prim extract_bundle = graph.get_default_graph_context().get_bundle( "/World/TestGraph/ExtractBundle/outputs_passThrough" ) self.assertTrue(extract_bundle.is_valid()) extract_bundle2 = factory.get_bundle(graph.get_default_graph_context(), extract_bundle) self.assertTrue(extract_bundle2.valid) extract_bundle = graph.get_default_graph_context().get_output_bundle(extract_node, "outputs_passThrough") self.assertTrue(extract_bundle.is_valid()) extract_bundle2 = factory.get_bundle(graph.get_default_graph_context(), extract_bundle) self.assertTrue(extract_bundle2.valid) # Check number of children and attributes for Extract Bundle self.assertEqual(extract_bundle2.get_child_bundle_count(), 0) attrib_names = extract_bundle2.get_attribute_names() self.assertTrue(len(attrib_names) > 0) extract_node_controller = og.Controller(og.Controller.attribute("inputs:primPath", extract_prim)) controller.edit( "/World/TestGraph", { keys.CONNECT: [ ("ExtractBundle.outputs:size", "Add.inputs:a"), ("ExtractBundle.outputs:size", "Add.inputs:b"), ("Add.outputs:sum", "Write.inputs:size"), ] }, ) extract_node = create_nodes[3] extract_node_controller = og.Controller(og.Controller.attribute("outputs:size", extract_node)) # Initially the graph is in simulation pipeline stage self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) # Check that graph.evaluate() causes graph evaluation graph.evaluate() self.assertEqual(extract_node_controller.get(), 1) graph.evaluate() self.assertEqual(extract_node_controller.get(), 2) graph.evaluate() self.assertEqual(extract_node_controller.get(), 4) # Check that omni.kit.app.get_app().next_update_async() also causes graph evaluation await omni.kit.app.get_app().next_update_async() self.assertEqual(extract_node_controller.get(), 8) await omni.kit.app.get_app().next_update_async() self.assertEqual(extract_node_controller.get(), 16) # Now change the pipeline stage to on-demand og.cmds.ChangePipelineStage(graph=graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND) self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND) # Check that graph.evaluate() still causes graph evaluation graph.evaluate() self.assertEqual(extract_node_controller.get(), 32) graph.evaluate() self.assertEqual(extract_node_controller.get(), 64) # Check that omni.kit.app.get_app().next_update_async() does NOT cause graph evaluation # because the graph is in on-demand pipeline stage await omni.kit.app.get_app().next_update_async() self.assertEqual(extract_node_controller.get(), 64) await omni.kit.app.get_app().next_update_async() self.assertEqual(extract_node_controller.get(), 64) # Undo the command to go back to the simulation pipeline stage omni.kit.undo.undo() omni.kit.undo.undo() omni.kit.undo.undo() self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) # Check that graph.evaluate() causes graph evaluation graph.evaluate() self.assertEqual(extract_node_controller.get(), 128) # Check that omni.kit.app.get_app().next_update_async() also causes graph evaluation await omni.kit.app.get_app().next_update_async() self.assertEqual(extract_node_controller.get(), 256) # ---------------------------------------------------------------------- async def test_ondemand_pipeline(self): """ test the on-demand pipeline stage. The on-demand pipeline stage allows graphs to be added to it that tick at unknown times instead of the fixed times of graph evaluation of other named stages. So here we will create some graphs in the stage, and manually evaluate it to make sure it works. """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() orchestration_graphs = og.get_global_orchestration_graphs() orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage( og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND ) self.assertEqual(len(orchestration_graphs), 1) self.assertEqual(orchestration_graphs[0].get_path_to_graph(), "/__onDemandRootGraph") self.assertEqual( orchestration_graphs[0].get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND ) self.assertEqual(orchestration_graphs[0].get_graph_backing_type(), og.GraphBackingType.GRAPH_BACKING_TYPE_NONE) orchestration_graph = orchestration_graphs[0] (result, wrapper_node) = og.cmds.CreateGraphAsNode( graph=orchestration_graph, node_name="my_push_graph", graph_path="/World/my_push_graph", evaluator_name="push", is_global_graph=True, backed_by_usd=True, fc_backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, ) self.assertTrue(result) self.assertTrue(wrapper_node.is_valid()) self.assertEqual(wrapper_node.get_prim_path(), "/__onDemandRootGraph/_World_my_push_graph") wrapped_graph = wrapper_node.get_wrapped_graph() self.assertTrue(wrapped_graph.is_valid()) self.assertEqual(wrapped_graph.get_path_to_graph(), "/World/my_push_graph") self.assertEqual(wrapped_graph.get_graph_backing_type(), og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED) self.assertEqual(wrapped_graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND) controller = og.Controller() keys = og.Controller.Keys cube_prim = ogts.create_cube(stage, "Cube", (1, 1, 1)) (graph, (_, write_node, _, _, extract_node), _, _) = controller.edit( "/World/my_push_graph", { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrims"), ("Write", "omni.graph.nodes.WritePrim"), ("Add", "omni.graph.nodes.Add"), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractPrim.inputs:prims"), ("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], keys.SET_VALUES: [ ("ExtractPrim.inputs:primPath", str(cube_prim.GetPath())), ], }, ) wrapped_graph.evaluate() omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath("/World/my_push_graph/Read.inputs:prims"), target=cube_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath("/World/my_push_graph/Write.inputs:prim"), target=cube_prim.GetPath(), ) wrapped_graph.evaluate() # node:type # node:typeVersion # inputs:bundle # outputs: passThrough n_static_attribs_extract = 4 # Check we have the expected dynamic attrib on ExtractBundle attribs = extract_node.get_attributes() bundle = wrapped_graph.get_default_graph_context().get_output_bundle(extract_node, "outputs_passThrough") self.assertTrue(bundle.is_valid()) self.assertEqual(len(attribs) - n_static_attribs_extract, bundle.get_attribute_data_count()) found_size_attrib = False for attrib in attribs: if attrib.get_name() == "outputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE: found_size_attrib = True self.assertTrue(found_size_attrib) # Check we have the expected dynamic attrib on WritePrim attribs = write_node.get_attributes() found_size_attrib = False for attrib in attribs: if attrib.get_name() == "inputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE: found_size_attrib = True self.assertTrue(found_size_attrib) # check that evaluations propagate in a read/write cycle as expected controller.edit( graph, { keys.CONNECT: [ ("/World/my_push_graph/ExtractBundle.outputs:size", "/World/my_push_graph/Add.inputs:a"), ("/World/my_push_graph/ExtractBundle.outputs:size", "/World/my_push_graph/Add.inputs:b"), ("/World/my_push_graph/Add.outputs:sum", "/World/my_push_graph/Write.inputs:size"), ] }, ) wrapped_graph.evaluate() extract_node_controller = og.Controller(og.Controller.attribute("outputs:size", extract_node)) self.assertEqual(extract_node_controller.get(), 1) wrapped_graph.evaluate() self.assertEqual(extract_node_controller.get(), 2) wrapped_graph.evaluate() self.assertEqual(extract_node_controller.get(), 4) # Verify that the graph is not still evaluating while we are not pumping the evaluate # OM-4258 await omni.kit.app.get_app().next_update_async() self.assertEqual(extract_node_controller.get(), 4) await omni.kit.app.get_app().next_update_async() self.assertEqual(extract_node_controller.get(), 4) # ---------------------------------------------------------------------- async def test_ondemand_pipeline_part_two(self): """ More validation tests for the on-demand pipeline stage. This test was added as part of the changes described in OM-87603 to ensure that the pipeline stage behaves correctly now that it is executed via the EF code path (as opposed to utilizing the legacy schedulers). """ # Define a utility method for creating a simple graph of variable # evaluator type and pipeline stage. def create_graph(graph_path: str, evaluator_name: str, pipeline: og.GraphPipelineStage): """Create a simple graph that increments a counter on a node every time the graph ticks.""" (graph, nodes, _, _) = og.Controller.edit( {"graph_path": graph_path, "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Counter", "omni.graph.action.Counter"), ], og.Controller.Keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)], og.Controller.Keys.CONNECT: ("OnTick.outputs:tick", "Counter.inputs:execIn"), }, ) og.cmds.ChangePipelineStage(graph=graph, new_pipeline_stage=pipeline) self.assertEqual(graph.get_pipeline_stage(), pipeline) return graph, nodes # Currently-supported pipeline stages. pipeline_stages = [ og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_PRERENDER, og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER, og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, ] # Create a push graph that subscribes to the on-demand pipeline. # Doing so should result in the initial population of the OnDemand # stage. Check that it only computes when an explicit request to do # so is made, and that only the OnDemand orchestration graph has # any graph nodes (in this case one). _, push_nodes = create_graph("/PushGraph", "push", og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND) push_out_cnt_attr = push_nodes[1].get_attribute("outputs:count") await og.Controller.evaluate() await og.Controller.evaluate() await og.Controller.evaluate() self.assertEqual(push_out_cnt_attr.get(), 3) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(push_out_cnt_attr.get(), 3) for pipeline_stage in pipeline_stages: orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage) self.assertEqual(len(orchestration_graphs), 1) orchestration_graph = orchestration_graphs[0] if pipeline_stage == og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND: self.assertEqual(len(orchestration_graph.get_nodes()), 1) else: self.assertEqual(len(orchestration_graph.get_nodes()), 0) # Confirm that newly added OnDemand graphs (after the initial population) # will properly trigger a repopulation of the OnDemand stage to include # those new graphs, thus allowing them to be executed. Also check that # the OnDemand orchestration graph now has two graph nodes, while the others # still have zero. exec_graph, exec_nodes = create_graph( "/ExecutionGraph", "execution", og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND ) exec_out_cnt_attr = exec_nodes[1].get_attribute("outputs:count") await og.Controller.evaluate() await og.Controller.evaluate() await og.Controller.evaluate() self.assertEqual(push_out_cnt_attr.get(), 6) self.assertEqual(exec_out_cnt_attr.get(), 3) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(push_out_cnt_attr.get(), 6) self.assertEqual(exec_out_cnt_attr.get(), 3) for pipeline_stage in pipeline_stages: orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage) self.assertEqual(len(orchestration_graphs), 1) orchestration_graph = orchestration_graphs[0] if pipeline_stage == og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND: self.assertEqual(len(orchestration_graph.get_nodes()), 2) else: self.assertEqual(len(orchestration_graph.get_nodes()), 0) # Confirm that removing OnDemand graphs triggers a repopulation of the # OnDemand stage that won't include those graphs, resulting in them # no longer executing on an "on-demand" basis. Here we simply switch # the pipeline stage of the exec_graph to be something other than # OnDemand (Simulation). Check that both the Simulation and OnDemand # orchestration graphs now have one graph node apiece. og.cmds.ChangePipelineStage( graph=exec_graph, new_pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION ) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(push_out_cnt_attr.get(), 6) self.assertEqual(exec_out_cnt_attr.get(), 6) for pipeline_stage in pipeline_stages: orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage) self.assertEqual(len(orchestration_graphs), 1) orchestration_graph = orchestration_graphs[0] if pipeline_stage in ( og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, ): self.assertEqual(len(orchestration_graph.get_nodes()), 1) else: self.assertEqual(len(orchestration_graph.get_nodes()), 0) # Confirm that editing OnDemand graphs triggers a repopulation of # the OnDemand stage, resulting in subsequent evaluations picking up # on the new changes. Here we check for this by creating an OnDemand # dirty_push graph and altering one of the underlying node connections # halfway through the evaluation checks; this change should trigger # a compute on the graph + should be picked up in the OnDemand pipeline. # Also check that the OnDemand orchestration graph now has two graph nodes, # while the Simulation orchestration graph still only has one. _, dirty_push_nodes = create_graph( "/DirtyPushGraph", "dirty_push", og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND ) dirty_push_ontick_node = dirty_push_nodes[0] dirty_push_counter_node = dirty_push_nodes[1] dirty_push_out_cnt_attr = dirty_push_counter_node.get_attribute("outputs:count") await og.Controller.evaluate() await og.Controller.evaluate() await og.Controller.evaluate() self.assertEqual(push_out_cnt_attr.get(), 9) self.assertEqual(exec_out_cnt_attr.get(), 9) self.assertEqual(dirty_push_out_cnt_attr.get(), 1) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(push_out_cnt_attr.get(), 9) self.assertEqual(exec_out_cnt_attr.get(), 12) self.assertEqual(dirty_push_out_cnt_attr.get(), 1) og.Controller.disconnect( dirty_push_ontick_node.get_attribute("outputs:tick"), dirty_push_counter_node.get_attribute("inputs:execIn") ) await og.Controller.evaluate() await og.Controller.evaluate() await og.Controller.evaluate() self.assertEqual(push_out_cnt_attr.get(), 12) self.assertEqual(exec_out_cnt_attr.get(), 15) self.assertEqual(dirty_push_out_cnt_attr.get(), 2) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(push_out_cnt_attr.get(), 12) self.assertEqual(exec_out_cnt_attr.get(), 18) self.assertEqual(dirty_push_out_cnt_attr.get(), 2) for pipeline_stage in pipeline_stages: orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage) self.assertEqual(len(orchestration_graphs), 1) orchestration_graph = orchestration_graphs[0] if pipeline_stage == og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND: self.assertEqual(len(orchestration_graph.get_nodes()), 2) elif pipeline_stage == og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION: self.assertEqual(len(orchestration_graph.get_nodes()), 1) else: self.assertEqual(len(orchestration_graph.get_nodes()), 0) # ---------------------------------------------------------------------- async def test_commands_with_group_undo_redo(self): """ Tests direct and indirect commands work as expected when grouped under a single undo, including when nodes are created and destroyed """ controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_, _, add3, add4), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add"), ("Add3", "omni.graph.nodes.Add"), ("Add4", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Add1.outputs:sum", "Add2.inputs:a"), ], }, ) og.cmds.DisableNode(node=add3) with omni.kit.undo.group(): # add a new node controller.create_node("/World/Graph/Constant", "omni.graph.nodes.ConstantInt", undoable=True) node = graph.get_node("/World/Graph/Constant") controller.set(node.get_attribute("inputs:value"), 2, undoable=True) controller.connect("/World/Graph/Add1.outputs:sum", "/World/Graph/Add2.inputs:b", undoable=True) controller.disconnect("/World/Graph/Add1.outputs:sum", "/World/Graph/Add2.inputs:a", undoable=True) self.assertFalse( controller.attribute("/World/Graph/Add1.outputs:sum").is_connected( controller.attribute("/World/Graph/Add2.inputs:a") ) ) og.cmds.EnableNode(node=add3) og.cmds.DisableNode(node=add4) controller.create_node("/World/Graph/Add5", "omni.graph.nodes.Add") og.cmds.DisableNode(node=graph.get_node("/World/Graph/Add5")) controller.delete_node("/World/Graph/Add2", update_usd=True, undoable=True) for _ in range(0, 3): graph = og.get_graph_by_path("/World/Graph") self.assertTrue(graph.is_valid()) self.assertTrue(graph.get_node("/World/Graph/Constant").is_valid()) self.assertTrue(graph.get_node("/World/Graph/Add1").is_valid()) self.assertFalse(graph.get_node("/World/Graph/Add2").is_valid()) self.assertEqual(controller.get(controller.attribute("/World/Graph/Constant.inputs:value")), 2) self.assertFalse(graph.get_node("/World/Graph/Add3").is_disabled()) self.assertTrue(graph.get_node("/World/Graph/Add4").is_disabled()) self.assertTrue(graph.get_node("/World/Graph/Add5").is_disabled()) omni.kit.undo.undo() graph = og.get_graph_by_path("/World/Graph") self.assertTrue(graph.is_valid()) self.assertFalse(graph.get_node("/World/Graph/Constant").is_valid()) self.assertTrue(graph.get_node("/World/Graph/Add1").is_valid()) self.assertTrue(graph.get_node("/World/Graph/Add2").is_valid()) self.assertTrue(graph.get_node("/World/Graph/Add3").is_disabled()) self.assertFalse(graph.get_node("/World/Graph/Add4").is_disabled()) self.assertFalse(graph.get_node("/World/Graph/Add5").is_valid()) omni.kit.undo.redo() # ---------------------------------------------------------------------- async def test_create_graph_with_group_undo_redo(self): """ Tests that commands perform as expected when the graph creation is part of the same undo group """ orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage( og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION ) self.assertEqual(len(orchestration_graphs), 1) orchestration_graph = orchestration_graphs[0] with omni.kit.undo.group(): (result, _) = og.cmds.CreateGraphAsNode( graph=orchestration_graph, node_name="my_push_graph", graph_path="/World/Graph", evaluator_name="push", is_global_graph=True, backed_by_usd=True, fc_backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE, ) self.assertTrue(result) graph = og.Controller.graph("/World/Graph") og.cmds.CreateNode( graph=graph, node_path="/World/Graph/ConstantInt", node_type="omni.graph.nodes.ConstantInt", create_usd=True, ) og.cmds.SetAttr( attr=og.Controller.attribute("/World/Graph/ConstantInt.inputs:value"), value=5, update_usd=True ) og.cmds.CreateNode( graph=graph, node_path="/World/Graph/Add", node_type="omni.graph.nodes.Add", create_usd=True ) og.cmds.ConnectAttrs( src_attr="/World/Graph/ConstantInt.inputs:value", dest_attr="/World/Graph/Add.inputs:a", modify_usd=True ) og.cmds.CreateVariable( graph=graph, variable_name="int_var", variable_type=og.Type(og.BaseDataType.INT), variable_value=5, ) for _ in range(0, 3): self.assertTrue(og.Controller.graph("/World/Graph").is_valid()) self.assertTrue(og.Controller.node("/World/Graph/ConstantInt").is_valid()) self.assertTrue(og.Controller.node("/World/Graph/Add").is_valid()) self.assertTrue(og.Controller.attribute("/World/Graph/ConstantInt.inputs:value").is_valid()) self.assertTrue(og.Controller.attribute("/World/Graph/Add.inputs:a").is_valid()) self.assertEquals(og.Controller.get(og.Controller.attribute("/World/Graph/ConstantInt.inputs:value")), 5) self.assertTrue( og.Controller.attribute("/World/Graph/Add.inputs:a").is_connected( og.Controller.attribute("/World/Graph/ConstantInt.inputs:value") ) ) context = og.Controller.graph("/World/Graph").get_default_graph_context() self.assertEquals(og.Controller.variable("/World/Graph.graph:variable:int_var").get(context), 5) omni.kit.undo.undo() self.assertIsNone(og.Controller.graph("/World/Graph")) with self.assertRaises(og.OmniGraphError): _ = og.Controller.node("/World/Graph/ConstantInt") with self.assertRaises(og.OmniGraphError): _ = og.Controller.node("/World/Graph/Add") with self.assertRaises(og.OmniGraphError): _ = og.Controller.attribute("/World/Graph/ConstantInt.inputs:value") with self.assertRaises(og.OmniGraphError): _ = og.Controller.attribute("/World/Graph/Add.inputs:a") omni.kit.undo.redo() # ---------------------------------------------------------------------- async def test_resolve_attr_type_command(self): """Tests ResolveAttrTypeCommand""" controller = og.Controller() keys = controller.Keys (_, (add1,), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ], }, ) # Test undo-redo for simple type unknown_t = controller.attribute_type("unknown") a = controller.attribute("inputs:a", add1) self.assertEqual(a.get_resolved_type(), unknown_t) og.cmds.ResolveAttrType(attr=a, type_id="int") self.assertEqual(a.get_resolved_type(), controller.attribute_type("int")) omni.kit.undo.undo() self.assertEqual(a.get_resolved_type(), unknown_t) omni.kit.undo.redo() self.assertEqual(a.get_resolved_type(), controller.attribute_type("int"))
53,460
Python
46.690455
120
0.608137
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_context.py
"""Basic tests of the graph context""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands from pxr import Usd class TestOmniGraphContext(ogts.OmniGraphTestCase): """Tests graph context functionality""" TEST_GRAPH_PATH = "/TestGraph" # ---------------------------------------------------------------------- async def test_graph_context_input_target_bundles(self): """ Tests that the getting the input target bundles on a graph context works correctly """ usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() controller = og.Controller() cube_prim = ogts.create_cube(stage, "Cube", (1, 0, 0)) cone_prim = ogts.create_cone(stage, "Cone", (0, 1, 0)) xform_prim = stage.DefinePrim("/Xform", "Xform") keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadCube", "omni.graph.nodes.ReadPrims"), ("ReadCone", "omni.graph.nodes.ReadPrims"), ("WritePrims", "omni.graph.nodes.WritePrimsV2"), ], keys.CONNECT: [ ("ReadCube.outputs_primsBundle", "WritePrims.inputs:primsBundle"), ("ReadCone.outputs_primsBundle", "WritePrims.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/ReadCube.inputs:prims"), target=cube_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/ReadCone.inputs:prims"), target=cone_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/WritePrims.inputs:prims"), target=xform_prim.GetPath(), ) await controller.evaluate(graph) graph_context = graph.get_default_graph_context() self.assertTrue(graph_context.is_valid()) write_prims_node = graph.get_node(f"{self.TEST_GRAPH_PATH}/WritePrims") self.assertTrue(write_prims_node.is_valid()) read_cube_node = graph.get_node(f"{self.TEST_GRAPH_PATH}/ReadCube") self.assertTrue(read_cube_node.is_valid()) read_cone_node = graph.get_node(f"{self.TEST_GRAPH_PATH}/ReadCone") self.assertTrue(read_cone_node.is_valid()) write_prims_targets = graph_context.get_input_target_bundles(write_prims_node, "inputs:primsBundle") self.assertEqual(len(write_prims_targets), 2) [mbib0, mbib1] = write_prims_targets self.assertEqual(mbib0.get_child_bundle_count(), 1) self.assertEqual(mbib1.get_child_bundle_count(), 1) [spib0] = mbib0.get_child_bundles() [spib1] = mbib1.get_child_bundles() source_prim_paths = [ spib0.get_attribute_by_name("sourcePrimPath").get(), spib1.get_attribute_by_name("sourcePrimPath").get(), ] # sort the paths because get_input_target_bundles does not define an ordering source_prim_paths.sort() self.assertEqual(source_prim_paths[0], "/Cone") self.assertEqual(source_prim_paths[1], "/Cube")
3,603
Python
35.04
108
0.596725
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
201
Python
32.666661
112
0.716418
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_reparent_graph.py
"""Tests reparenting workflows""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # ====================================================================== class TestReparentGraph(ogts.OmniGraphTestCase): """Run tests that exercises the reparenting of graph and checks that fabric is cleaned up properly this is separate from test_rename_and_reparent.py tests because of different settings need via OmniGraphDefaultTestCase in order for legacy prims to be added to fabric. """ async def test_reparent_fabric(self): """Test basic reparenting a graph back away and then back to original parent.""" flags = [] world_graph_key = '"/World/ActionGraph"' xform_graph_key = '"/World/Xform/ActionGraph"' # Load the test scene which has /World/ActionGraph and /World/Xform (result, error) = await ogts.load_test_file("TestReparentGraph.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # Verify that fabric has "/World/ActionGraph" and not "/World/Xform/ActionGraph" self.assertEqual(len(og.get_compute_graph_contexts()), 1) ctx = og.get_compute_graph_contexts()[0] post_load_fabric = og.OmniGraphInspector().as_json(ctx, flags=flags) self.assertTrue(post_load_fabric.find(world_graph_key) >= 0) self.assertTrue(post_load_fabric.find(xform_graph_key) == -1) # Reparent the graph to the Xform omni.kit.commands.execute("MovePrim", path_from="/World/ActionGraph", path_to="/World/Xform/ActionGraph") await omni.kit.app.get_app().next_update_async() # Verify that fabric no longer has "/World/ActionGraph" and now has "/World/Xform/ActionGraph" self.assertEqual(len(og.get_compute_graph_contexts()), 1) ctx = og.get_compute_graph_contexts()[0] post_reparent_to_xform_fabric = og.OmniGraphInspector().as_json(ctx, flags=flags) self.assertTrue(post_reparent_to_xform_fabric.find(world_graph_key) == -1) self.assertTrue(post_reparent_to_xform_fabric.find(xform_graph_key) >= 0)
2,139
Python
47.636363
113
0.670407
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_abi_attribute.py
"""Runs tests on the ABIs in the Python bindings""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import usdrt from pxr import Sdf, Usd # ============================================================================================================== class TestAttributePythonBindings(ogts.OmniGraphTestCase): async def test_abi(self): """Tests that the bindings for omni.graph.core.Attribute operate as expected""" interface = og.Attribute ogts.validate_abi_interface( interface, instance_methods=[ "connect", "connectEx", "connectPrim", "deprecation_message", "disconnect", "disconnectPrim", "get_all_metadata", "get_array", "get_attribute_data", "get_disable_dynamic_downstream_work", "get_downstream_connection_count", "get_downstream_connections_info", "get_downstream_connections", "get_extended_type", "get_handle", "get_metadata_count", "get_metadata", "get_name", "get_node", "get_path", "get_port_type", "get_resolved_type", "get_type_name", "get_union_types", "get_upstream_connection_count", "get_upstream_connections_info", "get_upstream_connections", "get", "is_array", "is_compatible", "is_connected", "is_deprecated", "is_dynamic", "is_runtime_constant", "is_valid", "register_value_changed_callback", "set_default", "set_disable_dynamic_downstream_work", "set_metadata", "set_resolved_type", "set", "update_attribute_value", ], static_methods=[ "ensure_port_type_in_name", "get_port_type_from_name", "remove_port_type_from_name", "write_complete", ], properties=[ "gpu_ptr_kind", "is_optional_for_compute", ], constants=[ ("resolved_prefix", str), ], ) # TODO: Now that we've confirmed the functions exist we also need to confirm that they work # -------------------------------------------------------------------------------------------------------------- async def test_constants(self): """Test that the constants in the Attribute interface work as expected""" self.assertEqual(og.Attribute.resolved_prefix, "__resolved_") # -------------------------------------------------------------------------------------------------------------- async def test_properties(self): """Test that the properties in the Attribute interface work as expected""" (_, (node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.test.PerturbPointsGpu")} ) attr_points = og.Controller.attribute("inputs:points", node) self.assertEqual(attr_points.gpu_ptr_kind, og.PtrToPtrKind.NA) attr_points.gpu_ptr_kind = og.PtrToPtrKind.GPU self.assertEqual(attr_points.gpu_ptr_kind, og.PtrToPtrKind.GPU) self.assertFalse(attr_points.is_optional_for_compute) attr_points.is_optional_for_compute = True self.assertTrue(attr_points.is_optional_for_compute) # -------------------------------------------------------------------------------------------------------------- async def test_static_methods(self): """Test that the static methods of the Attribute interface work as expected""" interface = og.Attribute p_in = og.AttributePortType.INPUT p_out = og.AttributePortType.OUTPUT p_state = og.AttributePortType.STATE # -------------------------------------------------------------------------------------------------------------- # Test Attribute.ensure_port_type_in_name # Test data is a list of (expected_output, name_input, port_type, is_bundle) test_data = [ ("inputs:attr", "inputs:attr", p_in, False), ("outputs:attr", "outputs:attr", p_out, False), ("state:attr", "state:attr", p_state, False), ("inputs:attr", "inputs:attr", p_in, True), ("outputs_attr", "outputs_attr", p_out, True), ("state_attr", "state_attr", p_state, True), ("inputs:attr", "attr", p_in, False), ("outputs:attr", "attr", p_out, False), ("state:attr", "attr", p_state, False), ("inputs:attr", "attr", p_in, True), ("outputs_attr", "attr", p_out, True), ("state_attr", "attr", p_state, True), ("inputs:attr:first", "inputs:attr:first", p_in, False), ("outputs:attr:first", "outputs:attr:first", p_out, False), ("state:attr:first", "state:attr:first", p_state, False), ("inputs:attr:first", "inputs:attr:first", p_in, True), ("outputs_attr_first", "outputs_attr_first", p_out, True), ("state_attr_first", "state_attr_first", p_state, True), ] for (expected, original, port_type, is_bundle) in test_data: msg = f"ensure_port_type_in_name({expected}, {original}, {port_type}, {is_bundle})" self.assertEqual(expected, interface.ensure_port_type_in_name(original, port_type, is_bundle), msg) # -------------------------------------------------------------------------------------------------------------- # Test Attribute.get_port_type_from_name # Test data is a list of (expected_result, name_input) test_data = [ (og.AttributePortType.INPUT, "inputs:attr"), (og.AttributePortType.OUTPUT, "outputs:attr"), (og.AttributePortType.STATE, "state:attr"), (og.AttributePortType.INPUT, "inputs:attr"), (og.AttributePortType.OUTPUT, "outputs_attr"), (og.AttributePortType.STATE, "state_attr"), (og.AttributePortType.UNKNOWN, "input:attr"), ] for (expected, original) in test_data: msg = f"get_port_type_from_name({expected}, {original})" self.assertEqual(expected, interface.get_port_type_from_name(original), msg) # -------------------------------------------------------------------------------------------------------------- # Test Attribute.remove_port_type_from_name # Test data is a list of (expected_output, name_input, port_type, is_bundle) test_data = [ ("attr", "inputs:attr", False), ("attr", "outputs:attr", False), ("attr", "state:attr", False), ("attr", "inputs:attr", True), ("attr", "outputs_attr", True), ("attr", "state_attr", True), ("attr", "attr", False), ("attr", "attr", False), ("attr", "attr", False), ("attr", "attr", True), ("attr", "attr", True), ("attr", "attr", True), ("attr:first", "inputs:attr:first", False), ("attr:first", "outputs:attr:first", False), ("attr:first", "state:attr:first", False), ("attr:first", "inputs:attr:first", True), ("attr_first", "outputs_attr_first", True), ("attr_first", "state_attr_first", True), ("input:attr", "input:attr", False), ("input:attr", "input:attr", True), ("output:attr", "output:attr", False), ("output_attr", "output_attr", True), ("attr", "attr", False), ("attr", "attr", True), ] for (expected, original, is_bundle) in test_data: msg = f"remove_port_type_from_name({expected}, {original}, {is_bundle})" self.assertEqual(expected, interface.remove_port_type_from_name(original, is_bundle), msg) # -------------------------------------------------------------------------------------------------------------- # Test Attribute.write_complete # There's no easy way to judge that this worked as expected so instead just confirm that it returns okay (_, (node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.test.TestAllDataTypes")} ) attrs = [ og.Controller.attribute(name, node) for name in ["outputs:a_bool", "outputs:a_float", "outputs:a_double"] ] self.assertTrue(all(attr.is_valid() for attr in attrs)) interface.write_complete(attrs) interface.write_complete(tuple(attrs)) # -------------------------------------------------------------------------------------------------------------- async def test_target_attribute_setting(self): """Tests various forms of setting an attribute with a target type""" (_, (node,), _, _) = og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.nodes.GetPrimPaths"), og.Controller.Keys.CREATE_PRIMS: [("/World/Prim1", "Xform"), ("/World/Prim2", "Xform")], }, ) attr = og.Controller.attribute("inputs:prims", node) # string og.Controller.set(attr, "/World/Prim1") self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1")]) # Sdf.Path og.Controller.set(attr, Sdf.Path("/World/Prim2")) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim2")]) # usdrt.Sdf.Path og.Controller.set(attr, usdrt.Sdf.Path("/World/Prim1")) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1")]) # string list og.Controller.set(attr, ["/World/Prim1", "/World/Prim2"]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2")]) # Sdf.Path list og.Controller.set(attr, [Sdf.Path("/World/Prim2"), Sdf.Path("/World/Prim1")]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim2"), usdrt.Sdf.Path("/World/Prim1")]) # usdrt.Sdf.Path list og.Controller.set(attr, [usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2")]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2")]) # empty list og.Controller.set(attr, []) self.assertEqual(og.Controller.get(attr), []) # mixed list og.Controller.set(attr, [Sdf.Path("/World/Prim2"), "/World/Prim1"]) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path("/World/Prim2"), usdrt.Sdf.Path("/World/Prim1")]) # graph target path og.Controller.set(attr, og.INSTANCING_GRAPH_TARGET_PATH) self.assertEqual(og.Controller.get(attr), [usdrt.Sdf.Path(og.INSTANCING_GRAPH_TARGET_PATH)]) # validate non-sdf paths throw omni.kit.commands.set_logging_enabled(False) with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, 5) with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, "!a non valid sdf path") with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, ["/World/Prim1", 5]) with self.assertRaises(og.OmniGraphError): og.Controller.set(attr, (usdrt.Sdf.Path("/World/Prim1"), usdrt.Sdf.Path("/World/Prim2"))) omni.kit.commands.set_logging_enabled(True) # -------------------------------------------------------------------------------------------------------------- async def test_objectlookup_attribute_with_paths(self): """Tests that og.Controller.attribute works with both strings and Sdf.Path objects for all types""" (_, (node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: ("TestNode", "omni.graph.test.TestAllDataTypes")} ) for attr in node.get_attributes(): if attr.get_port_type() not in ( og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ): continue path = attr.get_path() self.assertEquals(attr, og.Controller.attribute(str(path))) self.assertEquals(attr, og.Controller.attribute(Sdf.Path(path))) # -------------------------------------------------------------------------------------------------------------- async def test_objectlookup_usd_object_from_attributes(self): """Tests that og.ObjectLookup finds the correct usd object from an attribute""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, (node,), _, _) = controller.edit( "/TestGraph", {keys.CREATE_NODES: ("TestNode", "omni.graph.test.TestAllDataTypes")} ) for attr in node.get_attributes(): port_type = attr.get_port_type() if port_type not in ( og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ): continue # the exception is bundle outputs. They are neither attributes nor relationships. attribute_type = og.Controller.attribute_type(attr) if ( port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and attribute_type.role == og.AttributeRole.BUNDLE ): with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(attr) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_relationship(attr) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_property(attr) continue # everything else is an attribute or relationship path = attr.get_path() usd_property = og.ObjectLookup.usd_property(attr) self.assertTrue(usd_property.IsValid()) self.assertEqual(usd_property, og.ObjectLookup.usd_property(Sdf.Path(path))) self.assertEqual(usd_property, og.ObjectLookup.usd_property(str(path))) # validate the property is a relationship or an attribute and that the corresponding inverse calls fail for item in [attr, Sdf.Path(path), str(path)]: if isinstance(usd_property, Usd.Relationship): self.assertEqual(usd_property, og.ObjectLookup.usd_relationship(item)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(item) else: self.assertEqual(usd_property, og.ObjectLookup.usd_attribute(item)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_relationship(item)
15,477
Python
46.771605
120
0.519481
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_subgraphs.py
"""Tests relating to management of OmniGraph graphs and subgraphs""" import tempfile from pathlib import Path import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit import omni.usd class TestOmniGraphSubgraphs(ogts.OmniGraphTestCase): async def test_execution_subgraph_in_push_graph(self): """Verify the push evaluator ticks the execution subgraph""" controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() (graph, _, _, _) = controller.edit("/World/TestGraph") subgraph_path = "/World/TestGraph/exec_sub" graph.create_subgraph(subgraph_path, evaluator="execution") subgraph = graph.get_subgraph(subgraph_path) self.assertTrue(subgraph.is_valid()) controller.edit( subgraph, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("FlipFlop", "omni.graph.action.FlipFlop"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: ("Prim1", {"attrBool": ("bool", False)}), keys.CONNECT: [ ("OnTick.outputs:tick", "FlipFlop.inputs:execIn"), ("FlipFlop.outputs:a", "Set.inputs:execIn"), ("FlipFlop.outputs:b", "Set.inputs:execIn"), ("FlipFlop.outputs:isA", "Set.inputs:value"), ], keys.SET_VALUES: [ ("Set.inputs:primPath", "/Prim1"), ("Set.inputs:name", "attrBool"), ("Set.inputs:usePath", True), ("OnTick.inputs:onlyPlayback", False), ], }, ) await og.Controller.evaluate() sub_ff_node = subgraph_path + "/FlipFlop" sub_flipflop_node = subgraph.get_node(sub_ff_node) self.assertTrue(sub_flipflop_node.is_valid()) # Check the flip-flop is being toggled and that attribs are being flushed to USD ff_state_0 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node)) self.assertEqual(stage.GetPropertyAtPath("/Prim1.attrBool").Get(), ff_state_0) await og.Controller.evaluate() ff_state_1 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node)) self.assertNotEqual(ff_state_0, ff_state_1) self.assertEqual(stage.GetPropertyAtPath("/Prim1.attrBool").Get(), ff_state_1) # -------------------------------------------------------------------------------------------------------------- async def test_multiple_schema_root_graphs(self): """Check that a configuration with more than one root level graph can be created, saved, and loaded. This test creates three root-level graphs and then executes all of them to confirm that they are working properly. Each graph is a simple addition sequence, where one is an action graph to confirm that different graphs can use different evaluators. Const1 ---v Add ---> SimpleData Const2 ---^ OnTick --> Counter """ keys = og.Controller.Keys (graph_1, (const_nodea_1, const_nodeb_1, _, simple_data_node_1), _, _) = og.Controller.edit( "/Graph1", { keys.CREATE_NODES: [ ("ConstA", "omni.graph.nodes.ConstantInt"), ("ConstB", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ("SimpleData", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ConstA.inputs:value", "Add.inputs:a"), ("ConstB.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "SimpleData.inputs:a_int"), ], keys.SET_VALUES: [ ("ConstA.inputs:value", 3), ("ConstB.inputs:value", 7), ], }, ) simple_data_node_1_path = simple_data_node_1.get_prim_path() graph_1_path = graph_1.get_path_to_graph() (graph_2, (const_nodea_2, const_nodeb_2, _, simple_data_node_2), _, _) = og.Controller.edit( "/Graph2", { keys.CREATE_NODES: [ ("ConstA", "omni.graph.nodes.ConstantInt"), ("ConstB", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ("SimpleData", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ConstA.inputs:value", "Add.inputs:a"), ("ConstB.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "SimpleData.inputs:a_int"), ], keys.SET_VALUES: [ ("ConstA.inputs:value", 33), ("ConstB.inputs:value", 77), ], }, ) simple_data_node_2_path = simple_data_node_2.get_prim_path() graph_2_path = graph_2.get_path_to_graph() (graph_3, (ontick_node, counter_node), _, _) = og.Controller.edit( { "graph_path": "/Graph3", "evaluator_name": "execution", }, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Counter", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Counter.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ], }, ) counter_node_path = counter_node.get_prim_path() graph_3_path = graph_3.get_path_to_graph() # ============================================================================================================== # OM-52190 specifies work that will prevent the need for this temporary setting. Without it, the values being # set onto the attributes will not be part of USD, and hence will not be saved out to the file, # causing the second half of the test to fail. stage = omni.usd.get_context().get_stage() stage.GetPrimAtPath(const_nodea_1.get_prim_path()).GetAttribute("inputs:value").Set(3) stage.GetPrimAtPath(const_nodeb_1.get_prim_path()).GetAttribute("inputs:value").Set(7) stage.GetPrimAtPath(const_nodea_2.get_prim_path()).GetAttribute("inputs:value").Set(33) stage.GetPrimAtPath(const_nodeb_2.get_prim_path()).GetAttribute("inputs:value").Set(77) stage.GetPrimAtPath(ontick_node.get_prim_path()).GetAttribute("inputs:onlyPlayback").Set(False) # ============================================================================================================== await og.Controller.evaluate([graph_1, graph_2, graph_3]) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_1)).get(), 10) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_2)).get(), 110) self.assertTrue(og.Controller(("state:count", counter_node)).get() > 0) with tempfile.TemporaryDirectory() as tmpdirname: await omni.kit.app.get_app().next_update_async() # save the file tmp_file_path = Path(tmpdirname) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) graph_1 = og.get_graph_by_path(graph_1_path) graph_2 = og.get_graph_by_path(graph_2_path) graph_3 = og.get_graph_by_path(graph_3_path) simple_data_node_1 = og.get_node_by_path(simple_data_node_1_path) simple_data_node_2 = og.get_node_by_path(simple_data_node_2_path) counter_node = og.get_node_by_path(counter_node_path) self.assertIsNotNone(simple_data_node_1) self.assertIsNotNone(simple_data_node_2) self.assertIsNotNone(counter_node) await og.Controller.evaluate([graph_1, graph_2, graph_3]) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_1)).get(), 10) self.assertEqual(og.Controller(("inputs:a_int", simple_data_node_2)).get(), 110) self.assertTrue(og.Controller(("state:count", counter_node)).get() > 0)
8,800
Python
44.601036
120
0.531023
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_commands.py
"""Tests for the various OmniGraph commands""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.usd class TestOmniGraphCommands(ogts.OmniGraphTestCase): # ---------------------------------------------------------------------- async def test_disable_node_command(self): # The basic idea of the test is as follows: # We load up the TestTranslatingCube.usda file, which has a cube # that continually moves in X. We make sure first the # node is working, and then we disable the node. Once we do # that, we make sure cube no longer move as the node should be # disabled. (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = og.get_graph_by_path("/World/moveX") # make sure the box and the attribute we expect are there. usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") translate_attr = cube_prim.GetAttribute("xformOp:translate") self.assertTrue(translate_attr.IsValid()) # !!make a copy as the above is a reference of the data, that will change the next frame!! translate = translate_attr.Get() t0 = translate[0] # wait 1 frame await omni.kit.app.get_app().next_update_async() # get the updated cube position and make sure it moved translate = translate_attr.Get() t1 = translate[0] diff = abs(t1 - t0) self.assertGreater(diff, 0.1) # disable the node subtract_node = graph.get_node("/World/moveX/subtract") # we're piggy backing off this test to also test that the inputs and outputs of this node are # properly categorized (so this part is separate from the main test) input_attr = subtract_node.get_attribute("inputs:a") self.assertEqual(input_attr.get_port_type(), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) output_attr = subtract_node.get_attribute("outputs:out") self.assertEqual(output_attr.get_port_type(), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) og.cmds.DisableNode(node=subtract_node) # wait another frame, but this time make sure there is no moving of the cube await omni.kit.app.get_app().next_update_async() translate = translate_attr.Get() diff = abs(translate[0] - t1) self.assertEqual(diff, 0, 0.01) # ---------------------------------------------------------------------- async def verify_example_graph_disabled(self): """ basic idea behind this test: load up the translating cubes sample. The file is set initially such that the graph is disabled. We'll run the command to enable and disable the graph a bunch of times, each time checking the position of the moving cube. """ graph = og.get_all_graphs()[0] self.assertTrue(graph.is_disabled()) translate_attr = og.Controller.usd_attribute("/World/Cube.xformOp:translate") # initial position of cube should have x = 0.0. Since the graph is initially # disabled, this should remain the case: translate = translate_attr.Get() self.assertAlmostEqual(translate[0], 0.0, places=1) og.cmds.EnableGraph(graph=graph) self.assertFalse(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -1.0, places=1) omni.kit.undo.undo() self.assertTrue(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -1.0, places=1) omni.kit.undo.redo() self.assertFalse(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -2.0, places=1) og.cmds.DisableGraph(graph=graph) self.assertTrue(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -2.0, places=1) omni.kit.undo.undo() self.assertFalse(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -3.0, places=1) omni.kit.undo.redo() self.assertTrue(graph.is_disabled()) await og.Controller.evaluate() translate = translate_attr.Get() self.assertAlmostEqual(translate[0], -3.0, places=1) # ---------------------------------------------------------------------- async def verify_example_graph_rename(self): """ This test checks if renaming a graph will update the scene properly and keep the USD scene, the graph, and the fabric are in sync throughout two different renaming commands and their undos. """ graph_path = "/World/moveX" renamed_path = f"{graph_path}Renamed" graph = og.Controller.graph(graph_path) self.assertTrue(graph.is_valid()) usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") translate_attr = cube_prim.GetAttribute("xformOp:translate") self.assertTrue(translate_attr.IsValid()) # verify graph updates at the beginning await og.Controller.evaluate() translate = og.Controller.get(og.Controller.attribute(f"{graph_path}/compose.outputs:double3")) self.assertAlmostEqual(translate[0], -3.0, places=1) # Rename using MovePrimCommand omni.kit.commands.execute("MovePrim", path_from=graph_path, path_to=renamed_path) await omni.kit.app.get_app().next_update_async() graph = og.Controller.graph(graph_path) self.assertTrue(graph is None or not graph.is_valid()) graph = og.Controller.graph(renamed_path) self.assertTrue(graph.is_valid()) # verify graph update after rename translate = og.Controller.get(og.Controller.attribute(f"{renamed_path}/compose.outputs:double3")) self.assertAlmostEqual(translate[0], -4.0, places=1) # verify graph update after undo omni.kit.undo.undo() await omni.kit.app.get_app().next_update_async() graph = og.Controller.graph(renamed_path) self.assertTrue(graph is None or not graph.is_valid()) graph = og.Controller.graph(graph_path) self.assertTrue(graph.is_valid()) translate = og.Controller.get(og.Controller.attribute(f"{graph_path}/compose.outputs:double3")) self.assertAlmostEqual(translate[0], -5.0, places=1) # ---------------------------------------------------------------------- async def test_rename_graph_command(self): (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) await self.verify_example_graph_rename() # ---------------------------------------------------------------------- async def test_set_attr_command_v2(self): (result, error) = await ogts.load_test_file("TestTranslatingCube.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = og.get_graph_by_path("/World/moveX") subtract_node = graph.get_node("/World/moveX/subtract") b_attr = subtract_node.get_attribute("inputs:b") og.cmds.SetAttr(attr=b_attr, value=8.8) value = og.Controller.get(b_attr) self.assertAlmostEqual(value, 8.8, places=2) # Test is flaky. Disable this part for now to see if it's to blame # omni.kit.undo.undo() # value = og.Controller.get(multiplier_attr) # self.assertAlmostEqual(value, old_value, places=2) # omni.kit.undo.redo() # value = og.Controller.get(multiplier_attr) # self.assertAlmostEqual(value, 8.8, places=2)
8,188
Python
41.430052
109
0.622741
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_listener.py
"""Tests for OmniGraph Usd Listener """ import tempfile from pathlib import Path import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # ====================================================================== class TestOmniGraphUsdListener(ogts.OmniGraphTestCase): """Test for omni graph usd listener""" async def test_reparent_target_of_path_attribute(self): """Listener is required to update attributes with role set to path, when its target changes location""" controller = og.Controller() keys = og.Controller.Keys (_, create_nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("ConstantPath", "omni.graph.nodes.ConstantPath")], keys.CREATE_PRIMS: [("/Cube", "Cube"), ("/Xform", "Xform")], }, ) constant_path_node = create_nodes[0] value_attribute = constant_path_node.get_attribute("inputs:value") value_attribute.set("/Cube") # MovePrim command in this case will cause 'didAddNonInertPrim' and 'didRemoveNonInertPrim' flags to be # populated and reparenting takes place omni.kit.commands.execute("MovePrim", path_from="/Cube", path_to="/Xform/Cube") value = value_attribute.get() self.assertEqual(value, "/Xform/Cube") with tempfile.TemporaryDirectory() as tmp_dir_name: await omni.kit.app.get_app().next_update_async() # save tmp_file_path = Path(tmp_dir_name) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) constant_path_node = og.get_node_by_path("/TestGraph/ConstantPath") value_attribute = constant_path_node.get_attribute("inputs:value") self.assertEqual(value_attribute.get(), "/Xform/Cube") async def test_rename_target_of_path_attribute(self): """Listener is required to update attributes with role set to path, when its target changes path""" controller = og.Controller() keys = og.Controller.Keys (_, create_nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("ConstantPath", "omni.graph.nodes.ConstantPath")], keys.CREATE_PRIMS: [("/Cube", "Cube")], }, ) constant_path_node = create_nodes[0] value_attribute = constant_path_node.get_attribute("inputs:value") value_attribute.set("/Cube") for src_dst in (("/Cube", "/Cube1"), ("/Cube1", "/Cube2"), ("/Cube2", "/Cube3")): omni.kit.commands.execute("MovePrim", path_from=src_dst[0], path_to=src_dst[1]) self.assertEqual(value_attribute.get(), src_dst[1]) with tempfile.TemporaryDirectory() as tmp_dir_name: await omni.kit.app.get_app().next_update_async() # save tmp_file_path = Path(tmp_dir_name) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) constant_path_node = og.get_node_by_path("/TestGraph/ConstantPath") value_attribute = constant_path_node.get_attribute("inputs:value") self.assertEqual(value_attribute.get(), src_dst[1]) async def test_extended_path_type(self): """Resolve extended type to path and confirm that has been subscribed to the listener""" class TestExtendedPathABIPy: @staticmethod def compute(db): return True @staticmethod def get_node_type() -> str: return "omni.graph.tests.TestExtendedPathABIPy" @staticmethod def initialize_type(node_type): node_type.add_extended_input( "inputs:extended_input", "path,token", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) return True og.register_node_type(TestExtendedPathABIPy, 1) controller = og.Controller() keys = og.Controller.Keys (_, create_nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("TestExtendedPath", "omni.graph.tests.TestExtendedPathABIPy")], keys.CREATE_PRIMS: [("/Cube", "Cube")], }, ) extended_node = create_nodes[0] extended_input = extended_node.get_attribute("inputs:extended_input") # set resolved type to path extended_input.set_resolved_type(og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.PATH)) self.assertEqual(extended_input.get_resolved_type().role, og.AttributeRole.PATH) extended_input.set("/Cube") self.assertEqual(extended_input.get(), "/Cube") omni.kit.commands.execute("MovePrim", path_from="/Cube", path_to="/Cube1") value = extended_input.get() self.assertEqual(value, "/Cube1")
5,541
Python
38.028169
114
0.58401
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_import_nodes.py
import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.usd from pxr import Gf, UsdGeom class TestImportNodes(ogts.OmniGraphTestCase): TEST_GRAPH_PATH = "/World/TestGraph" async def test_import_time_samples(self): await self._test_import_time_samples_impl("omni.graph.nodes.ReadPrimsV2") async def test_import_time_samples_legacy(self): await self._test_import_time_samples_impl("omni.graph.nodes.ReadPrims") async def _test_import_time_samples_impl(self, read_prims_node_type: str): """Verify that time sample data is correctly imported""" (result, error) = await ogts.load_test_file("TestUSDTimeCode.usda", use_caller_subdirectory=True) self.assertTrue(result, f"{error}") controller = og.Controller() keys = og.Controller.Keys (_, nodes, cube, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"), ("ReadAttr", "omni.graph.nodes.ReadPrimAttribute"), ("ExtractRPB", "omni.graph.nodes.ExtractBundle"), ("ExtractRP", "omni.graph.nodes.ExtractBundle"), ("ExtractPrimRPB", "omni.graph.nodes.ExtractPrim"), ("ExtractPrimRP", "omni.graph.nodes.ExtractPrim"), ("ReadPrims", read_prims_node_type), ("Const", "omni.graph.nodes.ConstantDouble"), ("Const2", "omni.graph.nodes.ConstantDouble"), ], keys.CREATE_PRIMS: [ ("/World/Cube2", "Cube"), ], keys.SET_VALUES: [ ("ReadAttr.inputs:usePath", True), ("ReadAttr.inputs:primPath", "/World/Cube"), ("ExtractPrimRPB.inputs:primPath", "/World/Cube"), ("ExtractPrimRP.inputs:primPath", "/World/Cube"), ("ReadAttr.inputs:name", "size"), ("ReadAttr.inputs:usdTimecode", 0), ("ReadPrimsBundle.inputs:usdTimecode", 0), ("ReadPrims.inputs:usdTimecode", 0), ], keys.CONNECT: [ ("ReadPrimsBundle.outputs_primsBundle", "ExtractPrimRPB.inputs:prims"), ("ExtractPrimRPB.outputs_primBundle", "ExtractRPB.inputs:bundle"), ("ReadPrims.outputs_primsBundle", "ExtractPrimRP.inputs:prims"), ("ExtractPrimRP.outputs_primBundle", "ExtractRP.inputs:bundle"), ], }, ) stage = omni.usd.get_context().get_stage() input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrimsBundle.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube") input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrims.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube") # evaluate so dynamic attributes are created await controller.evaluate() # connect the size attribute so it gets updated controller.edit( "/TestGraph", { keys.CONNECT: [ ("ExtractRPB.outputs:size", "Const.inputs:value"), ("ExtractRP.outputs:size", "Const2.inputs:value"), ] }, ) cs = 10 cube_size = cube[0].GetProperty("size") cube_size.Set(cs) await controller.evaluate() out_from_read_attr = nodes[1].get_attribute("outputs:value") out_from_read_prims_bundle = nodes[2].get_attribute("outputs:size") out_from_read_prims = nodes[3].get_attribute("outputs:size") self.assertTrue(out_from_read_attr.get() == 100) self.assertTrue(out_from_read_prims_bundle.get() == 100) self.assertTrue(out_from_read_prims.get() == 100) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("ReadAttr.inputs:usdTimecode", 25), ("ReadPrimsBundle.inputs:usdTimecode", 25), ("ReadPrims.inputs:usdTimecode", 25), ] }, ) await controller.evaluate() self.assertTrue(out_from_read_attr.get() == 50) self.assertTrue(out_from_read_prims_bundle.get() == 50) self.assertTrue(out_from_read_prims.get() == 50) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("ReadAttr.inputs:usdTimecode", 50), ("ReadPrimsBundle.inputs:usdTimecode", 50), ("ReadPrims.inputs:usdTimecode", 50), ] }, ) await controller.evaluate() self.assertTrue(out_from_read_attr.get() == 1) self.assertTrue(out_from_read_prims_bundle.get() == 1) self.assertTrue(out_from_read_prims.get() == 1) # now check that if we change the targets, the values correctly update controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("ReadAttr.inputs:primPath", "/World/Cube2"), ("ExtractPrimRPB.inputs:primPath", "/World/Cube2"), ("ExtractPrimRP.inputs:primPath", "/World/Cube2"), ] }, ) input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrimsBundle.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube2") input_prim_prop = stage.GetPropertyAtPath("/TestGraph/ReadPrims.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=input_prim_prop, target="/World/Cube2") await controller.evaluate() self.assertTrue(out_from_read_attr.get() == cs) self.assertTrue(out_from_read_prims_bundle.get() == cs) self.assertTrue(out_from_read_prims.get() == cs) async def test_import_matrix_and_bbox(self): await self._test_import_matrix_and_bbox_impl("omni.graph.nodes.ReadPrimsV2") async def test_import_matrix_and_bbox_legacy(self): await self._test_import_matrix_and_bbox_impl("omni.graph.nodes.ReadPrims") async def _test_import_matrix_and_bbox_impl(self, read_prims_node_type: str): # Verify that bounding box and matrix are correctly computed controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) UsdGeom.Xformable(cube).AddTranslateOp() (_, nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrims", read_prims_node_type), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ("Inv", "omni.graph.nodes.OgnInvertMatrix"), ("Const0", "omni.graph.nodes.ConstantDouble3"), ("Const1", "omni.graph.nodes.ConstantDouble3"), ], keys.SET_VALUES: [ ("ReadPrims.inputs:pathPattern", "/World/Cube"), ("ExtractPrim.inputs:primPath", "/World/Cube"), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "ExtractPrim.inputs:prims"), ("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], }, ) if read_prims_node_type == "omni.graph.nodes.ReadPrims": controller.edit("/TestGraph", {keys.SET_VALUES: [("ReadPrims.inputs:useFindPrims", True)]}) extract_bundle = nodes[2] # creates dynamic attributes await controller.evaluate() # connect the matrix controller.edit("/TestGraph", {keys.CONNECT: ("ExtractBundle.outputs:worldMatrix", "Inv.inputs:matrix")}) # get initial output await controller.evaluate() # We did not ask for BBox self.assertFalse(extract_bundle.get_attribute_exists("outputs:bboxMinCorner")) self.assertFalse(extract_bundle.get_attribute_exists("outputs:bboxMaxCorner")) self.assertFalse(extract_bundle.get_attribute_exists("outputs:bboxTransform")) # but we should have the default matrix mat_attr = extract_bundle.get_attribute("outputs:worldMatrix") mat = mat_attr.get() self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).all()) # move the cube, check the new matrix pos = cube.GetAttribute("xformOp:translate") pos.Set((2, 2, 2)) await controller.evaluate() mat = mat_attr.get() self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 2, 2, 1]).all()) # now ask for bbox, and check its value controller.edit( "/TestGraph", { keys.SET_VALUES: ("ReadPrims.inputs:computeBoundingBox", True), }, ) await controller.evaluate() self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMinCorner")) self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMaxCorner")) self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxTransform")) # connect the bbox controller.edit( "/TestGraph", { keys.CONNECT: [ ("ExtractBundle.outputs:bboxMinCorner", "Const0.inputs:value"), ("ExtractBundle.outputs:bboxMaxCorner", "Const1.inputs:value"), ] }, ) await controller.evaluate() bbox_min = extract_bundle.get_attribute("outputs:bboxMinCorner") bbox_max = extract_bundle.get_attribute("outputs:bboxMaxCorner") bbox_min_val = bbox_min.get() bbox_max_val = bbox_max.get() self.assertTrue((bbox_min_val == [-0.5, -0.5, -0.5]).all()) self.assertTrue((bbox_max_val == [0.5, 0.5, 0.5]).all()) # then resize the cube, and check new bbox ext = cube.GetAttribute("extent") ext.Set([(-10, -10, -10), (10, 10, 10)]) await controller.evaluate() bbox_min_val = bbox_min.get() bbox_max_val = bbox_max.get() self.assertTrue((bbox_min_val == [-10, -10, -10]).all()) self.assertTrue((bbox_max_val == [10, 10, 10]).all()) async def test_readomnigraphvalue_tuple(self): """Test ReadOmniGraphValue by reading from a constant node (tuple)""" test_value = Gf.Vec3d(1.0, 2.0, 3.0) controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantDouble3"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v[0], test_value[0]) self.assertEqual(v[1], test_value[1]) self.assertEqual(v[2], test_value[2]) # try editing value test_value = Gf.Vec3d(4.0, 5.0, 6.0) og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v[0], test_value[0]) self.assertEqual(v[1], test_value[1]) self.assertEqual(v[2], test_value[2]) async def test_readomnigraphvalue_single(self): """Test ReadOmniGraphValue by reading from a constant node (single)""" test_value = 1337 controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantInt"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = 42 og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_string(self): """Test ReadOmniGraphValue by reading from a constant node (string)""" test_value = "test value" controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantString"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = "test value 2" og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_array(self): """Test ReadOmniGraphValue by reading from a constant node (array)""" test_values = [1.0, 2.0, 3.0] controller = og.Controller() keys = og.Controller.Keys (graph, (val0, val1, val2, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Val0", "omni.graph.nodes.ConstantHalf"), ("Val1", "omni.graph.nodes.ConstantHalf"), ("Val2", "omni.graph.nodes.ConstantHalf"), ("Array", "omni.graph.nodes.MakeArray"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CONNECT: [ ("Val0.inputs:value", "Array.inputs:a"), ("Val1.inputs:value", "Array.inputs:b"), ("Val2.inputs:value", "Array.inputs:c"), ], keys.SET_VALUES: [ ("Array.inputs:arraySize", 3), ("Val0.inputs:value", test_values[0]), ("Val1.inputs:value", test_values[1]), ("Val2.inputs:value", test_values[2]), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Array"), ("Get.inputs:name", "outputs:array"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v[0], test_values[0]) self.assertEqual(v[1], test_values[1]) self.assertEqual(v[2], test_values[2]) # # try editing value test_values = [4.0, 5.0, 6.0] og.Controller.attribute("inputs:value", val0).set(test_values[0]) og.Controller.attribute("inputs:value", val1).set(test_values[1]) og.Controller.attribute("inputs:value", val2).set(test_values[2]) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v[0], test_values[0]) self.assertEqual(v[1], test_values[1]) self.assertEqual(v[2], test_values[2]) async def test_readomnigraphvalue_tuple_array(self): """Test ReadOmniGraphValue by reading from a constant node (array of tuple)""" test_values = [Gf.Vec4f(1.0, 2.0, 3.0, 4.0), Gf.Vec4f(5.0, 6.0, 7.0, 8.0)] controller = og.Controller() keys = og.Controller.Keys (graph, (val0, val1, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Val0", "omni.graph.nodes.ConstantFloat4"), ("Val1", "omni.graph.nodes.ConstantFloat4"), ("Array", "omni.graph.nodes.MakeArray"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CONNECT: [ ("Val0.inputs:value", "Array.inputs:a"), ("Val1.inputs:value", "Array.inputs:b"), ], keys.SET_VALUES: [ ("Array.inputs:arraySize", 2), ("Val0.inputs:value", test_values[0]), ("Val1.inputs:value", test_values[1]), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Array"), ("Get.inputs:name", "outputs:array"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) array = out_controller.get() self.assertEqual(array[0][0], test_values[0][0]) self.assertEqual(array[0][1], test_values[0][1]) self.assertEqual(array[0][2], test_values[0][2]) self.assertEqual(array[0][3], test_values[0][3]) self.assertEqual(array[1][0], test_values[1][0]) self.assertEqual(array[1][1], test_values[1][1]) self.assertEqual(array[1][2], test_values[1][2]) self.assertEqual(array[1][3], test_values[1][3]) # # try editing value test_values = [Gf.Vec4f(1.0, 2.0, 3.0, 4.0), Gf.Vec4f(5.0, 6.0, 7.0, 8.0)] og.Controller.attribute("inputs:value", val0).set(test_values[0]) og.Controller.attribute("inputs:value", val1).set(test_values[1]) await controller.evaluate(graph) array = out_controller.get() self.assertEqual(array[0][0], test_values[0][0]) self.assertEqual(array[0][1], test_values[0][1]) self.assertEqual(array[0][2], test_values[0][2]) self.assertEqual(array[0][3], test_values[0][3]) self.assertEqual(array[1][0], test_values[1][0]) self.assertEqual(array[1][1], test_values[1][1]) self.assertEqual(array[1][2], test_values[1][2]) self.assertEqual(array[1][3], test_values[1][3]) async def test_readomnigraphvalue_any(self): """Test ReadOmniGraphValue by reading from a constant node (any)""" test_value = 42 controller = og.Controller() keys = og.Controller.Keys (graph, (var_node, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var", "omni.graph.nodes.ConstantInt"), ("ToString", "omni.graph.nodes.ToString"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CONNECT: [ ("Var.inputs:value", "ToString.inputs:value"), ], keys.SET_VALUES: [ ("Var.inputs:value", test_value), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/ToString"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = 1234 og.Controller.attribute("inputs:value", var_node).set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_prim(self): """Test ReadOmniGraphValue by reading from a prim""" test_value = 555.0 controller = og.Controller() keys = og.Controller.Keys # use ReadPrimAttribute node to cache the attribute into Fabric (graph, _, (prim,), _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadPrim", "omni.graph.nodes.ReadPrimAttribute"), ], keys.CREATE_PRIMS: ("/World/Float", {"myfloat": ("float", test_value)}), keys.SET_VALUES: [ ("ReadPrim.inputs:usePath", True), ("ReadPrim.inputs:primPath", "/World/Float"), ("ReadPrim.inputs:name", "myfloat"), ], }, ) await controller.evaluate(graph) (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Get.inputs:path", "/World/Float"), ("Get.inputs:name", "myfloat"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_value) # try editing value test_value = 42.0 prim.GetProperty("myfloat").Set(test_value) await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_value) async def test_readomnigraphvalue_change_attribute(self): """Test ReadOmniGraphValue if attribute name is changed at runtime""" test_values = [42, 360] controller = og.Controller() keys = og.Controller.Keys (graph, (_, _, get_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Var0", "omni.graph.nodes.ConstantInt"), ("Var1", "omni.graph.nodes.ConstantInt"), ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.SET_VALUES: [ ("Var0.inputs:value", test_values[0]), ("Var1.inputs:value", test_values[1]), ("Get.inputs:path", f"{self.TEST_GRAPH_PATH}/Var0"), ("Get.inputs:name", "inputs:value"), ], }, ) await controller.evaluate(graph) out_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) v = out_controller.get() self.assertEqual(v, test_values[0]) # try changing path og.Controller.attribute("inputs:path", get_node).set(f"{self.TEST_GRAPH_PATH}/Var1") await controller.evaluate(graph) v = out_controller.get() self.assertEqual(v, test_values[1]) async def test_readomnigraphvalue_invalid(self): """Test ReadOmniGraphValue by reading something that is not in Fabric""" controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Get", "omni.graph.nodes.ReadOmniGraphValue"), ], keys.CREATE_PRIMS: ("/World/Cube", "Cube"), keys.SET_VALUES: [ ("Get.inputs:path", "/World/Cube"), ("Get.inputs:name", "xformOp:translate"), ], }, ) get_node.clear_old_compute_messages() with ogts.ExpectedError(): await controller.evaluate(graph) self.assertEqual(len(get_node.get_compute_messages(og.WARNING)), 1)
25,193
Python
38.42723
113
0.539594
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_execution_framework.py
"""Basic tests of the execution framework with OG""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands from pxr import OmniGraphSchemaTools, Sdf # ====================================================================== class SimpleGraphScene: def __init__(self): self.graph = None self.nodes = None # ====================================================================== def create_simple_graph(): """Create a scene containing a PushGraph with a TestExecutionTask.""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("TestNode1", "omni.graph.test.TestExecutionTask"), ("TestNode2", "omni.graph.test.TestExecutionTask"), ("TestNode3", "omni.graph.test.TestExecutionTask"), ("TestNode4", "omni.graph.test.TestExecutionTask"), ], }, ) return scene # ====================================================================== def create_concurrency_graph(): """Create a scene containing a PushGraph with a TestConcurrency.""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("TestNode1", "omni.graph.test.TestConcurrency"), ("TestNode2", "omni.graph.test.TestConcurrency"), ("TestNode3", "omni.graph.test.TestConcurrency"), ("TestNode4", "omni.graph.test.TestConcurrency"), ], og.Controller.Keys.SET_VALUES: [ ("TestNode1.inputs:expected", 4), ("TestNode2.inputs:expected", 4), ("TestNode3.inputs:expected", 4), ("TestNode4.inputs:expected", 4), ("TestNode1.inputs:timeOut", 100), ("TestNode2.inputs:timeOut", 100), ("TestNode3.inputs:timeOut", 100), ("TestNode4.inputs:timeOut", 100), ], }, ) return scene # ====================================================================== def create_isolate_graph(): """Create a scene containing a PushGraph with TestIsolate, TestSerial, and TestConcurrency nodes.""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("TC0", "omni.graph.test.TestConcurrency"), ("TC1", "omni.graph.test.TestConcurrency"), ("TC2", "omni.graph.test.TestConcurrency"), ("TC3", "omni.graph.test.TestConcurrency"), ("TC4", "omni.graph.test.TestConcurrency"), ("TI0", "omni.graph.test.TestIsolate"), ("TI1", "omni.graph.test.TestIsolate"), ("TI2", "omni.graph.test.TestIsolate"), ("TS0", "omni.graph.test.TestSerial"), ("TS1", "omni.graph.test.TestSerial"), ("TS2", "omni.graph.test.TestSerial"), ("TS3", "omni.graph.test.TestSerial"), ("TS4", "omni.graph.test.TestSerial"), ], og.Controller.Keys.SET_VALUES: [ ("TC0.inputs:expected", 5), ("TC1.inputs:expected", 5), ("TC2.inputs:expected", 5), ("TC3.inputs:expected", 5), ("TC4.inputs:expected", 5), ("TC0.inputs:timeOut", 100), ("TC1.inputs:timeOut", 100), ("TC2.inputs:timeOut", 100), ("TC3.inputs:timeOut", 100), ("TC4.inputs:timeOut", 100), ], }, ) return scene # ====================================================================== def create_cyclic_graph(evaluator_name: str): """Create a scene containing a graph with cycles.""" # 4 cycles exist, which are made up of: # 1. Nodes 8 and 9. # 2. Nodes 11 and 12. # 3. Nodes 11, 13, and 15. # 4. Nodes 11, 13, 14, and 15. # Note that we also use a mix of serial- and parallel-scheduled # nodes for this test graph, just for fun :) scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( {"graph_path": "/World/TestGraph", "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("Node0", "omni.graph.test.TestCyclesSerial"), ("Node1", "omni.graph.test.TestCyclesParallel"), ("Node2", "omni.graph.test.TestCyclesParallel"), ("Node3", "omni.graph.test.TestCyclesSerial"), ("Node4", "omni.graph.test.TestCyclesSerial"), ("Node5", "omni.graph.test.TestCyclesParallel"), ("Node6", "omni.graph.test.TestCyclesSerial"), ("Node7", "omni.graph.test.TestCyclesParallel"), ("Node8", "omni.graph.test.TestCyclesParallel"), ("Node9", "omni.graph.test.TestCyclesParallel"), ("Node10", "omni.graph.test.TestCyclesParallel"), ("Node11", "omni.graph.test.TestCyclesParallel"), ("Node12", "omni.graph.test.TestCyclesParallel"), ("Node13", "omni.graph.test.TestCyclesParallel"), ("Node14", "omni.graph.test.TestCyclesSerial"), ("Node15", "omni.graph.test.TestCyclesSerial"), ("Node16", "omni.graph.test.TestCyclesSerial"), ], og.Controller.Keys.CONNECT: [ ("Node0.outputs:a", "Node4.inputs:a"), ("Node4.outputs:a", "Node5.inputs:a"), ("Node5.outputs:a", "Node2.inputs:a"), ("Node5.outputs:b", "Node6.inputs:a"), ("Node2.outputs:a", "Node3.inputs:a"), ("Node6.outputs:a", "Node3.inputs:b"), ("Node1.outputs:a", "Node2.inputs:b"), ("Node0.outputs:b", "Node8.inputs:a"), ("Node8.outputs:a", "Node9.inputs:a"), ("Node9.outputs:a", "Node8.inputs:b"), ("Node9.outputs:b", "Node7.inputs:a"), ("Node3.outputs:a", "Node7.inputs:b"), ("Node0.outputs:c", "Node10.inputs:a"), ("Node10.outputs:a", "Node11.inputs:a"), ("Node11.outputs:a", "Node12.inputs:a"), ("Node12.outputs:a", "Node11.inputs:b"), ("Node11.outputs:b", "Node16.inputs:a"), ("Node11.outputs:c", "Node13.inputs:a"), ("Node13.outputs:a", "Node14.inputs:a"), ("Node14.outputs:a", "Node15.inputs:a"), ("Node13.outputs:b", "Node15.inputs:b"), ("Node15.outputs:a", "Node11.inputs:c"), ("Node0.outputs:d", "Node0.inputs:d"), ("Node5.outputs:c", "Node5.inputs:c"), ("Node10.outputs:b", "Node10.inputs:b"), ("Node14.outputs:b", "Node14.inputs:b"), ], }, ) return scene # ====================================================================== def create_single_node_cyclic_graph(evaluator_name: str): """Create a scene containing a graph with single-node cycles""" scene = SimpleGraphScene() (scene.graph, scene.nodes, _, _) = og.Controller.edit( {"graph_path": "/World/TestGraph", "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("Node0", "omni.graph.test.TestCyclesSerial"), ("Node1", "omni.graph.test.TestCyclesParallel"), ], og.Controller.Keys.CONNECT: [ ("Node0.outputs:a", "Node0.inputs:a"), ("Node0.outputs:a", "Node1.inputs:a"), ("Node1.outputs:b", "Node1.inputs:b"), ], }, ) return scene # ====================================================================== class TestExecutionFrameworkSanity(ogts.OmniGraphTestCase): """Execution Framework Unit Tests""" async def test_execution_task(self): """Validate that execution framework is executing nodes in the graph.""" scene = create_simple_graph() # Verify starting condition. for node in scene.nodes: self.assertFalse(og.Controller(("outputs:result", node)).get()) # Execute the update once and we want explicitly to execute entire app update pipeline. await omni.kit.app.get_app().next_update_async() # Verify all nodes were executed with EF. for node in scene.nodes: self.assertTrue(og.Controller(("outputs:result", node)).get()) async def test_parallel_execution(self): """Validate that nodes are executed concurrently.""" scene = create_concurrency_graph() def _check_all_reached_concurrency(scene): result = True for node in scene.nodes: result = result and og.Controller(("outputs:result", node)).get() return result # Verify starting condition. self.assertFalse(_check_all_reached_concurrency(scene)) # First executions are forced to be run in isolation. await omni.kit.app.get_app().next_update_async() self.assertFalse(_check_all_reached_concurrency(scene)) # Now we should be getting parallel execution. await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_reached_concurrency(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_reached_concurrency(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_reached_concurrency(scene)) async def test_on_demand_execution_task(self): """Validate that execution framework is executing nodes in the graph.""" scene = create_simple_graph() # Verify starting condition. for node in scene.nodes: self.assertFalse(og.Controller(("outputs:result", node)).get()) # Execute given graph explicitly/on-demand. await og.Controller.evaluate(scene.graph) # Verify all nodes were executed with EF. for node in scene.nodes: self.assertTrue(og.Controller(("outputs:result", node)).get()) async def test_isolate_execution(self): """Check that nodes with the "usd-write" scheduling hint get executed in isolation.""" scene = create_isolate_graph() def _check_all_successful(scene): result = True for node in scene.nodes: result = result and og.Controller(("outputs:result", node)).get() return result # Verify starting condition. self.assertFalse(_check_all_successful(scene)) # First executions are forced to be run in isolation. await omni.kit.app.get_app().next_update_async() # In subsequent executions each node gets executed per # its scheduling hint. Should not get any conflicts. await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_successful(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_successful(scene)) await omni.kit.app.get_app().next_update_async() self.assertTrue(_check_all_successful(scene)) async def test_cycling_push_graph(self): """Check that cycles in push graphs correctly get ignored during execution.""" scene = create_cyclic_graph("push") # Set of node indices that will evaluate. node_indices_that_evaluate = {0, 1, 2, 3, 4, 5, 6, 10} # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # For each tick, only the nodes in the index list should get evaluated; # all other nodes either lie within a cycle or downstream of a cycle, and # thus will be ignored. for i in range(4): await omni.kit.app.get_app().next_update_async() for j, state_cnt_attr in enumerate(state_cnt_attrs): self.assertEqual(state_cnt_attr.get(), i + 1 if j in node_indices_that_evaluate else 0) async def test_cycling_pull_graph(self): """Check that cycles in pull graphs correctly get ignored during execution.""" scene = create_cyclic_graph("dirty_push") # Set of node indices that will evaluate when node 0 is dirtied. node_indices_that_evaluate = {0, 1, 2, 3, 4, 5, 6, 10} # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # Trigger a graph evaluation by adding/removing a connection between nodes 0 and 4. # Only the nodes in the index list should get evaluated; all other nodes either lie # within a cycle or downstream of a cycle, and thus will be ignored. for i in range(4): if i % 2 == 0: og.Controller.connect( scene.nodes[0].get_attribute("outputs:d"), scene.nodes[4].get_attribute("inputs:d") ) else: og.Controller.disconnect( scene.nodes[0].get_attribute("outputs:d"), scene.nodes[4].get_attribute("inputs:d") ) await omni.kit.app.get_app().next_update_async() for j, state_cnt_attr in enumerate(state_cnt_attrs): self.assertEqual(state_cnt_attr.get(), i + 1 if j in node_indices_that_evaluate else 0) async def test_push_graph_with_single_node_cycles(self): """Check that single-node cycles in push graphs do not block execution.""" scene = create_single_node_cyclic_graph("push") # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # Check that all nodes get executed each tick. for i in range(4): await omni.kit.app.get_app().next_update_async() for state_cnt_attr in state_cnt_attrs: self.assertEqual(state_cnt_attr.get(), i + 1) async def test_pull_graph_with_single_node_cycles(self): """Check that single-node cycles in pull graphs do not block execution.""" scene = create_single_node_cyclic_graph("dirty_push") # Get all state counters. state_cnt_attrs = [node.get_attribute("state:count") for node in scene.nodes] # Trigger a graph evaluation by adding/removing an extra connection between nodes # 0 and 1. All nodes should execute. for i in range(4): if i % 2 == 0: og.Controller.connect( scene.nodes[0].get_attribute("outputs:c"), scene.nodes[1].get_attribute("inputs:c") ) else: og.Controller.disconnect( scene.nodes[0].get_attribute("outputs:c"), scene.nodes[1].get_attribute("inputs:c") ) await omni.kit.app.get_app().next_update_async() for state_cnt_attr in state_cnt_attrs: self.assertEqual(state_cnt_attr.get(), i + 1) async def test_partitioning_with_instancing(self): """ Check that injection of either a NodeDefLambda or NodeGraphDef into the OG execution graph backend continues to work with instancing. """ # Run the test against both test partition passes. partition_pass_settings = [ "/app/omni.graph.test/enableTestNodeDefLambdaPass", "/app/omni.graph.test/enableTestNodeGraphDefPass", ] for si, pps in enumerate(partition_pass_settings): with og.Settings.temporary(pps, True): # Run the test over push and dirty_push evaluator types. Once partitioning # is supported by the Action Graph executor, we should be able to also # test the "execution" evaluator here as well. evaluator_names = [ "push", "dirty_push", # "execution", ] for evaluator_name in evaluator_names: # Create our graph, which will contain a ReadVariable and # WriteVariable node. graph_path = "/World/TestGraph" (graph, (read_variable_node, write_variable_node), _, _) = og.Controller.edit( {"graph_path": graph_path, "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("WriteVariable", "omni.graph.core.WriteVariable"), ], og.Controller.Keys.CREATE_VARIABLES: [ ("in_int_var", og.Type(og.BaseDataType.INT)), ("out_int_var", og.Type(og.BaseDataType.INT)), ], og.Controller.Keys.CONNECT: [ ("ReadVariable.outputs:value", "WriteVariable.inputs:value"), ], og.Controller.Keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "in_int_var"), ("WriteVariable.inputs:variableName", "out_int_var"), ], }, ) # Create the custom counter attribute on both nodes so # that they get picked up by the partition pass. og.Controller.create_attribute( read_variable_node, "outputs:test_counter_attribute", og.Type(og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) og.Controller.create_attribute( write_variable_node, "outputs:test_counter_attribute", og.Type(og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) # Get some attributes/variables that we'll need for the test. in_var = graph.find_variable("in_int_var") rn_out_value = read_variable_node.get_attribute("outputs:value") wn_in_value = write_variable_node.get_attribute("inputs:value") wn_out_value = write_variable_node.get_attribute("outputs:value") out_var = graph.find_variable("out_int_var") rn_cnt = read_variable_node.get_attribute("outputs:test_counter_attribute") wn_cnt = write_variable_node.get_attribute("outputs:test_counter_attribute") # Create 3 graph instances, each with unique "in_int_var" values # and "out_int_var" set to zero. num_prims = 3 prim_ids = [None] * num_prims prim_paths = [None] * num_prims prims = [None] * num_prims stage = omni.usd.get_context().get_stage() graph_context = graph.get_default_graph_context() for i in range(0, num_prims): prim_ids[i] = i prim_paths[i] = f"/World/Prim_{i}" prims[i] = stage.DefinePrim(prim_paths[i]) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_paths[i], graph_path) prims[i].CreateAttribute("graph:variable:in_int_var", Sdf.ValueTypeNames.Int).Set(i) prims[i].CreateAttribute("graph:variable:out_int_var", Sdf.ValueTypeNames.Int).Set(0) # When we evaluate the graph we should see that (a) the counter attribute on the # authoring node gets ticked (which is handled directly by the partition passes, # thus letting us know that they actually went through successfully/weren't just # no-ops), and (b) the out_int_var variable gets successfully written out to with # the value listed on the in_int_var variable. await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() for i in range(0, num_prims): expected_value = i self.assertEqual(in_var.get(graph_context, instance_path=prim_paths[i]), expected_value) # Note that the instanced nodes (and thus the attributes we're looking up) # need not be ordered according to the iteration index, e.g., instance with # index 0 may correspond to the prim at the i == 2 index in the prim_paths # list This is why we perform the subsequent 3 checks as shown below. self.assertIn(rn_out_value.get(instance=i), prim_ids) self.assertIn(wn_in_value.get(instance=i), prim_ids) self.assertIn(wn_out_value.get(instance=i), prim_ids) self.assertEqual(out_var.get(graph_context, instance_path=prim_paths[i]), expected_value) if ( evaluator_name == "push" ): # Needed because PushGraphs have some special vectorization going on? if si == 0: self.assertEqual(rn_cnt.get(), 2) self.assertEqual(wn_cnt.get(), 2) self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) else: self.assertEqual(rn_cnt.get(), 0) self.assertEqual(wn_cnt.get(), 0) if i == 0: self.assertEqual(rn_cnt.get(instance=i), 2) self.assertEqual(wn_cnt.get(instance=i), 2) else: self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) else: if si == 0: self.assertEqual(rn_cnt.get(), 6) self.assertEqual(wn_cnt.get(), 6) self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) else: self.assertEqual(rn_cnt.get(), 0) self.assertEqual(wn_cnt.get(), 0) if i == 0: self.assertEqual(rn_cnt.get(instance=i), 6) self.assertEqual(wn_cnt.get(instance=i), 6) else: self.assertEqual(rn_cnt.get(instance=i), 0) self.assertEqual(wn_cnt.get(instance=i), 0) # Delete all prims in the stage. for i in range(0, num_prims): stage.RemovePrim(prim_paths[i]) graph.remove_variable(in_var) graph.remove_variable(out_var) stage.RemovePrim(graph_path) await omni.kit.app.get_app().next_update_async() async def test_constant_node_removal(self): """ Check that we do not include constant OG nodes in the execution graph backend for push and action graphs, and that doing so does not impact graph computation to yield incorrect results. """ stage = omni.usd.get_context().get_stage() # Run the test over each evaluator type. evaluator_names = [ "push", "dirty_push", "execution", ] for evaluator_name in evaluator_names: # Create our test graph. graph_path = "/World/TestGraph" test_prim_path = "/World/TestPrim" (graph, (constant_double0_node, constant_double1_node, add_node, _, _, _), _, _) = og.Controller.edit( {"graph_path": graph_path, "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("ConstantDouble0", "omni.graph.nodes.ConstantDouble"), ("ConstantDouble1", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("OnTick", "omni.graph.action.OnTick"), ("WritePrimAttribute", "omni.graph.nodes.WritePrimAttribute"), ("WriteVariable", "omni.graph.core.WriteVariable"), ], og.Controller.Keys.CREATE_PRIMS: ( test_prim_path, { "value": ("double", 0), }, ), og.Controller.Keys.CREATE_VARIABLES: [ ("out_double_var", og.Type(og.BaseDataType.DOUBLE)), ], og.Controller.Keys.CONNECT: [ ("ConstantDouble0.inputs:value", "Add.inputs:a"), ("ConstantDouble1.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "WritePrimAttribute.inputs:value"), ("Add.outputs:sum", "WriteVariable.inputs:value"), ("OnTick.outputs:tick", "WritePrimAttribute.inputs:execIn"), ("WritePrimAttribute.outputs:execOut", "WriteVariable.inputs:execIn"), ], og.Controller.Keys.SET_VALUES: [ ("ConstantDouble0.inputs:value", 5.0), ("ConstantDouble1.inputs:value", 1.0), ("OnTick.inputs:onlyPlayback", False), ("WritePrimAttribute.inputs:name", "value"), ("WritePrimAttribute.inputs:primPath", "/World/TestPrim"), ("WriteVariable.inputs:variableName", "out_double_var"), ], }, ) out_double_var = graph.find_variable("out_double_var") inputs_value_attr_0 = constant_double0_node.get_attribute("inputs:value") inputs_value_attr_1 = constant_double1_node.get_attribute("inputs:value") outputs_sum_attr = add_node.get_attribute("outputs:sum") # Check that the summation is correctly computed, and that the # ConstantDouble nodes aren't computed. await omni.kit.app.get_app().next_update_async() self.assertAlmostEqual(outputs_sum_attr.get(), 6.0, places=2) if evaluator_name in ("push", "execution"): self.assertEqual(constant_double0_node.get_compute_count(), 0) self.assertEqual(constant_double1_node.get_compute_count(), 0) else: self.assertEqual(constant_double0_node.get_compute_count(), 1) self.assertEqual(constant_double1_node.get_compute_count(), 1) # Check that this still holds if we alter attributes on the nodes. inputs_value_attr_0.set(8) inputs_value_attr_1.set(2) await omni.kit.app.get_app().next_update_async() self.assertAlmostEqual(outputs_sum_attr.get(), 10.0, places=2) if evaluator_name in ("push", "execution"): self.assertEqual(constant_double0_node.get_compute_count(), 0) self.assertEqual(constant_double1_node.get_compute_count(), 0) else: self.assertEqual(constant_double0_node.get_compute_count(), 2) self.assertEqual(constant_double1_node.get_compute_count(), 2) # Next, instance the graph 3 times and perform similar checks as before. graph_context = graph.get_default_graph_context() num_graph_instances = 3 graph_instance_ids = [None] * num_graph_instances graph_instance_paths = [None] * num_graph_instances graph_instances = [None] * num_graph_instances for i in range(0, num_graph_instances): graph_instance_ids[i] = i graph_instance_paths[i] = f"/World/GraphInstance_{i}" graph_instances[i] = stage.DefinePrim(graph_instance_paths[i]) OmniGraphSchemaTools.applyOmniGraphAPI(stage, graph_instance_paths[i], graph_path) graph_instances[i].CreateAttribute("graph:variable:out_double_var", Sdf.ValueTypeNames.Double).Set(0) inputs_value_attr_0.set(1) inputs_value_attr_1.set(3) await omni.kit.app.get_app().next_update_async() for i in range(0, num_graph_instances): # TODO: Instanced "execution" type graphs aren't getting updated here # for some reason, needs a bit more investigation... if evaluator_name == "execution": self.assertEqual(out_double_var.get(graph_context, instance_path=graph_instance_paths[i]), 0.0) else: self.assertEqual(out_double_var.get(graph_context, instance_path=graph_instance_paths[i]), 4.0) if evaluator_name in ("push", "execution"): self.assertEqual(constant_double0_node.get_compute_count(), 0) self.assertEqual(constant_double1_node.get_compute_count(), 0) else: self.assertEqual(constant_double0_node.get_compute_count(), 6) self.assertEqual(constant_double1_node.get_compute_count(), 6) # Delete all prims in the stage. for i in range(0, num_graph_instances): stage.RemovePrim(graph_instance_paths[i]) stage.RemovePrim(test_prim_path) stage.RemovePrim(graph_path) await omni.kit.app.get_app().next_update_async()
30,924
Python
47.320312
117
0.530235
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_bundles.py
"""Tests exercising bundles in OmniGraph""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit # ====================================================================== class TestOmniGraphBundles(ogts.OmniGraphTestCase): async def test_get_prims_use_target_prims(self): controller = og.Controller() keys = og.Controller.Keys graph_path = "/World/Graph" (graph, (_, get_prims), (surface1, surface2, surface3), _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadPrims", "omni.graph.nodes.ReadPrims"), ("GetPrims", "omni.graph.nodes.GetPrims"), ], keys.CREATE_PRIMS: [ ("/Surface1", "Cube"), ("/Surface2", "Cube"), ("/Surface3", "Cube"), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "GetPrims.inputs:bundle"), ], }, ) stage = omni.usd.get_context().get_stage() context = graph.get_default_graph_context() bundle = context.get_output_bundle(get_prims, "outputs_bundle") omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(graph_path + "/ReadPrims.inputs:prims"), targets=[surface1.GetPath(), surface2.GetPath(), surface3.GetPath()], ) # get two prims omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(graph_path + "/GetPrims.inputs:prims"), targets=[surface1.GetPath(), surface2.GetPath()], ) graph.evaluate() self.assertEqual(bundle.get_child_bundle_count(), 2) # switch back to default to get all omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(graph_path + "/GetPrims.inputs:prims"), targets=[], ) graph.evaluate() self.assertEqual(bundle.get_child_bundle_count(), 3) async def test_bundle_child_producer_consumer(self): controller = og.Controller() keys = og.Controller.Keys graph_path = "/World/Graph" (graph, (_, child_producer_node, child_consumer_node), (surface1, surface2), _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadPrims", "omni.graph.nodes.ReadPrims"), ("BundleChildProducer", "omni.graph.test.BundleChildProducerPy"), ("BundleChildConsumer", "omni.graph.test.BundleChildConsumerPy"), ], keys.CREATE_PRIMS: [ ("/Surface1", "Cube"), ("/Surface2", "Cube"), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "BundleChildProducer.inputs:bundle"), ("BundleChildProducer.outputs_bundle", "BundleChildConsumer.inputs:bundle"), ], }, ) stage = omni.usd.get_context().get_stage() omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(graph_path + "/ReadPrims.inputs:prims"), target=surface1.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(graph_path + "/ReadPrims.inputs:prims"), target=surface2.GetPath(), ) graph.evaluate() self.assertEqual(child_producer_node.get_attribute("outputs:numChildren").get(), 2) self.assertEqual(child_consumer_node.get_attribute("outputs:numChildren").get(), 1) self.assertEqual(child_consumer_node.get_attribute("outputs:numSurfaces").get(), 2) graph.evaluate() self.assertEqual(child_producer_node.get_attribute("outputs:numChildren").get(), 2) self.assertEqual(child_consumer_node.get_attribute("outputs:numChildren").get(), 1) self.assertEqual(child_consumer_node.get_attribute("outputs:numSurfaces").get(), 2) async def __test_input_bundle_validity(self, bundle_properties_name): """Test if connecting/disconnecting invalidates the database and reinitializes BundleContents for input bundle""" controller = og.Controller() keys = og.Controller.Keys # Disconnected input bundle should be invalid (graph, (_, bundle_properties), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("BundleConstructor", "omni.graph.nodes.BundleConstructor"), ("BundleProperties", f"omni.graph.test.{bundle_properties_name}"), ], }, ) graph.evaluate() self.assertFalse(bundle_properties.get_attribute("outputs:valid").get()) # Connected input bundle should be valid (graph, _, _, _) = controller.edit( "/World/Graph", { keys.CONNECT: [ ("BundleConstructor.outputs_bundle", "BundleProperties.inputs:bundle"), ], }, ) graph.evaluate() self.assertTrue(bundle_properties.get_attribute("outputs:valid").get()) # ---------------------------------------------------------------------- async def test_is_input_bundle_valid_cpp(self): """Test if connecting/disconnecting invalidates the database and reinitializes BundleContents for input bundle for C++""" await self.__test_input_bundle_validity("BundleProperties") # ---------------------------------------------------------------------- async def test_is_input_bundle_valid_py(self): """Test if connecting/disconnecting invalidates the database and reinitializes BundleContents for input bundle for Python""" await self.__test_input_bundle_validity("BundlePropertiesPy") async def __test_producer_consumer_bundle_change_tracking(self, producer_name, consumer_name): controller = og.Controller() keys = og.Controller.Keys # +--------------------+ +---------------------+ # | | | | # | Bundle Producer --------> Bundle Consumer | # | | | | # +--------------------+ +---------------------+ # (make changes) (recompute if input changed) (graph, (producer_node, consumer_node), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("BundleProducer", f"omni.graph.test.{producer_name}"), ("BundleConsumer", f"omni.graph.test.{consumer_name}"), ], keys.CONNECT: [ ("BundleProducer.outputs_bundle", "BundleConsumer.inputs:bundle"), ], }, ) context = graph.get_context() producer_bundle = context.get_output_bundle(producer_node, "outputs_bundle") consumer_bundle = context.get_output_bundle(consumer_node, "outputs_bundle") # First evaluation is necessary. graph.evaluate() self.assertTrue(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) # Next evaluation producer did not create any data. graph.evaluate() self.assertFalse(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) # Create a child at the producer, then check if consumer recomputes. producer_bundle.create_child_bundle("surface0") graph.evaluate() self.assertTrue(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) self.assertEqual(consumer_bundle.get_child_bundle_count(), 1) # Next evaluation producer did not create any data. graph.evaluate() self.assertFalse(consumer_node.get_attribute("outputs:hasOutputBundleChanged").get()) # ---------------------------------------------------------------------- async def test_producer_consumer_bundle_change_tracking_cpp(self): await self.__test_producer_consumer_bundle_change_tracking("BundleProducer", "BundleConsumer") # ---------------------------------------------------------------------- async def test_producer_consumer_bundle_change_tracking_py(self): await self.__test_producer_consumer_bundle_change_tracking("BundleProducerPy", "BundleConsumerPy") # ---------------------------------------------------------------------- async def test_bundle_to_target_connection(self): """Backwards compatibility test to open a USD file where node with a bundle and target is connected. This test is to check if the connection from USD file is properly deserialized. """ (result, error) = await ogts.load_test_file("TestBundleToTargetConnection.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph_path = "/World/PushGraph" controller = og.Controller() graph = controller.graph(graph_path) await controller.evaluate(graph) node = controller.node(f"{graph_path}/test_node_bundle_to_target_connection_01") attr = controller.attribute("inputs:target", node) connections = attr.get_upstream_connections() self.assertEqual(len(connections), 1) self.assertEqual( connections[0].get_path(), f"{graph_path}/test_node_bundle_to_target_connection/outputs_bundle" )
9,784
Python
43.276018
132
0.557543
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_controller_api.py
# noqa PLC0302 """Basic tests of the controller classes in omni.graph.core""" import omni.graph.core.tests as ogts # ============================================================================================================== class TestControllerApi(ogts.OmniGraphTestCase): """Run a simple set of unit tests that exercise the API of the controller. Tests are formatted in such a way that the documentation can be extracted directly from the running code, to ensure it stays up to date. """ # -------------------------------------------------------------------------------------------------------------- async def test_controller_api(self): """Contrived test that exercises the entire API of the Controller, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-controller-XX pairs. """ # begin-controller-boilerplate import omni.graph.core as og keys = og.Controller.Keys # Usually handy to keep this name short as it is used often controller = og.Controller() # end-controller-boilerplate # begin-controller-as-static og.Controller.edit("/World/MyGraph", {keys.CREATE_NODES: ("MyClassNode", "omni.graph.tutorials.SimpleData")}) og.Controller.edit("/World/MyGraph", {keys.SET_VALUES: ("/World/MyGraph/MyClassNode.inputs:a_bool", False)}) # end-controller-as-static # begin-controller-as-object controller.edit("/World/MyGraph", {keys.CREATE_NODES: ("MyNode", "omni.graph.tutorials.SimpleData")}) controller.edit("/World/MyGraph", {keys.SET_VALUES: ("MyNode.inputs:a_bool", False)}) # end-controller-as-object # begin-controller-remember (graph, nodes, prims, name_to_path_map) = og.Controller.edit( "/World/MyGraph", {keys.CREATE_NODES: ("KnownNode", "omni.graph.tutorials.SimpleData")} ) assert not prims # graph = og.Graph # the newly created or existing graph, here the one at the path "/World/MyGraph" # nodes = list[og.Node] # the list of nodes created, here [the node named "KnownNode"] # prims = list[Usd.Prim] # the list of prims created via the keys.CREATE_PRIMS directive, here [] # name_to_path_map = dict[str, str] # the map of short names to full paths created, here {"KnownNode": "/World/MyGraph/KnownNode"} # You can use the node directly to find the attribute og.Controller.edit(graph, {keys.SET_VALUES: (("inputs:a_bool", nodes[0]), False)}) # You can pass in the map so that the short name of the node can be used to find the attribute og.Controller.edit(graph, {keys.SET_VALUES: ("KnownNode.inputs:a_bool", False)}, name_to_path_map) # end-controller-remember # For later use og.Controller.connect("/World/MyGraph/MyClassNode.outputs:a_bool", "/World/MyGraph/KnownNode.inputs:a_bool") # begin-controller-access-type await og.Controller.evaluate() await controller.evaluate() # end-controller-access-type # begin-controller-evaluate # This version evaluates all graphs asynchronously await og.Controller.evaluate() # This version evaluates the graph defined by the controller object synchronously controller.evaluate_sync() # This version evaluates the single named graph synchronously og.Controller.evaluate_sync(graph) # end-controller-evaluate # begin-controller-attr-construct controller = og.Controller(og.Controller.attribute("/World/MyGraph/MyNode.inputs:a_bool")) if controller.get(): print("This should not be hit as the value was already set to False") if og.Controller.get(og.Controller.attribute("/World/MyGraph/MyNode.inputs:a_bool")): print("Similarly, this is a variation of the same call that should give the same result") # end-controller-attr-construct self.assertFalse(controller.get()) # begin-controller-big-edit # Keywords are shown for the edit arguments, however they are not required (graph, nodes, prims, name_to_path_map) = og.Controller.edit( # First parameter is a graph reference, created if it doesn't already exist. # See omni.graph.core.GraphController.create_graph() for more options graph_id="/World/MyGraph", # Second parameter is a dictionary edit_commands={ # Delete a node or list of nodes that already existed in the graph # See omni.graph.core.GraphController.delete_nodes() for more options keys.DELETE_NODES: ["MyNode"], # Create new nodes in the graph - the resulting og.Nodes are returned in the "nodes" part of the tuple # See omni.graph.core.GraphController.create_node() for more options keys.CREATE_NODES: [ ("src", "omni.graph.tutorials.SimpleData"), ("dst", "omni.graph.tutorials.SimpleData"), ], # Create new (dynamic) attributes on some nodes. # See omni.graph.core.NodeController.create_attribute() for more options keys.CREATE_ATTRIBUTES: [ ("src.inputs:dyn_float", "float"), ("dst.inputs:dyn_any", "any"), ], # Create new prims in the stage - the resulting Usd.Prims are returned in the "prims" part of the tuple # See omni.graph.core.GraphController.create_prims() for more options keys.CREATE_PRIMS: [ ("Prim1", {"attrFloat": ("float", 2.0)}), ("Prim2", {"attrBool": ("bool", True)}), ], # Expose on of the prims to OmniGraph by creating a USD import node to read it as a bundle. # The resulting node is in the "nodes" part of the tuple, after any native OmniGraph node types. # See omni.graph.core.GraphController.expose_prims() for more options keys.EXPOSE_PRIMS: [(og.Controller.PrimExposureType.AS_BUNDLE, "Prim1", "Prim1Exposed")], # Connect a source output to a destination input to create a flow of data between the two nodes # See omni.graph.core.GraphController.connect() for more options keys.CONNECT: [("src.outputs:a_int", "dst.inputs:a_int")], # Disconnect an already existing connection. # See omni.graph.core.GraphController.disconnect() for more options keys.DISCONNECT: [ ("/World/MyGraph/MyClassNode.outputs:a_bool", "/World/MyGraph/KnownNode.inputs:a_bool") ], # Define an attribute's value (inputs and state attributes only - outputs are computed) # See omni.graph.core.DataView.set() for more options keys.SET_VALUES: [("src.inputs:a_int", 5)], # Create graph-local variable values # See omni.graph.core.GraphController.create_variables() for more options keys.CREATE_VARIABLES: [("a_float_var", og.Type(og.BaseDataType.FLOAT)), ("a_bool_var", "bool")], }, # Parameters from here down could also be saved as part of the object and reused repeatedly if you had # created a controller rather than calling edit() as a class method path_to_object_map=None, # Saved object-to-path map, bootstraps any created as part of the call update_usd=True, # Immediately echo the changes to the underlying USD undoable=True, # If False then do not remember previous state - useful for writing tests allow_exists_node=False, # If True then silently succeed requests to create already existing nodes allow_exists_prim=False, # If True then silently succeed requests to create already existing prims ) # end-controller-big-edit # -------------------------------------------------------------------------------------------------------------- async def test_object_lookup_api(self): """Contrived test that exercises the entire API of the ObjectLookup, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-object-lookup-XX pairs. """ # begin-object-lookup-boilerplate import omni.graph.core as og import omni.usd from pxr import OmniGraphSchema, Sdf keys = og.Controller.Keys # Note that when you extract the parameters this way it is important to have the trailing "," in the node # and prim tuples so that Python doesn't try to interpret them as single objects. (graph, (node,), (prim,), _) = og.Controller.edit( "/World/MyGraph", { keys.CREATE_NODES: ("MyNode", "omni.graph.test.TestAllDataTypes"), keys.CREATE_PRIMS: ("MyPrim", {"myFloat": ("float", 0)}), keys.CREATE_VARIABLES: ("MyVariable", "float"), }, ) assert prim.IsValid() attribute = node.get_attribute("inputs:a_bool") relationship_attribute = node.get_attribute("inputs:a_target") attribute_type = attribute.get_resolved_type() node_type = node.get_node_type() variable = graph.get_variables()[0] stage = omni.usd.get_context().get_stage() # end-object-lookup-boilerplate # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-graph # Look up the graph directly from itself (to simplify code) assert graph == og.Controller.graph(graph) # Look up the graph by path assert graph == og.Controller.graph("/World/MyGraph") # Look up the graph by Usd Prim graph_prim = stage.GetPrimAtPath("/World/MyGraph") assert graph == og.Controller.graph(graph_prim) # Look up by a Usd Schema object graph_schema = OmniGraphSchema.OmniGraph(graph_prim) assert graph == og.Controller.graph(graph_schema) # Look up the graph by SdfPath path = Sdf.Path("/World/MyGraph") assert graph == og.Controller.graph(path) # Look up a list of graphs by passing a list of any of the above for new_graph in og.Controller.graph([graph, "/World/MyGraph", path]): assert graph == new_graph # end-object-lookup-graph # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-node # Look up the node directly from itself (to simplify code) assert node == og.Controller.node(node) # Look up the node by path assert node == og.Controller.node("/World/MyGraph/MyNode") # Look up the node by partial path and graph. # The graph parameter can be any of the ones supported by og.Controller.graph() assert node == og.Controller.node(("MyNode", graph)) # Look up the node by SdfPath node_path = Sdf.Path("/World/MyGraph/MyNode") assert node == og.Controller.node(node_path) # Look up the node from its underlying USD prim backing, if it exists node_prim = stage.GetPrimAtPath("/World/MyGraph/MyNode") assert node == og.Controller.node(node_prim) # Look up a list of nodes by passing a list of any of the above for new_node in og.Controller.node([node, "/World/MyGraph/MyNode", ("MyNode", graph), node_path, node_prim]): assert node == new_node # end-object-lookup-node # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-attribute # Look up the attribute directly from itself (to simplify code) assert attribute == og.Controller.attribute(attribute) # Look up the attribute by path assert attribute == og.Controller.attribute("/World/MyGraph/MyNode.inputs:a_bool") # Look up the attribute by SdfPath assert attribute == og.Controller.attribute(Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool")) # Look up the attribute by name and node assert attribute == og.Controller.attribute(("inputs:a_bool", node)) # These can chain, so you can also look up the attribute by name and node, where node is further looked up by # relative path and graph assert attribute == og.Controller.attribute(("inputs:a_bool", ("MyNode", graph))) # Look up the attribute by SdfPath attr_path = Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool") assert attribute == og.Controller.attribute(attr_path) # Look up the attribute through its Usd counterpart stage = omni.usd.get_context().get_stage() node_prim = stage.GetPrimAtPath("/World/MyGraph/MyNode") usd_attribute = node_prim.GetAttribute("inputs:a_bool") assert attribute == og.Controller.attribute(usd_attribute) # Look up a list of attributes by passing a list of any of the above for new_attribute in og.Controller.attribute( [ attribute, "/World/MyGraph/MyNode.inputs:a_bool", Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool"), ("inputs:a_bool", node), ("inputs:a_bool", ("MyNode", graph)), attr_path, usd_attribute, ] ): assert attribute == new_attribute # end-object-lookup-attribute # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-attribute-type attribute_type = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION) # Look up the attribute type by OGN type name assert attribute_type == og.Controller.attribute_type("pointf[3][]") # Look up the attribute type by SDF type name assert attribute_type == og.Controller.attribute_type("point3f[]") # Look up the attribute type directly from itself (to simplify code) assert attribute_type == og.Controller.attribute_type(attribute_type) # Look up the attribute type from the attribute with that type point_attribute = og.Controller.attribute(("inputs:a_pointf_3_array", node)) assert attribute_type == og.Controller.attribute_type(point_attribute) # Look up the attribute type from the attribute data whose attribute has that type (most commonly done with # attributes that have extended types or attributes belonging to bundles) point_attribute_data = point_attribute.get_attribute_data() assert attribute_type == og.Controller.attribute_type(point_attribute_data) # end-object-lookup-attribute-type # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-node-type node_type = node.get_node_type() # Look up the node type directly from itself (to simplify code) assert node_type == og.Controller.node_type(node_type) # Look up the node type from the string that uniquely identifies it assert node_type == og.Controller.node_type("omni.graph.test.TestAllDataTypes") # Look up the node type from the node with that type assert node_type == og.Controller.node_type(node) # Look up the node type from the USD Prim backing a node of that type assert node_type == og.Controller.node_type(node_prim) # Look up a list of node types by passing a list of any of the above for new_node_type in og.Controller.node_type( [ node_type, "omni.graph.test.TestAllDataTypes", node, node_prim, ] ): assert node_type == new_node_type # end-object-lookup-node-type # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-prim # Look up the prim directly from itself (to simplify code) assert node_prim == og.Controller.prim(node_prim) # Look up the prim from the prim path as a string assert node_prim == og.Controller.prim("/World/MyGraph/MyNode") # Look up the prim from the Sdf.Path pointing to the prim assert node_prim == og.Controller.prim(node_path) # Look up the prim from the OmniGraph node for which it is the backing assert node_prim == og.Controller.prim(node) # Look up the prim from the (node_path, graph) tuple defining the OmniGraph node for which it is the backing assert node_prim == og.Controller.prim(("MyNode", graph)) # Look up the prim from an OmniGraph graph assert graph_prim == og.Controller.prim(graph) # Look up a list of prims by passing a list of any of the above for new_prim in og.Controller.prim( [ node_prim, "/World/MyGraph/MyNode", node_path, node, ("MyNode", graph), ] ): assert node_prim == new_prim # end-object-lookup-prim # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-usd-attribute # USD attributes can be looked up with the same parameters as for looking up an OmniGraph attribute # Look up the USD attribute directly from itself (to simplify code) assert usd_attribute == og.Controller.usd_attribute(usd_attribute) # Look up the USD attribute by path assert usd_attribute == og.Controller.usd_attribute("/World/MyGraph/MyNode.inputs:a_bool") # Look up the USD attribute by name and node assert usd_attribute == og.Controller.usd_attribute(("inputs:a_bool", node)) # These can chain, so you can also look up the USD attribute by name and node, where node is further looked up by # relative path and graph assert usd_attribute == og.Controller.usd_attribute(("inputs:a_bool", ("MyNode", graph))) # Look up the USD attribute by SdfPath attr_path = Sdf.Path("/World/MyGraph/MyNode.inputs:a_bool") assert usd_attribute == og.Controller.usd_attribute(attr_path) # Look up the USD attribute through its OmniGraph counterpart assert usd_attribute == og.Controller.usd_attribute(attribute) # Look up a list of attributes by passing a list of any of the above for new_usd_attribute in og.Controller.usd_attribute( [ usd_attribute, "/World/MyGraph/MyNode.inputs:a_bool", ("inputs:a_bool", node), ("inputs:a_bool", ("MyNode", graph)), attr_path, attribute, ] ): assert usd_attribute == new_usd_attribute # end-object-lookup-usd-attribute # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-usd-relationship # USD relationships can be looked up with the same parameters as for looking up an OmniGraph attribute. This applies # when the attribute is backed by a USD relationship instead of a USD attribute. usd_relationship = node_prim.GetRelationship("inputs:a_target") # Look up the USD relationship directly from itself (to simplify code) assert usd_relationship == og.Controller.usd_relationship(usd_relationship) # Look up the USD relationship by path assert usd_relationship == og.Controller.usd_relationship("/World/MyGraph/MyNode.inputs:a_target") # Look up the USD relationship by name and node assert usd_relationship == og.Controller.usd_relationship(("inputs:a_target", node)) # These can chain, so you can also look up the USD relationship by name and node, where node is further looked up by # relative path and graph assert usd_relationship == og.Controller.usd_relationship(("inputs:a_target", ("MyNode", graph))) # Look up the USD attribute by SdfPath relationship_path = Sdf.Path("/World/MyGraph/MyNode.inputs:a_target") assert usd_relationship == og.Controller.usd_relationship(relationship_path) # Look up the USD attribute through its OmniGraph counterpart assert usd_relationship == og.Controller.usd_relationship(relationship_attribute) # Look up a list of relationship by passing a list of any of the above for new_usd_relationship in og.Controller.usd_relationship( [ usd_relationship, "/World/MyGraph/MyNode.inputs:a_target", ("inputs:a_target", node), ("inputs:a_target", ("MyNode", graph)), relationship_path, relationship_attribute, ] ): assert usd_relationship == new_usd_relationship # end-object-lookup-usd-relationship # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-usd-property # USD properties can be looked up with the same parameters as for looking up an OmniGraph attribute. A property # is useful when it is not known ahead of time whether an og.Attribute is backed by a USD attribute or a USD relationship. # Look up the USD property directly from itself (to simplify code) assert usd_relationship == og.Controller.usd_property(usd_relationship) assert usd_attribute == og.Controller.usd_property(usd_attribute) # Look up the USD property by path assert usd_relationship == og.Controller.usd_property("/World/MyGraph/MyNode.inputs:a_target") assert usd_attribute == og.Controller.usd_property("/World/MyGraph/MyNode.inputs:a_bool") # Look up the USD property by name and node assert usd_relationship == og.Controller.usd_property(("inputs:a_target", node)) assert usd_attribute == og.Controller.usd_property(usd_attribute) # These can chain, so you can also look up the USD property by name and node, where node is further looked up by # relative path and graph assert usd_relationship == og.Controller.usd_property(("inputs:a_target", ("MyNode", graph))) assert usd_attribute == og.Controller.usd_property(("inputs:a_bool", ("MyNode", graph))) # Look up the USD property by SdfPath assert usd_relationship == og.Controller.usd_property(relationship_path) assert usd_attribute == og.Controller.usd_property(attr_path) # Look up the USD property through its OmniGraph counterpart assert usd_relationship == og.Controller.usd_property(relationship_attribute) assert usd_attribute == og.Controller.usd_property(usd_attribute) # Look up a list of properties by passing a list of any of the above for new_usd_property in og.Controller.usd_property( [ usd_relationship, usd_attribute, "/World/MyGraph/MyNode.inputs:a_target", "/World/MyGraph/MyNode.inputs:a_bool", ("inputs:a_target", node), ("inputs:a_bool", node), ("inputs:a_target", ("MyNode", graph)), ("inputs:a_bool", ("MyNode", graph)), relationship_path, attr_path, relationship_attribute, usd_attribute, ] ): assert new_usd_property in (usd_relationship, usd_attribute) # end-object-lookup-usd-property # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-variable # Look up the variable directly from itself (to simplify code) assert variable == og.Controller.variable(variable) # Look up the variable from a tuple with the variable name and the graph to which it belongs assert variable == og.Controller.variable((graph, "MyVariable")) # Look up the variable from a path string pointing directly to it assert variable == og.Controller.variable(variable.source_path) # Look up the variable from an Sdf.Path pointing directly to it variable_path = Sdf.Path(variable.source_path) assert variable == og.Controller.variable(variable_path) # Look up a list of variables by passing a list of any of the above for new_variable in og.Controller.variable( [ variable, (graph, "MyVariable"), variable.source_path, variable_path, ] ): assert variable == new_variable # end-object-lookup-variable # -------------------------------------------------------------------------------------------------------------- # begin-object-lookup-utilities # Look up the path to an attribute given any of the types an attribute lookup recognizes for attribute_spec in [ attribute, "/World/MyGraph/MyNode.inputs:a_bool", ("inputs:a_bool", node), ("inputs:a_bool", ("MyNode", graph)), attr_path, usd_attribute, ]: assert attribute.get_path() == og.Controller.attribute_path(attribute_spec) # Look up the path to a node given any of the types a node lookup recognizes for node_spec in [node, "/World/MyGraph/MyNode", ("MyNode", graph), node_path, node_prim]: assert node.get_prim_path() == og.Controller.node_path(node_spec) # Look up the path to a prim given any of the types a prim lookup recognizes for prim_spec in [node_prim, "/World/MyGraph/MyNode", node_path, node, ("MyNode", graph)]: assert node_prim.GetPrimPath() == og.Controller.prim_path(prim_spec) # Look up the path to a prim given any of the types a graph lookup recognizes graph_path = graph.get_path_to_graph() for graph_spec in [graph, graph_path, Sdf.Path(graph_path)]: assert graph_path == og.Controller.prim_path(graph_spec) # Look up a list of paths to prims given a list of any of the types a prim lookup recognizes for new_path in og.Controller.prim_path( [node_prim, "/World/MyGraph/MyNode", node_path, node, ("MyNode", graph)] ): assert node_prim.GetPrimPath() == new_path # Separate the graph name from the node name in a full path to a node assert (graph, "MyNode") == og.Controller.split_graph_from_node_path("/World/MyGraph/MyNode") # Separate the graph name from the node name in an Sdf.Path to a node assert (graph, "MyNode") == og.Controller.split_graph_from_node_path(node_path) # end-object-lookup-utilities # -------------------------------------------------------------------------------------------------------------- async def test_graph_controller_api(self): """Contrived test that exercises the entire API of the GraphController, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-graph-controller-XX pairs. """ # begin-graph-controller-boilerplate import omni.graph.core as og import omni.kit from pxr import Sdf node_type_name = "omni.graph.test.TestAllDataTypes" node_type = og.Controller.node_type(node_type_name) # end-graph-controller-boilerplate # begin-graph-controller-init # Explanation of the non-default values in the constructor controller = og.GraphController( update_usd=False, # Only update Fabric when paths are added are removed, do not propagate to USD undoable=False, # Do not save information on changes for later undo (most applicable to testing) # If a node specification in og.GraphController.create_node() exists then silently succeed instead of # raising an exception allow_exists_node=True, # If a prim specification in og.GraphController.create_prim() exists then silently succeed instead of # raising an exception allow_exists_prim=True, ) assert controller is not None # The default values are what is assumed when class methods are called. Where they apply to any of the # functions they can also be passed to the class method functions to specify non-default values. # end-graph-controller-init # begin-graph-controller-create_graph # Simple method of creating a graph just passes the desire prim path to it. This creates a graph using all # of the default parameters. graph = og.GraphController.create_graph("/World/MyGraph") assert graph.is_valid() # If you want to customize the type of graph then instead of passing just a path you can pass a dictionary # graph configuration values. See the developer documentation of omni.graph.core.GraphController.create_graph # for details on what each parameter means action_graph = og.GraphController.create_graph( { "graph_path": "/World/MyActionGraph", "node_name": "MyActionGraph", "evaluator_name": "execution", "is_global_graph": True, "backed_by_usd": True, "fc_backing_type": og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, "evaluation_mode": og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC, } ) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-create_graph # begin-graph-controller-create_node # Creates a new node in an existing graph. # The two mandatory parameters are node path and node type. The node path can be any of the types recognized # by the omni.graph.core.ObjectLookup.node_path() method and the node type can be any of the types recognized # by the omni.graph.core.ObjectLookup.node_type() method. node_by_path = og.GraphController.create_node( node_id="/World/MyGraph/MyNode", node_type_id=node_type_name, ) assert node_by_path.is_valid() node_by_name = og.GraphController.create_node( node_id=("MyNodeByName", graph), node_type_id=node_type, ) assert node_by_name.is_valid() node_by_sdf_path = Sdf.Path("/World/MyGraph/MyNodeBySdf") node_by_sdf = og.GraphController.create_node(node_id=node_by_sdf_path, node_type_id=node_by_name) assert node_by_sdf.is_valid() # Also accepts the "update_usd", "undoable", and "allow_exists_node" shared construction parameters # end-graph-controller-create_node # begin-graph-controller-create_prim # Creates a new prim on the USD stage # You can just specify the prim path to get a default prim type with no attributes. The prim_path argument # can accept any value accepted by omni.graph.core.ObjectLookup.prim_path prim_empty = og.GraphController.create_prim(prim_path="/World/MyEmptyPrim") assert prim_empty.IsValid() # You can add a prim type if you want the prim to be a specific type, including schema types prim_cube = og.GraphController.create_prim(prim_path=Sdf.Path("/World/MyCube"), prim_type="Cube") assert prim_cube.IsValid() # You can also populate the prim with some attributes and values using the attribute_values parameter, which # accepts a dictionary of Name:(Type,Value). An attribute named "Name" will be created with type "Type" # (specified in either USD or SDF type format), and initial value "Value" (specified in any format compatible # with the Usd.Attribute.Set() function). The names do not have to conform to the usual OGN standards of # starting with one of the "inputs", "outputs", or "state" namespaces, though they can. The "Type" value is # restricted to the USD-native types, so things like "any", "bundle", and "execution" are not allowed. prim_with_values = og.GraphController.create_prim( prim_path="/World/MyValuedPrim", attribute_values={ "someFloat": ("float", 3.0), "inputs:float3": ("float3", [1.0, 2.0, 3.0]), "someFloat3": ("float[3]", [4.0, 5.0, 6.0]), "someColor": ("color3d", [0.5, 0.6, 0.2]), }, ) assert prim_with_values.IsValid() # Also accepts the "undoable" and "allow_exists_prim" shared construction parameters # end-graph-controller-create_prim # begin-graph-controller-create_variable # To construct a variable the graph must be specified, along with the name and type of variable. # The variable type can only be an omni.graph.core.Type or a string representing one of those types. float_variable = og.GraphController.create_variable(graph_id=graph, name="FloatVar", var_type="float") assert float_variable.valid color3_type = og.Type(og.BaseDataType.FLOAT, 3, role=og.AttributeRole.COLOR) color3_variable = og.GraphController.create_variable(graph_id=graph, name="Color3Var", var_type=color3_type) assert color3_variable.valid # Also accepts the "undoable" shared construction parameter # end-graph-controller-create_variable # begin-graph-controller-delete_node # To delete a node you can pass in a node_id, as accepted by omni.graph.core.ObjectLookup.node, or a node # name and a graph_id as accepted by omni.graph.core.ObjectLookup.graph. og.GraphController.delete_node(node_by_sdf) # The undo flag was the global default so this operation is undoable omni.kit.undo.undo() # HOWEVER, you must get the node reference back as it may have been altered by the undo node_by_sdf = og.Controller.node(node_by_sdf_path) # Try it a different way og.GraphController.delete_node(node_id="MyNodeBySdf", graph_id=graph) # If you do not know if the node exists or not you can choose to ignore that case and silently succeed og.GraphController.delete_node(node_id=node_by_sdf_path, ignore_if_missing=True) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-delete_node # begin-graph-controller-expose_prim # USD prims cannot be directly visible in OmniGraph so instead you must expose them through an import or # export node. See the documentation of the function for details on the different ways you can expose a prim # to OmniGraph. # A prim is exposed as a new OmniGraph node of a given type where the exposure process creates the node and # the necessary links to the underlying prim. The OmniGraph node can then be used as any others might. # The prim_id can accept any type accepted by omni.graph.core.ObjectLookup.prim() and the node_path_id can # accept any type accepted by omni.graph.core.ObjectLookup.node_path() exposed_empty = og.GraphController.expose_prim( exposure_type=og.GraphController.PrimExposureType.AS_BUNDLE, prim_id="/World/MyEmptyPrim", node_path_id="/World/MyActionGraph/MyEmptyNode", ) assert exposed_empty is not None exposed_cube = og.GraphController.expose_prim( exposure_type=og.GraphController.PrimExposureType.AS_ATTRIBUTES, prim_id=prim_cube, node_path_id=("MyCubeNode", action_graph), ) assert exposed_cube is not None # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-expose_prim # begin-graph-controller-connect # Once you have more than one node in a graph you will want to connect them so that the results of one node's # computation can be passed on to another for further computation - the true power of OmniGraph. The connection # sends data from the attribute in "src_spec" and sends it to the attribute in "dst_spec". Both of those # parameters can accept anything accepted by omni.graph.core.ObjectLookup.attribute og.GraphController.connect( src_spec=("outputs:a_bool", ("MyNode", graph)), dst_spec="/World/MyGraph/MyNodeByName/outputs:a_bool", ) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-connect # begin-graph-controller-disconnect # As part of wiring the nodes together you may also want to break connections, either to make a new connection # elsewhere or just to leave the attributes unconnected. The disconnect method is a mirror of the connect # method, taking the same parameters and breaking any existing connection between them. It is any error to try # to disconnect two unconnected attributes. og.GraphController.disconnect( src_spec=("outputs:a_bool", ("MyNode", graph)), dst_spec="/World/MyGraph/MyNodeByName/outputs:a_bool", ) omni.kit.undo.undo() # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-disconnect # begin-graph-controller-disconnect_all # Sometimes you don't know or don't care what an attribute is connected to, you just want to remove all of its # connections, both coming to and going from it. The single attribute_spec parameter tells which attribute is to # be disconnected, accepting any value accepted by omni.graph.ObjectLookup.attribute og.GraphController.disconnect_all(attribute_spec=("outputs:a_bool", ("MyNode", graph))) # As this just disconnects "all" if an attribute is not connected to anything it will silently succeed og.GraphController.disconnect_all(attribute_spec=("outputs:a_bool", ("MyNode", graph))) # Also accepts the "update_usd" and "undoable" shared construction parameters # end-graph-controller-disconnect_all # begin-graph-controller-set_variable_default_value # After creation a graph variable will have zeroes as its default value. You may want to set some other default # so that when the graph is instantiated a second time the defaults are non-zero. The variable_id parameter # accepts anything accepted by omni.graph.core.ObjectLookup.variable() and the value must be a data type # compatible with the type of the (already existing) variable # For example you might have a color variable that you wish to initialize in all subsequent graphs to red og.GraphController.set_variable_default_value(variable_id=(graph, "Color3Var"), value=(1.0, 0.0, 0.0)) # end-graph-controller-set_variable_default_value # begin-graph-controller-get_variable_default_value # If you are using variables to configure your graphs you probably want to know what the default values are, # especially if someone else created them. You can read the default for a given variable, where the variable_id # parameter accepts anything accepted by omni.graph.core.ObjectLookup.variable(). color_default = og.GraphController.get_variable_default_value(variable_id=color3_variable) assert color_default == (1.0, 0.0, 0.0) # end-graph-controller-get_variable_default_value # -------------------------------------------------------------------------------------------------------------- async def test_node_controller_api(self): """Contrived test that exercises the entire API of the NodeController, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-node-controller-XX pairs. """ # begin-node-controller-boilerplate import omni.graph.core as og keys = og.Controller.Keys (_, (node,), _, _) = og.Controller.edit( "/World/MyGraph", { keys.CREATE_NODES: ("MyNode", "omni.graph.test.TestAllDataTypes"), }, ) assert node.is_valid() # end-node-controller-boilerplate # begin-node-controller-init # The NodeController constructor only recognizes one parameter controller = og.NodeController( update_usd=False, # Only update Fabric when attributes are added or removed, do not propagate to USD ) assert controller is not None # end-node-controller-init # begin-node-controller-create_attribute # Creating new, or "dynamic", attributes on a node requires the same information you would find in a .ogn # description of the attribute. The mandatory pieces are "node" on which it is to be created, accepting # anything accepted by omni.graph.core.ObjectLookup.node, the name of the attribute not including the port # namespace (i.e. without the "inputs:", "outputs:", or "state:" prefix, though you can leave it on if you # prefer), the type "attr_type" of the attribute, accepting anything accepted by # omni.graph.core.ObjectLookup.attribute_type. # The default here is to create an input attribute of type float float_attr = og.NodeController.create_attribute(node, "theFloat", "float") assert float_attr.is_valid() # Using the namespace is okay, but redundant double_attr = og.NodeController.create_attribute("/World/MyGraph/MyNode", "inputs:theDouble", "double") assert double_attr.is_valid() # Unless you want a non-default port type, in which case it will be extracted from the name int_attr = og.NodeController.create_attribute(node, "outputs:theInt", og.Type(og.BaseDataType.INT)) assert int_attr.is_valid() # ...or you can just specify the port explicitly and omit the namespace int2_attr = og.NodeController.create_attribute( node, "theInt2", "int2", attr_port=og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) assert int2_attr.is_valid() # The default will set an initial value on your attribute, though it is not remembered in the future float_1_attr = og.NodeController.create_attribute(node, "the1Float", "float", attr_default=1.0) assert float_1_attr.is_valid() # Mismatching between an explicit namespace and a port type will result in a duplicated namespace so be careful error_attr = og.NodeController.create_attribute(node, "outputs:theError", "float") assert error_attr.get_path() == "/World/MyGraph/MyNode.inputs:outputs:theError" assert error_attr.is_valid() # Lastly the special "extended" types of attributes (any or union) can be explicitly specified through # the "attr_extended_type" parameter. When this is anything other than the default then the "attr_type" # parameter will be ignored in favor of the extended type definition, however it must still be a legal type. # This simplest type of extended attribute is "any", whose value can be any legal type. union_attr = og.NodeController.create_attribute( node, "theAny", attr_type="float", attr_extended_type=og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) assert union_attr.is_valid() # Note that with any extended type the "default" is invalid and will be ignored any_other_attr = og.NodeController.create_attribute( node, "theOtherAny", "token", default=5, attr_extended_type=og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) assert any_other_attr.is_valid() # If you want a more restricted set of types you can instead use the extended union type. When specifying # that type it will be a 2-tuple where the second value is a list of types accepted by the union. For example # this attribute will accept either doubles or floats as value types. (See the documentation on extended # attribute types for more information on how types are resolved.) union_attr = og.NodeController.create_attribute( node, "theUnion", "token", attr_extended_type=(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, ["double", "float"]), ) assert union_attr.is_valid() # Also accepts the "undoable" shared construction parameter # end-node-controller-create_attribute # begin-node-controller-remove_attribute # Dynamic attributes are a powerful method of reconfiguring a node at runtime, and as such you will also want # to remove them. The "attribute" parameter accepts anything accepted by # omni.graph.core.ObjectLookup.attribute(). (The "node" parameter, while still functional, is only there for # historical reasons and can be ignored.) og.NodeController.remove_attribute(error_attr) og.NodeController.remove_attribute(("inputs:theUnion", node)) # Also accepts the "undoable" shared construction parameter # end-node-controller-remove_attribute # begin-node-controller-safe_node_name # This is a utility you can use to ensure a node name is safe for use in the USD backing prim. Normally # OmniGraph will take care of this for you but if you wish to dynamically create nodes using USD names you can # use this to confirm that your name is safe for use as a prim. assert og.NodeController.safe_node_name("omni.graph.node.name") == "omni_graph_node_name" # There is also an option to use a shortened name rather than replacing dots with underscores assert og.NodeController.safe_node_name("omni.graph.node.name", abbreviated=True) == "name" # end-node-controller-safe_node_name # -------------------------------------------------------------------------------------------------------------- async def test_data_view_api(self): """Contrived test that exercises the entire API of the DataView, as well as serving as a location for documentation to be extracted, illustrated by running code so that the documentation does not get out of date. The documentation sections are demarcated by {begin/end}-data-view-XX pairs. """ # begin-data-view-boilerplate import omni.graph.core as og keys = og.Controller.Keys (_, (node, any_node,), _, _) = og.Controller.edit( "/World/MyGraph", { keys.CREATE_NODES: [ ("MyNode", "omni.graph.test.TestAllDataTypes"), ("MyAnyNode", "omni.graph.tutorials.ExtendedTypes"), ], keys.SET_VALUES: [ ("MyNode.inputs:a_int", 3), ], }, ) int_attr = og.Controller.attribute("inputs:a_int", node) union_attr = og.Controller.attribute("inputs:floatOrToken", any_node) float_array_attr = og.Controller.attribute("outputs:a_float_array", node) double_array_attr = og.Controller.attribute("outputs:a_double_array", node) # end-data-view-boilerplate # begin-data-view-init # The DataView constructor can take a number of parameters, mostly useful if you intend to make repeated # calls with the same configuration. # The most common parameter is the attribute on which you will operate. The parameter accepts anything # accepted by omni.graph.core.ObjectLookup.attribute() per_attr_view = og.DataView(attribute=int_attr) assert per_attr_view # Subsequent calls to per_attr_view functions will always apply to "int_attr" # You can also force USD and undo configurations, as per other classes like omni.graph.core.NodeController do_now = og.DataView(update_usd=False, undoable=False) assert do_now is not None # To keep memory operations on a single device you can configure the DataView to always use the GPU gpu_view = og.DataView(on_gpu=True, gpu_ptr_kind=og.PtrToPtrKind.CPU) # You can retrieve the GPU pointer kind (i.e. where the memory pointing to GPU arrays lives) assert gpu_view.gpu_ptr_kind == og.PtrToPtrKind.CPU # And if you are working with an instanced graph you can isolate the DataView to a single instance. Also # handy for looping through different instances. instance_view = og.DataView(instance=1) assert instance_view is not None # end-data-view-init # begin-data-view-get # Reading the value of an attribute is the most common operation you'll want to use. assert og.DataView.get(attribute=int_attr) == 3 # If you've already configured the attribute you don't need to specify it, and you can reuse it assert per_attr_view.get() == 3 assert per_attr_view.get() == 3 # As a special case, when you have array attributes that you want to write on you can specify an array size # when you get the reference with the "reserved_element_count" parameter array_to_write = og.DataView.get(attribute=float_array_attr) assert len(array_to_write) == 2 array_to_write = og.DataView.get(attribute=float_array_attr, reserved_element_count=5) assert len(array_to_write) == 5 # Only valid on GPU array attributes is the "return_type" argument. Normally array values are returned in # numpy wrappers, however you can get the data as raw pointers as well if you want to handle processing of # the data yourself or cast it to some other library type. This also illustrates how you can use the # pre-configured constructed GPU view to get specific attribute values on the GPU. raw_array = gpu_view.get(attribute=double_array_attr, return_type=og.WrappedArrayType.RAW) # The return value is omni.graph.core.DataWrapper, which describes its device-specific data and configuration assert raw_array.gpu_ptr_kind == og.PtrToPtrKind.CPU # Also accepts overrides to the global parameters "on_gpu", "gpu_ptr_kind", and "instance" # end-data-view-get # begin-data-view-get_array_size # An array size may be set without actually allocating space for it. In the case of very large arrays this can # be quite useful. The get_array_size function lets you find the number of elements that will be in the array # if you request the data, either on GPU or CPU. assert og.DataView.get_array_size(float_array_attr) == 5 # Also accepts overrides to the global parameter "instance" # end-data-view-get_array_size # begin-data-view-set # The counterpart to getting values is of course setting them. Normally through this interface you will be # setting values on input attributes, or sometimes state attributes, relying on the generated database to # provide the interface for setting output values as part of your node's compute function. # The "attribute" parameter accepts anything accepted by omni.graph.core.ObjectLookup.attribute(), and the # "value" parameter must be a legal value for the attribute type. og.DataView.set(attribute=int_attr, value=5) assert og.DataView.get(int_attr) == 5 # An optional "update_usd" argument does what you'd expect, preventing the update of the USD backing value # for the attribute you just set. await og.Controller.evaluate() og.DataView.set(int_attr, value=10, update_usd=False) usd_attribute = og.ObjectLookup.usd_attribute(int_attr) assert usd_attribute.Get() != 10 # The values being set are flexible as well, with the ability to use a dictionary format so that you can set # the type for any of the extended attributes. og.DataView.set(union_attr, value={"type": "float", "value": 3.5}) assert og.DataView.get(union_attr) == 3.5 # Also accepts overrides to the global parameters "on_gpu", "gpu_ptr_kind", and "instance" # end-data-view-set # begin-data-view-context # Sometimes you are calling unknown code and you want to ensure USD updates are performed the way you want # them. The DataView class provides a method that returns a contextmanager for just such a purpose. with og.DataView.force_usd_update(False): int_view = og.DataView(int_attr) int_view.set(value=20) # The USD value does not update, even though normally the default is to update assert usd_attribute.Get() != 20 with og.DataView.force_usd_update(True): int_view = og.DataView(int_attr) int_view.set(value=30) # The USD value updates assert usd_attribute.Get() == 30 # end-data-view-context
54,518
Python
53.247761
130
0.627884
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_node_type_forwarding.py
"""Tests that exercise node type forwarding using real node types as examples""" import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts # ============================================================================================================== class TestNodeTypeForwarding(ogts.OmniGraphTestCase): async def test_simple_forward(self): """Test that a simple forwarding using a known hardcoded forwarding works properly""" old_type = "omni.graph.nodes.ComposeTuple2" new_type = "omni.graph.nodes.MakeVector2" new_extension = "omni.graph.nodes" interface = ogu.get_node_type_forwarding_interface() self.assertEqual(interface.find_forward(old_type, 1), (new_type, 1, new_extension)) keys = og.Controller.Keys (_, (node,), _, _) = og.Controller.edit("/TestGraph", {keys.CREATE_NODES: ("ForwardedNode", old_type)}) self.assertEqual(node.get_node_type().get_node_type(), new_type) # -------------------------------------------------------------------------------------------------------------- async def test_runtime_forward(self): """Test that a forwarding that is added at runtime works properly""" old_type = "omni.graph.nodes.MakeVector2" new_type = "omni.graph.nodes.MakeVector3" new_extension = "omni.graph.nodes" interface = ogu.get_node_type_forwarding_interface() interface.define_forward(old_type, 1, new_type, 1, new_extension) self.assertEqual(interface.find_forward(old_type, 1), (new_type, 1, new_extension)) keys = og.Controller.Keys (graph, (node,), _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: ("ForwardedNode", old_type), }, ) # Make sure the node type was properly forwarded self.assertEqual(node.get_node_type().get_node_type(), new_type) # Remove the forwarding and check that the same creation type now yields the original unforwarded node type interface.remove_forward(old_type, 1) (_, (new_node,), _, _) = og.Controller.edit( graph, { keys.CREATE_NODES: ("RegularNode", old_type), }, ) self.assertEqual(new_node.get_node_type().get_node_type(), old_type)
2,380
Python
43.092592
116
0.569748
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_simple.py
"""Basic tests of the compute graph""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands class TestOmniGraphSimple(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" # ---------------------------------------------------------------------- async def test_undo_dangling_connections(self): # If a dangling connection (see previous test) is created by an undoable # command, the connection should be restored if the command is undone. (_, (src_node, dest_node), _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("src", "omni.graph.tutorials.SimpleData"), ("dest", "omni.graph.tutorials.SimpleData"), ], og.Controller.Keys.CONNECT: [("src.outputs:a_float", "dest.inputs:a_float")], }, ) src_attr = src_node.get_attribute("outputs:a_float") dest_attr = dest_node.get_attribute("inputs:a_float") # Check that the connection is there, on both sides. self.assertEqual(len(src_attr.get_downstream_connections()), 1, "Check initial connection, src side.") self.assertEqual(len(dest_attr.get_upstream_connections()), 1, "Check initial connection, dest side.") # Delete the src prim and confirm that the connection is gone. omni.kit.commands.execute("DeletePrims", paths=[src_node.get_prim_path()]) self.assertEqual(len(dest_attr.get_upstream_connections()), 0, "Check no connection after deletion.") # Undo the deletion. omni.kit.undo.undo() # Wait a couple of ticks for OG to restore everything. for _ in range(2): await omni.kit.app.get_app().next_update_async() # Check that the connection has been restored. src_attr = og.Controller.attribute("/World/PushGraph/src.outputs:a_float") conns = src_attr.get_downstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo, src side.") self.assertEqual(conns[0], dest_attr, "Check connection is correct after undo, src side.") conns = dest_attr.get_upstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo, dest side.") self.assertEqual(conns[0], src_attr, "Check connection is correct after undo, dest side.") # Redo the deletion. omni.kit.undo.redo() self.assertEqual(len(dest_attr.get_upstream_connections()), 0, "Check no connection after redo.") # Undo the redo. omni.kit.undo.undo() # Wait a couple of ticks for OG to restore everything. for _ in range(2): await omni.kit.app.get_app().next_update_async() # Check that the connection has been restored. src_attr = og.Controller.attribute("/World/PushGraph/src.outputs:a_float") conns = src_attr.get_downstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo of redo, src side.") self.assertEqual(conns[0], dest_attr, "Check connection is correct after undo of redo, src side.") conns = dest_attr.get_upstream_connections() self.assertEqual(len(conns), 1, "Check connection exists after undo of redo, dest side.") self.assertEqual(conns[0], src_attr, "Check connection is correct after undo of redo, src side.") # ---------------------------------------------------------------------- async def test_disconnect(self): """ Check that after a disconnection, we find the default value at input runtime location, and that the output still has a correct value """ (_, _, _, _) = og.Controller.edit( "/World/PushGraph", { og.Controller.Keys.CREATE_NODES: [ ("src", "omni.graph.tutorials.SimpleData"), ("dest", "omni.graph.tutorials.SimpleData"), ], og.Controller.Keys.CONNECT: [("src.outputs:a_float", "dest.inputs:a_float")], }, ) dst_attr = og.Controller.attribute("/World/PushGraph/dest.inputs:a_float") src_attr = og.Controller.attribute("/World/PushGraph/src.outputs:a_float") await og.Controller.evaluate() # since both attribute are connected, they now have the same value: the compute result self.assertEqual(dst_attr.get(), 1) self.assertEqual(src_attr.get(), 1) # do the disconnect src_attr.disconnect(dst_attr, True) # we get back the default on the input, the output still has the compute result self.assertEqual(dst_attr.get(), 0) self.assertEqual(src_attr.get(), 1) # ---------------------------------------------------------------------- async def test_unknown_type(self): """ Basic idea of test: Load up an existing file that has an unknown type, and make sure that we are not creating a node for it. """ (result, error) = await ogts.load_test_file("TestNodeWithUnknownType.usda", use_caller_subdirectory=True) self.assertTrue(result, error) await omni.kit.app.get_app().next_update_async() graph = og.Controller.graph("/World/Graph") unknown_node = graph.get_node("/World/Graph/SomeUnknownNode") self.assertFalse(unknown_node.is_valid()) # ---------------------------------------------------------------------- async def test_file_format_upgrade(self): """ Basic idea of test: Register a file format upgrade callback. Load up file with bad node type name, and fix it as part of the file format upgrade. """ def my_test_pre_load_file_format_upgrade_callback(_old_format_version, _new_format_version, _graph): usd_context = omni.usd.get_context() stage = usd_context.get_stage() subtract_double_node_prim = stage.GetPrimAtPath("/World/innerPushGraph/test_node_subtract_double_c_") self.assertTrue(subtract_double_node_prim.IsValid()) node_type_attr = subtract_double_node_prim.GetAttribute("node:type") node_type_attr.Set("omni.graph.test.SubtractDoubleC") handle = og.register_pre_load_file_format_upgrade_callback(my_test_pre_load_file_format_upgrade_callback) try: (result, error) = await ogts.load_test_file("TestBadNodeTypeName.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph = og.get_graph_by_path("/World/innerPushGraph") # make sure the box and the attribute we expect are there. node = graph.get_node("/World/innerPushGraph/test_node_subtract_double_c_") self.assertTrue(node.is_valid()) self.assertEqual(node.get_node_type().get_node_type(), "omni.graph.test.SubtractDoubleC") finally: og.deregister_pre_load_file_format_upgrade_callback(handle) # ---------------------------------------------------------------------- async def test_controller_on_initialize(self): # Basic idea of test: here we have a test node that uses the og.Controller at initialize # Time. There was a bug that made this not possible. We test for a clean open here without # errors. See https://nvidia.slack.com/archives/CN05UCXT5/p1614278655049700 for details (result, error) = await ogts.load_test_file("TestInitWithController.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # ---------------------------------------------------------------------- async def test_is_compatible(self): """ Test Attribute.is_compatible() for extended and simple types. `is_compatible` is verified for a representitive sample of connection combinations, bad_connections are connections that should be rejected, ok_connections are connections that should be approved. Note that this test is meant to take into account (and test!) the auto-conversion mechanism """ controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("TupleA", "omni.tutorials.TupleData"), ("ArrayA", "omni.graph.tutorials.ArrayData"), ("TupleArrayA", "omni.graph.tutorials.TupleArrays"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ("TupleB", "omni.tutorials.TupleData"), ("ArrayB", "omni.graph.tutorials.ArrayData"), ("TupleArrayB", "omni.graph.tutorials.TupleArrays"), ("ExtendedA", "omni.graph.tutorials.ExtendedTypes"), ("ExtendedB", "omni.graph.tutorials.ExtendedTypes"), ] }, ) await controller.evaluate(graph) # Helper for doing verification on a list of connection specs between 2 nodes def verify_connections(connections, should_work): for src, dest in connections: src_node, src_attr = src.split(".", 1) dest_node, dest_attr = dest.split(".", 1) src_attrib = controller.node(src_node, graph).get_attribute(src_attr) dest_attrib = controller.node(dest_node, graph).get_attribute(dest_attr) if should_work: self.assertTrue( src_attrib.is_compatible(dest_attrib), f"{src_node}.{src_attr} is compatible with {dest_node}.{dest_attr}", ) else: self.assertFalse( src_attrib.is_compatible(dest_attrib), f"{src_node}.{src_attr} is not compatible with {dest_node}.{dest_attr}", ) # Test simple connections ok_connections = [ ("SimpleA.outputs:a_int", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_int"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_float"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_double"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:unsigned:a_uint", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_int"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_int64"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_float"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_double"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:unsigned:a_uint"), ("SimpleA.outputs:unsigned:a_uint64", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_half", "SimpleB.inputs:a_half"), ] bad_connections = [ ("SimpleA.outputs:a_bool", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_bool", "SimpleB.inputs:a_int"), ("SimpleA.outputs:a_float", "SimpleB.inputs:unsigned:a_uint"), ("SimpleA.outputs:a_int", "SimpleB.inputs:unsigned:a_uint64"), ("SimpleA.outputs:a_half", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_double", "SimpleB.inputs:a_half"), # FIXME: What about input -> output? # ('SimpleB.inputs:a_float', 'SimpleA.outputs:a_float') ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test tuple connections ok_connections = [ ("TupleA.outputs:a_float2", "TupleB.inputs:a_double2"), ("TupleA.outputs:a_int2", "TupleB.inputs:a_int2"), ("TupleA.outputs:a_float2", "TupleB.inputs:a_float2"), ("TupleA.outputs:a_double3", "TupleB.inputs:a_double3"), ("TupleA.outputs:a_float3", "TupleB.inputs:a_float3"), ] bad_connections = [ ("TupleA.outputs:a_double2", "TupleB.inputs:a_double3"), ("TupleA.outputs:a_half2", "TupleB.inputs:a_float2"), ("TupleA.outputs:a_half2", "SimpleB.inputs:a_half"), ("TupleA.outputs:a_double3", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_double", "TupleB.inputs:a_double3"), ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test array connections ok_connections = [ ("ArrayA.outputs:result", "ArrayB.inputs:original"), ("ArrayA.outputs:negativeValues", "ArrayB.inputs:gates"), ] bad_connections = [ ("ArrayA.outputs:result", "ArrayB.inputs:gates"), ("ArrayA.outputs:result", "TupleB.inputs:a_float3"), ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test tuple-array connections ok_connections = [("TupleArrayA.inputs:a", "TupleArrayB.inputs:b")] bad_connections = [ ("TupleArrayA.inputs:a", "ArrayB.inputs:original"), ("TupleArrayA.outputs:result", "TupleArrayB.inputs:a"), ] verify_connections(ok_connections, True) verify_connections(bad_connections, False) # Test 'any' and enum connections ok_connections = [ ("ExtendedA.outputs:doubledResult", "ExtendedB.inputs:tuple"), ("ExtendedA.outputs:flexible", "ExtendedB.inputs:floatOrToken"), ("ExtendedA.outputs:tuple", "TupleB.inputs:a_double3"), ("ExtendedA.outputs:flexible", "ExtendedB.inputs:flexible"), ] verify_connections(ok_connections, True) # incompatible enum connections bad_connections = [ ("ExtendedA.outputs:flexible", "SimpleB.inputs:a_double"), ("SimpleB.outputs:a_double", "ExtendedA.inputs:flexible"), ] verify_connections(bad_connections, False) # Wire up ExtendedA in order to resolve doubledResult to be token, and verify the check fails # also resolve outputs:tuple to be int[2], and verify the check fails controller.edit( "/TestGraph", { keys.CONNECT: [ ("SimpleA.outputs:a_token", "ExtendedA.inputs:floatOrToken"), ("TupleA.outputs:a_int2", "ExtendedA.inputs:tuple"), # FIXME: Do I need to connect the output in order to resolve the type? ("ExtendedA.outputs:doubledResult", "SimpleB.inputs:a_token"), ] }, ) ok_connections = [("TupleA.outputs:a_float2", "ExtendedA.inputs:tuple")] verify_connections(ok_connections, True) bad_connections = [ ("ExtendedA.outputs:doubledResult", "SimpleB.inputs:a_float"), ("ExtendedA.inputs:floatOrToken", "SimpleB.inputs:a_float"), ("SimpleB.inputs:a_float", "ExtendedA.inputs:floatOrToken"), ] verify_connections(bad_connections, False) # ---------------------------------------------------------------------- async def test_simple_converted_connections(self): """ Test conversions between simple types. `simple_converted_connections` tests a representitive sample of connection combinations of different types, and makes sure the expected values are actually retrieved """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ], "connect": [ ("SimpleA.outputs:a_double", "SimpleB.inputs:a_float"), ("SimpleA.outputs:a_int", "SimpleB.inputs:a_bool"), ("SimpleA.outputs:a_int64", "SimpleB.inputs:a_double"), ("SimpleA.outputs:a_float", "SimpleB.inputs:a_int"), ], "set_values": [ ("SimpleA.inputs:a_double", 10.5), ("SimpleA.inputs:a_int", 11), ("SimpleA.inputs:a_int64", 12), ("SimpleA.inputs:a_float", 13.5), ], }, ) await controller.evaluate() simple_b_node = nodes[1] # A.input.a_double (10.5) -> A.output.a_double (11.5) -> B.input.a_float(11.5) -> B.output.a_float(12.5) self.assertEqual(simple_b_node.get_attribute("outputs:a_float").get(), 12.5) # A.input.a_int64 (12) -> A.output.a_int64 (13) -> B.input.a_double(13.0) -> B.output.a_double(14.0) self.assertEqual(simple_b_node.get_attribute("outputs:a_double").get(), 14.0) # A.input.a_float (13.5) -> A.output.a_float (14.5) -> B.input.a_int(14) -> B.output.a_int(15) self.assertEqual(simple_b_node.get_attribute("outputs:a_int").get(), 15) # A.input.a_int (11) -> A.output.a_int (12) -> B.input.a_bool(True) -> B.output.a_bool(False) self.assertFalse(simple_b_node.get_attribute("outputs:a_bool").get()) # ---------------------------------------------------------------------- async def test_tuple_converted_connections(self): """ Test conversions between tuple types. `tuple_converted_connections` tests a representitive sample of connection combinations of different types, and makes sure the expected values are actually retrieved """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [("TupleA", "omni.tutorials.TupleData"), ("TupleB", "omni.tutorials.TupleData")], "connect": [ ("TupleA.outputs:a_double2", "TupleB.inputs:a_float2"), ("TupleA.outputs:a_int2", "TupleB.inputs:a_double2"), ("TupleA.outputs:a_float2", "TupleB.inputs:a_int2"), ("TupleA.outputs:a_float3", "TupleB.inputs:a_double3"), ("TupleA.outputs:a_double3", "TupleB.inputs:a_float3"), ], "set_values": [ ("TupleA.inputs:a_double2", (10.5, 11.5)), ("TupleA.inputs:a_int2", (13, 14)), ("TupleA.inputs:a_float2", (15.5, 16.5)), ("TupleA.inputs:a_float3", (17.5, 18.5, 19.5)), ("TupleA.inputs:a_double3", (20.5, 21.5, 22.5)), ], }, ) await controller.evaluate() tuple_b_node = nodes[1] # A.input.a_double2 (10.5,11.5) -> A.output.a_double2 (11.5,12.5) # -> B.input.a_float2(11.5, 12.5) -> B.output.a_float2(12.5,13.5) self.assertTrue((tuple_b_node.get_attribute("outputs:a_float2").get() == (12.5, 13.5)).all()) # A.input.a_int2 (13,14) -> A.output.a_int2 (14,15) # -> B.input.a_double2(14.0, 15.0) -> B.output.a_double2(15.0, 16.0) self.assertTrue((tuple_b_node.get_attribute("outputs:a_double2").get() == (15.0, 16.0)).all()) # A.input.a_float2 (15.5, 16.5) -> A.output.a_float2 (16.5, 17.5) # -> B.input.a_int2(16, 17) -> B.output.a_int2(17, 18) self.assertTrue((tuple_b_node.get_attribute("outputs:a_int2").get() == (17, 18)).all()) # A.input.a_float3 (17.5, 18.5, 19.5) -> A.output.a_float3 (18.5, 19.5, 20.5) # -> B.input.a_double3(18.5, 19.5, 20.5) -> B.output.a_double3(19.5, 20.5, 21.5) self.assertTrue((tuple_b_node.get_attribute("outputs:a_double3").get() == (19.5, 20.5, 21.5)).all()) # A.input.a_double3 (20.5,21.5,22.5) -> A.output.a_double3 (21.5,22.5, 23.5) # -> B.input.a_float3(21.5,22.5, 23.5) -> B.output.a_float3(22.5, 23.5, 24.5) self.assertTrue((tuple_b_node.get_attribute("outputs:a_float3").get() == (22.5, 23.5, 24.5)).all()) # ---------------------------------------------------------------------- async def test_converted_runtime_connections(self): """ Test conversions of runtime attributes ie. when the actual type of the attribute is not listed in the list of accepted input types, but a conversion exits """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("Simple", "omni.graph.tutorials.SimpleData"), ("Extended", "omni.graph.tutorials.ExtendedTypes"), ], "connect": [("Simple.outputs:a_double", "Extended.inputs:floatOrToken")], "set_values": [ ("Simple.inputs:a_double", 1.5), ("Simple.inputs:a_int", 2), ("Simple.inputs:a_float", 3.5), ], }, ) await controller.evaluate() ext_node = nodes[1] # Simple.in.a_double (1.5) -> Simple.out.a_double (2.5) -> Extended.floatOrToken (2.5) -> Extended.doubled (5.0) val = ext_node.get_attribute("outputs:doubledResult").get() self.assertTrue(val == 5.0) # ---------------------------------------------------------------------- async def test_converted_prefered_runtime_connections(self): """ Test that the proper conversion of runtime attribute is chosen when several are available """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("Simple", "omni.graph.tutorials.SimpleData"), ("A", "omni.graph.nodes.ATan2"), ("A2", "omni.graph.nodes.ATan2"), ], "connect": [("Simple.outputs:a_int", "A.inputs:a"), ("Simple.outputs:a_int64", "A2.inputs:a")], }, ) t = nodes[1].get_attribute("inputs:a").get_resolved_type().base_type self.assertTrue(t == og.BaseDataType.FLOAT) t = nodes[2].get_attribute("inputs:a").get_resolved_type().base_type self.assertTrue(t == og.BaseDataType.DOUBLE) # ---------------------------------------------------------------------- async def test_converted_coupled_attributes(self): """ Tests that the conversion for coupled attribute type resolution works """ controller = og.Controller() (_, nodes, _, _) = controller.edit( "/Root", { "create_nodes": [ ("Mul", "omni.graph.nodes.Multiply"), ("Double", "omni.graph.nodes.ConstantDouble"), ("Float", "omni.graph.nodes.ConstantFloat"), ], "connect": [("Double.inputs:value", "Mul.inputs:a"), ("Float.inputs:value", "Mul.inputs:b")], "set_values": [("Double.inputs:value", 5.0), ("Float.inputs:value", 10.0)], }, ) await controller.evaluate() out = nodes[0].get_attribute("outputs:product") # the first pin is used to determine the output type base_type = out.get_resolved_type().base_type self.assertTrue(base_type == og.BaseDataType.DOUBLE) # check that the node executed correctly val = out.get() self.assertTrue(val == 50)
25,107
Python
47.007648
120
0.558529
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_compound_subgraphs.py
# noqa PLC0302 from typing import List import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.usd from pxr import Sdf COMPOUND_SUBGRAPH_NODE_TYPE = "omni.graph.nodes.CompoundSubgraph" DEFAULT_SUBGRAPH_NAME = "Subgraph" # ----------------------------------------------------------------------------- class TestCompoundSubgraphs(ogts.OmniGraphTestCase): """Tests functionality using subgraph-style compound nodes""" _test_graph_path = "/World/TestGraph" # ------------------------------------------------------------------------- async def setUp(self): await super().setUp() omni.kit.commands.set_logging_enabled(False) # ------------------------------------------------------------------------- async def tearDown(self): omni.timeline.get_timeline_interface().stop() await super().tearDown() omni.kit.commands.set_logging_enabled(True) # ------------------------------------------------------------------------- def _get_input_attributes(self, node: og.Node) -> List[og.Attribute]: return [ attr for attr in node.get_attributes() if attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ] # ------------------------------------------------------------------------- def _get_output_attributes(self, node: og.Node) -> List[og.Attribute]: return [ attr for attr in node.get_attributes() if attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ] # ------------------------------------------------------------------------- async def test_compound_subgraph_placeholder_node(self): """Validation For the placeholder node used for compound subgraph nodes""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, (node,), _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: ("PlaceHolder", COMPOUND_SUBGRAPH_NODE_TYPE)} ) self.assertTrue(node.is_valid()) self.assertTrue(node.is_compound_node()) def is_input_or_output(attr): return attr.get_port_type() in [ og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ] self.assertEqual(0, len(list(filter(is_input_or_output, node.get_attributes())))) stage = omni.usd.get_context().get_stage() self.assertTrue(stage.GetPrimAtPath(f"{node.get_prim_path()}/{DEFAULT_SUBGRAPH_NAME}").IsValid()) # ------------------------------------------------------------------------ async def test_create_compound_subgraph_command(self): """Validates the create compound subgraph command, including undo and redo""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, _, _, _) = controller.edit(self._test_graph_path, {keys.CREATE_NODES: ("Add", "omni.graph.nodes.Add")}) # create a compound subgraph with the default name stage = omni.usd.get_context().get_stage() # validate the node is created ogu.cmds.CreateCompoundSubgraph(graph=graph, node_name="Node1", subgraph_name=DEFAULT_SUBGRAPH_NAME) node = graph.get_node(f"{self._test_graph_path}/Node1") subgraph_path = f"{node.get_prim_path()}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(node.is_valid()) self.assertTrue(stage.GetPrimAtPath(subgraph_path).IsValid()) omni.kit.undo.undo() node = graph.get_node(f"{self._test_graph_path}/Node1") self.assertFalse(node.is_valid()) self.assertFalse(stage.GetPrimAtPath(subgraph_path).IsValid()) omni.kit.undo.redo() node = graph.get_node(f"{self._test_graph_path}/Node1") self.assertTrue(node.is_valid()) self.assertTrue(stage.GetPrimAtPath(subgraph_path).IsValid()) # validate with a different subgraph name subgraph2_name = f"{DEFAULT_SUBGRAPH_NAME}_02" ogu.cmds.CreateCompoundSubgraph(graph=graph, node_name="Node2", subgraph_name=subgraph2_name) node = graph.get_node(f"{self._test_graph_path}/Node2") subgraph_path = f"{node.get_prim_path()}/{subgraph2_name}" self.assertTrue(node.is_valid()) self.assertTrue(stage.GetPrimAtPath(subgraph_path).IsValid()) # ------------------------------------------------------------------------ async def test_compound_subgraph_loaded_from_file(self): """Validates that a compound node with a subgraph can be loaded and evaluated""" (result, error) = await ogts.load_test_file("TestCompoundSubgraph.usda", use_caller_subdirectory=True) self.assertTrue(result, f"{error}") # The file contains an outer graph of # [const_double] -> [compound] -> [to_string] # Followed by an inner compound containing an add node graph = og.get_graph_by_path("/World/PushGraph") self.assertTrue(graph.is_valid()) self.assertEquals(1, len(graph.get_subgraphs())) compound_node = graph.get_node("/World/PushGraph/compound") self.assertTrue(compound_node.is_valid()) self.assertTrue(compound_node.is_compound_node()) self.assertTrue(compound_node.get_node_type().is_valid()) result_node = graph.get_node("/World/PushGraph/to_string") self.assertTrue(result_node.is_valid()) output_attr = result_node.get_attribute("outputs:converted") self.assertTrue(output_attr.is_valid()) await og.Controller.evaluate(graph) self.assertEqual("20", og.Controller.get(output_attr)) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph(self): """Tests for replacing a portion of a graph with a subgraph""" compound_node_name = "Compound" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_, _, _, add, mul, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("ConstDouble1", "omni.graph.nodes.ConstantDouble"), ("ConstDouble2", "omni.graph.nodes.ConstantDouble"), ("ConstDouble3", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("Mul", "omni.graph.nodes.Multiply"), ("ToDouble", "omni.graph.nodes.ToDouble"), ], keys.CONNECT: [ ("ConstDouble1.inputs:value", "Add.inputs:a"), ("ConstDouble2.inputs:value", "Add.inputs:b"), ("ConstDouble3.inputs:value", "Mul.inputs:b"), ("Add.outputs:sum", "Mul.inputs:a"), ("Mul.outputs:product", "ToDouble.inputs:value"), ], keys.SET_VALUES: [ ("ConstDouble1.inputs:value", 1.0), ("ConstDouble2.inputs:value", 2.0), ("ConstDouble3.inputs:value", 3.0), ], }, ) # evaluate the graph with a given constant value. async def validate_graph(c1_val): # update the constant and verify the graph is still functioning c1_attr = og.Controller.attribute(f"{self._test_graph_path}/ConstDouble1.inputs:value") og.Controller.set(c1_attr, c1_val, undoable=False) await og.Controller.evaluate(graph) res_attr = og.Controller.attribute(f"{self._test_graph_path}/ToDouble.outputs:converted") self.assertEqual((c1_val + 2.0) * 3.0, og.Controller.get(res_attr)) await validate_graph(1.0) # the command will invalidate any og references to the graph ogu.cmds.ReplaceWithCompoundSubgraph( nodes=[add.get_prim_path(), mul.get_prim_path()], compound_name=compound_node_name ) # validate the replacement generated the objects we are expecting graph = og.Controller.graph(self._test_graph_path) sub_graph_path = f"{self._test_graph_path}/{compound_node_name}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(graph.is_valid()) self.assertTrue(og.Controller.graph(sub_graph_path).is_valid()) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Add")) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Mul")) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Add").is_valid()) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Mul").is_valid()) # update the constant and verify the graph is still functioning await validate_graph(2.0) # apply an undo omni.kit.undo.undo() graph = og.Controller.graph(self._test_graph_path) sub_graph_path = f"{self._test_graph_path}/{compound_node_name}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(graph.is_valid()) self.assertIsNone(og.get_graph_by_path(sub_graph_path)) self.assertTrue(og.Controller.node(f"{self._test_graph_path}/Add").is_valid()) self.assertTrue(og.Controller.node(f"{self._test_graph_path}/Mul").is_valid()) self.assertIsNone(og.get_node_by_path(f"{sub_graph_path}/Add")) self.assertIsNone(og.get_node_by_path(f"{sub_graph_path}/Mul")) # update the constant and verify the graph is still functioning await validate_graph(3.0) # and a redo omni.kit.undo.redo() graph = og.Controller.graph(self._test_graph_path) sub_graph_path = f"{self._test_graph_path}/{compound_node_name}/{DEFAULT_SUBGRAPH_NAME}" self.assertTrue(graph.is_valid()) self.assertTrue(og.Controller.graph(sub_graph_path).is_valid()) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Add")) self.assertIsNone(og.get_node_by_path(f"{self._test_graph_path}/Mul")) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Add").is_valid()) self.assertTrue(og.Controller.node(f"{sub_graph_path}/Mul").is_valid()) # update the constant and verify the graph is still functioning await validate_graph(4.0) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_input_resolved_types(self): """ Tests which inputs are exposed in a generated compound graph When all the types are resolved """ def _create_compound_graph(evaluator_name): controller = og.Controller(update_usd=True) keys = controller.Keys graph_path = f"{self._test_graph_path}_{evaluator_name}" # simple graph # [ConstDouble]->[AllTypes]->[AllTypes (via execution)] controller.edit({"graph_path": graph_path, "evaluator_name": evaluator_name}) (_, (all1, all2, _), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("AllTypes1", "omni.graph.test.TestAllDataTypes"), ("AllTypes2", "omni.graph.test.TestAllDataTypes"), ("ConstDouble", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("AllTypes1.outputs:a_execution", "AllTypes2.inputs:a_execution"), ("ConstDouble.inputs:value", "AllTypes1.inputs:a_double"), ], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[all1.get_prim_path(), all2.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) return self._get_input_attributes(node) # for push, expect 1 exposed input, the constant double input_ports = _create_compound_graph("push") self.assertEquals(1, len(input_ports)) self.assertEquals(og.Type(og.BaseDataType.DOUBLE), input_ports[0].get_resolved_type()) # for action graph, the execution port should also be exposed input_ports = _create_compound_graph("execution") input_types = [input_port.get_resolved_type() for input_port in input_ports] self.assertEquals(2, len(input_ports)) self.assertIn(og.Type(og.BaseDataType.DOUBLE), input_types) self.assertIn(og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION), input_types) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_input_unresolved_types(self): """ Tests the replace with compound subgraph exposes any unresolved types """ # Partially connected graph of add nodes # [Add1]->[Add2]->[Add3] # Add1 a,b are left unresolved # Add2 a is connected, b is resolved # Add3 a is connected, b is unresolved controller = og.Controller(update_usd=True) keys = controller.Keys (_, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add"), ("Add3", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Add1.outputs:sum", "Add2.inputs:a"), ("Add2.outputs:sum", "Add3.inputs:a"), ], }, ) # manually resolve nodes[1].get_attribute("inputs:b").set_resolved_type(og.Type(og.BaseDataType.DOUBLE)) # create the subgraph (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[node.get_prim_path() for node in nodes]) self.assertTrue(success) self.assertTrue(node.is_valid()) inputs = self._get_input_attributes(node) outputs = self._get_output_attributes(node) self.assertEqual(3, len(inputs)) self.assertEqual(1, len(outputs)) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_output_types(self): """ Validates the behaviour of outputs when a compound replacement is made. If a node is a terminal node, it's outputs will be exposed """ # create a graph with two nodes that contain a near complete subset of all types def _create_compound_graph(evaluator_name): controller = og.Controller(update_usd=True) keys = controller.Keys graph_path = f"{self._test_graph_path}_{evaluator_name}" # simple graph # [AllTypes]->[AllTypes] with one connection in between controller.edit({"graph_path": graph_path, "evaluator_name": evaluator_name}) (_, (all1, all2), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("AllTypes1", "omni.graph.test.TestAllDataTypes"), ("AllTypes2", "omni.graph.test.TestAllDataTypes"), ], keys.CONNECT: [("AllTypes1.outputs:a_double", "AllTypes2.inputs:a_double")], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[all1.get_prim_path(), all2.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) output_types = [attr.get_resolved_type() for attr in self._get_output_attributes(node)] return output_types # in the case of a push graph, it will generate an output for each type, except execution output_types = _create_compound_graph("push") push_count = len(output_types) self.assertEqual(0, output_types.count(og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.DOUBLE))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.INT))) # in the case of a push graph, it will generate an output for each type, except execution output_types = _create_compound_graph("execution") exec_count = len(output_types) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.DOUBLE))) self.assertEqual(1, output_types.count(og.Type(og.BaseDataType.INT))) self.assertGreater(exec_count, push_count) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_fan_in_out(self): """Validates replace with compound subgraph works with fan in/out""" controller = og.Controller(update_usd=True) keys = controller.Keys # Graph with Fan-In and Fan-Out # [OnImpulseEvent]-> |Sequence| -> [Sequence] # [OnImpulseEvent]-> | | -> [Sequence] controller.edit({"graph_path": self._test_graph_path, "evaluator_name": "execution"}) (_, (_, _, convert, _, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Input1", "omni.graph.action.OnImpulseEvent"), ("Input2", "omni.graph.action.OnImpulseEvent"), ("Convert", "omni.graph.action.Sequence"), ("Output1", "omni.graph.action.Sequence"), ("Output2", "omni.graph.action.Sequence"), ], keys.CONNECT: [ ("Input1.outputs:execOut", "Convert.inputs:execIn"), ("Input2.outputs:execOut", "Convert.inputs:execIn"), ("Convert.outputs:a", "Output1.inputs:execIn"), ("Convert.outputs:a", "Output2.inputs:execIn"), ], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[convert.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) inputs = self._get_input_attributes(node) outputs = self._get_output_attributes(node) self.assertEquals(1, len(inputs)) self.assertEquals(1, len(outputs)) self.assertEquals(2, inputs[0].get_upstream_connection_count()) self.assertEquals(2, outputs[0].get_downstream_connection_count()) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_with_constant_nodes(self): """ Validates replace with compound subgraph works with constant nodes, that use output only inputs """ controller = og.Controller(update_usd=True) keys = controller.Keys # Create a graph with a connected constant and an unconnected constant # Converting the constants to a subgraph should create outputs for both # but keep the connection in tact (_, (c1, c2, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Const1", "omni.graph.nodes.ConstantDouble"), ("Const2", "omni.graph.nodes.ConstantInt"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Const1.inputs:value", "Add.inputs:a"), ], }, ) (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[c1.get_prim_path(), c2.get_prim_path()]) self.assertTrue(success) self.assertTrue(node.is_valid()) outputs = self._get_output_attributes(node) self.assertEquals(2, len(outputs)) self.assertEquals(1, outputs[0].get_downstream_connection_count()) self.assertEquals(0, outputs[1].get_downstream_connection_count()) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_catches_common_errors(self): """ Validates ReplaceWithCompoundSubgraph handles typical error conditions """ controller = og.Controller(update_usd=True) keys = controller.Keys (graph1, (add1,), _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add")]} ) (_, (add2,), _, _) = controller.edit( f"{self._test_graph_path}_2", {keys.CREATE_NODES: [("Add2", "omni.graph.nodes.Add")]} ) with ogts.ExpectedError(): # no nodes means no compound is returned (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[]) self.assertFalse(success) self.assertIsNone(node) # not all nodes from the same graph with ogts.ExpectedError(): (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[add1.get_prim_path(), add2.get_prim_path()]) self.assertFalse(success) self.assertIsNone(node) # invalid nodes with ogts.ExpectedError(): (success, node) = ogu.cmds.ReplaceWithCompoundSubgraph( nodes=[add1.get_prim_path(), graph1.get_path_to_graph()] ) self.assertFalse(success) self.assertIsNone(node) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_with_relationship_inputs(self): """Validates ReplacewithCompoundSubgraph handles relationship inputs (bundles and targets)""" controller = og.Controller(update_usd=True) keys = controller.Keys # Graph with various types relationship inputs # [BundleConstructor] -> [BundleInspector] # [BundleInspector (with target set)] # [BundleInspector (with target unset)] # [GetGraphTargetPrim] -> [GetPrimPaths] # [GetPrimPaths (with target set)] # [GetPrimPaths (with target unset)] (_graph, _, _, _) = controller.edit( self._test_graph_path, { # create nodes that have bundle inputs and target inputs keys.CREATE_NODES: [ ("BundleCreator", "omni.graph.nodes.BundleConstructor"), ("ConnectedInspector", "omni.graph.nodes.BundleInspector"), ("SetInspector", "omni.graph.nodes.BundleInspector"), ("UnsetInspector", "omni.graph.nodes.BundleInspector"), ("GraphTargetPrim", "omni.graph.nodes.GetGraphTargetPrim"), ("ConnectedTarget", "omni.graph.nodes.GetPrimPaths"), ("SetTarget", "omni.graph.nodes.GetPrimPaths"), ("UnsetTarget", "omni.graph.nodes.GetPrimPaths"), ], keys.CONNECT: [ ("BundleCreator.outputs_bundle", "ConnectedInspector.inputs:bundle"), ("GraphTargetPrim.outputs:prim", "ConnectedTarget.inputs:prims"), ], keys.CREATE_PRIMS: [("Prim", "Cube")], keys.SET_VALUES: [ ("SetTarget.inputs:prims", f"{self._test_graph_path}/Prim"), ], }, ) # set the bundle manually stage = omni.usd.get_context().get_stage() stage.GetRelationshipAtPath(f"{self._test_graph_path}/SetInspector.inputs:bundle").SetTargets( [f"{self._test_graph_path}/Prim"] ) # Replace the bundle inspector with a compound subgraph. Use names since a conversion can make # previous node handles invalid nodes_to_replace = [ "ConnectedInspector", "SetInspector", "UnsetInspector", "ConnectedTarget", "SetTarget", "UnsetTarget", ] compounds = [] for node_name in nodes_to_replace: node = og.Controller.node(f"{self._test_graph_path}/{node_name}") (success, compound_node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[node]) self.assertTrue(success) self.assertTrue(compound_node.is_valid()) compounds.append(compound_node.get_prim_path()) def validate_result(compound_node_path, node_name, attr_name, expected_target): # make sure the inner node was created node = og.Controller.node(f"{compound_node_path}/Subgraph/{node_name}") self.assertTrue(node.is_valid()) # make sure the relationship has the expected value rel = stage.GetRelationshipAtPath(f"{node.get_prim_path()}.{attr_name}") self.assertTrue(rel.IsValid()) self.assertEquals(expected_target, rel.GetTargets()) # validate the inner node have the expected connection validate_result(compounds[0], nodes_to_replace[0], "inputs:bundle", [f"{compounds[0]}.inputs:bundle"]) validate_result(compounds[1], nodes_to_replace[1], "inputs:bundle", [f"{self._test_graph_path}/Prim"]) validate_result(compounds[2], nodes_to_replace[2], "inputs:bundle", []) validate_result(compounds[3], nodes_to_replace[3], "inputs:prims", [f"{compounds[3]}.inputs:prims"]) validate_result(compounds[4], nodes_to_replace[4], "inputs:prims", [f"{self._test_graph_path}/Prim"]) validate_result(compounds[5], nodes_to_replace[5], "inputs:prims", []) def get_input_count(node_path: str): node = og.Controller.node(node_path) self.assertTrue(node.is_valid()) return len( [ attr for attr in node.get_attributes() if attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ] ) # validate that the new compounds have the correct number of inputs. They will have an input if they were connected # via a node connection self.assertEqual(get_input_count(compounds[0]), 1) self.assertEqual(get_input_count(compounds[1]), 0) self.assertEqual(get_input_count(compounds[2]), 0) self.assertEqual(get_input_count(compounds[3]), 1) self.assertEqual(get_input_count(compounds[4]), 0) self.assertEqual(get_input_count(compounds[5]), 0) # validate the inputs have the correct target values self.assertEquals( stage.GetRelationshipAtPath(f"{compounds[0]}.inputs:bundle").GetTargets(), [f"{self._test_graph_path}/BundleCreator/outputs_bundle"], ) self.assertEquals( stage.GetRelationshipAtPath(f"{compounds[3]}.inputs:prims").GetTargets(), [f"{self._test_graph_path}/GraphTargetPrim.outputs:prim"], ) # ------------------------------------------------------------------------ async def test_promoted_bundle_inputs_retain_values(self): """Test that when a bundle input is promoted from a compound, it retains the value that was set for it""" controller = og.Controller(update_usd=True) keys = controller.Keys (_graph, (compound,), (prim,), node_map) = controller.edit( self._test_graph_path, { keys.CREATE_PRIMS: [("/World/Prim", "Cube")], keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: ("Inspector", "omni.graph.nodes.BundleInspector"), }, ) ], }, ) # Set the bundle input on the compound node path = f"{node_map['Inspector'].get_prim_path()}.inputs:bundle" print(path) rel = omni.usd.get_context().get_stage().GetRelationshipAtPath(path) self.assertTrue(rel.IsValid()) rel.SetTargets([prim.GetPath()]) # Promote the input controller.edit(self._test_graph_path, {keys.PROMOTE_ATTRIBUTES: ("Inspector.inputs:bundle", "inputs:bundle")}) # get the bundle relationship on the promoted node rel = omni.usd.get_context().get_stage().GetRelationshipAtPath(f"{compound.get_prim_path()}.inputs:bundle") self.assertTrue(rel.IsValid()) self.assertEquals(str(rel.GetTargets()[0]), str(prim.GetPath())) # ------------------------------------------------------------------------ async def test_replace_with_compound_subgraph_with_relationship_outputs(self): """Tests that ReplaceWithCompoundSubgraph works with relationship outputs produces errors as is is currently not supported. """ # # [BundleConstructor]->[BundleInspector] controller = og.Controller(update_usd=True) keys = controller.Keys (_graph, (bundle_constructor, _bundle_inspector), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constructor", "omni.graph.nodes.BundleConstructor"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: [ ("Constructor.outputs_bundle", "Inspector.inputs:bundle"), ], }, ) # Attempt to replace the bundle constructor with a compound subgraph. with ogts.ExpectedError(): (success, compound_node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[bundle_constructor]) self.assertFalse(success) self.assertIsNone(compound_node) # ------------------------------------------------------------------------ async def test_replace_with_subgraph_handles_target_types(self): """Tests that ReplaceWithCompoundSubgraph works with target inputs and outputs""" # Create a graph with the following setup # |--------------------| |-------------------| # [GetPrimPath]-|o-[GetPrimsAtPath]-o|-->|o-[GetPrimsPaths]-o|->[GetPrimsAtPath] # |--------------------| |-------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, nodes, (prim, prim1, prim2), _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("P0", "omni.graph.nodes.GetPrimPath"), ("P1", "omni.graph.nodes.GetPrimsAtPath"), ("P2", "omni.graph.nodes.GetPrimPaths"), ("P3", "omni.graph.nodes.GetPrimsAtPath"), ], keys.CONNECT: [ ("P0.outputs:primPath", "P1.inputs:path"), ("P1.outputs:prims", "P2.inputs:prims"), ("P2.outputs:primPaths", "P3.inputs:path"), ], keys.CREATE_PRIMS: [ ("/World/Prim", "Cube"), ("/World/Prim1", "Cube"), ("/World/Prim2", "Cube"), ], keys.SET_VALUES: [ ("P0.inputs:prim", "/World/Prim"), ], }, ) # save the node paths, since the nodes can become invalid on a replace call node_paths = [og.Controller.node_path(node) for node in nodes] await og.Controller.evaluate(graph) attr = og.Controller.attribute("outputs:prims", nodes[3]) self.assertEqual(str(prim.GetPath()), str(og.Controller.get(attr)[0])) # replace node with string input, path output p1 = og.Controller.node(node_paths[1]) (success, c1) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[p1]) self.assertTrue(success) self.assertTrue(c1.is_valid()) self.assertGreater(og.Controller.attribute(("inputs:path", c1)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("inputs:path", c1)).get_downstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:prims", c1)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:prims", c1)).get_downstream_connection_count(), 0) # evaluate with a new input and makes sure the output through the compounds is correct og.Controller.set(og.Controller.attribute(f"{node_paths[0]}/inputs:prim"), prim1.GetPath()) await og.Controller.evaluate(graph) p3 = og.Controller.node(node_paths[3]) attr = og.Controller.attribute("outputs:prims", p3) self.assertEqual(str(prim1.GetPath()), str(og.Controller.get(attr)[0])) # replace node with path input, path string output p2 = og.Controller.node(node_paths[2]) (success, c2) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[p2]) self.assertTrue(success) self.assertTrue(c2.is_valid()) self.assertGreater(og.Controller.attribute(("inputs:prims", c2)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("inputs:prims", c2)).get_downstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:primPaths", c2)).get_upstream_connection_count(), 0) self.assertGreater(og.Controller.attribute(("outputs:primPaths", c2)).get_downstream_connection_count(), 0) # evaluate with a new input and makes sure the output through the compounds is correct og.Controller.set(og.Controller.attribute(f"{node_paths[0]}/inputs:prim"), prim2.GetPath()) await og.Controller.evaluate(graph) p3 = og.Controller.node(node_paths[3]) attr = og.Controller.attribute("outputs:prims", p3) self.assertEqual(str(prim2.GetPath()), str(og.Controller.get(attr)[0])) # ------------------------------------------------------------------------ async def test_replace_with_subgraph_in_nested_compounds_types(self): """Tests that replace with compound subgraph works with nested compounds""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_,), _, nodes) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "OuterCompound", { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("Add.inputs:b", "inputs:b"), ("Add.outputs:sum", "outputs:sum"), ], }, ) ], }, ) graph_path = graph.get_path_to_graph() (success, c1) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[nodes["Add"]]) self.assertTrue(success) self.assertTrue(c1.is_valid()) compound_graph = c1.get_compound_graph_instance() self.assertTrue(compound_graph.is_valid()) self.assertTrue(compound_graph.get_node(f"{compound_graph.get_path_to_graph()}/Add").is_valid()) outer_compound = og.Controller.node(f"{graph_path}/OuterCompound") self.assertEqual(c1.get_graph().get_owning_compound_node(), outer_compound) # create an extra level of compounds by replacing the new compound with a compound # [OuterCompound] -> [C1] -> [Add] becomes # [OuterCompound] -> [C2] -> [C1] -> [Add] (success, c2) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[c1]) self.assertTrue(success) self.assertTrue(c2.is_valid()) outer_compound = og.Controller.node(f"{graph_path}/OuterCompound") self.assertEquals(c2.get_graph().get_owning_compound_node(), outer_compound) compound_graph = c2.get_compound_graph_instance() sub_graph_node = compound_graph.get_nodes()[0] self.assertTrue(sub_graph_node.is_compound_node()) self.assertTrue(sub_graph_node.get_compound_graph_instance().is_valid()) add_node = sub_graph_node.get_compound_graph_instance().get_nodes()[0] self.assertTrue(add_node.is_valid()) self.assertEqual(Sdf.Path(add_node.get_prim_path()).name, "Add") # --------------------------------------------------------------------- async def test_subgraph_with_constants_evaluates(self): """Tests that a subgraph with no inputs evaluates correctly in a push graph setup""" # Create a subgraph/graph pair with the following setup # # |--------------------------------------| # | [Constant]----->|----------| | # | [Constant]----->| Add |-----> o | ---> [Magnitude] # | |----------| | # | -------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (constant1, constant2, add, abs_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant1.inputs:value", "Add.inputs:a"), ("Constant2.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "Abs.inputs:input"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 5.0), ("Constant2.inputs:value", 1.0), ], }, ) await og.Controller.evaluate(graph) attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(6.0, og.Controller.get(attr)) # push the variable nodes into a subgraph (_, compound_node) = ogu.cmds.ReplaceWithCompoundSubgraph(nodes=[constant1, constant2, add]) self.assertIsNotNone(compound_node) self.assertTrue(compound_node.is_valid()) # update the constant so we get different result constant = og.Controller.node(f"{compound_node.get_prim_path()}/Subgraph/Constant2") constant_attr = og.Controller.attribute(("inputs:value", constant)) og.Controller.set(constant_attr, 2.0) await og.Controller.evaluate(graph) abs_node = og.Controller.node(f"{self._test_graph_path}/Abs") attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(7.0, og.Controller.get(attr)) # --------------------------------------------------------------------- async def test_attribute_promotion_supports_fan_in(self): """Tests than an attribute that supports fan-in can be promoted, even if connected or already promoted""" # Creates a graph where an execution pin is both connected internally and promoted twice # |---------------------------------------------------------------| # | -------------- | # | o----------------->|o execIn | | # | o----------------->| | | # | /\-------------- | # | ----------- | | # | |execOut o|-----| | # | ----------- | # | | # |---------------------------------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys og.Controller.edit({"graph_path": self._test_graph_path, "evaluator_name": "execution"}) (_, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("NodeA", "omni.graph.action.Counter"), ("NodeB", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("NodeB.outputs:execOut", "NodeA.inputs:execIn"), ], keys.PROMOTE_ATTRIBUTES: [ ("NodeA.inputs:execIn", "execIn1"), ("NodeA.inputs:execIn", "execIn2"), ], }, ) ] }, ) compound_node = node_map["Compound"] self.assertEqual(len(self._get_input_attributes(compound_node)), 2) node_a = node_map["NodeA"] self.assertEqual(len(node_a.get_attribute("inputs:execIn").get_upstream_connections()), 3) # --------------------------------------------------------------------- async def test_attribute_promotion_rejects_fan_in(self): """Test that validates that promotion of non-fan-in attributes is rejected""" controller = og.Controller(update_usd=True) keys = controller.Keys with self.assertRaises(og.OmniGraphError): (_, _, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("NodeA", "omni.graph.nodes.Add"), ], keys.PROMOTE_ATTRIBUTES: [ ("NodeA.inputs:a", "a1"), ("NodeA.inputs:a", "a2"), ], }, ) ] }, ) # --------------------------------------------------------------------- async def test_compound_graph_exec_ports_support_fan_in(self): """Test that validates compounds can support fan in on exec ports""" controller = og.Controller(update_usd=True) keys = controller.Keys # ------------- |----------------------------| # [OnTick]--->|Multigate o|---->|o-->[Counter]------------->o| # | o|---->| | # | o| | | # ------------- |----------------------------| og.Controller.edit({"graph_path": self._test_graph_path, "evaluator_name": "execution"}) (_, (compound, mg, _), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("Counter", "omni.graph.action.Counter"), ], keys.PROMOTE_ATTRIBUTES: [ ("Counter.inputs:execIn", "inputs:execIn"), ("Counter.outputs:count", "outputs:count"), ], }, ), ("Multigate", "omni.graph.action.Multigate"), ("Tick", "omni.graph.action.OnTick"), ], keys.CREATE_ATTRIBUTES: [ ("Multigate.outputs:output1", og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION)), ("Multigate.outputs:output2", og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION)), ], keys.CONNECT: [ ("Tick.outputs:tick", "Multigate.inputs:execIn"), ("Multigate.outputs:output0", "Compound.inputs:execIn"), ("Multigate.outputs:output1", "Compound.inputs:execIn"), ], }, ) omni.timeline.get_timeline_interface().play() # evaluate the graph a bunch of times. The counter should update 2 of every 3 times counter = compound.get_attribute("outputs:count") for _ in range(0, 8): await omni.kit.app.get_app().next_update_async() expected_counter = int(mg.get_compute_count() / 3) * 2 + (mg.get_compute_count() % 3) self.assertGreater(og.Controller.get(counter), 0) self.assertEqual(expected_counter, og.Controller.get(counter)) # --------------------------------------------------------------------- async def test_rename_compound_subgraph(self): """Validates that a compound subgraph can be successfully renamed""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ( "Compound2", { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("Add.inputs:b", "inputs:b"), ("Add.outputs:sum", "outputs:sum"), ], }, ), ], keys.PROMOTE_ATTRIBUTES: [ ("Compound2.inputs:a", "inputs:a"), ("Compound2.inputs:b", "inputs:b"), ("Compound2.outputs:sum", "outputs:sum"), ], }, ), ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ("Output", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant1.inputs:value", "Compound.inputs:a"), ("Constant2.inputs:value", "Compound.inputs:b"), ("Compound.outputs:sum", "Output.inputs:input"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 1.0), ("Constant2.inputs:value", 2.0), ], }, ) # iterate the paths from deepest to shallowest paths = [ node_map["Compound2"].get_prim_path(), node_map["Compound"].get_prim_path(), ] const_2_path = node_map["Constant2"].get_attribute("inputs:value").get_path() output_attr = node_map["Output"].get_attribute("outputs:magnitude").get_path() input_value = 2.0 # noqa SIM113 expected_result = 3.0 await og.Controller.evaluate(graph) self.assertEquals(expected_result, og.Controller.get(og.Controller.attribute(output_attr))) for path in paths: # rename the compound node specified by path compound = og.Controller.node(path).get_compound_graph_instance() old_name = compound.get_path_to_graph() new_name = old_name + "_renamed" omni.kit.commands.execute("RenameCompoundSubgraph", subgraph=compound, new_path=new_name) # increment the expected result input_value += 1.0 og.Controller.set(og.Controller.attribute(const_2_path), input_value) expected_result = input_value + 1.0 await og.Controller.evaluate(graph) # reload the compound node. the rename will have invalidated the node self.assertEquals(expected_result, og.Controller.get(og.Controller.attribute(output_attr))) # --------------------------------------------------------------------- async def tests_created_compounds_are_ineligible_for_delete(self): """Tests that compound subgraphs are flagged as ineligible for deletion""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, (compound,), _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: [("Compound", {keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add")]})]}, ) subgraph_path = compound.get_compound_graph_instance().get_path_to_graph() # suppress the warning. The command will succeed regardless, but print out a warning with ogts.ExpectedError(): omni.kit.commands.execute("DeletePrims", paths=[subgraph_path]) # validate that the prim still exists stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(subgraph_path) self.assertTrue(prim.IsValid()) self.assertTrue(compound.get_compound_graph_instance().is_valid()) # --------------------------------------------------------------------- async def tests_broken_compounds_produces_error(self): """Tests that a broken compound will produce error msgs when evaluated""" controller = og.Controller(update_usd=True) keys = controller.Keys (graph, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add")], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("Add.inputs:b", "inputs:b"), ("Add.outputs:sum", "outputs:sum"), ], }, ), ("Constant1", "omni.graph.nodes.ConstantDouble"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 1.0), ], keys.CONNECT: [ ("Constant1.inputs:value", "Compound.inputs:a"), ("Constant1.inputs:value", "Compound.inputs:b"), ], }, ) compound_path = node_map["Compound"].get_prim_path() subgraph_path = node_map["Compound"].get_compound_graph_instance().get_path_to_graph() stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(subgraph_path) self.assertTrue(prim.IsValid()) prim.SetMetadata("no_delete", False) omni.kit.commands.execute("DeletePrims", paths=[subgraph_path]) # suppress the error that is expected with ogts.ExpectedError(): await og.Controller.evaluate(graph) node = og.Controller.node(compound_path) self.assertTrue(node.is_valid()) msgs = node.get_compute_messages(og.Severity.ERROR) self.assertTrue(len(msgs) > 0) # ----------------------------------------------------------------------------- async def tests_rename_compound_command(self): """Tests the rename compound command""" controller = og.Controller(update_usd=True) keys = controller.Keys (_, _, _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound1", {keys.CREATE_NODES: [("Add1", "omni.graph.nodes.Add")]}), ("Compound2", {keys.CREATE_NODES: [("Add2", "omni.graph.nodes.Add")]}), ("Compound3", {keys.CREATE_NODES: [("Add3", "omni.graph.nodes.Add")]}), ("Compound4", {keys.CREATE_NODES: [("Add4", "omni.graph.nodes.Add")]}), ("Compound5", {keys.CREATE_NODES: [("Add5", "omni.graph.nodes.Add")]}), ] }, ) graph_paths = [ og.Controller.prim_path(node_map[f"Compound{idx}"].get_compound_graph_instance()) for idx in range(1, 6) ] # success case with undo og._unstable.cmds.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=graph_paths[0], new_path=graph_paths[0] + "_renamed" ) await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[0] + "_renamed")) omni.kit.undo.undo() await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[0])) omni.kit.undo.redo() await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[0] + "_renamed")) # failure case - bad path with ogts.ExpectedError(): (res, _) = og._unstable.cmds.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=graph_paths[1], new_path="This is an invalid path" ) self.assertFalse(res) # failure case - rename to an invalid name in immediate mode with ogts.ExpectedError(): self.assertIsNone( og._unstable.cmds.imm.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=graph_paths[2], new_path="invalid name" ) ) # pass by graph og._unstable.cmds.RenameCompoundSubgraph( # noqa: PLW0212 subgraph=og.Controller.graph(graph_paths[3]), new_path=graph_paths[3] + "_renamed" ) await omni.kit.app.get_app().next_update_async() self.assertTrue(og.Controller.graph(graph_paths[3] + "_renamed")) # failure case - path is not a child of the compound node with ogts.ExpectedError(): self.assertIsNone( og._unstable.cmds.imm.RenameCompoundSubgraph(graph_paths[4], "/World/OtherPath") # noqa: PLW0212 ) # ----------------------------------------------------------------------------- class TestCompoundSubgraphAttributeCommands(ogts.OmniGraphTestCase): """Tests related to commands to add, remove and rename attributes from compound nodes containing a subgraph """ _test_graph_path = "/World/TestGraph" # ------------------------------------------------------------------------- async def setUp(self): await super().setUp() # Set up a subgraph node as follows # The composedouble3 node as fixed-type inputs, so they aren't exposed # |-------------------------------------| # [Constant] --> | o(a) -->|------| | # | | Add1 | | # [Constant] --> | o(b) -->|------| --> |------| | # | | Add2 | --> o |-->[Add3] # | o(b_01) -----------> |------| | # | | # | |----------------| | # | | ComposeDouble3 | --> o | # | |----------------| | # |-------------------------------------| # # The inputs are a, b, b_01 # The outputs are sum and double3 controller = og.Controller(update_usd=True) keys = controller.Keys ( _, (self._constant_node_1, self._constant_node_2, self._compound_node, self._add3_node), _, mapping, ) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ( "Compound", { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add"), ("ComposeDouble3", "omni.graph.test.ComposeDouble3C"), ], keys.CONNECT: [ ("Add1.outputs:sum", "Add2.inputs:a"), ], keys.SET_VALUES: [ ("ComposeDouble3.inputs:x", 5.0), ], keys.PROMOTE_ATTRIBUTES: [ ("Add1.inputs:a", "a"), ("Add1.inputs:b", "b"), ("Add2.inputs:b", "b_01"), ("Add2.outputs:sum", "sum"), ("ComposeDouble3.outputs:double3", "double3"), ], }, ), ("Add3", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant1.inputs:value", "Compound.inputs:a"), ("Constant2.inputs:value", "Compound.inputs:b"), ("Compound.outputs:sum", "Add3.inputs:a"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 5.0), ], }, ) self._add1_node = mapping["Add1"] self._add2_node = mapping["Add2"] self._compose_node = mapping["ComposeDouble3"] self._compound_input_1 = og.ObjectLookup.attribute(("inputs:a", self._compound_node)) self._compound_input_2 = og.ObjectLookup.attribute(("inputs:b", self._compound_node)) self._compound_input_3 = og.ObjectLookup.attribute(("inputs:b_01", self._compound_node)) self._compound_output_1 = og.ObjectLookup.attribute(("outputs:sum", self._compound_node)) self._compound_output_2 = og.ObjectLookup.attribute(("outputs:double3", self._compound_node)) self._subgraph = og.ObjectLookup.graph(f"{self._compound_node.get_prim_path()}/Subgraph") # disable logging of command errors omni.kit.commands.set_logging_enabled(False) # ------------------------------------------------------------------------- async def tearDown(self): await super().tearDown() omni.kit.commands.set_logging_enabled(True) # ------------------------------------------------------------------------- async def test_create_input_command(self): """Test that input connections can be successfully added and works with undo and redo""" connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=connect_to_attr ) self.assertTrue(success) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_downstream_connections()[0], connect_to_attr) # validate the value was copied up to the graph self.assertEqual(og.Controller.get(attr), 5.0) omni.kit.undo.undo() self.assertTrue(self._compound_node.is_valid()) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(("inputs:added_input", self._compound_node)) self.assertEqual(og.Controller.get(connect_to_attr), 5.0) omni.kit.undo.redo() self.assertTrue(self._compound_node.is_valid()) attr = og.ObjectLookup.attribute(("inputs:added_input", self._compound_node)) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_downstream_connections()[0], connect_to_attr) self.assertEqual(og.Controller.get(attr), 5.0) # --------------------------------------------------------------------------- async def test_resolved_attribute_values_are_copied_on_create(self): """Tests that resolved attribute values are copied when used with create input""" # create a new node in the graph new_node = og.GraphController.create_node( node_id=("Add4", self._subgraph), node_type_id="omni.graph.nodes.Add", update_usd=True ) attr = og.ObjectLookup.attribute(("inputs:a", new_node)) attr.set_resolved_type(og.Type(og.BaseDataType.DOUBLE)) og.Controller.set(attr, 10.0, update_usd=True) self.assertEqual(og.Controller.get(attr), 10.0) (success, compound_attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=attr ) self.assertTrue(success) self.assertTrue(compound_attr.is_valid()) self.assertEqual(10, og.Controller.get(compound_attr)) # --------------------------------------------------------------------------- async def test_create_input_error_cases(self): """Validates known failure cases for create input commands""" # 1) connecting to an attribute not in the subgraph with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=og.ObjectLookup.attribute("inputs:b", self._add3_node), ) self.assertTrue(success) self.assertIsNone(attr) # 2) connecting to no/invalid attribute with self.assertRaises(og.OmniGraphError): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=None ) with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to="/World/Path.inputs:not_valid" ) self.assertTrue(success) self.assertIsNone(attr) # 3) connecting to an existing attribute name with ogts.ExpectedError(): connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="a", connect_to=connect_to_attr ) self.assertTrue(success) self.assertIsNone(attr) # 4) connecting to a non-compound node with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._add3_node, input_name="other", connect_to=connect_to_attr ) self.assertTrue(success) self.assertIsNone(attr) # 5) connecting to a connected attribute with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="other", connect_to=og.ObjectLookup.attribute(("inputs:a", self._add1_node)), ) self.assertTrue(success) self.assertIsNone(attr) # 6) connecting to output attribute with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="other", connect_to=og.ObjectLookup.attribute(("outputs:sum", self._add1_node)), ) self.assertTrue(success) self.assertIsNone(attr) # ------------------------------------------------------------------------- def _validate_create_output_command_with_undo_redo(self, connect_from_attr: og.Attribute): """Helper to validate create output""" (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from=connect_from_attr ) self.assertTrue(success) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_upstream_connections()[0], connect_from_attr) omni.kit.undo.undo() self.assertTrue(self._compound_node.is_valid()) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(("outputs:added_output", self._compound_node)) omni.kit.undo.redo() self.assertTrue(self._compound_node.is_valid()) attr = og.ObjectLookup.attribute(("outputs:added_output", self._compound_node)) self.assertTrue(attr.is_valid()) self.assertTrue(attr.get_upstream_connections()[0], connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command(self): """Tests that output connections can be successfully added, including undo, redo""" # add a node to the subgraph, so there is an unconnected output new_node = og.GraphController.create_node( node_id=("Add4", self._subgraph), node_type_id="omni.graph.nodes.Add", ) connect_from_attr = og.ObjectLookup.attribute(("outputs:sum", new_node)) self._validate_create_output_command_with_undo_redo(connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command_multiple_outputs(self): """Tests that the output command connectes to an already connected output""" connect_from_attr = og.ObjectLookup.attribute(("outputs:sum", self._add2_node)) self._validate_create_output_command_with_undo_redo(connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command_from_input(self): """Tests that the output command can create outputs from inputs as output nodes""" new_node = og.GraphController.create_node( node_id=("NewConstant", self._subgraph), node_type_id="omni.graph.nodes.ConstantDouble", ) connect_from_attr = og.ObjectLookup.attribute(("inputs:value", new_node)) self._validate_create_output_command_with_undo_redo(connect_from_attr) # ------------------------------------------------------------------------- async def test_create_output_command_error_cases(self): """Tests command error cases of output commands""" # 1) connecting to an attribute not in the subgraph with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from=og.ObjectLookup.attribute("outputs:sum", self._add3_node), ) self.assertTrue(success) self.assertIsNone(attr) # 2) connecting to no/invalid attribute with self.assertRaises(og.OmniGraphError): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from=None ) with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="added_output", connect_from="/World/Path.outputs:not_valid", ) self.assertTrue(success) self.assertIsNone(attr) # 3) connecting to an existing attribute name with ogts.ExpectedError(): connect_from_attr = og.ObjectLookup.attribute(("outputs:double3", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="sum", connect_from=connect_from_attr ) self.assertTrue(success) self.assertIsNone(attr) # 4) connecting to a non-compound node with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._add3_node, output_name="other", connect_from=connect_from_attr ) self.assertTrue(success) self.assertIsNone(attr) # 5) try to promote a bundle output og.Controller.edit( self._compound_node.get_compound_graph_instance(), {og.Controller.Keys.CREATE_NODES: ("BundleCreator", "omni.graph.nodes.BundleConstructor")}, ) node = og.Controller.node( f"{self._compound_node.get_compound_graph_instance().get_path_to_graph()}/BundleCreator" ) self.assertTrue(node.is_valid()) bundle_attr = node.get_attribute("outputs_bundle") self.assertTrue(bundle_attr.is_valid()) with ogts.ExpectedError(): (success, attr) = ogu.cmds.CreateCompoundSubgraphOutput( compound_node=self._compound_node, output_name="exposed_bundle", connect_from=bundle_attr ) self.assertTrue(success) self.assertIsNone(attr) # ------------------------------------------------------------------------- async def test_remove_compound_input(self): """Tests the remove compound attribute command can remove an input, including undo and redo""" self._compound_input_1.set_resolved_type(og.Type(og.BaseDataType.DOUBLE)) og.Controller.set(self._compound_input_1, 10.0, update_usd=True) connected_attr = self._compound_input_1.get_downstream_connections()[0] (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute=self._compound_input_1) self.assertTrue(success) self.assertTrue(result) self.assertFalse(self._compound_node.get_attribute_exists("inputs:a")) self.assertEqual(0, connected_attr.get_upstream_connection_count()) omni.kit.undo.undo() self.assertTrue(self._compound_node.get_attribute_exists("inputs:a")) attr = og.ObjectLookup.attribute(("inputs:a", self._compound_node)) self.assertGreater(attr.get_downstream_connection_count(), 0) self.assertEqual(attr.get_downstream_connections()[0], connected_attr) omni.kit.undo.redo() self.assertFalse(self._compound_node.get_attribute_exists("inputs:a")) self.assertEqual(0, connected_attr.get_upstream_connection_count()) # ------------------------------------------------------------------------- async def test_remove_compound_inputs_keeps_resolved_values(self): """Test the remove compound attribute restores resolved values""" # add the connection to the resolved node connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) (success, attr) = ogu.cmds.CreateCompoundSubgraphInput( compound_node=self._compound_node, input_name="added_input", connect_to=connect_to_attr ) self.assertTrue(success) self.assertTrue(attr.is_valid()) (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute=attr) self.assertTrue(success) self.assertTrue(result) connect_to_attr = og.ObjectLookup.attribute(("inputs:x", self._compose_node)) self.assertEqual(5.0, og.Controller.get(connect_to_attr)) # ------------------------------------------------------------------------- async def test_remove_compound_output(self): """Tests the remove compound attribute command can remove an output, including undo and redo""" connected_attr = self._compound_output_1.get_upstream_connections()[0] (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute=self._compound_output_1) self.assertTrue(success) self.assertTrue(result) self.assertFalse(self._compound_node.get_attribute_exists("outputs:sum")) self.assertEqual(0, connected_attr.get_downstream_connection_count()) omni.kit.undo.undo() self.assertTrue(self._compound_node.get_attribute_exists("outputs:sum")) attr = og.ObjectLookup.attribute(("outputs:sum", self._compound_node)) self.assertGreater(attr.get_upstream_connection_count(), 0) self.assertEqual(attr.get_upstream_connections()[0], connected_attr) omni.kit.undo.redo() self.assertFalse(self._compound_node.get_attribute_exists("outputs:sum")) self.assertEqual(0, connected_attr.get_downstream_connection_count()) # ------------------------------------------------------------------------- async def test_remove_compound_output_error_cases(self): """Validates known failure cases for remove attribute commands""" # 1) not a compound node with ogts.ExpectedError(): (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute( attribute=og.ObjectLookup.attribute("inputs:b", self._add3_node) ) self.assertTrue(success) self.assertFalse(result) # 2) not a valid attribute with ogts.ExpectedError(): (success, result) = ogu.cmds.RemoveCompoundSubgraphAttribute(attribute="/World/Path.outputs:invalid_attr") self.assertTrue(success) self.assertFalse(result) # ------------------------------------------------------------------------- async def test_rename_compound_input_output(self): """Tests the rename input/output functionality""" # Rename an input attribute upstream = self._compound_input_1.get_upstream_connections() downstream = self._compound_input_1.get_downstream_connections() old_attr_path = self._compound_input_1.get_path() (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute( attribute=self._compound_input_1, new_name="new_a" ) # Verify that connections are now on new attr and old attr has been removed self.assertTrue(success) self.assertTrue(new_attr.is_valid()) self.assertEqual(new_attr.get_upstream_connections(), upstream) self.assertEqual(new_attr.get_downstream_connections(), downstream) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(old_attr_path) new_attr_path = new_attr.get_path() omni.kit.undo.undo() # Verify undo restores the old attr and connections with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(new_attr_path) attr = og.ObjectLookup.attribute(old_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) # Verify redo omni.kit.undo.redo() attr = og.ObjectLookup.attribute(new_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(old_attr_path) # Rename an output attribute upstream = self._compound_output_1.get_upstream_connections() downstream = self._compound_output_1.get_downstream_connections() old_attr_path = self._compound_output_1.get_path() (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute( attribute=self._compound_output_1, new_name="new_sum" ) self.assertTrue(success) self.assertTrue(new_attr.is_valid()) self.assertEqual(new_attr.get_upstream_connections(), upstream) self.assertEqual(new_attr.get_downstream_connections(), downstream) new_attr_path = new_attr.get_path() omni.kit.undo.undo() with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(new_attr_path) attr = og.ObjectLookup.attribute(old_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) omni.kit.undo.redo() attr = og.ObjectLookup.attribute(new_attr_path) self.assertEqual(attr.get_upstream_connections(), upstream) self.assertEqual(attr.get_downstream_connections(), downstream) # ------------------------------------------------------------------------- async def test_rename_compound_input_output_error_cases(self): """Validates known failure cases for remove attribute commands""" # attempt to rename to an existing name with ogts.ExpectedError(): (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute( attribute=self._compound_input_1, new_name="b" ) self.assertFalse(success) self.assertEqual(new_attr, None) # ----------------------------------------------------------------------------- class TestCompoundSubgraphWithVariables(ogts.OmniGraphTestCase): _test_graph_path = "/World/TestGraph" # --------------------------------------------------------------------- async def test_subgraph_with_read_variables_evaluates(self): """Tests that a subgraph with variables in it evaluates correctly""" # Create a subgraph/graph pair with the following setup # # |--------------------------------------| # | [ReadVariable]->|----------| | # | [Constant]----->| Add |-----> o | ---> [Magnitude] # | |----------| | # | -------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (compound_node, abs_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound", { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("Constant", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "Add.inputs:a"), ("Constant.inputs:value", "Add.inputs:b"), ], keys.PROMOTE_ATTRIBUTES: [("Add.outputs:sum", "value")], }, ), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Compound.outputs:value", "Abs.inputs:input"), ], keys.CREATE_VARIABLES: [ ("double_var", og.Type(og.BaseDataType.DOUBLE), 5.0), ], keys.SET_VALUES: [("Constant.inputs:value", 1.0), ("ReadVariable.inputs:variableName", "double_var")], }, ) await og.Controller.evaluate(graph) attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(6.0, og.Controller.get(attr)) # update the constant so we get different result - because it 'moved' to the subgraph, the # existing variable is no longer valid constant = og.Controller.node(f"{compound_node.get_prim_path()}/Subgraph/Constant") constant_attr = og.Controller.attribute(("inputs:value", constant)) og.Controller.set(constant_attr, 2.0) await og.Controller.evaluate(graph) abs_node = og.Controller.node(f"{self._test_graph_path}/Abs") attr = og.Controller.attribute(("outputs:magnitude", abs_node)) self.assertEqual(7.0, og.Controller.get(attr)) # --------------------------------------------------------------------- async def test_subgraph_read_write_variables_across_subnet(self): """Tests that a subgraph can read and write variables regardless of where they live """ # A graph that doubles the variable value each time # A single read is in the main graph, one in the subgraph # |----------------------------------------| # | | # [ReadVariable] --> | o-------------->|------| | # | [ReadVariable]->| Add |--->[WriteVar] | # | |------| | # |----------------------------------------| controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_read1, _compound_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("ReadVariable1", "omni.graph.core.ReadVariable"), ( "Compound", { keys.CREATE_NODES: [ ("ReadVariable2", "omni.graph.core.ReadVariable"), ("Add", "omni.graph.nodes.Add"), ("WriteVariable", "omni.graph.core.WriteVariable"), ], keys.CONNECT: [ ("ReadVariable2.outputs:value", "Add.inputs:b"), ("Add.outputs:sum", "WriteVariable.inputs:value"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ("WriteVariable.outputs:value", "outputs:value"), ], keys.SET_VALUES: [ ("ReadVariable2.inputs:variableName", "double_var"), ("WriteVariable.inputs:variableName", "double_var"), ], }, ), ], keys.CREATE_VARIABLES: [ ("double_var", og.Type(og.BaseDataType.DOUBLE), 2.0), ], keys.CONNECT: [ ("ReadVariable1.outputs:value", "Compound.inputs:a"), ], keys.SET_VALUES: [ ("ReadVariable1.inputs:variableName", "double_var"), ], }, ) # get the variable value variable = graph.find_variable("double_var") var_value = variable.get(graph.get_default_graph_context()) for _ in range(0, 3): await og.Controller.evaluate(graph) new_var_value = variable.get(graph.get_default_graph_context()) self.assertEqual(var_value * 2, new_var_value) var_value = new_var_value async def test_promote_unconnected(self): """ Test promoting all unconnected inputs/outputs on a node in a compound. Ensure that it also creates a unique name """ controller = og.Controller(update_usd=True) keys = controller.Keys (graph, (_, _compound_node), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("ConstDouble", "omni.graph.nodes.ConstantDouble"), ( "Compound", { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ("ConstantFloat", "omni.graph.nodes.ConstantFloat"), ("RandomBool", "omni.graph.nodes.RandomBoolean"), ], keys.PROMOTE_ATTRIBUTES: [ ("Add.inputs:a", "inputs:a"), ], }, ), ], keys.CONNECT: [ ("ConstDouble.inputs:value", "Compound.inputs:a"), ], keys.SET_VALUES: [("ConstDouble.inputs:value", 2.0)], }, ) await og.Controller.evaluate(graph) self.assertTrue(_compound_node.get_attribute("inputs:a").is_valid()) self.assertFalse(_compound_node.get_attribute_exists("inputs:b")) add_node = og.Controller.node(f"{_compound_node.get_prim_path()}/Subgraph/Add") (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=add_node, inputs=True, outputs=False) self.assertTrue(success) self.assertEqual(len(ports), 1) self.assertTrue(ports[0].is_valid()) self.assertEqual(ports[0].get_name(), "inputs:b") self.assertTrue(_compound_node.get_attribute("inputs:b").is_valid()) omni.kit.undo.undo() self.assertFalse(_compound_node.get_attribute_exists("inputs:b")) omni.kit.undo.redo() self.assertTrue(_compound_node.get_attribute("inputs:b").is_valid()) # rename input "a" to "b" and promote unconnected again, should create b_01 omni.kit.undo.undo() self.assertFalse(_compound_node.get_attribute_exists("inputs:b")) attr = _compound_node.get_attribute("inputs:a") (success, new_attr) = ogu.cmds.RenameCompoundSubgraphAttribute(attribute=attr, new_name="b") self.assertTrue(success) self.assertTrue(new_attr.is_valid()) (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=add_node, inputs=True, outputs=False) self.assertTrue(success) self.assertEqual(len(ports), 1) self.assertTrue(ports[0].is_valid()) self.assertEqual(ports[0].get_name(), "inputs:b_01") omni.kit.undo.undo() c = og.Controller.create_attribute(add_node, "inputs:c", "double") self.assertTrue(c.is_valid()) (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=add_node, inputs=True, outputs=True) self.assertTrue(success) self.assertEqual(len(ports), 3) self.assertEqual(ports[0].get_name(), "inputs:b_01") self.assertEqual(ports[1].get_name(), "inputs:c") self.assertEqual(ports[2].get_name(), "outputs:sum") # verify that output-only inputs are promoted as outputs float_node = og.Controller.node(f"{_compound_node.get_prim_path()}/Subgraph/ConstantFloat") (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=float_node, inputs=False, outputs=True) self.assertTrue(success) self.assertEqual(len(ports), 1) self.assertEqual(ports[0].get_name(), "outputs:value") # test that literal only inputs are not promoted rand_node = og.Controller.node(f"{_compound_node.get_prim_path()}/Subgraph/RandomBool") (success, ports) = ogu.cmds.PromoteUnconnectedToCompoundSubgraph(node=rand_node, inputs=True, outputs=False) self.assertTrue(success) self.assertEqual(len(ports), 3) self.assertFalse("inputs:isNoise" in {p.get_name() for p in ports})
88,415
Python
45.855326
123
0.529152
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_controllers.py
"""Basic tests of the controller classes in omni.graph.core""" import json from typing import Any, Dict, List import carb import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.graph.core._impl.utils import _flatten_arguments, _Unspecified from pxr import Sdf _KEYS = og.Controller.Keys """Syntactic sugar to shorten the name required to access the keywords""" # ============================================================================================================== class TestControllers(ogts.OmniGraphTestCase): """Run a simple set of unit tests that exercise the main controller functionality""" # -------------------------------------------------------------------------------------------------------------- async def test_arg_flattening(self): """Test the utility that flattens arguments list into a common dictionary""" test_data = [ ([], [("a", 1)], [], {}, [1]), ([("a", _Unspecified)], [], [1], {}, [1]), ([("a", 1)], [], [], {}, [1]), ([("a", _Unspecified)], [], [], {"a": 2}, [2]), ([("a", _Unspecified)], [], [5], {}, [5]), ([("a", _Unspecified)], [("b", 7)], [5], {}, [5, 7]), ([("a", _Unspecified)], [("b", 7)], [], {"a": 3}, [3, 7]), ([("a", _Unspecified)], [("b", 7)], [5], {"b": 3}, [5, 3]), ([("a", _Unspecified)], [("b", _Unspecified)], [5], {"b": 3}, [5, 3]), ] for test_index, (mandatory, optional, args, kwargs, expected_results) in enumerate(test_data): flat_args = _flatten_arguments(mandatory, optional, args, kwargs) self.assertCountEqual(flat_args, expected_results, f"Test {test_index}") # Test cases where the arguments are invalid and exceptions are expected test_data_invalid = [ ([("a", _Unspecified)], [], [], {}, [1]), # Missing mandatory arg ([("a", _Unspecified)], [], [], {"b": 1}, []), # Unknown kwarg ([("a", _Unspecified)], [], [1, 2], {}, [1]), # Too many args ([("a", _Unspecified)], [], [1], {"a": 2}, [1]), # Ambiguous arg value ([("a", _Unspecified)], [("b", 7)], [5], {"a": 3}, [5, 3]), # Ambiguous arg value ] for mandatory, optional, args, kwargs, _expected_results in test_data_invalid: with self.assertRaises(og.OmniGraphError): _ = _flatten_arguments(mandatory, optional, args, kwargs) carb.log_error(f"Should have failed with {mandatory}, {optional}, {args}, {kwargs}") # -------------------------------------------------------------------------------------------------------------- async def test_flattening_example(self): """Test that runs the code cited in the documentation for the _flatten_arguments function""" feet = 1 yards = 3 miles = 5280 class Toady: def __init__(self): self.__height_default = 1 self.__height_unit = yards self.jump = self.__jump_obj @classmethod def jump(cls, *args, **kwargs): # noqa: PLE0202 Hiding it is the point return cls.__jump(cls, args=args, kwargs=kwargs) def __jump_obj(self, *args, **kwargs): return self.__jump( self, how_high=self.__height_default, unit=self.__height_unit, args=args, kwargs=kwargs ) @staticmethod def __jump(obj, how_high: int = None, unit: str = miles, args=List[Any], kwargs=Dict[str, Any]): (how_high, unit) = _flatten_arguments( mandatory=[("how_high", how_high)], optional=[("unit", unit)], args=args, kwargs=kwargs ) return how_high, unit # Legal calls to this function self.assertEqual((123, miles), Toady.jump(how_high=123)) self.assertEqual((123, miles), Toady.jump(123)) self.assertEqual((123, feet), Toady.jump(123, unit=feet)) self.assertEqual((123, feet), Toady.jump(how_high=123, unit=feet)) # The main difference in object-based calls is the use of the object members for defaults, also allowing it # to omit the "mandatory" members in the call. smithers = Toady() self.assertEqual((1, yards), smithers.jump()) self.assertEqual((123, yards), smithers.jump(how_high=123)) self.assertEqual((123, yards), smithers.jump(123)) self.assertEqual((123, feet), smithers.jump(123, unit=feet)) self.assertEqual((123, feet), smithers.jump(how_high=123, unit=feet)) self.assertEqual((1, feet), smithers.jump(unit=feet)) # -------------------------------------------------------------------------------------------------------------- async def test_graph_construction(self): """Test the basic graph construction function of the og.Controller class""" controller = og.Controller() (graph, _, _, _) = controller.edit("/World/PushGraph") self.assertTrue(graph, "Created a new graph") await controller.evaluate(graph) graph_by_path = og.get_graph_by_path("/World/PushGraph") self.assertEqual(graph, graph_by_path, "Created graph lookup") self.assertEqual(graph.get_pipeline_stage(), og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION) self.assertEqual(graph.get_graph_backing_type(), og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED) (same_graph, _, _, _) = controller.edit(graph) self.assertEqual(graph, same_graph, "Edit of the same graph twice") await controller.evaluate(same_graph) index = 0 all_graphs = [graph] for backing_type in og.GraphBackingType.__members__.values(): if backing_type in [ og.GraphBackingType.GRAPH_BACKING_TYPE_UNKNOWN, og.GraphBackingType.GRAPH_BACKING_TYPE_NONE, og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_WITH_HISTORY, ]: continue for pipeline_stage in og.GraphPipelineStage.__members__.values(): if pipeline_stage in [og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_UNKNOWN]: continue for evaluation_mode in [ og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED, ]: error_msg = ( f"Created graph with backing {backing_type}, pipeline {pipeline_stage} " "and evaluation mode {evaluation_mode}" ) (new_graph, _, _, _) = controller.edit( { "graph_path": f"/World/TestGraph{index}", "fc_backing_type": backing_type, "pipeline_stage": pipeline_stage, "evaluation_mode": evaluation_mode, } ) self.assertTrue(new_graph, error_msg) self.assertEqual(new_graph.get_pipeline_stage(), pipeline_stage, error_msg) self.assertEqual(new_graph.get_graph_backing_type(), backing_type, error_msg) self.assertEqual(new_graph.evaluation_mode, evaluation_mode, error_msg) self.assertTrue( any( new_graph == pipeline_graph for pipeline_graph in og.get_graphs_in_pipeline_stage(pipeline_stage) ) ) index += 1 all_graphs.append(new_graph) await controller.evaluate(all_graphs) # ---------------------------------------------------------------------- async def test_graph_population(self): """Test node creation and deletion via the og.Controller class""" controller = og.Controller() simple_node_type = "omni.graph.tutorials.SimpleData" # Create a couple of random nodes (graph, nodes_created, _, _) = controller.edit( "/World/PushGraph", { _KEYS.CREATE_NODES: [ ("Simple1", simple_node_type), ("Simple2", simple_node_type), ("Simple3", simple_node_type), ] }, ) for node in nodes_created: self.assertTrue(node.is_valid(), "Created node is valid") self.assertEqual(node.get_node_type().get_node_type(), simple_node_type) self.assertEqual(len(nodes_created), 3, "Correct number of nodes created and returned") nodes_matched = 0 for node in graph.get_nodes(): for expected_node in nodes_created: if node == expected_node: nodes_matched += 1 break self.assertEqual(nodes_matched, 3, "Found all created nodes in the return values") # Delete one node, add two nodes, then delete an earlier one. # Uses a static controller instead of the existing one for some operations to confirm that also works controller.edit(graph, {_KEYS.DELETE_NODES: "Simple1"}) (static_graph, static_nodes, _, static_path_node_map) = og.Controller.edit( graph, { _KEYS.CREATE_NODES: [ ("Simple1", simple_node_type), ("Simple4", simple_node_type), ] }, ) self.assertEqual(graph, static_graph, "Static controller uses same graph") self.assertEqual(len(static_nodes), 2, "Static node creation") self.assertCountEqual(["Simple1", "Simple4"], list(static_path_node_map.keys()), "Static node path map") (_, _, _, new_path_node_map) = controller.edit(graph, {_KEYS.DELETE_NODES: "Simple2"}) self.assertCountEqual( ["Simple3"], list(new_path_node_map.keys()), "Path map is only aware of object-based changes" ) # Delete a node then immediately create one with the same name but a different type, using the non-list forms (_, retyped_nodes, _, retyped_path_node_map) = controller.edit( graph, { _KEYS.DELETE_NODES: "Simple1", _KEYS.CREATE_NODES: ("Simple1", "omni.tutorials.TupleData"), }, ) self.assertCountEqual( ["Simple1", "Simple3"], list(retyped_path_node_map.keys()), "Path map deleted and added a node of the same name", ) self.assertEqual( "omni.tutorials.TupleData", controller.node_type(retyped_nodes[0]).get_node_type(), "Same node name, different type", ) # Attempt to add a node with a bad type with self.assertRaises(og.OmniGraphError): og.Controller.edit(graph, {_KEYS.CREATE_NODES: [("NoSuchNode", "omni.no.such.type")]}) # Attempt to delete a non-existing node (using a static Controller object instead of the existing one) with self.assertRaises(og.OmniGraphError): og.Controller.edit(graph, {_KEYS.DELETE_NODES: ["/This/Node/Does/Not/Exist"]}) # -------------------------------------------------------------------------------------------------------------- async def test_prim_construction(self): """Test the controller's ability to create USD prims. This is just testing basic functionality. A separate test will exercise creation of prims with all of the available attribute types. Testing Type Matrix: prim_path: str, Sdf.Path, Invalid attribute_id: dict of KEY: str, Invalid VALUE: 2-tuple of VALUE[0]: str(ogn type), str(sdf type), og.Type, Invalid VALUE[1]: Matching Value Type, Unmatching Value Type, Invalid prim_type: str, None """ controller = og.Controller() (graph, _, prims, _,) = controller.edit( "/PrimGraph", { controller.Keys.CREATE_PRIMS: [ # (str, {str: (ogn_str, value)}) ("PrimFloat2", {"float2Value": ("float[2]", [1.0, 2.0])}), # (str, {Sdf.Path: (sdf_str, value)}) (Sdf.Path("PrimFloat3"), {"float3Value": ("float3", [1.0, 2.0, 3.0])}), # (str, {str: (og.Type, value)}) ("PrimFloat4", {"float4Value": (og.Type(og.BaseDataType.FLOAT, 4, 0), [1.0, 2.0, 3.0, 4.0])}), # str "PrimWithNoAttributes", ] }, ) # Verify prims are created with the right attributes self.assertEqual(len(prims), 4) self.assertTrue(all(prim.IsValid() for prim in prims)) float2_attr = prims[0].GetAttribute("float2Value") self.assertTrue(float2_attr.IsValid()) self.assertEqual([1.0, 2.0], float2_attr.Get()) float3_attr = prims[1].GetAttribute("float3Value") self.assertTrue(float3_attr.IsValid()) self.assertEqual([1.0, 2.0, 3.0], float3_attr.Get()) float4_attr = prims[2].GetAttribute("float4Value") self.assertTrue(float4_attr.IsValid()) self.assertEqual([1.0, 2.0, 3.0, 4.0], float4_attr.Get()) # Test that non-string prim path fails with self.assertRaises(og.OmniGraphError): og.Controller.edit(graph, {controller.Keys.CREATE_PRIMS: [prims[0]]}) # Test that attempt to create prim in already existing location fails, with both absolute and relative paths with self.assertRaises(og.OmniGraphError): controller.edit(graph, {controller.Keys.CREATE_PRIMS: [("PrimFloat2", "Cube")]}) with self.assertRaises(og.OmniGraphError): controller.edit(graph, {controller.Keys.CREATE_PRIMS: [("/PrimFloat2", "Cube", {})]}) # Test that prims are forbidden from being created inside an OmniGraph with self.assertRaises(og.OmniGraphError): controller.edit(graph, {controller.Keys.CREATE_PRIMS: [("/PrimGraph/IllegalLocation", {})]}) # Test that non-string attribute name fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttribute", {None: None}), ] }, ) # Test that invalid attribute data type fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttributeData", {"complex": [1.0, 2.0]}), ] }, ) # Test that non-matching attribute data type fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttributeData", {"float": None}), ] }, ) # Test that invalid attribute data fails with self.assertRaises(og.OmniGraphError): controller.edit( graph, { controller.Keys.CREATE_PRIMS: [ ("PrimWithBadAttributeData", {"float": None}), ] }, ) # -------------------------------------------------------------------------------------------------------------- def __confirm_connection_counts(self, attribute: og.Attribute, upstream_count: int, downstream_count: int): """Check that the given attribute has the proscribed number of upstream and downstream connections""" self.assertEqual(attribute.get_upstream_connection_count(), upstream_count) self.assertEqual(attribute.get_downstream_connection_count(), downstream_count) # -------------------------------------------------------------------------------------------------------------- async def test_connections(self): """Test the various connection-related functions on the graph controller.""" # Use the main controller for testing as it derives from the graph controller controller = og.Controller() # Source --> Sink --> InOut # \ \ / # \ -----/ # --> FanOut # Command 1 (graph, nodes_created, _, _) = controller.edit( "/TestGraph", { controller.Keys.CREATE_NODES: [ ("Source", "omni.graph.tutorials.SimpleData"), ("Sink", "omni.graph.tutorials.SimpleData"), ("FanOut", "omni.graph.tutorials.SimpleData"), ("InOut", "omni.graph.tutorials.SimpleData"), ], controller.Keys.CONNECT: [ ("Source.outputs:a_bool", "Sink.inputs:a_bool"), (("outputs:a_bool", "Source"), ("inputs:a_bool", "FanOut")), ("Sink.inputs:a_bool", "InOut.inputs:a_bool"), ], }, ) (source_node, sink_node, fanout_node, inout_node) = nodes_created def _get_nodes(): return ( controller.node(("Source", graph)), controller.node(("Sink", graph)), controller.node(("FanOut", graph)), controller.node(("InOut", graph)), ) def _get_attributes(): return ( controller.attribute(("outputs:a_bool", source_node)), controller.attribute("inputs:a_bool", sink_node), controller.attribute(("inputs:a_bool", fanout_node)), controller.attribute("inputs:a_bool", inout_node), ) source_output, sink_input, fanout_input, inout_input = _get_attributes() # The sequence tests successful restoration when everything is deleted and restored in groups; # DisconnectAll(Source.outputs:a_bool) # Removes Source->Sink and Source->FanOut # DisconnectAll(Sink.inputs:a_bool) # Removes Sink->InOut # Delete Source, Sink, InOut, FanOut # undo deletes # undo second disconnect # Restores Sink->InOut # undo first disconnect # Restores Source->Sink and Source->FanOut # redo and undo to go the beginning and get back here again # DisconnectAll(Sink.inputs:a_bool) # Removes Sink->InOut and Source->Sink # undo # Command 2 controller.disconnect_all(("outputs:a_bool", source_node)) self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 1) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 1, 0) # Command 3 controller.disconnect_all(sink_input) self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 0) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 0, 0) # Command 4 controller.edit(graph, {controller.Keys.DELETE_NODES: [source_node, sink_node, fanout_node, inout_node]}) omni.kit.undo.undo() # Command 4 omni.kit.undo.undo() # Command 3 # May have lost the objects through the undo process so get them again (source_node, sink_node, fanout_node, inout_node) = _get_nodes() source_output, sink_input, fanout_input, inout_input = _get_attributes() self.__confirm_connection_counts(source_output, 0, 0) self.__confirm_connection_counts(sink_input, 0, 1) self.__confirm_connection_counts(fanout_input, 0, 0) self.__confirm_connection_counts(inout_input, 1, 0) omni.kit.undo.undo() # Command 2 self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) # Go back and forth in the undo queue to get back to having all objects and connections present omni.kit.undo.redo() # Command 2 omni.kit.undo.redo() # Command 3 omni.kit.undo.redo() # Command 4 omni.kit.undo.undo() # Command 4 omni.kit.undo.undo() # Command 3 omni.kit.undo.undo() # Command 2 # May have lost the objects through the undo process so get them again (source_node, sink_node, fanout_node, inout_node) = _get_nodes() source_output, sink_input, fanout_input, inout_input = _get_attributes() self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) # Direct calls are okay when the attribute is fully specified # Command 5 og.Controller.disconnect_all(sink_input) self.__confirm_connection_counts(source_output, 0, 1) self.__confirm_connection_counts(sink_input, 0, 0) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 0, 0) omni.kit.undo.undo() # Command 5 self.__confirm_connection_counts(source_output, 0, 2) self.__confirm_connection_counts(sink_input, 1, 1) self.__confirm_connection_counts(fanout_input, 1, 0) self.__confirm_connection_counts(inout_input, 1, 0) # -------------------------------------------------------------------------------------------------------------- async def test_prim_exposure(self): """Test the controller's ability to expose USD prims to OmniGraph. def expose_prim(cls, exposure_type: PrimExposureType, prim_id: Prim_t, node_path_id: NewNode_t) -> Union[og.Node, List[og.Node]]: The test proceeds by first creating a few prims and then exposing them to OmniGraph, confirming that the OmniGraph nodes do in fact get the correct values from their underlying prims. """ controller = og.Controller() exposure_types = og.GraphController.PrimExposureType (graph, _, _, path_to_object_map,) = controller.edit( "/PrimGraph", { _KEYS.CREATE_PRIMS: [ ("PrimFloat2", {"float2Value": ("float[2]", [1.0, 2.0])}), ("Cube", "Cube"), ("PrimVelocity", {"velocity": ("float[3]", [1.0, 2.0, 3.0])}, "Velocity"), ("Prim1"), ("Prim2"), ("Prim3"), ("PrimPosition", {"position": ("pointf[3]", [1.0, 2.0, 3.0])}, "Position"), ] }, ) # Test exposure of a prim as a bundle (_, exposed_nodes, _, _) = og.Controller.edit( graph, { _KEYS.EXPOSE_PRIMS: (exposure_types.AS_BUNDLE, "PrimFloat2", "ExposedAsBundle"), }, path_to_object_map, ) await controller.evaluate(graph) self.assertEqual(len(exposed_nodes), 1, "Exposed a simple prim by bundle") self.assertTrue("ExposedAsBundle" in path_to_object_map) self.assertEqual(exposed_nodes[0].get_prim_path(), "/PrimGraph/ExposedAsBundle") self.assertEqual(exposed_nodes[0].get_type_name(), "omni.graph.nodes.ExtractPrim") (_, inspector_nodes, _, _) = controller.edit( graph, { _KEYS.CREATE_NODES: ("Inspector", "omni.graph.nodes.BundleInspector"), _KEYS.CONNECT: ("ExposedAsBundle.outputs_primBundle", "Inspector.inputs:bundle"), }, ) await controller.evaluate(graph) # float2Value is in the exposed bundle inspector_node = inspector_nodes[0] bundle_names = og.Controller.get(controller.attribute("outputs:names", inspector_node)) index = bundle_names.index("float2Value") self.assertTrue(index >= 0) # The value of that attribute is [1.0, 2.0] try: bundle_values = og.Controller.get(controller.attribute("outputs:values", inspector_node)) # This weird thing is necessary because the tuple values are not JSON-compatible tuple_to_list = json.loads(bundle_values[index].replace("(", "[").replace(")", "]")) self.assertCountEqual(tuple_to_list, [1.0, 2.0]) except AssertionError as error: carb.log_warn(f"ReadBundle node can't get the bundle to the inspector - {error}") # Test exposure of a prim as attributes (_, exposed_nodes, _, _) = og.Controller.edit( graph, { _KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "PrimVelocity", "ExposedAsAttribute"), }, path_to_object_map, ) await controller.evaluate(graph) self.assertEqual(len(exposed_nodes), 1, "Exposed a simple prim by attribute") self.assertTrue("ExposedAsAttribute" in path_to_object_map) self.assertEqual(exposed_nodes[0].get_prim_path(), "/PrimGraph/ExposedAsAttribute") self.assertEqual(exposed_nodes[0].get_type_name(), "omni.graph.nodes.ReadPrimAttributes") # in order to read data, the attribute needs to be connected, and an eval must be done (graph, _, _, _) = og.Controller.edit( graph, { _KEYS.CREATE_NODES: [ ("Const", "omni.graph.nodes.ConstantFloat3"), ], }, ) # we need to evaluate for dynamic attributes to appear on ExtractPrim2 await controller.evaluate(graph) # after attributes appeared on ExtractBundle2 we can connect them (graph, _, _, _) = og.Controller.edit( graph, { _KEYS.CONNECT: ("/PrimGraph/ExposedAsAttribute.outputs:velocity", "/PrimGraph/Const.inputs:value"), }, ) await controller.evaluate(graph) self.assertCountEqual( [1.0, 2.0, 3.0], og.Controller.get(controller.attribute(("outputs:velocity", exposed_nodes[0]))) ) # Test exposure of a list of prims (_, exposed_nodes, _, _) = og.Controller.edit( graph, { _KEYS.EXPOSE_PRIMS: [ (exposure_types.AS_ATTRIBUTES, "Prim1", "Exposed1"), (exposure_types.AS_ATTRIBUTES, "Prim2", "Exposed2"), (exposure_types.AS_ATTRIBUTES, "Prim3", "Exposed3"), ] }, path_to_object_map, ) await controller.evaluate(graph) self.assertEqual(len(exposed_nodes), 3, "Exposed a list of prims by attribute") for index in range(3): self.assertTrue(f"Exposed{index + 1}" in path_to_object_map) self.assertEqual(exposed_nodes[index].get_prim_path(), f"/PrimGraph/Exposed{index + 1}") self.assertEqual(exposed_nodes[index].get_type_name(), "omni.graph.nodes.ReadPrimAttributes") # Test exposure as write (_, exposed_nodes, _, _) = controller.edit( graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_WRITABLE, "PrimPosition", "ExposedWritable")} ) await controller.evaluate(graph) write_node = exposed_nodes[0] self.assertEqual(len(exposed_nodes), 1, "Exposed a simple writable prim") self.assertTrue("ExposedWritable" in path_to_object_map) self.assertEqual(write_node.get_prim_path(), "/PrimGraph/ExposedWritable") self.assertEqual(write_node.get_type_name(), "omni.graph.nodes.WritePrim") # Check we have the expected dynamic attrib on WritePrim attribs = write_node.get_attributes() found_size_attrib = False for attrib in attribs: if attrib.get_name() == "inputs:position" and attrib.get_resolved_type().get_ogn_type_name() == "pointf[3]": found_size_attrib = True self.assertTrue(found_size_attrib) # Test invalid attempt to expose non-existent prim with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "NotAPrim", "NotANode")}) # Test invalid attempt to expose prim on node path that's not in a graph with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "Cube", "/NotANode")}) # Test invalid attempt to expose prim on an already existing node with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.EXPOSE_PRIMS: (exposure_types.AS_ATTRIBUTES, "Cube", "Exposed1")}) # -------------------------------------------------------------------------------------------------------------- async def test_set_values(self): """Test the controller's ability to set values on nodes. def set(AttributeValues_t) """ controller = og.Controller() (graph, (node1, _, _, add_node), _, _) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: [ ("Node1", "omni.graph.tutorials.SimpleData"), ("Node2", "omni.graph.tutorials.SimpleData"), ("Node3", "omni.graph.tutorials.SimpleData"), ("AddNode", "omni.graph.nodes.Add"), ], }, ) # Test setting of a regular attribute value controller.edit(graph, {_KEYS.SET_VALUES: [("Node1.inputs:a_float", 17.0)]}) await controller.evaluate(graph) # Exercise the controller version that takes an attribute (passing it up to the DataView) data_controller = og.Controller(attribute="/TestGraph/Node1.outputs:a_float") self.assertEqual(18.0, data_controller.get()) # Test setting of an extended attribute value with a resolution type controller.edit( graph, { _KEYS.SET_VALUES: [ (("inputs:a", add_node), og.TypedValue(17.0, "float")), ("AddNode.inputs:b", og.TypedValue(51.0, "float")), ] }, ) await controller.evaluate(graph) # Until type resolution works when values are set as well as connections are made this cannot check the output self.assertEqual(17.0, og.DataView.get(og.ObjectLookup.attribute(("inputs:a", add_node)))) # Test setting of multiple attributes in one shot controller.edit( graph, { _KEYS.SET_VALUES: [ ("Node1.inputs:a_float", 42.0), ("Node1.inputs:a_double", 23.0), ] }, ) await controller.evaluate(graph) self.assertEqual(43.0, og.DataView.get(og.ObjectLookup.attribute(("outputs:a_float", node1)))) self.assertEqual(24.0, og.Controller.get("/TestGraph/Node1.outputs:a_double")) # Test invalid attempt to set non-existent attribute with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.SET_VALUES: ("Node1.inputs:a_not_there", 5.0)}) # Test invalid attempt to set extended attribute with non-existent type with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.SET_VALUES: (("inputs:a", add_node), 17.0, "not_a_type")}) # -------------------------------------------------------------------------------------------------------------- async def test_variables(self): """Test variable methods via the og.Controller class def get_variable_default_value(cls, variable_id: Variable_t): def set_variable_default_value(cls, variable_id: Variable_t, value): """ controller = og.Controller() (graph, _, _, _) = controller.edit( "/TestGraph", { _KEYS.CREATE_VARIABLES: [ ("Variable_1", og.Type(og.BaseDataType.FLOAT)), ("Variable_2", og.Type(og.BaseDataType.INT)), ], }, ) variable_1_id = graph.find_variable("Variable_1") og.Controller.set_variable_default_value(variable_1_id, 5) self.assertEqual(og.Controller.get_variable_default_value(variable_1_id), 5) variable_2_id = (graph, "Variable_2") og.Controller.set_variable_default_value(variable_2_id, 6) self.assertEqual(og.Controller.get_variable_default_value(variable_2_id), 6) with self.assertRaises(og.OmniGraphError): og.Controller.set_variable_default_value(variable_1_id, "Not a float") with self.assertRaises(og.OmniGraphError): og.Controller.get_variable_default_value((graph, "InvalidVariable")) with self.assertRaises(og.OmniGraphError): og.Controller.set_variable_default_value((graph, "InvalidVariable"), 5) with self.assertRaises(og.OmniGraphError): og.Controller.get_variable_default_value(None) # -------------------------------------------------------------------------------------------------------------- async def test_compound_subgraph_graph_population(self): """Test graph population when using compound subgraphs""" controller = og.Controller() simple_node_type = "omni.graph.tutorials.SimpleData" (graph, nodes, _, _path_node_map) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: [ ( "Compound_1", {_KEYS.CREATE_NODES: [("Compound_1_1", simple_node_type), ("Compound_1_2", simple_node_type)]}, ), ( "Compound_2", { _KEYS.CREATE_NODES: [ ( "Compound_2_1", { _KEYS.CREATE_NODES: [ ("Compound_2_1_1", simple_node_type), ("Compound_2_1_2", simple_node_type), ] }, ) ] }, ), ] }, ) # test graph level self.assertTrue(graph.is_valid()) self.assertEqual(2, len(nodes), "Expected 2 nodes create in graph") self.assertTrue(nodes[0].is_compound_node()) self.assertTrue(nodes[1].is_compound_node()) # test sublevels are constructed correctly compound_1_graph = nodes[0].get_compound_graph_instance() self.assertTrue(compound_1_graph.is_valid()) compound_1_graph_nodes = compound_1_graph.get_nodes() self.assertEqual(2, len(compound_1_graph_nodes)) self.assertEqual(compound_1_graph_nodes[0].get_node_type().get_node_type(), simple_node_type) self.assertEqual(compound_1_graph_nodes[1].get_node_type().get_node_type(), simple_node_type) compound_2_graph = nodes[1].get_compound_graph_instance() self.assertTrue(compound_2_graph.is_valid()) compound_2_graph_nodes = compound_2_graph.get_nodes() self.assertEqual(1, len(compound_2_graph_nodes)) compound_2_1_graph = compound_2_graph_nodes[0].get_compound_graph_instance() self.assertTrue(compound_2_1_graph.is_valid()) compound_2_1_graph_nodes = compound_2_1_graph.get_nodes() self.assertEquals(2, len(compound_2_1_graph_nodes)) self.assertEqual(compound_2_1_graph_nodes[0].get_node_type().get_node_type(), simple_node_type) self.assertEqual(compound_2_1_graph_nodes[1].get_node_type().get_node_type(), simple_node_type) # try to create a node with the same name in the subgraph. All node names must be unique with self.assertRaises(og.OmniGraphError): controller.edit("/TestGraph", {_KEYS.CREATE_NODES: ("Compound_1_1", simple_node_type)}) # node with the same name on a subgraph as the parent with self.assertRaises(og.OmniGraphError): controller.edit( nodes[0].get_compound_graph_instance(), {_KEYS.CREATE_NODES: ("Compound_1", simple_node_type)} ) # allowed with a new controller though og.Controller.edit( nodes[0].get_compound_graph_instance(), {_KEYS.CREATE_NODES: ("Compound_1", simple_node_type)} ) self.assertTrue(compound_1_graph.get_node(f"{compound_1_graph.get_path_to_graph()}/Compound_1").is_valid()) # create another graph that uses the class lookup (og.Controller) instead of an object (_graph2, nodes2, _, path_node_map2) = og.Controller.edit( "/TestGraph2", { _KEYS.CREATE_NODES: [ ("Compound_1", {_KEYS.CREATE_NODES: ("Compound_1_1", simple_node_type)}), ] }, ) self.assertTrue(nodes2[0].is_valid()) self.assertTrue(nodes2[0].is_compound_node()) self.assertTrue(path_node_map2["Compound_1_1"].is_valid()) self.assertFalse(path_node_map2["Compound_1_1"].is_compound_node()) # -------------------------------------------------------------------------------------------------------------- async def test_attribute_promotion(self): """Tests the functionality of promoting attributes using the Controller._KEYS.PROMOTE_ATTRIBUTES command and the NodeController.promote_attribute() method""" controller = og.Controller(update_usd=True, undoable=True) simple_node_type = "omni.graph.tutorials.SimpleData" # graph with a subgraphs (graph, (compound, _non_compound), _, path_node_map) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: [ ( "Compound_1", { _KEYS.CREATE_NODES: [ ("Compound_1_1", simple_node_type), ("Compound_1_2", simple_node_type), ( "Compound_1_3", { _KEYS.CREATE_NODES: [ ("Compound_1_3_1", simple_node_type), ] }, ), ] }, ), ("NonCompound", simple_node_type), ] }, ) # cannot promote on the top-level graph with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("NonCompound.inputs:a_int", "inputs:a_int")}) subgraph = compound.get_compound_graph_instance() # promote basic inputs, using both the graph and subgraph controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_int", "inputs:a_int")}) controller.edit(subgraph, {_KEYS.PROMOTE_ATTRIBUTES: [("Compound_1_2.outputs:a_int", "outputs:a_int")]}) self.assertTrue(compound.get_attribute_exists("inputs:a_int")) self.assertTrue(compound.get_attribute_exists("outputs:a_int")) # inputs already connected should fail. with ogts.ExpectedError(): with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_int", "inputs:a_int_2")}) # output already connected should pass controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_2.outputs:a_int", "outputs:a_int_2")}) self.assertTrue(compound.get_attribute_exists("outputs:a_int_2")) # input already exists with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_2.inputs:a_int", "inputs:a_int")}) # output already exists with self.assertRaises(og.OmniGraphError): controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.outputs:a_int", "outputs:a_int")}) # input can be promoted as output controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_bool", "outputs:a_bool")}) # output cannot be promoted as input controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.outputs:a_bool", "inputs:a_bool_2")}) self.assertTrue(compound.get_attribute_exists("outputs:inputs:a_bool_2")) # promoted name without prefix, the prefix is automatically added controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.inputs:a_float", "a_float")}) controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_1.outputs:a_float", "a_float")}) self.assertTrue(compound.get_attribute_exists("inputs:a_float")) self.assertTrue(compound.get_attribute_exists("outputs:a_float")) # validate output only inputs promote as outputs controller.edit(subgraph, {_KEYS.CREATE_NODES: ("Compound_1_4", "omni.graph.nodes.ConstantDouble")}) controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_4.inputs:value", "constant")}) self.assertTrue(compound.get_attribute_exists("outputs:constant")) # similar tests but using the NodeController API directly compound_1_1_node = path_node_map["Compound_1_1"] compound_1_2_node = path_node_map["Compound_1_2"] og.NodeController.promote_attribute(og.Controller.attribute("inputs:a_half", compound_1_1_node), "a_half") og.NodeController.promote_attribute(og.Controller.attribute("outputs:a_half", compound_1_2_node), "a_half") self.assertTrue(compound.get_attribute_exists("inputs:a_half")) self.assertTrue(compound.get_attribute_exists("outputs:a_half")) # already exists with self.assertRaises(og.OmniGraphError): og.NodeController.promote_attribute(og.Controller.attribute("inputs:a_double", compound_1_1_node), "a_half") with self.assertRaises(og.OmniGraphError): og.NodeController.promote_attribute( og.Controller.attribute("outputs:a_double", compound_1_1_node), "a_half" ) # promote attributes on a nested recursion level controller.edit(graph, {_KEYS.PROMOTE_ATTRIBUTES: ("Compound_1_3_1.inputs:a_int", "inputs:value")}) self.assertTrue(path_node_map["Compound_1_3"].get_attribute_exists("inputs:value")) # ---------------------------------------------------------------------- async def test_attribute_creation(self): """Test attribute creation via the og.Controller class""" controller = og.Controller(undoable=False) (graph, (node,), _, _) = controller.edit( "/TestGraph", { _KEYS.CREATE_NODES: ("TestNode", "omni.graph.test.TestDynamicAttributeRawData"), _KEYS.CREATE_ATTRIBUTES: [ ("TestNode.inputs:a_float", "float"), ], }, ) self.assertTrue(node.is_valid()) a_float = node.get_attribute("inputs:a_float") self.assertTrue(a_float.is_valid()) base_attribute_count = len(node.get_attributes()) # A scattered assortment of spec combinations that covers all of the types accepted by the command test_configs = [ ("a_double", "/TestGraph/TestNode.inputs:a_double", "double"), ("a_any", Sdf.Path("/TestGraph/TestNode.inputs:a_any"), "any"), ("a_real", ("inputs:a_real", node), ["float", "double"]), ("a_numbers", (("a_numbers", og.AttributePortType.INPUT), node), ["numerics"]), ("a_bundle", ("inputs:a_bundle", "TestNode", graph), "bundle"), ("a_mesh", (("a_mesh", og.AttributePortType.INPUT), "TestNode", graph), "pointd[3][]"), ] for attr_name, attr_spec, attr_type in test_configs: controller.edit(graph, {_KEYS.CREATE_ATTRIBUTES: (attr_spec, attr_type)}) attr = node.get_attribute(f"inputs:{attr_name}") self.assertTrue(attr.is_valid()) self.assertEqual(base_attribute_count + len(test_configs), len(node.get_attributes())) # AttributeTypeSpec_t = str | og.Type | list[str] # """Typing that identifies a regular or extended type definition # 1. "any" # 2. og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.VECTOR) # 3. ["float", "integral_scalers"] # """ # NewAttribute_t = Path_t | tuple[AttributeName_t, Node_t] | tuple[AttributeName_t, str, Graph_t] # """Typing for the information required to uniquely identify an attribute that does not yet exist # 1a. "/MyGraph/MyNode/inputs:new_attr" # 1b. Sdf.Path("/MyGraph/MyNode/inputs:new_attr") # 2a. ("inputs:new_attr", og.Controller.node("/MyGraph/MyNode")) # 2b. (("new_attr", og.AttributePortType.INPUT), og.Controller.node("/MyGraph/MyNode")) # 3a. ("inputs:new_attr", "MyNode", og.Controller.graph("/MyGraph")) # 3b. (("new_attr", og.AttributePortType.INPUT), "MyNode", og.Controller.graph("/MyGraph")) # """
46,319
Python
46.556468
120
0.549299
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_math_nodes.py
"""Test the math nodes""" import math import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts # ====================================================================== class TestMathNodes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def test_add_node_simple(self): """Test the add node for a variety of simple types""" controller = og.Controller() keys = og.Controller.Keys (graph, (simple_node_a, simple_node_b, simple_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ("SimpleSum", "omni.graph.tutorials.SimpleData"), ("Add", "omni.graph.nodes.Add"), ] }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (ATTRIBUTE, A, B, SUM): # ATTRIBUTE: the name of the attribute to be connected from the "Simple" nodes to resolve the data types # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the simple nodes add 1 to inputs to get outputs SUM != A + B) test_data = [ ["a_float", 5.25, 6.25, 13.5], ["a_double", 5.125, 6.125, 13.25], ["a_half", 5.0, 6.0, 13.0], ["a_int", 6, 7, 15], ["a_int64", 8, 9, 19], ["unsigned:a_uchar", 10, 11, 23], ["unsigned:a_uint", 12, 13, 27], ["unsigned:a_uint64", 14, 15, 31], ] for (attribute_name, a, b, expected) in test_data: connection_list = [ ((f"outputs:{attribute_name}", simple_node_a), input_a), ((f"outputs:{attribute_name}", simple_node_b), input_b), (output_sum, (f"inputs:{attribute_name}", simple_node_sum)), ] controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: connection_list, keys.SET_VALUES: [ ((f"inputs:{attribute_name}", simple_node_a), a), ((f"inputs:{attribute_name}", simple_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertAlmostEqual(expected, actual) # Disconnecting the connections we just made lets the loop work controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connection_list}) # ---------------------------------------------------------------------- async def test_add_node_mismatched(self): """Test the add node for simple types that have compatible but not identical types""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, _, _, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ("SimpleSum", "omni.graph.tutorials.SimpleData"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("SimpleA.outputs:a_double", "Add.inputs:a"), ("SimpleB.outputs:a_int", "Add.inputs:b"), ("Add.outputs:sum", "SimpleSum.inputs:a_float"), ], keys.SET_VALUES: [ ("SimpleA.inputs:a_double", 5.5), ("SimpleB.inputs:a_int", 11), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(controller.attribute("outputs:sum", add_node)) self.assertAlmostEqual(18.5, actual) # ---------------------------------------------------------------------- async def test_add_node_tuples(self): """Test the add node for a variety of tuple types""" controller = og.Controller() keys = og.Controller.Keys (graph, (tuple_node_a, tuple_node_b, tuple_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("TupleA", "omni.tutorials.TupleData"), ("TupleB", "omni.tutorials.TupleData"), ("TupleSum", "omni.tutorials.TupleData"), ("Add", "omni.graph.nodes.Add"), ] }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (ATTRIBUTE, A, B, SUM): # ATTRIBUTE: the name of the attribute to be connected from the "Tuple" nodes to resolve the data types # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the tuple nodes add 1 to input elements to get outputs SUM != A + B) test_data = [ ["a_double2", (20.0, 30.0), (20.1, 30.1), (42.1, 62.1)], ["a_float2", (2.0, 3.0), (2.1, 3.1), (6.1, 8.1)], ["a_half2", (1.0, 2.0), (3.0, 4.0), (6.0, 8.0)], ["a_int2", (16, -5), (22, 5), (40, 2)], ["a_float3", (1.1, 2.2, 3.3), (2.2, 3.3, 4.4), (5.3, 7.5, 9.7)], ["a_double3", (10.1, 20.2, 30.3), (20.2, 30.3, 40.4), (32.3, 52.5, 72.7)], ] for (attribute_name, a, b, expected) in test_data: connection_list = [ ((f"outputs:{attribute_name}", tuple_node_a), input_a), ((f"outputs:{attribute_name}", tuple_node_b), input_b), (output_sum, (f"inputs:{attribute_name}", tuple_node_sum)), ] controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: connection_list, keys.SET_VALUES: [ ((f"inputs:{attribute_name}", tuple_node_a), a), ((f"inputs:{attribute_name}", tuple_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertTrue(np.allclose(expected, actual), f"{expected} != {actual}") # Disconnecting the connections we just made lets the loop work controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connection_list}) # ---------------------------------------------------------------------- async def test_add_node_arrays(self): """Test the add node for a variety of array types""" controller = og.Controller() keys = og.Controller.Keys (graph, (array_node_a, array_node_b, array_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ArrayA", "omni.graph.tutorials.ArrayData"), ("ArrayB", "omni.graph.tutorials.ArrayData"), ("ArraySum", "omni.graph.tutorials.ArrayData"), ("Add", "omni.graph.nodes.Add"), ], keys.SET_VALUES: [ # Set the array nodes up to double the values ("ArrayA.inputs:multiplier", 2.0), ("ArrayB.inputs:multiplier", 2.0), ], }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (A, B, SUM): # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the array nodes add 1 to input elements to get outputs SUM != A + B) test_data = [ [[20.0, 30.0], [20.1, 30.1], [80.2, 120.2]], [[1.0, 2.0, 3.0, 4.0], [-1.0, -2.0, -3.0, -4.0], [0.0, 0.0, 0.0, 0.0]], ] for (a, b, expected) in test_data: controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [ (("outputs:result", array_node_a), input_a), (("outputs:result", array_node_b), input_b), (output_sum, ("inputs:original", array_node_sum)), ], keys.SET_VALUES: [ (("inputs:gates", array_node_a), [True] * len(a)), (("inputs:gates", array_node_b), [True] * len(b)), (("inputs:original", array_node_a), a), (("inputs:original", array_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertTrue(np.allclose(expected, actual), f"{expected} != {actual}") # ---------------------------------------------------------------------- async def test_add_node_tuple_arrays(self): """Test the add node for array-of-tuple types""" controller = og.Controller() keys = og.Controller.Keys (graph, (tuple_array_node_a, tuple_array_node_b, tuple_array_node_sum, add_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("TupleArrayA", "omni.graph.test.TupleArrays"), ("TupleArrayB", "omni.graph.test.TupleArrays"), ("TupleArraySum", "omni.graph.test.TupleArrays"), ("Add", "omni.graph.nodes.Add"), ], keys.SET_VALUES: [ # Set the array nodes up to double the values ("TupleArrayA.inputs:multiplier", 2.0), ("TupleArrayB.inputs:multiplier", 2.0), ], }, ) input_a = add_node.get_attribute("inputs:a") input_b = add_node.get_attribute("inputs:b") output_sum = add_node.get_attribute("outputs:sum") # Test data is a list of lists, one per test configuration, containing (A, B, SUM): # A: First value to add # B: Second value to add # SUM: Expected sum # (Note that since the array nodes add 1 to input elements to get outputs SUM != A + B) test_data = [ [ [[1.0, 2.0, 3.0], [1.1, 2.2, 3.3]], [[10.0, 20.0, 30.0], [11.0, 22.0, 33.0]], [[22.0, 44.0, 66.0], [24.2, 48.4, 72.6]], ], ] for (a, b, expected) in test_data: controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [ (("outputs:float3Array", tuple_array_node_a), input_a), (("outputs:float3Array", tuple_array_node_b), input_b), (output_sum, ("inputs:float3Array", tuple_array_node_sum)), ], keys.SET_VALUES: [ (("inputs:float3Array", tuple_array_node_a), a), (("inputs:float3Array", tuple_array_node_b), b), ], }, ) await controller.evaluate(graph) actual = og.Controller.get(output_sum) self.assertTrue(np.allclose(expected, actual), f"{expected} != {actual}") # ---------------------------------------------------------------------- async def test_add_all_types(self): """Test the OgnAdd node with all types""" node_name = "omni.graph.nodes.Add" # Input attributes to be resolved input_attribute_names = ["inputs:a", "inputs:b"] # Output attributes to be tested output_attribute_names = ["outputs:sum"] # list of unsupported types unsupported_types = ["string", "token", "path", "bool", "uint64", "bundle", "target"] # Operation giving the expected value operation = np.add # ---------------------------------------------------------- controller = og.Controller() keys = og.Controller.Keys (graph, (test_node, data_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [("TestNode", node_name), ("TestData", "omni.graph.test.TestAllDataTypes")]}, ) # Generate Test data consisting of the input attribute followed by the expected output values test_data = [] for attribute in data_node.get_attributes(): type_base_name = attribute.get_resolved_type().get_base_type_name() if ( "output" not in attribute.get_name() or type_base_name in unsupported_types or attribute.get_type_name() in unsupported_types or attribute.get_resolved_type().role == og.AttributeRole.EXECUTION ): continue value = og.Controller.get(attribute) test_data.append([attribute, operation(value, value)]) input_attributes = [test_node.get_attribute(input_attribute) for input_attribute in input_attribute_names] output_attributes = [test_node.get_attribute(output_attribute) for output_attribute in output_attribute_names] for data_attribute, expected_value in test_data: connections = [(data_attribute, input_attribute) for input_attribute in input_attributes] controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: connections}) await controller.evaluate(graph) # Check outputs for output_attribute in output_attributes: actual_value = og.Controller.get(output_attribute) self.assertTrue(np.allclose(expected_value, actual_value), f"{expected_value} != {actual_value}") controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connections}) # ---------------------------------------------------------------------- async def test_multiply_all_types(self): """Test the OgnMultiply node with all types""" node_name = "omni.graph.nodes.Multiply" # Input attributes to be resolved input_attribute_names = ["inputs:a", "inputs:b"] # Output attributes to be tested output_attribute_names = ["outputs:product"] # list of unsupported types unsupported_types = ["string", "token", "path", "bool", "uint64", "bundle", "target"] # Operation giving the expected value operation = np.multiply # ---------------------------------------------------------- controller = og.Controller() keys = og.Controller.Keys (graph, (test_node, data_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [("TestNode", node_name), ("DataNode", "omni.graph.test.TestAllDataTypes")]}, ) # Generate Test data consisting of the input attribute followed by the expected output values test_data = [] for attribute in data_node.get_attributes(): type_base_name = attribute.get_resolved_type().get_base_type_name() if ( "output" not in attribute.get_name() or type_base_name in unsupported_types or attribute.get_type_name() in unsupported_types or attribute.get_resolved_type().role == og.AttributeRole.EXECUTION ): continue value = og.Controller.get(attribute) test_data.append([attribute, operation(value, value)]) input_attributes = [test_node.get_attribute(input_attribute) for input_attribute in input_attribute_names] output_attributes = [test_node.get_attribute(output_attribute) for output_attribute in output_attribute_names] for data_attribute, expected_value in test_data: connections = [(data_attribute, input_attribute) for input_attribute in input_attributes] controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: connections}) await controller.evaluate(graph) # Check outputs for output_attribute in output_attributes: actual_value = og.Controller.get(output_attribute) self.assertTrue(np.allclose(expected_value, actual_value), f"{expected_value} != {actual_value}") controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: connections}) # ---------------------------------------------------------------------- async def test_constant_pi_node(self): """Test the constant pi node""" controller = og.Controller() keys = og.Controller.Keys() (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [("constPi", "omni.graph.nodes.ConstantPi")]} ) result = nodes[0].get_attribute("outputs:value") setter = og.Controller(attribute=og.Controller.attribute("inputs:factor", nodes[0])) getter = og.Controller(attribute=result) # Test data is a list, one per test configuration, containing (A, SUM): # A: Multiply this by Pi to get the result # SUM: Expected value test_data = [ [1.0, math.pi], [2.0, 2.0 * math.pi], [0.5, 0.5 * math.pi], ] for (multiplier, expected) in test_data: setter.set(multiplier) await og.Controller.evaluate(graph) self.assertAlmostEqual(expected, getter.get()) # --------------------------------------------------------------------- async def test_nth_root_node(self): """Test the nthroot node""" controller = og.Controller() keys = og.Controller.Keys() (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("nthRoot", "omni.graph.nodes.NthRoot"), ("src", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [("src.inputs:value", "nthRoot.inputs:value")], }, ) result = nodes[0].get_attribute("outputs:result") value_setter = og.Controller(attribute=og.Controller.attribute("inputs:value", nodes[1])) nth_root_setter = og.Controller(attribute=og.Controller.attribute("inputs:nthRoot", nodes[0])) getter = og.Controller(attribute=result) # Test data is a list, one per test configuration, containing (nthroot, value): # nthroot: Take the nthroot of the value # value: The number that is to be taken roots test_data = [[2, -4], [4, -8.0], [5, -1]] for (nthroot, value) in test_data: nth_root_setter.set(nthroot) value_setter.set(value) await og.Controller.evaluate(graph) self.assertTrue(np.isnan(getter.get())) test_data = [[3, -8.0, -2], [3, -1, -1]] for (nthroot, value, expected) in test_data: nth_root_setter.set(nthroot) value_setter.set(value) await og.Controller.evaluate(graph) self.assertEqual(expected, getter.get()) # ---------------------------------------------------------------------- async def test_floor_node_backwards_compatibility(self): """Test the floor node extended outputs for backwards compatibility""" # Test data contains floor nodes with int output, instead of token (result, error) = await ogts.load_test_file("TestFloorOutput.usda", use_caller_subdirectory=True) self.assertTrue(result, f"{error}") controller = og.Controller() graph = controller.graph("/World/TestGraph") def assert_attr_is_int(node): attr = controller.attribute("outputs:result", node, graph) self.assertEqual(attr.get_resolved_type().base_type, og.BaseDataType.INT) assert_attr_is_int("floor_double") assert_attr_is_int("floor_float") assert_attr_is_int("floor_half")
20,905
Python
44.947253
118
0.510261
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_extended_attributes.py
# noqa PLC0302 """Tests that exercise the functionality of the extended (union and any) attribute types""" import os import tempfile from typing import List, Optional import carb import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.app import omni.kit.stage_templates import omni.kit.test import omni.usd from pxr import Gf, Sdf, UsdGeom, Vt # ====================================================================== class TestExtendedAttributes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def test_output_type_resolution(self): """Test the automatic type resolution for extended types based on output connection types""" controller = og.Controller() keys = og.Controller.Keys # Node is by itself, union attributes have no type (use Attribute.getTypeName to check) (graph, (extended_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("ExtendedNode", "omni.graph.test.TypeResolution")} ) value_output = "outputs:value" array_output = "outputs:arrayValue" tuple_output = "outputs:tupleValue" tuple_array_output = "outputs:tupleArrayValue" mixed_output = "outputs:mixedValue" any_output = "outputs:anyValue" resolved_type = controller.attribute("outputs:resolvedType", extended_node) value = controller.attribute(value_output, extended_node) array_value = controller.attribute(array_output, extended_node) tuple_value = controller.attribute(tuple_output, extended_node) tuple_array_value = controller.attribute(tuple_array_output, extended_node) mixed_value = controller.attribute(mixed_output, extended_node) any_value = controller.attribute(any_output, extended_node) await controller.evaluate(graph) def result(): return og.Controller.get(resolved_type) def expected( value_type: Optional[str] = None, array_type: Optional[str] = None, tuple_type: Optional[str] = None, tuple_array_type: Optional[str] = None, mixed_type: Optional[str] = None, any_type: Optional[str] = None, ) -> List[str]: """Return an expected output array for the given resolved types (None means unresolved)""" return [ f"{value_output},{value_type if value_type else 'unknown'}", f"{array_output},{array_type if array_type else 'unknown'}", f"{tuple_output},{tuple_type if tuple_type else 'unknown'}", f"{tuple_array_output},{tuple_array_type if tuple_array_type else 'unknown'}", f"{mixed_output},{mixed_type if mixed_type else 'unknown'}", f"{any_output},{any_type if any_type else 'unknown'}", ] default_expected = expected() default_actual = result() self.assertEqual(len(default_expected), len(default_actual)) self.assertCountEqual(default_expected, default_actual) # Node has float/token output connected to a float input - type should be float controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Simple", "omni.graph.tutorials.SimpleData"), keys.CONNECT: (value, "Simple.inputs:a_float"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("float"), result()) # Node disconnects, then connects the same output to an int input - type should be int controller.edit( self.TEST_GRAPH_PATH, { keys.DISCONNECT: (value, "Simple.inputs:a_float"), }, ) controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: (value, "Simple.inputs:a_int"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("int"), result()) # Node totally disconnects - type should be reverted to unknown controller.edit( self.TEST_GRAPH_PATH, { keys.DISCONNECT: (value, "Simple.inputs:a_int"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected(), result()) # Adding array type connection controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Array", "omni.graph.tutorials.ArrayData"), keys.CONNECT: (array_value, "Array.inputs:original"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("unknown", "float[]"), result()) # Adding tuple, tupleArray, and mixed type connections controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Tuple", "omni.tutorials.TupleData"), ("TupleArray", "omni.graph.tutorials.TupleArrays"), ], keys.CONNECT: [ (tuple_value, "Tuple.inputs:a_float3"), (tuple_array_value, "TupleArray.inputs:a"), (mixed_value, "Array.inputs:original"), ], }, ) await controller.evaluate(graph) self.assertCountEqual(expected("unknown", "float[]", "float[3]", "float[3][]", "float[]"), result()) # Adding anyValue connection, check type controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: (any_value, "Simple.inputs:a_float"), }, ) await controller.evaluate(graph) self.assertCountEqual(expected("unknown", "float[]", "float[3]", "float[3][]", "float[]", "float"), result()) # Now test the type-resolution cascade for a linear chain of any-type connections (_, (extended_node_a, extended_node_b, extended_node_c), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("ExtendedNodeC", "omni.graph.test.TypeResolution"), ], keys.CONNECT: [ ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeB.inputs:anyValueIn"), ("ExtendedNodeB.outputs:anyValue", "ExtendedNodeC.inputs:anyValueIn"), ], }, ) await controller.evaluate(graph) node_a_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_a)) node_b_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_b)) node_c_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_c)) resolved_types = node_c_controller.get() self.assertCountEqual(expected(), resolved_types) # connect a concrete type to the start of the chain and verify it cascades to the last output controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: ("Simple.outputs:a_double", "ExtendedNodeA.inputs:anyValueIn"), }, ) await controller.evaluate(graph) resolved_types = node_a_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_b_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_c_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) # remove the concrete connection and verify it cascades unresolved to the last output # FIXME: Auto-unresolve is not supported yet # controller.edit(self.TEST_GRAPH_PATH, { # keys.DISCONNECT: ("Simple.outputs:a_double", "ExtendedNodeA.inputs:anyValueIn"), # }) # await controller.evaluate(graph) # # resolved_types = node_a_controller.get() # self.assertCountEqual(expected(), resolved_types) # resolved_types = node_b_controller.get() # self.assertCountEqual(expected(), resolved_types) # resolved_types = node_c_controller.get() # self.assertCountEqual(expected(), resolved_types) # add a concrete type to the output connection at the end of the chain and verify it cascades upwards # to the input of the start of the chain (_, (extended_node_a, extended_node_b, extended_node_c), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.DELETE_NODES: [ extended_node_a, extended_node_b, extended_node_c, ], keys.CREATE_NODES: [ ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("ExtendedNodeC", "omni.graph.test.TypeResolution"), ], keys.CONNECT: [ ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeB.inputs:anyValueIn"), ("ExtendedNodeB.outputs:anyValue", "ExtendedNodeC.inputs:anyValueIn"), ("ExtendedNodeC.outputs:anyValue", "Simple.inputs:a_double"), ], }, ) await controller.evaluate(graph) node_a_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_a)) node_b_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_b)) node_c_controller = og.Controller(og.Controller.attribute("outputs:resolvedType", extended_node_c)) resolved_types = node_c_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_b_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) resolved_types = node_a_controller.get() self.assertCountEqual(expected(any_type="double"), resolved_types) # ---------------------------------------------------------------------- async def test_type_propagation(self): """Test the propagation of type resolution through the network""" controller = og.Controller() keys = og.Controller.Keys # Test with a more complicated diamond-shaped topology # +-----+ # +-->| B +-+ +-----+ # +-----+ +------+-+ +-----+ |-->| | +-----+ # | SA +--->| A | | Add |-->| SB + # +-----+ +------+-+ +-----+ |-->| | +-----+ # +-->| C +-+ +-----+ # +-----+ # (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleA", "omni.graph.tutorials.SimpleData"), ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("ExtendedNodeC", "omni.graph.test.TypeResolution"), ("Add", "omni.graph.nodes.Add"), ("SimpleB", "omni.graph.tutorials.SimpleData"), ], keys.CONNECT: [ ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeB.inputs:anyValueIn"), ("ExtendedNodeA.outputs:anyValue", "ExtendedNodeC.inputs:anyValueIn"), ("ExtendedNodeB.outputs:anyValue", "Add.inputs:a"), ("ExtendedNodeC.outputs:anyValue", "Add.inputs:b"), ("Add.outputs:sum", "SimpleB.inputs:a_double"), # Concrete double wired to front of chain to propagate forward ("SimpleA.outputs:a_double", "ExtendedNodeA.inputs:anyValueIn"), ], keys.SET_VALUES: [ ("SimpleA.inputs:a_double", 10.0), ], }, ) await controller.evaluate(graph) (simple_a_node, extended_node_a, _, _, add_node, simple_b_node) = nodes v = og.Controller.get(controller.attribute("outputs:a_double", simple_a_node)) self.assertEqual(v, 11.0) v = og.Controller.get(controller.attribute("outputs:anyValue", extended_node_a)) self.assertEqual(v, 11.0) v = og.Controller.get(controller.attribute("outputs:sum", add_node)) self.assertEqual(v, 22.0) # connect the last any output to a concrete input, verify value controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: ("Add.outputs:sum", "SimpleB.inputs:a_double"), }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:a_double", simple_b_node)) self.assertEqual(v, 23.0) # disconnect and re-connect the connection, verify the value is the same (tests output re-connect) controller.edit(self.TEST_GRAPH_PATH, {keys.DISCONNECT: ("Add.outputs:sum", "SimpleB.inputs:a_double")}) await controller.evaluate(graph) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: ("Add.outputs:sum", "SimpleB.inputs:a_double")}) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:a_double", simple_b_node)) self.assertEqual(v, 23.0) # disconnect and re-connect the extended inputs to sum and verify (tests input re-connect) controller.edit( self.TEST_GRAPH_PATH, { keys.DISCONNECT: [ ("ExtendedNodeB.outputs:anyValue", "Add.inputs:a"), ("ExtendedNodeC.outputs:anyValue", "Add.inputs:b"), ] }, ) await controller.evaluate(graph) controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [ ("ExtendedNodeB.outputs:anyValue", "Add.inputs:a"), ("ExtendedNodeC.outputs:anyValue", "Add.inputs:b"), ] }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:a_double", simple_b_node)) self.assertEqual(v, 23.0) # ---------------------------------------------------------------------- async def test_sandwiched_type_resolution(self): """modulo (which only operate on integers) is sandwiched between 2 nodes that feed/expect double this setup will test that this conversion are correctly chosen""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Modulo", "omni.graph.nodes.Modulo"), ("ConstD", "omni.graph.nodes.ConstantDouble"), ("ConstF", "omni.graph.nodes.ConstantFloat"), ("Scale", "omni.graph.nodes.ScaleToSize"), ], keys.CONNECT: [ ("ConstD.inputs:value", "Modulo.inputs:a"), ("ConstD.inputs:value", "Modulo.inputs:b"), ("Modulo.outputs:result", "Scale.inputs:speed"), ], }, ) await controller.evaluate(graph) # Helper to verify the base data type of an attribute def assert_attrib_is(attrib, node, base_type): attrib = controller.attribute(attrib, node, graph) self.assertEqual(attrib.get_resolved_type().base_type, base_type) assert_attrib_is("outputs:result", "Modulo", og.BaseDataType.INT64) # Disconnect the Multiply inputs to cause a wave of unresolutions controller.edit( graph, {keys.DISCONNECT: [("ConstD.inputs:value", "Modulo.inputs:a"), ("ConstD.inputs:value", "Modulo.inputs:b")]}, ) await controller.evaluate(graph) assert_attrib_is("outputs:result", "Modulo", og.BaseDataType.UNKNOWN) # now connect a float on input:a, that should make it the prefered type to choose conversion from # which will be INT this time controller.edit( graph, {keys.CONNECT: [("ConstF.inputs:value", "Modulo.inputs:a"), ("ConstD.inputs:value", "Modulo.inputs:b")]}, ) await controller.evaluate(graph) assert_attrib_is("outputs:result", "Modulo", og.BaseDataType.INT) # ---------------------------------------------------------------------- async def test_reconnect_different_type(self): """Tests re-resolving and the RESOLVE_ATTRIBUTE event""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, node, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("ForEach", "omni.graph.action.ForEach"), ("Get", "omni.graph.nodes.ReadPrimAttribute"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [ ("/World/Source", {"myfloatarray": ("float[]", [1000.5]), "myintarray": ("int64[]", [2**40])}), ("/World/Sink", {"myfloat": ("float", 0), "myint": ("int64", 0)}), ], keys.CONNECT: [ ("OnTick.outputs:tick", "ForEach.inputs:execIn"), ("Get.outputs:value", "ForEach.inputs:arrayIn"), ("ForEach.outputs:element", "Set.inputs:value"), ], keys.SET_VALUES: [ ("Set.inputs:name", "myfloat"), ("Set.inputs:primPath", "/World/Sink"), ("Set.inputs:usePath", True), ("Get.inputs:name", "myfloatarray"), ("Get.inputs:primPath", "/World/Source"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:element", node)) self.assertEqual(v, 1000.5) # Trigger unresolve and re-resolve of the 2 ForEach attributes event_counter = [0] def on_node_event(event): self.assertEqual(event.type, int(og.NodeEvent.ATTRIBUTE_TYPE_RESOLVE)) event_counter[0] += 1 # Hold on to the sub! sub = node.get_event_stream().create_subscription_to_pop(on_node_event) with ogts.ExpectedError(): controller.edit( self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Set.inputs:name", "myint"), ("Get.inputs:name", "myintarray")]}, ) await controller.evaluate(graph) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("outputs:element", node)) self.assertEqual(v, 2**40) # Check we got the right number of callbacks (2x callbacks for 2 attributes) self.assertEqual(event_counter[0], 4) del sub # ---------------------------------------------------------------------- # Tests of ReadPrimAttribute follow async def test_readprimattribute_scaler(self): """Exercise ReadPrimAttribute for scaler value""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/Float", {"myfloat": ("float", 42.0)}), keys.SET_VALUES: [ ("Get.inputs:name", "myfloat"), ("Get.inputs:primPath", "/World/Float"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) await controller.evaluate(graph) get_node_controller = og.Controller(og.Controller.attribute("outputs:value", get_node)) self.assertEqual(get_node_controller.get(), 42.0) # Change USD attrib, check we get the new value on our output attr = stage.GetPropertyAtPath("/World/Float.myfloat") attr.Set(0.0) await controller.evaluate(graph) self.assertEqual(get_node_controller.get(), 0.0) # Same test but with bundle input stage.GetPrimAtPath(f"{self.TEST_GRAPH_PATH}/Get").GetRelationship("inputs:prim").SetTargets( [Sdf.Path("/World/Float")] ) attr.Set(42.0) controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("Get.inputs:usePath", False)}) await controller.evaluate(graph) self.assertEqual(get_node_controller.get(), 42.0) # Change USD attrib, check we get the new value on our output attr = stage.GetPropertyAtPath("/World/Float.myfloat") attr.Set(0.0) await controller.evaluate(graph) self.assertEqual(get_node_controller.get(), 0.0) # ---------------------------------------------------------------------- async def test_readprimattribute_noexist(self): """Test ReadPrimAttribute can handle attribute that exists in USD but not in FC""" controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), (prim,), _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/Cube", "Cube"), keys.SET_VALUES: [ ("Get.inputs:name", "visibility"), ("Get.inputs:primPath", "/World/Cube"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) await controller.evaluate(graph) self.assertEqual(og.Controller.get(controller.attribute("outputs:value", get_node)), "inherited") # Change USD attrib, check we get the new value on our output UsdGeom.Imageable(prim).MakeInvisible() await controller.evaluate(graph) # ReadPrimAttribute will put the visibility value to Fabric, but it doesn't get # updated by the FSD USD handler. # Instead it updates the visibility of the prim, so this is a workaround to test # that the visibility of the prim been updated. if carb.settings.get_settings().get("/app/useFabricSceneDelegate"): import usdrt stage = usdrt.Usd.Stage.Attach(omni.usd.get_context().get_stage_id()) prim = stage.GetPrimAtPath("/World/Cube") attr = prim.GetAttribute("_worldVisibility") self.assertFalse(attr.Get()) else: self.assertEqual(og.Controller.get(controller.attribute("outputs:value", get_node)), "invisible") # ---------------------------------------------------------------------- async def test_readprimattribute_tuple(self): """Exercise ReadPrimAttribute for a tuple value""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/Double3", {"mydouble3": ("double[3]", Gf.Vec3d(42.0, 40.0, 1.0))}), keys.SET_VALUES: [ ("Get.inputs:name", "mydouble3"), ("Get.inputs:primPath", "/World/Double3"), ("Get.inputs:usePath", True), ], }, ) await controller.evaluate(graph) og.Controller.get(controller.attribute("outputs:value", get_node)) self.assertEqual( Gf.Vec3d(*og.Controller.get(controller.attribute("outputs:value", get_node))), Gf.Vec3d(42.0, 40.0, 1.0) ) # Change USD attrib, check we get the new value on our output attr = stage.GetPropertyAtPath("/World/Double3.mydouble3") attr.Set(Gf.Vec3d(0, 0, 0)) await controller.evaluate(graph) self.assertEqual( Gf.Vec3d(*og.Controller.get(controller.attribute("outputs:value", get_node))), Gf.Vec3d(0, 0, 0) ) # ---------------------------------------------------------------------- async def test_readprimattribute_array(self): """Exercise ReadPrimAttribute for an array value""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys small_array = [0xFF for _ in range(10)] (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.ReadPrimAttribute"), keys.CREATE_PRIMS: ("/World/IntArray", {"myintarray": ("int[]", small_array)}), keys.SET_VALUES: [ ("Get.inputs:name", "myintarray"), ("Get.inputs:usePath", True), ("Get.inputs:primPath", "/World/IntArray"), ], }, ) await controller.evaluate(graph) self.assertSequenceEqual( og.Controller.get(controller.attribute("outputs:value", get_node)).tolist(), small_array ) # Change USD attrib, check we get the new value on our output big_array = Vt.IntArray(1000, [0 for _ in range(1000)]) attr = stage.GetPropertyAtPath("/World/IntArray.myintarray") attr.Set(big_array) await controller.evaluate(graph) self.assertSequenceEqual(og.Controller.get(controller.attribute("outputs:value", get_node)).tolist(), big_array) # ---------------------------------------------------------------------- async def test_dynamic_extended_attributes_any(self): """Test functionality of extended any attributes when they are created dynamically""" # Set up a graph that tests dynamically created extended attrs. Here we have a node with # extended attribute attr1. We create another extended attribute dynamically (dynamic_attr1) # we then make sure these two behave the same. dyanmic_attr1 is an any attribute in this case # # SimpleIn ----=> Extended1 # -inputs:anyValueIn # -inputs:dynamic_attr1 # controller = og.Controller() keys = og.Controller.Keys (graph, (simple_node, extended_node_1), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("Extended1", "omni.graph.test.TypeResolution"), ], keys.CONNECT: ("SimpleIn.outputs:a_float", "Extended1.inputs:anyValueIn"), keys.SET_VALUES: ("SimpleIn.inputs:a_float", 5.0), }, ) await controller.evaluate(graph) # Check that the inputs into the extended type nodes are correct self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:anyValueIn", extended_node_1))) extended_node_1.create_attribute( "inputs:dynamic_attr1", og.Type(og.BaseDataType.TOKEN), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, "", ) controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: (("outputs:a_float", simple_node), ("inputs:dynamic_attr1", extended_node_1))}, ) await controller.evaluate(graph) self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:dynamic_attr1", extended_node_1))) # ---------------------------------------------------------------------- async def test_dynamic_extended_attributes_union(self): """Test functionality of extended union attributes when they are created dynamically""" # Set up a graph that tests dynamically created extended attrs. Here we have a node with # extended attribute attr1. We create another extended attribute dynamically (dynamic_attr1) # we then make sure these two behave the same. dyanmic_attr1 is a union attribute in this case # # SimpleIn ----=> Extended1 # -inputs:anyValueIn # -inputs:dynamic_attr1 # controller = og.Controller() keys = og.Controller.Keys (graph, (simple_node, extended_node_1), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleIn", "omni.graph.tutorials.SimpleData"), ("Extended1", "omni.graph.tutorials.ExtendedTypes"), ], keys.CONNECT: ("SimpleIn.outputs:a_float", "Extended1.inputs:floatOrToken"), keys.SET_VALUES: ("SimpleIn.inputs:a_float", 5.0), }, ) await controller.evaluate(graph) # Check that the inputs into the extended type nodes are correct self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:floatOrToken", extended_node_1))) extended_node_1.create_attribute( "inputs:dynamic_attr1", og.Type(og.BaseDataType.TOKEN), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, "float,token", ) controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: (("outputs:a_float", simple_node), ("inputs:dynamic_attr1", extended_node_1))}, ) await controller.evaluate(graph) self.assertEqual(6.0, og.Controller.get(controller.attribute("inputs:dynamic_attr1", extended_node_1))) # ---------------------------------------------------------------------- async def test_unresolve_propagation(self): """Tests unresolve propagates through the network""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, _, _, _, to_string_node, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ConstDouble", "omni.graph.nodes.ConstantDouble"), ("Const1", "omni.graph.nodes.ConstantVec3d"), ("Multiply", "omni.graph.nodes.Multiply"), ("Magnitude", "omni.graph.nodes.Magnitude"), ("ToString", "omni.graph.nodes.ToString"), ("Const2", "omni.graph.nodes.ConstantDouble"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [("/World/Sink", {"mydouble": ("double", 0)})], keys.SET_VALUES: [ ("ConstDouble.inputs:value", 2.0), ("Const1.inputs:value", (0.5, 0, 0)), ("Set.inputs:name", "mydouble"), ("Set.inputs:primPath", "/World/Sink"), ("Set.inputs:usePath", True), ], keys.CONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ("Multiply.outputs:product", "Magnitude.inputs:input"), ("Magnitude.outputs:magnitude", "ToString.inputs:value"), ], }, ) await controller.evaluate(graph) v = og.Controller.get(controller.attribute("inputs:value", to_string_node)) self.assertEqual(v, 1.0) # Disconnect one of the Multiply inputs to cause a wave of unresolutions controller.edit( graph, { keys.DISCONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ] }, ) # Helper to verify the base data type of an attribute def assert_attrib_is(attrib, node, base_type): attrib = controller.attribute(attrib, node, graph) self.assertEqual(attrib.get_resolved_type().base_type, base_type) # Verify the irresolute quality of the downstream attributes assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.UNKNOWN) # Re-connect to observe resolution controller.edit( graph, { keys.CONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ] }, ) # Verify the resolute quality of the downstream attributes assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.DOUBLE) assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.DOUBLE) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.DOUBLE) # Disconnect as before controller.edit( graph, { keys.DISCONNECT: [ ("ConstDouble.inputs:value", "Multiply.inputs:a"), ("Const1.inputs:value", "Multiply.inputs:b"), ] }, ) # Wait on the next framework tick, we don't need a full evaluation await omni.kit.app.get_app().next_update_async() # Verify that this time the unresolution was blocked at Magnitude assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:a", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.UNKNOWN) # Now check that WritePrimAttribute will cause upstream propagation await controller.evaluate(graph) controller.edit(graph, {keys.CONNECT: [("Magnitude.outputs:magnitude", "Set.inputs:value")]}) await controller.evaluate(graph) # Verify that our network has flipped over to double assert_attrib_is("outputs:magnitude", "Magnitude", og.BaseDataType.DOUBLE) # Note that we no longer propagate resolution upstream from outputs->inputs, so unresolution # remains upstream of Magnitude assert_attrib_is("inputs:input", "Magnitude", og.BaseDataType.UNKNOWN) assert_attrib_is("outputs:product", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:a", "Multiply", og.BaseDataType.UNKNOWN) assert_attrib_is("inputs:value", "ToString", og.BaseDataType.DOUBLE) # ---------------------------------------------------------------------- async def test_unresolve_contradiction(self): """Tests unresolve contradiction is handled""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ConstVec3f", "omni.graph.nodes.ConstantVec3f"), ("Add", "omni.graph.nodes.Add"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("Add.outputs:sum", "Set.inputs:value"), ], }, ) await omni.kit.app.get_app().next_update_async() event_counter = [0] def on_node_event(event): event_counter[0] += 1 self.assertEqual(event.type, int(og.NodeEvent.ATTRIBUTE_TYPE_RESOLVE)) node = controller.node("Add", graph) sub = node.get_event_stream().create_subscription_to_pop(on_node_event) controller.edit( graph, { keys.CONNECT: [ ("ConstVec3f.inputs:value", "Add.inputs:a"), ("ConstVec3f.inputs:value", "Add.inputs:b"), ] }, ) for _ in range(10): await omni.kit.app.get_app().next_update_async() self.assertLess(event_counter[0], 10) del sub # ---------------------------------------------------------------------- async def test_unresolve_resolve_pingpong(self): """Tests resolve doesn't ping-pong is handled""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, get_node, _), (p_in, p_out), _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Get", "omni.graph.nodes.ReadPrimAttribute"), ("Set", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [("PIn", {"f": ("float", 1.0)}), ("POut", {"f": ("float", 1.0)})], keys.CONNECT: [ ("OnTick.outputs:tick", "Set.inputs:execIn"), ("Get.outputs:value", "Set.inputs:value"), ], }, ) controller.edit( graph, { keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("Get.inputs:usePath", True), ("Get.inputs:usePath", True), ("Get.inputs:name", "f"), ("Set.inputs:name", "f"), ("Get.inputs:primPath", p_in.GetPrimPath().pathString), ("Set.inputs:primPath", p_out.GetPrimPath().pathString), ], }, ) await omni.kit.app.get_app().next_update_async() event_counter = [0] def on_node_event(event): event_counter[0] += 1 self.assertEqual(event.type, int(og.NodeEvent.ATTRIBUTE_TYPE_RESOLVE)) sub = get_node.get_event_stream().create_subscription_to_pop(on_node_event) for _ in range(5): await omni.kit.app.get_app().next_update_async() self.assertLess(event_counter[0], 5) del sub # ---------------------------------------------------------------------- async def test_loading_extended_attribute_values(self): """Test that saved extended attribute values are de-serialized correctly""" (result, error) = await ogts.load_test_file("TestExtendedAttributes.usda", use_caller_subdirectory=True) self.assertTrue(result, error) graph_path = "/World/PushGraph" controller = og.Controller() graph = controller.graph(graph_path) await controller.evaluate(graph) tests = [ # name, og_type, input0, input1 ("make_array", "bool", True, False, None), ("make_array_01", "double", 42, 43, None), ("make_array_02", "token", "FOO", "BAR", None), ("make_array_03", "double[2]", np.array((1.0, 2.0)), np.array((3.0, 4.0)), Gf.Vec2d), ("make_array_04", "int[2]", np.array((1, 2)), np.array((3, 4)), Gf.Vec2i), ("make_array_05", "half", 42.0, 43.0, None), ( "make_array_06", "matrixd[3]", np.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)), np.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)), Gf.Matrix3d, ), ] # verify the values on the loaded nodes for name, og_type, expected_1, expected_2, _ in tests: make_array = controller.node(f"{graph_path}/{name}") input_0 = og.Controller.get(controller.attribute("inputs:input0", make_array)) input_type = controller.attribute("inputs:input0", make_array).get_resolved_type().get_ogn_type_name() input_1 = og.Controller.get(controller.attribute("inputs:input1", make_array)) value = og.Controller.get(controller.attribute("outputs:array", make_array)) self.assertEqual(input_type, og_type) try: self.assertEqual(input_0, expected_1) except ValueError: self.assertListEqual(list(input_0), list(expected_1)) try: self.assertEqual(input_1, expected_2) except ValueError: self.assertListEqual(list(input_1), list(expected_2)) try: self.assertListEqual(list(value), [expected_1, expected_2]) except ValueError: self.assertListEqual([list(v) for v in value], [list(expected_1), list(expected_2)]) usd_context = omni.usd.get_context() stage = usd_context.get_stage() # Reset the arrayType to clear the saved resolved values for name, _, _, _, _ in tests: og.Controller.set(controller.attribute(f"{graph_path}/{name}.inputs:arrayType"), "auto") # Verify that all the inputs are now unresolved for name, _, _, _, _ in tests: make_array = controller.node(f"{graph_path}/{name}") attrib = controller.attribute("inputs:input0", make_array) tp = attrib.get_resolved_type() self.assertEqual(tp.base_type, og.BaseDataType.UNKNOWN) attrib = controller.attribute("inputs:input1", make_array) tp = attrib.get_resolved_type() self.assertEqual(tp.base_type, og.BaseDataType.UNKNOWN) # Verify that in the re-serialized stage, the attrType and attrValue are reset await controller.evaluate(graph) for name, _, _, _, _ in tests: self.assertIsNone( stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:attrValue" ) ) self.assertEqual( "Any", stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:attrType" ), ) self.assertIsNone( stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:resolvedType" ) ) # Re-resolve and set different values for name, og_type, _, input_1, _ in tests: og.Controller.set(controller.attribute(f"{graph_path}/{name}.inputs:arrayType"), f"{og_type}[]") og.Controller.set(controller.attribute(f"{graph_path}/{name}.inputs:input1"), input_1) # Serialize stage again, verify the types and values await controller.evaluate(graph) for name, og_type, _, _, _ in tests: attr = stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1") self.assertIsNotNone(attr.GetCustomDataByKey("omni:graph:attrValue"), f"For {name}") self.assertIsNotNone(attr.GetCustomDataByKey("omni:graph:attrType"), f"For {name}") usd_value = stage.GetAttributeAtPath(f"{graph_path}/{name}.inputs:input1").GetCustomDataByKey( "omni:graph:resolvedType" ) self.assertEqual(og_type, usd_value, f"For {name}") # ---------------------------------------------------------------------- async def test_resolution_invalidates_existing_connection(self): """ Test that when the type resolution makes an existing connection invalid, that we get an error """ controller = og.Controller() keys = og.Controller.Keys (graph, (build_str, find_prims), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("BuildString", "omni.graph.nodes.BuildString"), ("FindPrims", "omni.graph.nodes.FindPrims"), ], keys.CREATE_PRIMS: [("/World/Cube", "Cube"), ("/World/Cone", "Cone")], keys.SET_VALUES: [("FindPrims.inputs:rootPrimPath", "/World")], keys.CONNECT: [("BuildString.outputs:value", "FindPrims.inputs:namePrefix")], }, ) await og.Controller.evaluate(graph) out = find_prims.get_attribute("outputs:prims") self.assertEqual(out.get(), [f"{self.TEST_GRAPH_PATH}", "/World/Cube", "/World/Cone"]) # Setting inputs to string will change resolution on output value to a string as well. But string -> token # connections are not supported. So this should raise an error with ogts.ExpectedError(): controller.edit( self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("BuildString.inputs:a", {"type": "string", "value": "Cu"})]}, ) err_list = build_str.get_compute_messages(og.Severity.ERROR) self.assertEqual(len(err_list), 1) err_list[0].startswith("Type error") await controller.evaluate(graph) out = build_str.get_attribute("outputs:value") self.assertEqual(out.get_resolved_type(), og.Controller.attribute_type("string")) # ---------------------------------------------------------------------- async def test_resolved_type_saved(self): """Test that a type resolution is saved when a value is never set""" # See OM-93596 controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ("ConstantFloat", "omni.graph.nodes.ConstantFloat"), ], keys.SET_VALUES: [ ("Add.inputs:a", {"type": "float", "value": 1.0}), ("ConstantFloat.inputs:value", 42.0), ], }, ) await controller.evaluate(graph) attr = stage.GetAttributeAtPath(f"{self.TEST_GRAPH_PATH}/Add.inputs:a") og_attr = controller.attribute(f"{self.TEST_GRAPH_PATH}/Add.inputs:a") self.assertIsNotNone(attr.GetCustomDataByKey("omni:graph:attrValue")) # Since the controller manually resolves the type above, verify the customData is there usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("float", usd_value) # manually resolve to a different type - verify it is saved og.cmds.ResolveAttrType(attr=og_attr, type_id="double") await controller.evaluate(graph) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("double", usd_value) # manually unresolve - verify the customData is gone og.cmds.ResolveAttrType(attr=og_attr, type_id="unknown") await controller.evaluate(graph) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertIsNone(usd_value) self.assertEqual(og_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN, 1, 0)) # Verify that: # 1. manually resolving # 2. connect # 3. disconnect # Restores the manual resolution customData AND literal value # FIXME: OM-94077 if False: # noqa PLW0125 og.cmds.ResolveAttrType(attr=og_attr, type_id="float") og.Controller.set(attr, {"type": "float", "value": 2.0}) await controller.evaluate(graph) self.assertEqual(attr.GetCustomDataByKey("omni:graph:attrValue"), 2.0) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("float", usd_value) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("ConstantFloat.inputs:value", "Add.inputs:a")]}) await controller.evaluate(graph) self.assertEqual(og_attr.get(), 42.0) controller.edit( self.TEST_GRAPH_PATH, {keys.DISCONNECT: [("ConstantFloat.inputs:value", "Add.inputs:a")]}, ) await controller.evaluate(graph) self.assertEqual(attr.GetCustomDataByKey("omni:graph:attrValue"), 2.0) usd_value = attr.GetCustomDataByKey("omni:graph:resolvedType") self.assertEqual("float", usd_value) self.assertEqual(og_attr.get(), 2.0) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("Add.outputs:sum", "ConstantFloat.inputs:value")]}) await controller.evaluate(graph) og_sum_attr = controller.attribute(f"{self.TEST_GRAPH_PATH}/Add.outputs:sum") self.assertEqual(og_sum_attr.get_resolved_type(), og.Type(og.BaseDataType.FLOAT, 1, 0)) controller.edit( self.TEST_GRAPH_PATH, {keys.DISCONNECT: [("Add.outputs:sum", "ConstantFloat.inputs:value")]}, ) await controller.evaluate(graph) self.assertEqual(og_sum_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN, 1, 0)) # ---------------------------------------------------------------------- async def test_resolved_types_serialized_in_compounds(self): """Validates that resolved types are serialized in compound graphs (OM-99390)""" controller = og.Controller(update_usd=True) keys = og.Controller.Keys (_, _, _, nodes) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ( "Compound", { keys.CREATE_NODES: [("CompoundAdd", "omni.graph.nodes.Add")], keys.SET_VALUES: [("CompoundAdd.inputs:a", {"type": "float", "value": 2.0})], }, ), ], keys.SET_VALUES: [ ("Add.inputs:a", {"type": "double", "value": 1.0}), ], }, ) add_path = nodes["Add"].get_prim_path() compound_add_path = nodes["CompoundAdd"].get_prim_path() # resolve and set attributes top_level_attr_a = nodes["Add"].get_attribute("inputs:a") top_level_attr_b = nodes["Add"].get_attribute("inputs:b") compound_attr_a = nodes["CompoundAdd"].get_attribute("inputs:a") compound_attr_b = nodes["CompoundAdd"].get_attribute("inputs:b") og.cmds.ResolveAttrType(attr=top_level_attr_b, type_id="double") og.cmds.ResolveAttrType(attr=compound_attr_b, type_id="float") controller.set(top_level_attr_b, 3.0) controller.set(compound_attr_b, 4.0) self.assertEqual(og.Controller.get(top_level_attr_a), 1.0) self.assertEqual(og.Controller.get(compound_attr_a), 2.0) self.assertEqual(og.Controller.get(top_level_attr_b), 3.0) self.assertEqual(og.Controller.get(compound_attr_b), 4.0) # save and reload the scene with tempfile.TemporaryDirectory() as test_directory: tmp_file_path = os.path.join(test_directory, "tmp_test_resolve_in_compounds.usda") (result, error, _) = await omni.usd.get_context().save_as_stage_async(str(tmp_file_path)) self.assertTrue(result, error) (result, error) = await omni.usd.get_context().reopen_stage_async() self.assertTrue(result, error) add_node = og.Controller.node(add_path) compound_add_node = og.Controller.node(compound_add_path) top_level_attr_a = add_node.get_attribute("inputs:a") top_level_attr_b = add_node.get_attribute("inputs:b") compound_attr_a = compound_add_node.get_attribute("inputs:a") compound_attr_b = compound_add_node.get_attribute("inputs:b") self.assertEqual(og.Controller.get(top_level_attr_a), 1.0) self.assertEqual(og.Controller.get(compound_attr_a), 2.0) self.assertEqual(og.Controller.get(top_level_attr_b), 3.0) self.assertEqual(og.Controller.get(compound_attr_b), 4.0)
53,468
Python
44.351145
120
0.550011
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_graph_settings.py
"""OmniGraph Graph Settings Tests""" import os import tempfile import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test import omni.kit.undo import omni.usd import omni.usd.commands from pxr import OmniGraphSchema class TestOmniGraphSchemaGraphSettings(ogts.OmniGraphTestCase): """Tests for OmniGraph Graph Settings with Schema Enabled""" # ---------------------------------------------------------------------- async def test_compute_settings_save_and_load(self): """Tests that creating, saving and loading compute graph settings writes and reads the correct settings""" pipeline_stages = list(og.GraphPipelineStage.__members__.values()) evaluation_modes = list(og.GraphEvaluationMode.__members__.values()) backing_types = [ og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY, og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, ] setting_tuples = zip(pipeline_stages[0:3], evaluation_modes[0:3], backing_types[0:3]) index = 0 for (pipeline_stage, evaluation_mode, backing_type) in setting_tuples: (graph, _, _, _) = og.Controller.edit( { "graph_path": f"/World/TestGraph{index}", "fc_backing_type": backing_type, "pipeline_stage": pipeline_stage, "evaluation_mode": evaluation_mode, } ) path = graph.get_path_to_graph() self.assertIsNotNone(graph) with tempfile.TemporaryDirectory() as tmpdirname: # save the file tmp_file_path = os.path.join(tmpdirname, f"tmp{index}.usda") result = omni.usd.get_context().save_as_stage(tmp_file_path) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(tmp_file_path) self.assertTrue(result, error) graph = omni.graph.core.get_graph_by_path(path) self.assertIsNotNone(graph, f"Failed to load graph at {path} from {tmp_file_path}") self.assertEquals(graph.evaluation_mode, evaluation_mode) self.assertEquals(graph.get_pipeline_stage(), pipeline_stage) self.assertEquals(graph.get_graph_backing_type(), backing_type) index = index + 1 await omni.usd.get_context().new_stage_async() # ---------------------------------------------------------------------- async def test_evaluation_mode_changed_from_usd(self): """Tests that changing evaluation mode from usd is applied to the underlying graph""" controller = og.Controller() keys = og.Controller.Keys stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" (graph, nodes, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ] }, ) self.assertEquals(graph.evaluation_mode, og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC) # automatic mode, computes because no references exist count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count + 1, nodes[0].get_compute_count()) prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) # change the evaluation to instanced schema_prim.GetEvaluationModeAttr().Set("Instanced") count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED, graph.evaluation_mode) self.assertEqual(count, nodes[0].get_compute_count()) # ---------------------------------------------------------------------- async def test_evaluator_type_changed_from_usd(self): """Tests that changing evaluation mode from usd is applied to the underlying graph""" stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" controller = og.Controller() (graph, (read_time, constant_node, _), _, _) = controller.edit( {"graph_path": graph_path, "evaluator_name": "dirty_push"}, { og.Controller.Keys.CREATE_NODES: [ ("ReadTime", "omni.graph.nodes.ReadTime"), ("ConstantInt", "omni.graph.nodes.ConstantInt"), ("Sub", "omni.graph.test.SubtractDoubleC"), ], og.Controller.Keys.CONNECT: [ ("ReadTime.outputs:timeSinceStart", "Sub.inputs:a"), ("ReadTime.outputs:timeSinceStart", "Sub.inputs:b"), ], og.Controller.Keys.SET_VALUES: [("ConstantInt.inputs:value", 3)], }, ) # skip the initial compute await omni.kit.app.get_app().next_update_async() # validate the graph ticks as expected count_time = read_time.get_compute_count() count_print = constant_node.get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count_time + 1, read_time.get_compute_count(), "Expected time to tick") self.assertEqual(count_print, constant_node.get_compute_count(), "Expected print not to tick") prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) # change the graph to push by changing the USD. schema_prim.GetEvaluatorTypeAttr().Set("push") await omni.kit.app.get_app().next_update_async() self.assertEqual(graph.get_evaluator_name(), "push") self.assertEqual(count_time + 2, read_time.get_compute_count(), "Expected time to tick") self.assertEqual(count_print + 1, constant_node.get_compute_count(), "Expected print to tick") # change the graph back schema_prim.GetEvaluatorTypeAttr().Set("dirty_push") await omni.kit.app.get_app().next_update_async() # skip the intial frame count_time = read_time.get_compute_count() count_print = constant_node.get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(graph.get_evaluator_name(), "dirty_push") self.assertEqual(count_time + 1, read_time.get_compute_count(), "Expected time to tick") self.assertEqual(count_print, constant_node.get_compute_count(), "Expected print not to tick") # --------------------------------------------------------------------- async def test_fabric_backing_changed_from_usd(self): stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" (graph, _, _, _) = og.Controller.edit( {"graph_path": graph_path, "fc_backing_type": og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED} ) self.assertEqual(og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, graph.get_graph_backing_type()) prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) schema_prim.GetFabricCacheBackingAttr().Set("StageWithoutHistory") await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY, graph.get_graph_backing_type()) # --------------------------------------------------------------------- async def test_pipeline_stage_changed_from_usd(self): """Tests the changing the pipeline stage in usd changes the underlying pipeline stage""" controller = og.Controller() keys = og.Controller.Keys stage = omni.usd.get_context().get_stage() graph_path = "/World/TestGraph" (graph, nodes, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ] }, ) self.assertEqual(og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, graph.get_pipeline_stage()) # validate the node updates count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count + 1, nodes[0].get_compute_count()) prim = stage.GetPrimAtPath(graph_path) self.assertTrue(prim.IsA(OmniGraphSchema.OmniGraph)) schema_prim = OmniGraphSchema.OmniGraph(prim) # change the pipeline stage to on demand schema_prim.GetPipelineStageAttr().Set("pipelineStageOnDemand") await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND, graph.get_pipeline_stage()) # validate the node did not update count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count, nodes[0].get_compute_count()) # change back to simulation schema_prim.GetPipelineStageAttr().Set("pipelineStageSimulation") await omni.kit.app.get_app().next_update_async() self.assertEqual(og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, graph.get_pipeline_stage()) # validate the node updates count = nodes[0].get_compute_count() await omni.kit.app.get_app().next_update_async() self.assertEqual(count + 1, nodes[0].get_compute_count())
9,968
Python
43.704036
119
0.60303
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_callbacks.py
""" Tests for omnigraph callbacks """ import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # Global variable for sharing callback location _callback_path = None # ====================================================================== class TestCallbacks(ogts.OmniGraphTestCase): _graph_path = "/World/TestGraph" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.conn_count = 0 self.disconn_count = 0 self.attr_count = 0 # ---------------------------------------------------------------------- async def test_connection_callbacks(self): """ Test attribute connect/disconnect callbacks. """ # Create the graph. (_, (simple1, simple2), _, _) = og.Controller.edit( self._graph_path, { og.Controller.Keys.CREATE_NODES: [ ("simple1", "omni.graph.tutorials.SimpleData"), ("simple2", "omni.graph.tutorials.SimpleData"), ], }, ) self.conn_count = 0 self.disconn_count = 0 self.attr_count = 0 def on_connection(attr1, attr2): self.conn_count += 1 # Were the correct arguments passed? if (attr1.get_name() == "outputs:a_int") and (attr2.get_name() == "inputs:a_int"): self.attr_count += 1 def on_disconnection(attr1, attr2): self.disconn_count += 1 # Were the correct arguments passed? if (attr1.get_name() == "outputs:a_int") and (attr2.get_name() == "inputs:a_int"): self.attr_count += 1 conn1_cb = simple1.register_on_connected_callback(on_connection) conn2_cb = simple2.register_on_connected_callback(on_connection) disconn1_cb = simple1.register_on_disconnected_callback(on_disconnection) self.assertEqual(self.conn_count, 0) self.assertEqual(self.disconn_count, 0) self.assertEqual(self.attr_count, 0) # Make a connection. We should get calls from both nodes. attr1 = simple1.get_attribute("outputs:a_int") attr2 = simple2.get_attribute("inputs:a_int") attr1.connect(attr2, True) self.assertEqual(self.conn_count, 2) self.assertEqual(self.disconn_count, 0) self.assertEqual(self.attr_count, 2) # Break the connection. We should only get a call from simple1. attr1.disconnect(attr2, True) self.assertEqual(self.conn_count, 2) self.assertEqual(self.disconn_count, 1) self.assertEqual(self.attr_count, 3) # Deregister one of the connection callbacks then make a connection. simple1.deregister_on_connected_callback(conn1_cb) attr1.connect(attr2, True) self.assertEqual(self.conn_count, 3) self.assertEqual(self.disconn_count, 1) self.assertEqual(self.attr_count, 4) # Deregistering the same callback again should have no effect. simple1.deregister_on_connected_callback(conn1_cb) # Cleanup. simple1.deregister_on_connected_callback(conn2_cb) simple1.deregister_on_connected_callback(disconn1_cb) # ---------------------------------------------------------------------- async def test_path_changed_callback(self): """ Test the ability to register callbacks on nodes so that they receive path change notices from USD """ # Create the graph. (graph, (simple_node,), _, _) = og.Controller.edit( self._graph_path, { og.Controller.Keys.CREATE_NODES: [("simple", "omni.graph.tutorials.SimpleData")], }, ) k_want_print = False k_not_received = "not_received" global _callback_path _callback_path = k_not_received def on_path_changed_callback(changed_paths): global _callback_path _callback_path = changed_paths[-1] def _do_the_print(changed_paths, want_print: bool = k_want_print): return print(changed_paths) if k_want_print else None print_changed_paths = _do_the_print async def test_callback(should_work: bool): cb_handle = simple_node.register_on_path_changed_callback(on_path_changed_callback) print_changed_paths_cb_handle = simple_node.register_on_path_changed_callback(print_changed_paths) usd_context = omni.usd.get_context() stage = usd_context.get_stage() stage.DefinePrim("/World/xform1", "Xform") await og.Controller.evaluate(graph) self.assertEqual(_callback_path, "/World/xform1" if should_work else k_not_received) simple_node.deregister_on_path_changed_callback(cb_handle) simple_node.deregister_on_path_changed_callback(print_changed_paths_cb_handle) stage.DefinePrim("/World/xform2", "Xform") # This time we should not receive a callback, so ensure path is unchanged self.assertEqual(_callback_path, "/World/xform1" if should_work else k_not_received) await og.Controller.evaluate(graph) with og.Settings.temporary(og.Settings.ENABLE_PATH_CHANGED_CALLBACK, True): await test_callback(True) _callback_path = k_not_received with og.Settings.temporary(og.Settings.ENABLE_PATH_CHANGED_CALLBACK, False): await test_callback(False) # ---------------------------------------------------------------------- async def test_register_value_changed_callback(self): """Test Attribute.register_value_changed callback""" connected_attr = None def on_value_changed(attr): nonlocal connected_attr connected_attr = attr controller = og.Controller() keys = og.Controller.Keys (_, (test_node_a, test_node_b, test_node_c), _, _) = controller.edit( self._graph_path, { keys.CREATE_NODES: [ ("NodeWithAllTypes1", "omni.graph.test.TestAllDataTypes"), ("NodeWithAllTypes2", "omni.graph.test.TestAllDataTypes"), ("NodeWithAllTypes3", "omni.graph.test.TestAllDataTypes"), ] }, ) test_values = [ ("inputs:a_bool", True), ("inputs:a_double", 42.0), ("inputs:a_float_2", (2.0, 3.0)), ("inputs:a_string", "test"), ] for name, value in test_values: src_attrib = test_node_b.get_attribute(name.replace("inputs:", "outputs:")) attrib = test_node_a.get_attribute(name) attrib.register_value_changed_callback(on_value_changed) # test the callback is hit when an attribute changes value og.Controller.set(attrib, value) self.assertEqual(connected_attr, attrib) # validate it is called on connection connected_attr = None og.Controller.connect(src_attrib, attrib) self.assertEqual(connected_attr, attrib) # validate it is called on disconnection connected_attr = None og.Controller.disconnect(src_attrib, attrib) self.assertEqual(connected_attr, attrib) # reset the callback, verify it is not called connected_attr = None attrib.register_value_changed_callback(None) og.Controller.set(attrib, value) self.assertIsNone(connected_attr) # Now validate it is hit when set with USD instead of OG read_attrib = None got_value = None def on_value_changed_2(_): nonlocal read_attrib nonlocal got_value # check if we have an attribute to read the value from if read_attrib: got_value = og.Controller.get(controller.attribute(read_attrib, test_node_c)) usd_context = omni.usd.get_context() stage = usd_context.get_stage() for name, value in test_values: attrib_c = test_node_c.get_attribute(name) attrib_c.register_value_changed_callback(on_value_changed_2) read_attrib = name got_value = None usd_attrib = stage.GetAttributeAtPath(attrib_c.get_path()) usd_attrib.Set(value) if isinstance(got_value, np.ndarray): self.assertSequenceEqual(got_value.tolist(), value) else: self.assertEqual(got_value, value) attrib_c.register_value_changed_callback(None) # Verify callbacks are _not_ sent when disableInfoNoticeHandlingInPlayback=true with og.Settings.temporary(og.Settings.DISABLE_INFO_NOTICE_HANDLING_IN_PLAYBACK, True): for name, value in test_values: attrib_c = test_node_c.get_attribute(name) attrib_c.register_value_changed_callback(on_value_changed_2) read_attrib = name got_value = None usd_attrib = stage.GetAttributeAtPath(attrib_c.get_path()) usd_attrib.Set(value) self.assertEqual(got_value, None) attrib_c.register_value_changed_callback(None)
9,379
Python
37.600823
110
0.579273
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_data_model.py
"""Tests OG Data Model""" import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # ====================================================================== class TestDataModel(ogts.OmniGraphTestCase): """ Run tests that exercises the data model features of omni graph, such as copy on write and data stealing. """ async def test_copy_on_write(self): """ Test all basic CoW behaviors: - Bundle passthrough is passing a reference to original bundle - Bundle mutation trigger CoW, but array attribute in the new bundle are references - Array attribute mutation in bundle trigger CoW on the attribute - Array attribute on node can be passed by ref, and mutation triggers CoW behavior Load the test scene which has 3 OgnTestDataModel nodes that performs some checks Node #1: - receives a passthrough bundle and the original one, and makes sure those are the same (not equal, the actual same in RAM) - mutate the "points" attribute in its output bundle - receives an array attribute and pass it through unchanged Node #2: - compare the original bundle to the output of node #1, makes sure it is a copy - Checks that all array attribute are actually pointing to the same buffer than the original one, BUT "points", that has been mutated by #1 - validate that the received array attribute is actually pointing to the original one - mutate it on its output Node #3: - validate that the array attribute out of node #2 is a new copy """ (result, error) = await ogts.load_test_file("TestCoW.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # run the graph 2 more times to exercise DB caching await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async()
2,022
Python
40.285713
109
0.62908
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_scriptnode.py
"""Basic tests of the action graph""" import omni.graph.core as og import omni.graph.core.tests as ogts # ====================================================================== class TestActionGraphIntegration(ogts.OmniGraphTestCase): """Tests for Script Node""" # ---------------------------------------------------------------------- async def test_compute_creates_dynamic_attrib_legacy(self): """Test that the script node can create dynamic attribs within its compute""" controller = og.Controller() keys = og.Controller.Keys script = """ attribute_exists = db.node.get_attribute_exists("inputs:multiplier") if attribute_exists != True: db.node.create_attribute("inputs:multiplier", og.Type(og.BaseDataType.DOUBLE)) db.outputs.data = db.inputs.data * db.inputs.multiplier""" (graph, (on_impulse_node, script_node), _, _,) = controller.edit( {"graph_path": "/TestGraph", "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("OnImpulse", "omni.graph.action.OnImpulseEvent"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.CONNECT: ("OnImpulse.outputs:execOut", "Script.inputs:execIn"), keys.SET_VALUES: [ ("OnImpulse.inputs:onlyPlayback", False), ("Script.inputs:script", script), ], }, ) script_node.create_attribute( "inputs:data", og.Type(og.BaseDataType.DOUBLE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ) script_node.create_attribute( "outputs:data", og.Type(og.BaseDataType.DOUBLE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:data", 42), ("Script.outputs:data", 0), ], }, ) await controller.evaluate(graph) # trigger graph evaluation once so the compute runs og.Controller.set(controller.attribute("state:enableImpulse", on_impulse_node), True) await controller.evaluate(graph) val = og.Controller.get(controller.attribute("outputs:data", script_node)) self.assertEqual(val, 0) # set value on the dynamic attrib and check compute og.Controller.set(controller.attribute("inputs:multiplier", script_node), 2.0) og.Controller.set(controller.attribute("state:enableImpulse", on_impulse_node), True) await controller.evaluate(graph) val = og.Controller.get(controller.attribute("outputs:data", script_node)) self.assertEqual(val, 84) # ---------------------------------------------------------------------- async def test_use_loaded_dynamic_attrib(self): """Test that the script node can use a dynamic attrib loaded from USD""" await ogts.load_test_file("TestScriptNode.usda", use_caller_subdirectory=True) controller = og.Controller() val = og.Controller.get(controller.attribute("outputs:data", "/World/ActionGraph/script_node")) self.assertEqual(val, 0) # trigger graph evaluation once so the compute runs og.Controller.set(controller.attribute("state:enableImpulse", "/World/ActionGraph/on_impulse_event"), True) await controller.evaluate() val = og.Controller.get(controller.attribute("outputs:data", "/World/ActionGraph/script_node")) self.assertEqual(val, 84) as_int = og.Controller.get(controller.attribute("outputs:asInt", "/World/ActionGraph/script_node")) as_float = og.Controller.get(controller.attribute("state:asFloat", "/World/ActionGraph/script_node")) self.assertEqual(as_int, 84) self.assertEqual(as_float, 84.0) # ---------------------------------------------------------------------- async def test_simple_scripts_legacy(self): """Test that some simple scripts work as intended""" controller = og.Controller() keys = og.Controller.Keys (graph, (script_node,), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: ("Script", "omni.graph.scriptnode.ScriptNode"), }, ) script_node.create_attribute( "inputs:my_input_attribute", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ) script_node.create_attribute( "outputs:my_output_attribute", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_controller = og.Controller(og.Controller.attribute("outputs:my_output_attribute", script_node)) controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", "db.outputs.my_output_attribute = 123"), }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 123) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:script", "db.outputs.my_output_attribute = -db.inputs.my_input_attribute"), ("Script.inputs:my_input_attribute", 1234), ] }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), -1234) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ( "Script.inputs:script", "db.outputs.my_output_attribute = db.inputs.my_input_attribute * db.inputs.my_input_attribute", ), ("Script.inputs:my_input_attribute", -12), ] }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 144) # ---------------------------------------------------------------------- async def test_internal_state_keeps_persistent_info_legacy(self): """Test that the script node can keep persistent information using internal state""" script = """ if (not hasattr(db.internal_state, 'num1')): db.internal_state.num1 = 0 db.internal_state.num2 = 1 else: sum = db.internal_state.num1 + db.internal_state.num2 db.internal_state.num1 = db.internal_state.num2 db.internal_state.num2 = sum db.outputs.data = db.internal_state.num1""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, script_node), _, _,) = controller.edit( {"graph_path": "/TestGraph", "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.CONNECT: ("OnTick.outputs:tick", "Script.inputs:execIn"), keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("Script.inputs:script", script), ], }, ) script_node.create_attribute( "outputs:data", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_controller = og.Controller(og.Controller.attribute("outputs:data", script_node)) # Check that the script node produces the Fibonacci numbers await controller.evaluate(graph) self.assertEqual(output_controller.get(), 0) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 1) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 1) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 2) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 3) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 5) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 8) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 13) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 21) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 34) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 55) # ---------------------------------------------------------------------- async def test_script_global_scope(self): """Test that variables, functions, and classes defined outside of the user-defined callbacks are visible""" controller = og.Controller() keys = og.Controller.Keys (graph, (script_node,), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: ("Script", "omni.graph.scriptnode.ScriptNode"), }, ) script_node.create_attribute( "outputs:output_a", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) script_node.create_attribute( "outputs:output_b", og.Type(og.BaseDataType.TOKEN), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_a_controller = og.Controller(og.Controller.attribute("outputs:output_a", script_node)) output_b_controller = og.Controller(og.Controller.attribute("outputs:output_b", script_node)) script_test_constants = """ MY_CONSTANT_A = 123 MY_CONSTANT_B = 'foo' def setup(db): db.outputs.output_a = MY_CONSTANT_A def compute(db): db.outputs.output_b = MY_CONSTANT_B""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_constants), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "foo") script_test_variables = """ my_variable = 123 def setup(db): global my_variable my_variable = 234 db.outputs.output_a = my_variable def compute(db): global my_variable db.outputs.output_b = f'{my_variable}' my_variable += 1""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_variables), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 234) self.assertEqual(output_b_controller.get(), "234") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "235") script_test_functions = """ def my_function_a(): return 123 my_variable_b = 'foo' def my_function_b(): return my_variable_b def setup(db): db.outputs.output_a = my_function_a() def compute(db): db.outputs.output_b = my_function_b() global my_variable_b my_variable_b = 'bar'""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_functions), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "bar") script_test_imports = """ import inspect import math my_lambda = lambda x: x code_len = len(inspect.getsource(my_lambda)) def setup(db): db.outputs.output_a = code_len def compute(db): db.outputs.output_b = f'{math.pi:.2f}'""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_imports), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 24) self.assertEqual(output_b_controller.get(), "3.14") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "3.14") script_test_classes = """ class MyClass: def __init__(self, value): self.value = value def get_value(self): return self.value @staticmethod def get_num(): return 123 my_variable = MyClass('foo') def setup(db): db.outputs.output_a = MyClass.get_num() def compute(db): db.outputs.output_b = my_variable.get_value() my_variable.value = 'bar'""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_classes), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "bar")
13,237
Python
35.874652
120
0.576641
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_helpers.py
"""Tests related to the helper scripts""" import json import re from contextlib import suppress from pathlib import Path from typing import Dict, Optional, Union import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn import omni.kit import omni.usd from omni.graph.core.typing import NodeType_t from pxr import Sdf, Usd # ============================================================================================================== # Iteration helpers GRAPH_BY_GRAPH = "og.Graph" GRAPH_BY_PATH = "path" GRAPH_BY_SDF_PATH = "Sdf path" GRAPH_NONE = "None" GRAPH_LOOKUPS = [GRAPH_BY_GRAPH, GRAPH_BY_PATH, GRAPH_BY_SDF_PATH, GRAPH_NONE] NODE_BY_NODE = "og.Node" NODE_BY_PATH = "path" NODE_BY_USD_PRIM = "Usd.Prim" NODE_NONE = "None" NODE_BY_TUPLE = "tuple" NODE_LOOKUPS = [NODE_BY_NODE, NODE_BY_PATH, NODE_BY_USD_PRIM, NODE_NONE, NODE_BY_TUPLE] NODE_TYPE_BY_NODE = "og.Node" NODE_TYPE_BY_USD_PRIM = "Usd.Prim" NODE_TYPE_BY_NAME = "name" NODE_TYPE_BY_NODE_TYPE = "og.NodeType" NODE_TYPE_LOOKUPS = [NODE_TYPE_BY_NODE, NODE_TYPE_BY_NAME, NODE_TYPE_BY_USD_PRIM, NODE_TYPE_BY_NODE_TYPE] ATTRIBUTE_BY_ATTRIBUTE = "og.Attribute" ATTRIBUTE_BY_PATH = "path" ATTRIBUTE_BY_SDF_PATH = "Sdf.Path" ATTRIBUTE_BY_USD_ATTRIBUTE = "Usd.Attribute" ATTRIBUTE_BY_TUPLE = "tuple" ATTRIBUTE_LOOKUPS = [ ATTRIBUTE_BY_ATTRIBUTE, ATTRIBUTE_BY_PATH, ATTRIBUTE_BY_SDF_PATH, ATTRIBUTE_BY_USD_ATTRIBUTE, ATTRIBUTE_BY_TUPLE, ] # ============================================================================================================== class TestHelpers(ogts.OmniGraphTestCase): """Testing to ensure OGN helpers work""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.outer_graph1_path = None self.outer_graph2_path = None self.inner_graph1_1_path = None self.inner_graph1_2_path = None self.inner_graph2_1_path = None self.inner_graph2_2_path = None self.graph_paths = None self.node1_path = None self.node2_path = None self.node3_path = None self.node4_path = None self.node5_path = None self.node1_1_path = None self.node1_2_path = None self.node2_1_path = None self.node2_2_path = None self.node_paths = None self.attribute1_path = None self.attribute2_path = None self.attribute1_1_path = None self.attribute1_2_path = None self.attribute2_1_path = None self.attribute2_2_path = None self.attribute1_target_input_path = None self.attribute1_target_output_path = None self.attribute1_bundle_input_path = None self.attribute_paths = None self.variable_bool_name = None self.variable_float_name = None self.variable_double_name = None self.variable_names = None # -------------------------------------------------------------------------------------------------------------- async def __populate_data(self): """ Read in the test file and populate the local variables to use for testing. Note that this test file has graph prims whose parents are other graph prims, i.e., the old subgraphs. While these are no longer supported (will not evaluate), we still keep this test file as-is in to ensure that the helper scripts continue to operate correctly even in situations that, while technically authorable, are no longer officially supported in OG. """ (result, error) = await ogts.load_test_file("TestObjectIdentification.usda", use_caller_subdirectory=True) self.assertTrue(result, error) self.outer_graph1_path = "/World/OuterGraph1" self.outer_graph2_path = "/World/OuterGraph2" self.inner_graph1_1_path = f"{self.outer_graph1_path}/InnerGraph1" self.inner_graph1_2_path = f"{self.outer_graph1_path}/InnerGraph2" self.inner_graph2_1_path = f"{self.outer_graph2_path}/InnerGraph1" self.inner_graph2_2_path = f"{self.outer_graph2_path}/InnerGraph2" self.graph_paths = [ self.outer_graph1_path, self.outer_graph2_path, self.inner_graph1_1_path, self.inner_graph1_2_path, self.inner_graph2_1_path, self.inner_graph2_2_path, ] self.node1_path = f"{self.outer_graph1_path}/constant_bool" self.node2_path = f"{self.outer_graph2_path}/constant_double" self.node3_path = f"{self.outer_graph1_path}/constant_prims" self.node4_path = f"{self.outer_graph1_path}/get_prims_at_path" self.node5_path = f"{self.outer_graph1_path}/extract_bundle" self.node1_1_path = f"{self.inner_graph1_1_path}/constant_float" self.node1_2_path = f"{self.inner_graph1_2_path}/constant_int" self.node2_1_path = f"{self.inner_graph2_1_path}/constant_uint" self.node2_2_path = f"{self.inner_graph2_2_path}/constant_uint64" self.node_paths = [ self.node1_path, self.node2_path, self.node3_path, self.node4_path, self.node5_path, self.node1_1_path, self.node1_2_path, self.node2_1_path, self.node2_2_path, ] self.attribute1_path = f"{self.node1_path}.inputs:value" self.attribute2_path = f"{self.node2_path}.inputs:value" self.attribute1_1_path = f"{self.node1_1_path}.inputs:value" self.attribute1_2_path = f"{self.node1_2_path}.inputs:value" self.attribute2_1_path = f"{self.node2_1_path}.inputs:value" self.attribute2_2_path = f"{self.node2_2_path}.inputs:value" # additional attributes of relationship types self.attribute1_target_input_path = f"{self.node3_path}.inputs:value" self.attribute1_target_output_path = f"{self.node4_path}.outputs:prims" self.attribute1_bundle_input_path = f"{self.node5_path}.inputs:bundle" self.attribute_paths = [ self.attribute1_path, self.attribute2_path, self.attribute1_1_path, self.attribute1_2_path, self.attribute2_1_path, self.attribute2_2_path, self.attribute1_target_input_path, self.attribute1_target_output_path, self.attribute1_bundle_input_path, ] self.variable_bool_name = "variable_bool" self.variable_float_name = "variable_float" self.variable_double_name = "variable_double" self.variable_names = [ self.variable_bool_name, self.variable_float_name, self.variable_double_name, ] # -------------------------------------------------------------------------------------------------------------- @staticmethod def __graph_id_from_path(graph_path: str, lookup_type: str) -> Union[str, Sdf.Path, og.Graph, None]: """Return a typed graph lookup value based on the lookup requested""" if lookup_type == GRAPH_BY_GRAPH: return og.get_graph_by_path(graph_path) if lookup_type == GRAPH_BY_PATH: return graph_path if lookup_type == GRAPH_BY_SDF_PATH: return Sdf.Path(graph_path) return None # -------------------------------------------------------------------------------------------------------------- @staticmethod def __node_id_from_path(node_path: str, lookup_type: str) -> Union[str, Usd.Prim, og.Node, None]: """Return a typed node lookup value based on the lookup requested""" if lookup_type == NODE_BY_NODE: return og.get_node_by_path(node_path) if lookup_type == NODE_BY_PATH: return node_path if lookup_type == NODE_BY_USD_PRIM: return omni.usd.get_context().get_stage().GetPrimAtPath(node_path) return None # -------------------------------------------------------------------------------------------------------------- @staticmethod def __node_type_id_from_info(type_name: str, node_type: og.NodeType, node: og.Node, lookup_type: str) -> NodeType_t: """Return a typed node type lookup value based on the lookup requested""" if lookup_type == NODE_TYPE_BY_NODE: return node if lookup_type == NODE_TYPE_BY_NODE_TYPE: return node_type if lookup_type == NODE_TYPE_BY_NAME: return og.get_node_type(type_name).get_node_type() if lookup_type == NODE_TYPE_BY_USD_PRIM: return omni.usd.get_context().get_stage().GetPrimAtPath(node.get_prim_path()) return None # -------------------------------------------------------------------------------------------------------------- @staticmethod def __attribute_id_from_path( attribute_path: str, attribute_type: str, node: Optional[og.Node] = None ) -> Union[str, Usd.Attribute, og.Attribute, None]: """Return a typed attribute lookup value based on the lookup requested. Args: attribute_path: Absolute (if node is None) or relative (if node is not None) path to attribute attribute_type: ID type to return that represents the attribute node: Optional node to which the attribute belongs Returns: ID type requested that corresponds to the attribute that was found Raises: og.OmniGraphError if the attribute configuration information does not provide a unique lookup location """ (node_path, attribute_relative_path) = attribute_path.split(".") if not attribute_relative_path: # No separator means the path is a relative attribute path and the node must be specified, and contain # the attribute passed in. if node is None: raise og.OmniGraphError(f"Relative attribute path {attribute_path} requires a node to resolve") attribute_relative_path = node_path node_path = node.get_prim_path() else: node_lookup = og.get_node_by_path(node_path) try: node_lookup_handle = node_lookup.get_handle() if node_lookup is not None else None except AttributeError as error: raise og.OmniGraphError( f"Node extracted from attribute path '{attribute_path}' was not a valid og.Node" ) from error # If a node was specified, and was also a part of the attribute path, make sure they match if node is not None: try: node_handle = node.get_handle() except AttributeError as error: raise og.OmniGraphError(f"Node description passed in ({node}) was not a valid og.Node") from error if node_lookup is None or node_handle != node_lookup_handle: raise og.OmniGraphError( f"Node extracted from attribute path '{attribute_path}' " "did not match the node passed in {node.get_prim_path()}" ) else: node = node_lookup if attribute_type == ATTRIBUTE_BY_ATTRIBUTE: if not node.get_attribute_exists(attribute_relative_path): raise og.OmniGraphError(f"No attribute {attribute_relative_path} exists on node {node.get_prim_path()}") return node.get_attribute(attribute_relative_path) if attribute_type == ATTRIBUTE_BY_PATH: return f"{node_path}.{attribute_relative_path}" if attribute_type == ATTRIBUTE_BY_SDF_PATH: return Sdf.Path(f"{node_path}.{attribute_relative_path}") if attribute_type == ATTRIBUTE_BY_USD_ATTRIBUTE: return ( omni.usd.get_context().get_stage().GetPropertyAtPath(Sdf.Path(f"{node_path}.{attribute_relative_path}")) ) return None # -------------------------------------------------------------------------------------------------------------- def __test_graph_lookup(self, graphs: Dict[str, og.Graph]): """Run the test on this method that looks up a graph from identifying information. def graph(cls, graph_id: GraphSpecs_t) -> Union[og.Graph, List[og.Graph]]: Args: graphs: Dictionary of path:graph for expected graphs being looked up """ # Test graph lookup for path, graph in graphs.items(): for lookup in GRAPH_LOOKUPS: graph_lookup = og.ObjectLookup.graph(self.__graph_id_from_path(path, lookup)) lookup_msg = f"Looking up graph {path} by {lookup}" if lookup == GRAPH_NONE: self.assertIsNone(graph_lookup, lookup_msg) else: self.assertIsNotNone(graph_lookup, lookup_msg) self.assertEqual(graph.get_handle(), graph_lookup.get_handle(), lookup_msg) # Test list of graph lookup graph_paths = list(graphs.keys()) all_graphs = og.ObjectLookup.graph(graph_paths) for index, path in enumerate(graph_paths): graph_lookup = all_graphs[index] self.assertIsNotNone(graph_lookup, f"List-based lookup of graph {path}") self.assertEqual( graph_lookup.get_handle(), graphs[path].get_handle(), f"Lookup graph by list, item {index} = {path}" ) # Test failing graph lookups self.assertIsNone(og.ObjectLookup.graph(None), "Looking up None graph") self.assertIsNone(og.ObjectLookup.graph("/NoGraph"), "Looking up unknown graph path") self.assertIsNone(og.ObjectLookup.graph(self.node1_path), "Looking up non-graph path") self.assertIsNone(og.ObjectLookup.graph(Sdf.Path("/NoGraph")), "Looking up unknown graph path") self.assertIsNone(og.ObjectLookup.graph(Sdf.Path(self.node1_path)), "Looking up non-graph Sdf path") # -------------------------------------------------------------------------------------------------------------- def __test_node_lookup(self, nodes: Dict[str, og.Node]): """Run the set of tests to look up nodes from identifying information using these API functions. def node(cls, node_id: NodeSpecs_t, graph: GraphSpec_t = None) -> Union[og.Node, List[og.Node]]: def prim(cls, node_id: NodeSpecs_t, graph: GraphSpec_t = None) -> Union[Usd.Prim, List[Usd.Prim]]: def node_path(cls, node_id: NodeSpecs_t, graph: GraphSpec_t = None) -> Union[str, List[str]]: Args: nodes: Dictionary of path:node for expected nodes being looked up """ # Test various node lookups for graph_lookup_type in GRAPH_LOOKUPS: for path, node in nodes.items(): graph_path = node.get_graph().get_path_to_graph() graph_id = self.__graph_id_from_path(graph_path, graph_lookup_type) for lookup in NODE_LOOKUPS: # Looking up a node without a node identifier is not possible if lookup == NODE_NONE: continue # If a node spec requires a graph and there isn't one then skip it (it will be tested below) if lookup in [NODE_BY_PATH, NODE_BY_TUPLE] and graph_id is None: continue if lookup == NODE_BY_TUPLE: (graph, node_path) = og.ObjectLookup.split_graph_from_node_path(path) node_lookup = og.ObjectLookup.node((node_path, graph)) else: node_id = self.__node_id_from_path(path, lookup) node_lookup = og.ObjectLookup.node(node_id, graph_id) lookup_msg = ( f"Looking up node {path} by {lookup} in graph {graph_path} found by {graph_lookup_type}" ) if lookup == NODE_NONE: self.assertIsNone(node_lookup, lookup_msg) else: self.assertIsNotNone(node_lookup, lookup_msg) self.assertEqual(node.get_handle(), node_lookup.get_handle(), lookup_msg) if graph_lookup_type == GRAPH_NONE: prim_lookup = og.ObjectLookup.prim(node_id) if lookup == NODE_NONE: self.assertIsNone(prim_lookup, lookup_msg) else: self.assertIsNotNone(prim_lookup, lookup_msg) self.assertEqual(node.get_prim_path(), prim_lookup.GetPrimPath(), lookup_msg) node_path_lookup = og.ObjectLookup.node_path(node_id) if lookup == NODE_NONE: self.assertIsNone(node_path_lookup, lookup_msg) else: self.assertIsNotNone(node_path_lookup, lookup_msg) self.assertEqual(node.get_prim_path(), node_path_lookup, lookup_msg) # Test list of node lookups node_paths = list(nodes.keys()) all_nodes = og.ObjectLookup.node(node_paths) for index, path in enumerate(node_paths): node_lookup = all_nodes[index] self.assertIsNotNone(node_lookup, f"List-based lookup of node {path}") self.assertEqual( node_lookup.get_handle(), nodes[path].get_handle(), f"Lookup by node, item {index} = {path}" ) # Test failing node lookups with self.assertRaises(og.OmniGraphValueError): og.ObjectLookup.node(None) for parameters in [ ["/NoNode"], # Non-existent path [self.inner_graph2_1_path], # Non-node path [self.node1_path, og.ObjectLookup.graph(self.outer_graph2_path)], # Mismatched graph ]: with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node(*parameters) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.prim("/NotAPrim") # -------------------------------------------------------------------------------------------------------------- def __test_node_type_lookup(self, nodes: Dict[str, og.Node]): """Run the set of tests to look up node types from identifying information using this API. def node_type(cls, type_id: NodeTypes_t) -> Union[og.NodeType, List[og.NodeType]]: Args: nodes: Dictionary of path:node for expected nodes being looked up """ node_types = [(node.get_node_type().get_node_type(), node.get_node_type(), node) for node in nodes.values()] for name, expected_node_type, node in node_types: self.assertTrue(expected_node_type.is_valid(), f"Checking lookup of node type {name}") for lookup in NODE_TYPE_LOOKUPS: lookup_msg = f"Looking up node type {name} by {lookup}" node_type_lookup = og.ObjectLookup.node_type( self.__node_type_id_from_info(name, expected_node_type, node, lookup) ) self.assertIsNotNone(node_type_lookup, lookup_msg) self.assertTrue(node_type_lookup, lookup_msg) # Test list of node type lookups all_lookups = [name for name, _, _ in node_types] all_lookups += [node_type for _, node_type, _ in node_types] all_lookups += [node for _, _, node in node_types] all_lookups += [og.ObjectLookup.prim(node) for _, _, node in node_types] all_node_types = og.ObjectLookup.node_type(all_lookups) node_type_count = len(node_types) for index, (_, node_type, _) in enumerate(node_types): msg = f"Lookup of {all_lookups[index]} by" self.assertEqual(all_node_types[index], node_type, f"{msg} name") self.assertEqual(all_node_types[index + node_type_count], node_type, f"{msg} node type") self.assertEqual(all_node_types[index + node_type_count * 2], node_type, f"{msg} node") self.assertEqual(all_node_types[index + node_type_count * 3], node_type, f"{msg} prim") # Test failing node type lookups with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type(None) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type("omni.this.type.is.invalid") with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type(og.get_node_by_path("/This/Is/Not/A/Node")) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.node_type(og.get_node_type("omni.this.type.is.invalid")) # -------------------------------------------------------------------------------------------------------------- def __test_variable_lookup(self): """Run the set of tests for running variable lookup from identifying information def variable(cls, variable_id: Variables_t) -> Union[og.IVariable, List[og.IVariable]]: """ graph_with_variables = og.ObjectLookup.graph(self.outer_graph1_path) graph_without_variables = og.ObjectLookup.graph(self.outer_graph2_path) variables = [graph_with_variables.find_variable(x) for x in self.variable_names] variable_tuples = [(graph_with_variables, x) for x in self.variable_names] # Test lookup of variable types for v in variables: self.assertTrue(bool(v)) self.assertEquals(v, og.ObjectLookup.variable(v)) self.assertEquals(v, og.ObjectLookup.variable((graph_with_variables, v.name))) self.assertEquals(v, og.ObjectLookup.variable(v.source_path)) self.assertEquals(v, og.ObjectLookup.variable(Sdf.Path(v.source_path))) # Test lookup with wrong graph with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable((graph_without_variables, v.name)) # Test lookup with wrong name with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable((graph_with_variables, "Variable4")) # Test list lookup self.assertEquals(variables, og.ObjectLookup.variable(variables)) self.assertEquals(variables, og.ObjectLookup.variable(variable_tuples)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable(None) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable("Invalid string") with self.assertRaises(og.OmniGraphError): og.ObjectLookup.variable([variables[0], "Invalid Entry"]) # -------------------------------------------------------------------------------------------------------------- def __test_attribute_lookup(self): """Run the set of tests to look up attributes from identifying information using this API. def attribute(cls, attribute_id: AttributeSpecs_t, node: NodeSpec_t = None, graph: GraphSpec_t = None) -> Union[og.Attribute, List[og.Attribute]]: def usd_attribute(cls, attribute_id: AttributeSpecs_t) -> Union[Usd.Attribute, List[Usd.Attribute]]: """ # Dictionary mapping the attribute path as a string to the actual attribute attributes = { attribute_path: self.__attribute_id_from_path(attribute_path, ATTRIBUTE_BY_ATTRIBUTE) for attribute_path in self.attribute_paths } # Dictionary mapping the attribute path as a string to the corresponding Usd.Attribute stage = omni.usd.get_context().get_stage() usd_attributes = { attribute_path: stage.GetPropertyAtPath(attribute_path) for attribute_path in self.attribute_paths } # Test various attribute lookups for graph_lookup_type in GRAPH_LOOKUPS: # noqa: PLR1702 for node_lookup_type in NODE_LOOKUPS: for path, attribute in attributes.items(): graph_path = attribute.get_node().get_graph().get_path_to_graph() graph_lookup_msg = f"graph {graph_path} found by {graph_lookup_type}" graph_lookup = self.__graph_id_from_path(graph_path, graph_lookup_type) node_path = attribute.get_node().get_prim_path() node_lookup_msg = f"in node {node_path} found by {node_lookup_type}" node_lookup = self.__node_id_from_path(node_path, node_lookup_type) for lookup in ATTRIBUTE_LOOKUPS: try: node = og.ObjectLookup.node(node_lookup) except og.OmniGraphValueError: node = None if lookup == ATTRIBUTE_BY_TUPLE: # The tuple lookup only works with valid nodes if node is None: continue attribute_lookup = og.ObjectLookup.attribute((attribute.get_name(), node)) usd_property_lookup = og.ObjectLookup.usd_property((attribute.get_name(), node)) else: attribute_id = self.__attribute_id_from_path(path, lookup, node) attribute_lookup = og.ObjectLookup.attribute(attribute_id, node_lookup, graph_lookup) if node_lookup is None and graph_lookup is None: usd_property_lookup = og.ObjectLookup.usd_property(attribute_id) else: # We have to catch the case of the lookup being None so use a different value to # flag the fact that this combination doesn't require testing of Usd.Attribute lookup usd_property_lookup = "" lookup_msg = f"Looking up attribute {path} by {lookup} {node_lookup_msg} {graph_lookup_msg}" self.assertIsNotNone(usd_property_lookup, lookup_msg) self.assertEqual(attribute.get_handle(), attribute_lookup.get_handle(), lookup_msg) lookup_msg = lookup_msg.replace("attribute", "Usd.Attribute") usd_attribute = usd_attributes[path] self.assertIsNotNone(attribute_lookup, lookup_msg) if usd_property_lookup != "": self.assertEqual(usd_attribute.GetPath(), usd_property_lookup.GetPath(), lookup_msg) # Test list of attribute lookups attribute_paths = list(attributes.keys()) all_attributes = og.ObjectLookup.attribute(attribute_paths) for index, path in enumerate(attribute_paths): attribute_lookup = all_attributes[index] self.assertIsNotNone(attribute_lookup, f"List-based lookup of attribute {path}") self.assertEqual( attribute_lookup.get_handle(), attributes[path].get_handle(), f"Lookup by attribute, item {index} = {path}", ) # Test failing attribute lookups with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(None) # None is illegal with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(f"{self.node1_path}.FooBar") # Non-existent attribute on legal node with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(self.inner_graph2_1_path) # Non-attribute path with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute(self.attribute1_path, self.node1_1_path) # Mismatched node with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(None) # None is illegal with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(f"{self.node1_path}.FooBar") # Non-existent attribute on legal node with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute(self.inner_graph2_1_path) # Non-attribute path with self.assertRaises(og.OmniGraphError): og.ObjectLookup.usd_attribute((self.attribute1_path, self.node1_1_path)) # Mismatched node # -------------------------------------------------------------------------------------------------------------- async def test_object_identification(self): """Test operation of the utility class that identifies nodes, attributes, and graphs from a variety of inputs. This is the structure of the relevant parts of the test file: def Xform "World" def OmniGraph "OuterGraph1" custom bool graph:variable:var_bool def OmniGraph "InnerGraph1" def OmniGraphNode "constant_float" custom float inputs:value def OmniGraph "InnerGraph2" def OmniGraphNode "constant_int" custom int inputs:value def OmniGraphNode "constant_bool" custom bool inputs:value def OmniGraph "OuterGraph2" def OmniGraphNode "constant_double" custom double inputs:value def ComputeGraph "InnerGraph1" def OmniGraphNode "constant_uint" custom uint inputs:value def ComputeGraph "InnerGraph2" def OmniGraphNode "constant_uint64" custom uint64 inputs:value """ await self.__populate_data() # Dictionary mapping the graph path as a string to the actual graph graphs = {graph_path: self.__graph_id_from_path(graph_path, GRAPH_BY_GRAPH) for graph_path in self.graph_paths} # Make sure all of the expected graphs from the file were found for path, graph in graphs.items(): self.assertIsNotNone(graph, f"Graph at {path}") # Dictionary mapping the node path as a string to the actual node nodes = {node_path: self.__node_id_from_path(node_path, NODE_BY_NODE) for node_path in self.node_paths} # Make sure all of the excpected node paths from the file were found for path, node in nodes.items(): self.assertIsNotNone(node, f"Node at {path}") # Make sure the nodes belong to their expected graph nodes_graph = {node: node.get_graph() for node in nodes.values()} for node, graph in nodes_graph.items(): self.assertIsNotNone(graph, f"Graph of node {node.get_prim_path()}") node_lookup = graph.get_node(node.get_prim_path()) self.assertIsNotNone(node_lookup, f"Lookup in graph of node {node.get_prim_path()}") self.assertEqual(node.get_handle(), node_lookup.get_handle(), f"Node {node.get_prim_path()} matches lookup") self.__test_graph_lookup(graphs) self.__test_node_lookup(nodes) self.__test_attribute_lookup() self.__test_node_type_lookup(nodes) self.__test_variable_lookup() # -------------------------------------------------------------------------------------------------------------- async def test_attribute_type_identification(self): """The attribute type ID does not rely on file contents so it can be tested in isolation.""" # AttributeType_t = Union[str, og.Type] # def attribute_type(cls, type_id: AttributeType_t) -> og.Type: attribute_types = { type_name: og.AttributeType.type_from_ogn_type_name(type_name) for type_name in ogn.supported_attribute_type_names() } # The list of all legal types for type_name, attr_type in attribute_types.items(): type_from_string = og.ObjectLookup.attribute_type(type_name) self.assertEqual(attr_type, type_from_string, f"Type from string {type_name}") type_from_type = og.ObjectLookup.attribute_type(attr_type) self.assertEqual(attr_type, type_from_type, f"Type from string {type_name}") # Illegal type names and types for illegal_type in [ "dubble", "double[5]", og.Type(og.BaseDataType.ASSET), og.Type(og.BaseDataType.TAG), og.Type(og.BaseDataType.PRIM), og.Type(og.BaseDataType.DOUBLE, 5), og.Type(og.BaseDataType.PRIM, 1, 1), og.Type(og.BaseDataType.INT, 3, 0, og.AttributeRole.COLOR), ]: if isinstance(illegal_type, og.Type): self.assertFalse(og.AttributeType.is_legal_ogn_type(illegal_type)) with self.assertRaises(og.OmniGraphError): og.ObjectLookup.attribute_type(illegal_type) # -------------------------------------------------------------------------------------------------------------- async def test_deprecation(self): """Uses the deprecation helpers to ensure the proper messaging is sent out for each type.""" (was_silenced, was_showing_stack, current_messages) = ( ogt.DeprecateMessage.SILENCE_LOG, ogt.DeprecateMessage.SHOW_STACK, ogt.DeprecateMessage._MESSAGES_LOGGED.copy(), # noqa: PLW0212 ) ogt.DeprecateMessage.SILENCE_LOG = True ogt.DeprecateMessage.SHOW_STACK = True ogt.DeprecateMessage.clear_messages() try: def __has_deprecation(pattern: str, expected_count: int) -> bool: """Returns True if the pattern appears in the deprecation messages the given number of times""" return ( sum( match is not None for match in [ re.search(pattern, message) for message in ogt.DeprecateMessage._MESSAGES_LOGGED # noqa: PLW0212 ] ) == expected_count ) class NewClass: CLASS_MEMBER = 1 def __init__(self, value: int): self._ro_value = value self._rw_value = value * 2 @classmethod def class_method(cls): pass @staticmethod def static_method(): pass def regular_method(self): pass @property def ro_property(self): return self._ro_value @property def rw_property(self): return self._rw_value @rw_property.setter def rw_property(self, value): self._rw_value = value @ogt.DeprecatedClass("Use NewClass") class DeadClass: pass renamed_class = ogt.RenamedClass(NewClass, "OldName", "Renamed to NewClass") @ogt.deprecated_function("Use new_function") def old_function(): return 7 self.assertFalse( ogt.DeprecateMessage._MESSAGES_LOGGED, "Defining deprecations should not log messages" # noqa: PLW0212 ) dead_class = DeadClass() self.assertIsNotNone(dead_class) self.assertTrue(__has_deprecation(".*Use NewClass", 1), "Instantiated a deprecated class") ogt.DeprecateMessage.clear_messages() for dead_class in [renamed_class, renamed_class(5)]: self.assertIsNotNone(dead_class) self.assertTrue(isinstance(dead_class, NewClass)) self.assertTrue(callable(dead_class.class_method)) self.assertTrue(callable(dead_class.static_method)) self.assertTrue(callable(dead_class.regular_method)) if dead_class.__class__.__name__ == "NewClass": self.assertEqual(dead_class.ro_property, 5) self.assertEqual(dead_class.rw_property, 10) dead_class.rw_property = 11 self.assertEqual(dead_class.rw_property, 11) self.assertEqual(dead_class.CLASS_MEMBER, 1) self.assertTrue( __has_deprecation(".*Renamed to NewClass", 2), f"Accessing a renamed class {ogt.DeprecateMessage.messages_logged}", ) ogt.DeprecateMessage.clear_messages() dead_value = old_function() self.assertEqual(dead_value, 7, "Return value from a deprecated function") self.assertTrue(__has_deprecation("old_function.*Use new_function", 1), "Called a deprecated function") ogt.DeprecateMessage.clear_messages() from .deprecated_module import test_function test_function() self.assertTrue( __has_deprecation("deprecated_module.*import omni.graph.core", 1), "Importing a deprecated module" ) finally: import sys ogt.DeprecateMessage.SILENCE_LOG = was_silenced ogt.DeprecateMessage.SHOW_STACK = was_showing_stack ogt.DeprecateMessage._MESSAGES_LOGGED = current_messages # noqa: PLW0212 with suppress(AttributeError): del omni.graph.test.tests.deprecated_module sys.modules.pop("omni.graph.test.tests.deprecated_module") # -------------------------------------------------------------------------------------------------------------- async def test_inspector_format(self): """Dumps out graph and Fabric contents for a sample file, just to make sure the format stays legal. This does not test any of the semantics of the data, only that it will produce legal .json data. """ await self.__populate_data() # Check the dump of the Fabric data contents = None try: context = og.get_compute_graph_contexts()[0] contents = og.OmniGraphInspector().as_json(context) json.loads(contents) except json.JSONDecodeError as error: self.assertFalse(True, f"Formatting of Fabric data inspection is not legal JSON ({error}) - {contents}") # Check the dump of the graph structure contents = None try: for graph in og.get_all_graphs(): contents = og.OmniGraphInspector().as_json(graph) json.loads(contents) except json.JSONDecodeError as error: self.assertFalse(True, f"Formatting of Fabric data inspection is not legal JSON ({error}) - {contents}") # -------------------------------------------------------------------------------------------------------------- async def test_extension_versions_match(self): """Checks to make sure the core versions cited in CHANGELOG.md and extensions.toml match.""" extension_manager = omni.kit.app.get_app().get_extension_manager() for extension_name in [ "omni.graph", "omni.graph.tools", "omni.graph.examples.cpp", "omni.graph.examples.python", "omni.graph.nodes", "omni.graph.tutorials", "omni.graph.action", "omni.graph.scriptnode", "omni.inspect", ]: # Find the canonical extension of the core, which will come from extension.toml enabled_version = None for version in extension_manager.fetch_extension_versions(extension_name): if version["enabled"]: sem_ver = version["version"] enabled_version = f"{sem_ver[0]}.{sem_ver[1]}.{sem_ver[2]}" extension_path = Path(version["path"]) self.assertIsNotNone(enabled_version, f"Failed to find enabled version of {extension_name}") # Find the latest version in the changelog and make sure it matches the enabled version re_version_changelog = re.compile( r"##\s*\[([0-9]+\.[0-9]+\.[0-9]+)\]\s*-\s*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\s*" ) changelog_path = extension_path / "docs" / "CHANGELOG.md" self.assertTrue(changelog_path.is_file(), f"Changelog file {changelog_path} not found") changelog_version = None with open(changelog_path, "r", encoding="utf-8") as log_fd: for line in log_fd: version_match = re_version_changelog.match(line) if version_match: changelog_version = version_match.group(1) break self.assertEqual(enabled_version, changelog_version, f"Mismatch in versions of {changelog_path}")
41,187
Python
48.386091
120
0.564766
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_dynamic_attributes.py
"""Tests related to the dynamic attribute Python interface generation feature""" import carb import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit from omni.graph.tools._impl.node_generator.attributes.naming import CPP_KEYWORDS, PYTHON_KEYWORDS, SAFE_CPP_KEYWORDS from pxr import UsdGeom # ============================================================================================================== class TestDynamicAttributes(ogts.OmniGraphTestCase): """Testing to ensure dynamic attributes works""" TEST_GRAPH_PATH = "/World/TestGraph" # -------------------------------------------------------------------------------------------------------------- async def __test_dynamic_attributes(self, node_type: str): """Test basic creation and interaction with the dynamic attribute accessors, used in the test node compute""" controller = og.Controller() keys = og.Controller.Keys (test_graph, _, _, _) = controller.edit(self.TEST_GRAPH_PATH) async def test_helper(create_usd): node_path = f"{self.TEST_GRAPH_PATH}/TestNode{create_usd}" og.cmds.CreateNode( graph=test_graph, node_path=node_path, node_type=f"omni.graph.tutorials.{node_type}", create_usd=create_usd, ) test_node = controller.node(node_path) self.assertTrue(test_node.is_valid()) controller.edit(test_graph, {keys.SET_VALUES: (("inputs:value", test_node), 127)}) output = controller.attribute("outputs:result", test_node) # Although this test only requires a single node it cannot be done via the .ogn test generator as it # needs to perform dynamic attribute manipulation between evaluations. # First test confirms the initial value is copied unchanged await controller.evaluate(test_graph) self.assertEqual(127, og.Controller.get(output)) # Second test adds a bit manipulator and confirms the bit it defines is manipulated properly self.assertTrue(test_node.create_attribute("inputs:firstBit", og.Type(og.BaseDataType.UINT))) controller.edit(test_graph, {keys.SET_VALUES: (("inputs:firstBit", test_node), 3)}) await controller.evaluate(test_graph) self.assertEqual(119, og.Controller.get(output)) # Third test adds a second bit manipulator and confirms that both bits are manipulated properly self.assertTrue(test_node.create_attribute("inputs:secondBit", og.Type(og.BaseDataType.UINT))) controller.edit(test_graph, {keys.SET_VALUES: (("inputs:secondBit", test_node), 7)}) await controller.evaluate(test_graph) self.assertEqual(247, og.Controller.get(output)) # Fourth test removes the first bit manipulator and confirms the output adapts accordingly self.assertTrue(test_node.remove_attribute("inputs:firstBit")) await controller.evaluate(test_graph) self.assertEqual(255, og.Controller.get(output)) # Fifth test alters the value of the modified bit and confirms the output adapts accordingly controller.edit(test_graph, {keys.SET_VALUES: (("inputs:secondBit", test_node), 4)}) await controller.evaluate(test_graph) self.assertEqual(111, og.Controller.get(output)) # Final test adds in the inversion attribute, with timecode role solely for the sake of checking role access self.assertTrue( test_node.create_attribute( "inputs:invert", og.Type(og.BaseDataType.FLOAT, 1, 0, og.AttributeRole.TIMECODE) ) ) await controller.evaluate(test_graph) self.assertEqual(0xFFFFFFFF - 111, og.Controller.get(output)) await test_helper(True) await test_helper(False) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_py(self): """Test basic creation and interaction with the dynamic attribute accessors for the Python implementation""" await self.__test_dynamic_attributes("DynamicAttributesPy") # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_bundle(self): """Test basic creation and interaction with a bundle dynamic attribute""" controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) UsdGeom.Xformable(cube).AddTranslateOp() (_, nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.SET_VALUES: [ ("ReadPrimsBundle.inputs:usePaths", True), ("ReadPrimsBundle.inputs:primPaths", {"value": "/World/Cube", "type": "path"}), ("ExtractPrim.inputs:primPath", "/World/Cube"), ], keys.CONNECT: [ ("ReadPrimsBundle.outputs_primsBundle", "ExtractPrim.inputs:prims"), ], }, ) # creates some attributes on the script node script = nodes[2] matrix_type = og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX) self.assertTrue( script.create_attribute( "inputs:bundle", og.Type(og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.BUNDLE) ) ) self.assertTrue( script.create_attribute("outputs:matrix", matrix_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) ) # connect them controller.edit("/TestGraph", {keys.CONNECT: ("ExtractPrim.outputs_primBundle", "Script.inputs:bundle")}) # set a script that extract the matrix s = 'db.outputs.matrix = db.inputs.bundle.get_attribute_by_name("worldMatrix").get()' controller.edit("/TestGraph", {keys.SET_VALUES: ("Script.inputs:script", s)}) # evaluate await controller.evaluate() # check that we have a matrix matrix_attr = controller.attribute("outputs:matrix", script) matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 0) self.assertEqual(matrix_val[13], 0) self.assertEqual(matrix_val[14], 0) attr = cube.GetAttribute("xformOp:translate") attr.Set((2, 3, 4)) # evaluate await controller.evaluate() # check that we have a new matrix matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 2) self.assertEqual(matrix_val[13], 3) self.assertEqual(matrix_val[14], 4) # ---------------------------------------------------------------------- async def test_deprecated_dynamic_attributes_deprecated_bundle(self): """Test basic creation and interaction with a bundle dynamic attribute This is a backward compatibility test for deprecated ReadPrim. """ controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) UsdGeom.Xformable(cube).AddTranslateOp() (_, nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrimBundle", "omni.graph.nodes.ReadPrimBundle"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.SET_VALUES: [ ("ReadPrimBundle.inputs:usePath", True), ("ReadPrimBundle.inputs:primPath", "/World/Cube"), ], keys.CONNECT: [ ("ReadPrimBundle.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], }, ) # creates some attributes on the script node script = nodes[2] matrix_type = og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX) self.assertTrue( script.create_attribute( "inputs:bundle", og.Type(og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.BUNDLE) ) ) self.assertTrue( script.create_attribute("outputs:matrix", matrix_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) ) # connect them controller.edit("/TestGraph", {keys.CONNECT: ("ExtractBundle.outputs_passThrough", "Script.inputs:bundle")}) # set a script that extract the matrix s = 'db.outputs.matrix = db.inputs.bundle.get_attribute_by_name("worldMatrix").get()' controller.edit("/TestGraph", {keys.SET_VALUES: ("Script.inputs:script", s)}) # evaluate await controller.evaluate() # check that we have a matrix matrix_attr = controller.attribute("outputs:matrix", script) matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 0) self.assertEqual(matrix_val[13], 0) self.assertEqual(matrix_val[14], 0) attr = cube.GetAttribute("xformOp:translate") attr.Set((2, 3, 4)) # evaluate await controller.evaluate() # check that we have a new matrix matrix_val = matrix_attr.get() self.assertEqual(matrix_val[12], 2) self.assertEqual(matrix_val[13], 3) self.assertEqual(matrix_val[14], 4) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_cpp(self): """Test basic creation and interaction with the dynamic attribute accessors for the C++ implementation""" await self.__test_dynamic_attributes("DynamicAttributes") # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attribute_load(self): """Test basic creation and interaction with the dynamic attribute accessors, used in the test node compute""" (result, error) = await ogts.load_test_file("TestDynamicAttributes.usda", use_caller_subdirectory=True) self.assertTrue(result, error) controller = og.Controller() keys = og.Controller.Keys # The files each contain a set of test nodes in the different configurations of their dynamic attributes. # The name indicates which dynamic attributes exist on the node, similar to what the above test uses. # Test data is a list of five elements: # Node to test # Should the firstBit attribute be present? # Should the secondBit attribute be present? # Should the invert attribute be present? # Expected output value when the input is set to 127 test_data = [ ["/graph/NoDynamicAttributes", False, False, False, 127], ["/graph/OnlyFirst", True, False, False, 119], ["/graph/FirstAndSecond", True, True, False, 103], ["/graph/SecondInvert", False, True, True, 0xFFFFFFFF - 111], ["/graph/NoDynamicAttributesPy", False, False, False, 127], ["/graph/OnlyFirstPy", True, False, False, 119], ["/graph/FirstAndSecondPy", True, True, False, 103], ["/graph/SecondInvertPy", False, True, True, 0xFFFFFFFF - 111], ] for node_name, first_expected, second_expected, invert_expected, result_expected in test_data: node = controller.node(node_name) controller.edit("/graph", {keys.SET_VALUES: (("inputs:value", node), 127)}) await controller.evaluate() output = controller.attribute("outputs:result", node) self.assertIsNotNone(output) # Test for the presence of the expected dynamic attributes attributes_actual = [a.get_name() for a in node.get_attributes()] first_actual = "inputs:firstBit" in attributes_actual self.assertEqual(first_actual, first_expected, f"Dynamic attribute firstBit presence in {node_name}") second_actual = "inputs:secondBit" in attributes_actual self.assertEqual(second_actual, second_expected, f"Dynamic attribute secondBit presence in {node_name}") invert_actual = "inputs:invert" in attributes_actual self.assertEqual(invert_actual, invert_expected, f"Dynamic attribute invert presence in {node_name}") # Test the correct output value self.assertEqual(result_expected, og.Controller.get(output)) # -------------------------------------------------------------------------------------------------------------- async def __remove_connected_attribute(self, use_controller: bool): """ Test what happens when removing dynamic attributes that have connections, both incoming and outgoing. Args: use_controller: If True then use the og.Controller methods rather than the direct commands (This is mostly possible due to the fact that the controller and the command take the same argument list.) """ controller = og.Controller() keys = og.Controller.Keys (_, (source_node, sink_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Source", "omni.graph.tutorials.DynamicAttributesPy"), ("Sink", "omni.graph.tutorials.DynamicAttributesPy"), ] }, ) def run_create(**kwargs): """Select and run the appropriate create attribute command""" if use_controller: return og.NodeController.create_attribute(**kwargs) is not None if not og.cmds.CreateAttr(**kwargs)[1]: raise og.OmniGraphError(f"Create attribute using {kwargs} failed") return True def run_remove(**kwargs): """Select and run the appropriate remove attribute command""" if use_controller: return og.NodeController.remove_attribute(**kwargs) if not og.cmds.RemoveAttr(**kwargs)[1]: raise og.OmniGraphError(f"Remove attribute using {kwargs} failed") return True # Set up dynamic attributes on both source and sink and connect them self.assertTrue( run_create( node=source_node, attr_name="source", attr_type="float", attr_port=og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) ) source_attr = source_node.get_attribute("outputs:source") self.assertIsNotNone(source_attr) self.assertTrue( run_create( node=sink_node, attr_name="sink", attr_type="float", attr_port=og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, ) ) sink_attr = sink_node.get_attribute("inputs:sink") self.assertIsNotNone(sink_attr) controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: (source_attr, sink_attr)}) self.assertEqual([source_attr], sink_attr.get_upstream_connections()) # Try to remove the source attribute, failing due to the connection existing with self.assertRaises(og.OmniGraphError): run_remove(attribute=source_attr) # Remove the connections, then remove the source attribute, which should now succeed (success, result) = og.cmds.DisconnectAllAttrs(attr=source_attr, modify_usd=True) self.assertTrue(success, f"Disconnect all from source - {result}") self.assertTrue(run_remove(attribute=source_attr), "Remove source") self.assertEqual(0, sink_attr.get_upstream_connection_count()) # Restore the attribute and confirm the connection has returned omni.kit.undo.undo() omni.kit.undo.undo() source_attr = source_node.get_attribute("outputs:source") self.assertEqual(1, sink_attr.get_upstream_connection_count()) self.assertEqual(1, source_attr.get_downstream_connection_count()) # Try to remove the source attribute, failing due to the connection existing with self.assertRaises(og.OmniGraphError): run_remove(attribute=sink_attr) # Remove the connection, then remove the sink attribute, which should now succeed (success, result) = og.cmds.DisconnectAllAttrs(attr=sink_attr, modify_usd=True) self.assertTrue(success, "Disconnect all from sink") self.assertTrue(run_remove(attribute=sink_attr), "Remove sink") # Restore the attribute and confirm the connection has returned omni.kit.undo.undo() omni.kit.undo.undo() sink_attr = sink_node.get_attribute("inputs:sink") self.assertEqual(1, sink_attr.get_upstream_connection_count()) self.assertEqual(1, source_attr.get_downstream_connection_count()) # Confirm that the attribute configuration hasn't changed self.assertEqual("outputs:source", source_attr.get_name()) self.assertEqual("float", source_attr.get_type_name()) self.assertEqual(og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, source_attr.get_port_type()) self.assertEqual(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, source_attr.get_extended_type()) # TODO: Check on the default once it has been added self.assertEqual(0.0, source_attr.get()) self.assertEqual("inputs:sink", sink_attr.get_name()) self.assertEqual("float", sink_attr.get_type_name()) self.assertEqual(og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, sink_attr.get_port_type()) self.assertEqual(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, sink_attr.get_extended_type()) # TODO: Check on the default once it has been added self.assertEqual(0.0, sink_attr.get()) # -------------------------------------------------------------------------------------------------------------- async def test_remove_connected_attribute_by_command(self): """Run the dynamic attribute removal tests by direct commands""" await self.__remove_connected_attribute(False) # -------------------------------------------------------------------------------------------------------------- async def test_remove_connected_attribute_by_controller(self): """Run the dynamic attribute removal tests by using the Controller class""" await self.__remove_connected_attribute(True) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_extended_attribute_customdata(self): """Test that creating dynamic extended attribute types sets the extended types correctly""" controller = og.Controller() keys = og.Controller.Keys (_, (node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("Node", "omni.graph.tutorials.DynamicAttributesPy")} ) exec_attr = controller.create_attribute( node, "outputs:exec", og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) any_attr = controller.create_attribute( node, "outputs:any", "any", og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, ) union_attr = controller.create_attribute( node, "outputs:union", "[int, double[3], float[3]]", og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, None, (og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, ["int", "double[3]", "float[3]"]), ) int_attr = controller.create_attribute(node, "inputs:int", "int") stage = omni.usd.get_context().get_stage() node_prim = stage.GetPrimAtPath(node.get_prim_path()) exec_metadata = node_prim.GetAttribute(exec_attr.get_name()).GetCustomData() any_metadata = node_prim.GetAttribute(any_attr.get_name()).GetCustomData() union_metadata = node_prim.GetAttribute(union_attr.get_name()).GetCustomData() int_metadata = node_prim.GetAttribute(int_attr.get_name()).GetCustomData() self.assertEqual(exec_metadata, {"ExecutionType": True}) self.assertEqual(any_metadata, {"ExtendedAttributeType": "Any", "omni": {"graph": {"attrType": "Any"}}}) self.assertEqual( union_metadata, { "ExtendedAttributeType": "Union-->int,double[3],float[3]", "omni": {"graph": {"attrType": "Union-->int,double[3],float[3]"}}, }, ) self.assertEqual(int_metadata, {}) # -------------------------------------------------------------------------------------------------------------- async def test_load_dynamic_extended_attribute_customdata(self): """The test file uses the deprecated global implicit graph so this also tests automatic conversion""" (result, error) = await ogts.load_test_file("TestDynamicExtendedAttributes.usda", use_caller_subdirectory=True) self.assertTrue(result, error) controller = og.Controller() exec_attr = controller.attribute("outputs:exec", "/__graphUsingSchemas/node") any_attr = controller.attribute("outputs:any", "/__graphUsingSchemas/node") union_attr = controller.attribute("outputs:union", "/__graphUsingSchemas/node") self.assertEqual(exec_attr.get_resolved_type(), og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION)) self.assertEqual(any_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN)) self.assertEqual(union_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN)) self.assertEqual(exec_attr.get_extended_type(), og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEqual(any_attr.get_extended_type(), og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertEqual(union_attr.get_extended_type(), og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEqual(exec_attr.get_union_types(), None) self.assertEqual(any_attr.get_union_types(), None) self.assertEqual(union_attr.get_union_types(), ["int", "double[3]", "float[3]"]) # -------------------------------------------------------------------------------------------------------------- async def test_dynamic_attributes_memory_location(self): """Test that modifying the memory location of dynamic attributes changes how the data is set or retrieved""" controller = og.Controller(undoable=False) keys = og.Controller.Keys (graph, (test_node, _, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("DynamicNode", "omni.graph.test.TestDynamicAttributeMemory"), ("ArrayDefault", "omni.graph.nodes.ConstantInt"), ("ArrayNode", "omni.graph.nodes.ConstructArray"), ("SimpleDefault", "omni.graph.nodes.ConstantDouble"), ], keys.SET_VALUES: [ ("ArrayDefault.inputs:value", 1), ("ArrayNode.inputs:arraySize", 5), ("ArrayNode.inputs:arrayType", "int[]"), ("SimpleDefault.inputs:value", 4.25), ], keys.CONNECT: [ ("ArrayDefault.inputs:value", "ArrayNode.inputs:input0"), ], }, ) await controller.evaluate() on_gpu_attr = controller.attribute("inputs:onGpu", test_node) use_gpu_attr = controller.attribute("inputs:gpuPtrsOnGpu", test_node) in_verify_attr = controller.attribute("outputs:inputMemoryVerified", test_node) out_verify_attr = controller.attribute("outputs:outputMemoryVerified", test_node) self.assertTrue(on_gpu_attr.is_valid()) self.assertTrue(use_gpu_attr.is_valid()) self.assertTrue(in_verify_attr.is_valid()) self.assertTrue(out_verify_attr.is_valid()) # Meta-test that the test node does not give false positives when no dynamic attributes exist self.assertFalse(controller.get(in_verify_attr)) self.assertFalse(controller.get(out_verify_attr)) # Add the dynamic attributes the test node will be looking for in_attr = controller.create_attribute(test_node, "inputs:simple", "double") self.assertTrue(in_attr is not None and in_attr.is_valid()) in_arr_attr = controller.create_attribute(test_node, "inputs:array", "int[]") self.assertTrue(in_arr_attr is not None and in_arr_attr.is_valid()) out_attr = controller.create_attribute(test_node, "outputs:simple", "double") self.assertTrue(out_attr is not None and out_attr.is_valid()) out_arr_attr = controller.create_attribute(test_node, "outputs:array", "int[]") self.assertTrue(out_arr_attr is not None and out_arr_attr.is_valid()) controller.edit(graph, {keys.CONNECT: ("ArrayNode.outputs:array", "DynamicNode.inputs:array")}) # Run through all of the legal memory locations, verifying the input and output memory locations for on_gpu in [False, True, True]: for use_gpu_ptr in [False, False, True]: controller.set(on_gpu_attr, on_gpu) controller.set(use_gpu_attr, use_gpu_ptr) await controller.evaluate() self.assertTrue(controller.get(in_verify_attr), f"on_gpu={on_gpu}, use_gpu_ptr={use_gpu_ptr}") self.assertTrue(controller.get(out_verify_attr), f"on_gpu={on_gpu}, use_gpu_ptr={use_gpu_ptr}") # ---------------------------------------------------------------------- async def test_illegal_dynamic_attributes(self): """Test that attempting to create illegal attributes correctly raises an exception""" keys = og.Controller.Keys (_, (test_node,), _, _) = og.Controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SimpleDefault", "omni.graph.nodes.ConstantDouble"), ], }, ) for undoable in [False, True]: controller = og.Controller(undoable=undoable) # First addition works in_attr = controller.create_attribute(test_node, "inputs:simple", "double") self.assertTrue(in_attr is not None and in_attr.is_valid()) # Second addition raises an exception with self.assertRaises(og.OmniGraphError): with ogts.ExpectedError(): controller.create_attribute(test_node, "inputs:simple", "double") # First removal works controller.remove_attribute(in_attr) # Second removal raises an exception with self.assertRaises(og.OmniGraphError): with ogts.ExpectedError(): controller.remove_attribute("inputs:simple", test_node) # -------------------------------------------------------------------------------------------------------------- async def test_adding_keyword_attributes(self): """Confirm that attempting to add attributes that are language keywords is disallowed""" controller = og.Controller() keys = og.Controller.Keys # The exact node type doesn't matter for this test, only that one is implemented in Python and one is C++ (_, (py_node, cpp_node), _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("PyNode", "omni.graph.test.TestSubtract"), ("CppNode", "omni.graph.test.Add2IntegerArrays"), ] }, ) # First check that the Python node types rejects attributes named for Python keywords for kw in PYTHON_KEYWORDS: with ogts.ExpectedError(): with self.assertRaises(ValueError): py_node.create_attribute(f"inputs:{kw}", og.Type(og.BaseDataType.UINT)) carb.log_error(f"Incorrectly allowed addition of attribute named for Python keyword '{kw}'") # Now do the same for the C++ nodes, which have some "safe" keywords, though they do issue a warning for kw in CPP_KEYWORDS: if kw in SAFE_CPP_KEYWORDS: self.assertTrue( cpp_node.create_attribute(f"inputs:{kw}", og.Type(og.BaseDataType.UINT)), f"Trying to add attribute using C++ keyword '{kw}'", ) else: with ogts.ExpectedError(): with self.assertRaises(ValueError): cpp_node.create_attribute(f"inputs:{kw}", og.Type(og.BaseDataType.UINT)) carb.log_error(f"Incorrectly allowed addition of attribute named for C++ keyword '{kw}'") # -------------------------------------------------------------------------------------------------------------- async def test_output_raw_data_works(self): """Validate that dynamic output and state attributes accessed from the node DB allow writing the raw data pointer""" controller = og.Controller(undoable=False) keys = og.Controller.Keys (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("DynamicNode", "omni.graph.test.TestDynamicAttributeRawData"), ], }, ) # Evaluate the graph once to ensure the node has a Database created await controller.evaluate(graph) test_node = nodes[0] for i in range(10): controller.create_attribute( test_node, f"inputs:input{i}", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, i, ) controller.create_attribute( test_node, "outputs:output0", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, 0, ) controller.create_attribute( test_node, "state:state0", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE, 0, ) # Act: evaluate the graph await controller.evaluate(graph) # Assert: read the sum output and test that the dynamic attributes were included in the computation output_attr = controller.attribute("outputs:output0", test_node) self.assertEqual(45, controller.get(output_attr), "The dynamic output does not have the expected value") state_attr = controller.attribute("state:state0", test_node) self.assertEqual(45, controller.get(state_attr), "The dynamic state does not have the expected value")
31,984
Python
47.462121
124
0.580728
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_omnigraph_all_types.py
"""Tests exercising every supported OGN data type""" from math import isnan from pathlib import Path from tempfile import TemporaryDirectory from typing import Set import carb import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.nodes.tests as ognts import omni.graph.tools.ogn as ogn import omni.kit.test import omni.usd # Fast lookup of matrix dimensions, to avoid sqrt call _MATRIX_DIMENSIONS = {4: 2, 9: 3, 16: 4} # ====================================================================== class TestOmniGraphAllTypes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises all of the data types supported by OmniGraph. These tests do not exercise any, union, or bundle types, which already have plenty of their own tests. """ # These are not part of the generated attribute pattern so they will be ignored. They could be tested separately # but that won't add any value to the tests. UNCHECKED_ATTRIBUTES = [ "node:type", "node:typeVersion", "NodeWithAllTypes", "inputs:doNotCompute", "inputs:a_target", "outputs:a_target", "state:a_target", "inputs:a_bundle", "outputs_a_bundle", "state_a_bundle", "state:a_stringEmpty", "state:a_firstEvaluation", ] TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- 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 # ---------------------------------------------------------------------- def __types_to_test(self) -> Set[str]: """Returns the set of attribute type names to be tested. This consists of every type accepted by OGN, minus a few that are tested separately""" # "any" types need a different set of tests as ultimately they only represent one of the other types. # "bundle" and "target" types have different tests as they are mainly concerned with membership rather than actual data # "transform" types are omitted as they are marked for deprecation in USD so we don't want to support them types_not_tested = ["any", "bundle", "target", "transform[4]", "transform[4][]"] return [type_name for type_name in ogn.supported_attribute_type_names() if type_name not in types_not_tested] # ---------------------------------------------------------------------- async def __verify_all_types_are_tested(self, node_type_name: str): """Meta-test to ensure that the list of types tested in the sample node is the same as the list of all supported types, according to the OGN node generator. It will use the full set of supported names, drawn from the generator, and compare against the set of attribute type names that appear on the given node, extracted from the node's ABI. Args: node_type_name: Registered node type name for the node to test """ # Get the list of types to test. supported_types = self.__types_to_test() nodes_attribute_types = [] controller = og.Controller() keys = og.Controller.Keys (_, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithAllTypes", node_type_name)} ) for attribute in test_node.get_attributes(): if attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: continue attribute_name = attribute.get_name() if attribute_name in self.UNCHECKED_ATTRIBUTES: continue attribute_type = attribute.get_resolved_type() port_name = og.get_port_type_namespace(attribute.get_port_type()) expected_name = f"{port_name}:{self.__attribute_type_to_name(attribute_type)}" type_name = attribute_type.get_ogn_type_name() self.assertEqual( expected_name, attribute_name, f"Generated name differs from actual name, type {type_name}" ) nodes_attribute_types.append(type_name) self.assertCountEqual(supported_types, nodes_attribute_types) # ---------------------------------------------------------------------- async def test_all_types_tested_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__verify_all_types_are_tested("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_all_types_tested_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__verify_all_types_are_tested("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- async def __test_all_data_types(self, node_type_name: str): """Test that sets values of all supported types on the node of the given type using automatic type generators. Both the name of the attribute and the sample values for an attribute of that type are supplied automatically. The node's only function should be to assign the input to the output, so all types can be validated by simply comparing the computed output against the values that were set on the input. It is assumed that actual compute operation and input/output correspondence is done elsewhere so this type of test is sufficient to validate that access to all data types as both an input and an output is correctly implemented. Args: node_type_name: Registered node type name for the node to test """ # Get the list of types to test. supported_types = self.__types_to_test() controller = og.Controller() keys = og.Controller.Keys (graph, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithAllTypes", node_type_name)} ) 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] for type_name in supported_types ] controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ((f"inputs:{name}", test_node), value) for name, value in zip(attribute_names, expected_values) ] + [(("inputs:doNotCompute", test_node), False)] }, ) await controller.evaluate(graph) actual_values = [ og.Controller.get(controller.attribute(f"outputs:{name}", test_node)) for name in attribute_names ] for actual_value, expected_value, attribute_name in zip(actual_values, expected_values, attribute_names): ogts.verify_values(expected_value, actual_value, f"Testing output data types on {attribute_name}") actual_values = [ og.Controller.get(controller.attribute(f"state:{name}", test_node)) for name in attribute_names ] for actual_value, expected_value, attribute_name in zip(actual_values, expected_values, attribute_names): ogts.verify_values(expected_value, actual_value, f"Testing state data types on {attribute_name}") # ---------------------------------------------------------------------- async def test_all_data_types_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__test_all_data_types("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_all_data_types_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__test_all_data_types("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- async def test_all_types_extended(self): """Tests that 'any' attribute can be resolved to and correctly read/write data of all types""" carb.log_warn("Warnings of the type 'No source has valid data' are expected during this test") # AllTypes resolves the types upstream through A and B. Then we set a value on A, and ensure # the value make it through to concrete AllTypes.inputs:attrib_name # 'Any' 'Any' # +------------+ +------------+ +-----------+ # | Extended A +---->| Extended B +---->|AllTypes | # +------------+ +------------+ +-----------+ controller = og.Controller() keys = og.Controller.Keys (_, (extended_node_a, extended_node_b, all_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtendedNodeA", "omni.graph.test.TypeResolution"), ("ExtendedNodeB", "omni.graph.test.TypeResolution"), ("AllTypes", "omni.graph.test.TestAllDataTypes"), ], keys.SET_VALUES: ("AllTypes.inputs:doNotCompute", False), }, ) any_in_a = controller.attribute("inputs:anyValueIn", extended_node_a) any_in_b = controller.attribute("inputs:anyValueIn", extended_node_b) any_out_a = controller.attribute("outputs:anyValue", extended_node_a) any_out_b = controller.attribute("outputs:anyValue", extended_node_b) async def test_type(attrib_name, expected_value): # Connect the 'any' output to the typed-input to get the 'any' input to be resolved. # Then set the value of the resolved input and measure the resolved output value (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: [(any_out_b, (attrib_name, all_node)), (any_out_a, any_in_b)]} ) await controller.evaluate(graph) controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: (any_in_a, expected_value)}) await controller.evaluate(graph) actual_value_a = og.Controller.get(any_out_a) actual_value_b = og.Controller.get(any_out_b) actual_value_all = og.Controller.get(controller.attribute(attrib_name, all_node)) if isinstance(expected_value, str) or ( isinstance(expected_value, list) and isinstance(expected_value[0], str) ): self.assertEqual(expected_value, actual_value_a) self.assertEqual(expected_value, actual_value_b) self.assertEqual(expected_value, actual_value_all) else: expected_array = np.ravel(np.array(expected_value)) self.assertTrue(np.allclose(np.ravel(np.atleast_1d(actual_value_a)), expected_array)) self.assertTrue(np.allclose(np.ravel(np.atleast_1d(actual_value_b)), expected_array)) self.assertTrue(np.allclose(np.ravel(np.atleast_1d(actual_value_all)), expected_array)) # Node totally disconnects - type should be reverted to unknown controller.edit( self.TEST_GRAPH_PATH, {keys.DISCONNECT: [(any_out_b, (attrib_name, all_node)), (any_out_a, any_in_b)]} ) await controller.evaluate(graph) # objectId can not connect to 'any', so remove that from this test supported_types = [ type_name for type_name in self.__types_to_test() if type_name not in ["objectId", "objectId[]", "execution", "path"] ] attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] # We can test 2 sets of sample values expected_values_set0 = [ ogn.get_attribute_manager_type(type_name).sample_values()[0] for type_name in supported_types ] expected_values_set1 = [ ogn.get_attribute_manager_type(type_name).sample_values()[1] for type_name in supported_types ] for attrib_name, value in sorted(zip(attribute_names, expected_values_set0)): await test_type(f"inputs:{attrib_name}", value) for attrib_name, value in sorted(zip(attribute_names, expected_values_set1)): await test_type(f"inputs:{attrib_name}", value) # ---------------------------------------------------------------------- async def test_all_usd_cast_types(self): """Test that checks that bundles with USD type casting works for all available USD types""" # Set up the contents for a prim with all types. Skip types that cannot be added to a prim bundle. supported_type_names = [ type_name for type_name in self.__types_to_test() if type_name not in ["execution", "objectId", "objectId[]"] ] supported_types = [og.AttributeType.type_from_ogn_type_name(type_name) for type_name in supported_type_names] attribute_names = [self.__attribute_type_to_name(supported_type) for supported_type in supported_types] expected_values = [ ogn.get_attribute_manager_type(type_name).sample_values()[0] for type_name in supported_type_names ] # This is the array of types for which the node will attempt USD casting, which should be all of the types # mentioned in omni/graph/core/ogn/UsdTypes.h usd_cast_types = [ "half", "token", "timecode", "half[]", "token[]", "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][]", # These are caught by the timecode cast "double", "double[]", # Roles are caught by the casts too since they are ignored at that point (and not checked in the node) "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][]", ] controller = og.Controller() keys = og.Controller.Keys (graph, (_, inspector_outputs_node, inspector_state_node, _), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("UsdCastingNode", "omni.graph.test.TestUsdCasting"), ("InspectorOutput", "omni.graph.nodes.BundleInspector"), ("InspectorState", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: [ ( "/World/Prim", { name: (type_name, value) for type_name, name, value in zip(supported_types, attribute_names, expected_values) }, ) ], keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/World/Prim", "PrimExtract"), keys.CONNECT: [ ("PrimExtract.outputs_primBundle", "UsdCastingNode.inputs:a_bundle"), ("UsdCastingNode.outputs_a_bundle", "InspectorOutput.inputs:bundle"), ("UsdCastingNode.state_a_bundle", "InspectorState.inputs:bundle"), ], }, ) await controller.evaluate(graph) expected_output = {} count = 1 for index, type_name in enumerate(supported_type_names): if type_name in usd_cast_types: count += 1 expected_output[attribute_names[index]] = [ supported_types[index].get_base_type_name(), supported_types[index].tuple_count, supported_types[index].array_depth, supported_types[index].get_role_name(), expected_values[index], ] # Add in the extra attributes that aren't explicit types expected_output["sourcePrimType"] = ["token", 1, 0, "none", "OmniGraphPrim"] expected_output["sourcePrimPath"] = ["token", 1, 0, "none", "/World/Prim"] expected_results = (len(expected_output), expected_output) ognts.verify_bundles_are_equal( ognts.filter_bundle_inspector_results( ognts.bundle_inspector_results(inspector_outputs_node), [], filter_for_inclusion=False ), expected_results, ) ognts.verify_bundles_are_equal( ognts.filter_bundle_inspector_results( ognts.bundle_inspector_results(inspector_state_node), [], filter_for_inclusion=False ), expected_results, ) # ---------------------------------------------------------------------- async def __test_read_all_types_default(self, node_type_name: str): """Test that saving and loading a file containing non-standard default values correctly brings back the default values for all types. Args: node_type_name: Registered node type name for the node to test """ # Create a file containing a node of the given type and save it controller = og.Controller() keys = og.Controller.Keys (graph, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithAllTypes", node_type_name)} ) await controller.evaluate(graph) test_node_path = test_node.get_prim_path() # Get the list of types to test. supported_types = self.__types_to_test() attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] # Remember the default values in the node. A copy has to be made because otherwise the data will reference # Fabric data, which goes away when the stage is saved (because currently at that point OmniGraph is rebuilt). expected_default_values = [] for name in attribute_names: value = og.Controller.get(og.Controller.attribute(f"inputs:{name}", test_node)) if isinstance(value, np.ndarray): expected_default_values.append(value.copy()) else: expected_default_values.append(value) # -------------------------------------------------------------------------------------------------------------- # First test that the node that was saved with no values comes back in with the expected default values with TemporaryDirectory() as test_directory: tmp_file_path = Path(test_directory) / f"{node_type_name}.usda" (result, error, _) = await omni.usd.get_context().save_as_stage_async(str(tmp_file_path)) self.assertTrue(result, error) (result, error) = await omni.usd.get_context().reopen_stage_async() self.assertTrue(result, error) await og.Controller.evaluate() test_node = og.Controller.node(test_node_path) actual_values = [ og.Controller.get(controller.attribute(f"inputs:{name}", test_node)) for name in attribute_names ] for name in attribute_names: value = og.Controller.get(controller.attribute(f"inputs:{name}", test_node)) for actual, expected, name in zip(actual_values, expected_default_values, attribute_names): ogts.verify_values(expected, actual, f"Testing input data types on {name}") # ---------------------------------------------------------------------- async def test_read_all_types_default_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__test_read_all_types_default("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_read_all_types_default_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__test_read_all_types_default("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- async def __test_read_all_types_modified(self, node_type_name: str): """Test that saving and loading a file containing non-default values correctly brings back the modified values for all types. Args: node_type_name: Registered node type name for the node to test """ node_type_base_name = node_type_name.split(".")[-1] # Get the list of all types to test. supported_types = self.__types_to_test() attribute_names = [ self.__attribute_type_to_name(og.AttributeType.type_from_ogn_type_name(type_name)) for type_name in supported_types ] # Sample values from the attribute managers are known to not be the defaults of the AllNodeTypes nodes expected_sample_values = [ ogn.get_attribute_manager_type(type_name).sample_values()[0] for type_name in supported_types ] test_file_name = f"{node_type_base_name}.NonDefault.usda" (result, error) = await ogts.load_test_file(test_file_name, use_caller_subdirectory=True) self.assertTrue(result, error) test_node = og.Controller.node(f"/World/TestGraph/{node_type_base_name}") actual_values = [ og.Controller.get(og.Controller.attribute(f"inputs:{name}", test_node)) for name in attribute_names ] for actual, expected, name in zip(actual_values, expected_sample_values, attribute_names): ogts.verify_values(expected, actual, f"Testing input data types on {name}") # ---------------------------------------------------------------------- async def test_read_all_types_modified_cpp(self): """Test that the C++ node exercising all allowed types has covered everything""" await self.__test_read_all_types_modified("omni.graph.test.TestAllDataTypes") # ---------------------------------------------------------------------- async def test_read_all_types_modified_python(self): """Test that the Python node exercising all allowed types has covered everything""" await self.__test_read_all_types_modified("omni.graph.test.TestAllDataTypesPy") # ---------------------------------------------------------------------- def _sanity_check_union_values(self, types: dict): """Runs a series of tests to validate the given dictionary of unions contains expected values""" def validate_subset(subset: str, superset: str): self.assertIsNotNone(types.get(subset, None)) self.assertIsNotNone(types.get(superset, None)) subset_items = types[subset] superset_items = types[superset] for item in subset_items: self.assertIn(item, superset_items, f"Expected {item} to be in {superset}") def validate_array_form(scalar_form: str, array_form: str): self.assertIsNotNone(types.get(scalar_form, None)) self.assertIsNotNone(types.get(array_form, None)) scalar_items = types[scalar_form] array_items = types[array_form] for item in scalar_items: self.assertIn(item + "[]", array_items, f"Expected {item} to be in {array_form}") self.assertGreater(len(types), 0) for x in ["uchar", "int", "uint", "uint64", "int64"]: self.assertIn(x, types["integral_scalers"]) for x in ["int[2]", "int[3]", "int[4]"]: self.assertIn(x, types["integral_tuples"]) for x in ["double", "float", "half", "timecode"]: self.assertIn(x, types["decimal_scalers"]) for x in [ "double[2]", "double[3]", "double[4]", "float[2]", "float[3]", "float[4]", "half[2]", "half[3]", "half[4]", "colord[3]", "colord[4]", "colorf[3]", "colorf[4]", "colorh[3]", "colorh[4]", "normald[3]", "normalf[3]", "normalh[3]", "pointd[3]", "pointf[3]", "pointh[3]", "texcoordd[2]", "texcoordd[3]", "texcoordf[2]", "texcoordf[3]", "texcoordh[2]", "texcoordh[3]", "quatd[4]", "quatf[4]", "quath[4]", "vectord[3]", "vectorf[3]", "vectorh[3]", ]: self.assertIn(x, types["decimal_tuples"]) validate_subset("integral_scalers", "integral_array_elements") validate_subset("integral_tuples", "integral_array_elements") validate_array_form("integral_array_elements", "integral_arrays") validate_subset("integral_array_elements", "integrals") validate_subset("integral_arrays", "integrals") validate_subset("decimal_scalers", "decimal_array_elements") validate_subset("decimal_tuples", "decimal_array_elements") validate_array_form("decimal_array_elements", "decimal_arrays") validate_subset("decimal_array_elements", "decimals") validate_subset("decimal_arrays", "decimals") validate_subset("integral_scalers", "numeric_scalers") validate_subset("decimal_scalers", "numeric_scalers") validate_subset("integral_tuples", "numeric_tuples") validate_subset("decimal_tuples", "numeric_tuples") validate_subset("numeric_scalers", "numeric_array_elements") validate_subset("numeric_tuples", "numeric_array_elements") validate_subset("matrices", "numeric_array_elements") validate_array_form("numeric_array_elements", "numeric_arrays") validate_subset("numeric_array_elements", "numerics") validate_subset("numeric_arrays", "numerics") validate_subset("numeric_array_elements", "array_elements") validate_subset("numeric_arrays", "arrays") self.assertIn("token", types["array_elements"]) self.assertIn("token[]", types["arrays"]) # ---------------------------------------------------------------------- async def test_union_types_contain_expected_values(self): """Performs a sanity check on the attribute union values returned from the runtime""" # The same configuration file is used to populate dictionaries form both dlls. # Validate they contain the same entries # Test the dictionary loaded from omni.graph.core self._sanity_check_union_values(og.AttributeType.get_unions()) # Validate the entries are the same self.assertDictEqual(og.AttributeType.get_unions(), ogn.ATTRIBUTE_UNION_GROUPS) # ---------------------------------------------------------------------- async def __test_nan_values(self, node_type_name: str): """Test that evaluating NaN values correctly copies and extracts the values. This could not be done with a regular test sequence as NaN != NaN Args: node_type_name: Registered node type name for the node to test """ controller = og.Controller() keys = og.Controller.Keys (graph, (test_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: ("NodeWithNans", node_type_name)} ) await controller.evaluate(graph) nan_attributes = [ "colord3", "colord4", "colord3_array", "colord4_array", "colorf3", "colorf4", "colorf3_array", "colorf4_array", "colorh3", "colorh4", "colorh3_array", "colorh4_array", "double", "double2", "double3", "double4", "double_array", "double2_array", "double3_array", "double4_array", "float", "float2", "float3", "float4", "float_array", "float2_array", "float3_array", "float4_array", "frame4", "frame4_array", "half", "half2", "half3", "half4", "half_array", "half2_array", "half3_array", "half4_array", "matrixd2", "matrixd3", "matrixd4", "matrixd2_array", "matrixd3_array", "matrixd4_array", "normald3", "normald3_array", "normalf3", "normalf3_array", "normalh3", "normalh3_array", "pointd3", "pointd3_array", "pointf3", "pointf3_array", "pointh3", "pointh3_array", "quatd4", "quatd4_array", "quatf4", "quatf4_array", "quath4", "quath4_array", "texcoordd2", "texcoordd3", "texcoordd2_array", "texcoordd3_array", "texcoordf2", "texcoordf3", "texcoordf2_array", "texcoordf3_array", "texcoordh2", "texcoordh3", "texcoordh2_array", "texcoordh3_array", "timecode", "timecode_array", "vectord3", "vectord3_array", "vectorf3", "vectorf3_array", "vectorh3", "vectorh3_array", ] def __is_nan(value) -> bool: if isinstance(value, list): return all(__is_nan(element) for element in value) if isinstance(value, np.ndarray): return np.alltrue(np.isnan(value)) return isnan(value) for attribute_name in nan_attributes: attr = controller.attribute(f"outputs:a_{attribute_name}_nan", test_node) value = controller.get(attr) self.assertTrue(__is_nan(value)) attr = controller.attribute(f"outputs:a_{attribute_name}_snan", test_node) value = controller.get(attr) self.assertTrue(__is_nan(value)) # ---------------------------------------------------------------------- async def test_nan_values_cpp(self): """Test that the C++ node exercising all allowed types handles NaN values correctly""" await self.__test_nan_values("omni.graph.test.TestNanInf") # ---------------------------------------------------------------------- async def test_nan_values_python(self): """Test that the Python node exercising all allowed types handles NaN values correctly""" await self.__test_nan_values("omni.graph.test.TestNanInfPy") async def test_node_database_id_py(self): """Test if database id is not changing between graph evaluations""" controller = og.Controller() keys = og.Controller.Keys # Disconnected input bundle should be invalid (graph, (_, node_database), _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("BundleConstructor", "omni.graph.nodes.BundleConstructor"), ("NodeDatabase", "omni.graph.test.NodeDatabasePy"), ], }, ) # database id remains the same because topology has not changed graph.evaluate() previous_id = node_database.get_attribute("outputs:id").get() graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id == current_id) previous_id = current_id graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id == current_id) # disconnect input connect rebuilds the database (graph, _, _, _) = controller.edit( "/World/Graph", { keys.CONNECT: [ ("BundleConstructor.outputs_bundle", "NodeDatabase.inputs:bundle"), ], }, ) graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id != current_id) # subsequent evaluation does not change id previous_id = current_id graph.evaluate() current_id = node_database.get_attribute("outputs:id").get() self.assertTrue(previous_id == current_id)
36,212
Python
42.68275
127
0.543798
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/deprecated_module.py
"""Test module that exercises import-level deprecation""" import omni.graph.tools as ogt ogt.DeprecatedImport("Use 'import omni.graph.core as og' instead") def test_function(): pass
189
Python
20.111109
66
0.746032
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_traversal.py
from typing import List, Set import omni.graph.core as og import omni.kit.test import omni.usd from omni.graph.core import traverse_downstream_graph, traverse_upstream_graph class TestTraversal(omni.graph.core.tests.OmniGraphTestCase): """Test cases for graph traversal functions.""" async def test_downstream_connections_works(self): """ Validate that downstream connections are collected correctly. """ stage = omni.usd.get_context().get_stage() # Test graph set up # [G1In1]-->[G1M1]-->[G1M2]--->[G1M4]--->[G1Out1] # [G1In2]---^ |---[G1M3]----| |--->[G1Out2] # # [G2In1]-->[G2M1]-->[G2Out1] # # [G3In1] controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("G1In1", "omni.graph.nodes.ConstantFloat"), ("G1In2", "omni.graph.nodes.ConstantFloat"), ("G1M1", "omni.graph.nodes.Add"), ("G1M2", "omni.graph.nodes.Add"), ("G1M3", "omni.graph.nodes.Add"), ("G1M4", "omni.graph.nodes.Add"), ("G1Out1", "omni.graph.nodes.Magnitude"), ("G1Out2", "omni.graph.nodes.Magnitude"), ("G2In1", "omni.graph.nodes.ConstantFloat"), ("G2M1", "omni.graph.nodes.Magnitude"), ("G2Out1", "omni.graph.nodes.Magnitude"), ("G3In1", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("G1In1.inputs:value", "G1M1.inputs:a"), ("G1In2.inputs:value", "G1M1.inputs:b"), ("G1M1.outputs:sum", "G1M2.inputs:a"), ("G1M1.outputs:sum", "G1M2.inputs:b"), ("G1M1.outputs:sum", "G1M3.inputs:a"), ("G1M1.outputs:sum", "G1M3.inputs:b"), ("G1M2.outputs:sum", "G1M4.inputs:a"), ("G1M3.outputs:sum", "G1M4.inputs:b"), ("G1M4.outputs:sum", "G1Out1.inputs:input"), ("G1M4.outputs:sum", "G1Out2.inputs:input"), ("G2In1.inputs:value", "G2M1.inputs:input"), ("G2M1.outputs:magnitude", "G2Out1.inputs:input"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) _, _, _, _, g1m3, g1m4, g1out1, g1out2, _, g2m1, g2out1, _ = prims # Valdate the set of visited nodes expected = [g1m3, g1m4, g1out1, g1out2, g2m1, g2out1] visited = traverse_downstream_graph([g2m1, g1m3]) actual = [og.Controller.prim(n) for n in visited] self.assertCountEqual(expected, actual, "Unexpected set of visited nodes downstream") async def test_downstream_connections_can_include_compound_graph_prim(self): """Test that calling for downstream connections with compounds can include the compound graph prim.""" node_type = "omni.graph.nodes.Add" controller = og.Controller() keys = controller.Keys # Test graph set up # |============================| # [O1]->|->[I1]---->|I2|----->|I3|-->|--->|O2] # |---------->| | | # |--->[I4] | # | [I5]->[I6] | # |============================| (_, _, _, nodes) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("Outer1", node_type), ("Outer2", node_type), ( "Compound", { keys.CREATE_NODES: [ ("Inner1", node_type), ("Inner2", node_type), ("Inner3", node_type), ("Inner4", node_type), ("Inner5", node_type), ("Inner6", node_type), ], keys.PROMOTE_ATTRIBUTES: [ ("Inner1.inputs:a", "inputs:one"), ("Inner2.inputs:a", "inputs:two"), ("Inner3.outputs:sum", "outputs:value"), ("Inner4.inputs:a", "inputs:three"), ], keys.CONNECT: [ ("Inner1.outputs:sum", "Inner2.inputs:b"), ("Inner2.outputs:sum", "Inner3.inputs:a"), ("Inner5.outputs:sum", "Inner6.inputs:a"), ], }, ), ], keys.CONNECT: [ ("Outer1.outputs:sum", "Compound.inputs:one"), ("Compound.outputs:value", "Outer2.inputs:a"), ], }, ) def assert_valid_traversal(items: List, expected_results: Set[og.Node]): """Helper method to validate traversal results.""" prims = [og.Controller.prim(i) for i in items] actual_set = traverse_downstream_graph(prims) self.assertEquals(expected_results, actual_set, "Unexpected set of visited nodes downstream") def assert_invalid_traversal(items): prims = [og.Controller.prim(i) for i in items] with self.assertRaises(og.OmniGraphError): traverse_downstream_graph(prims) compound_graph = nodes["Compound"].get_compound_graph_instance() # test traversal with compound graph assert_valid_traversal([nodes["Outer1"]], {nodes["Outer1"], nodes["Compound"], nodes["Outer2"]}) # test with just the compound graph assert_valid_traversal([compound_graph], {nodes["Inner1"], nodes["Inner2"], nodes["Inner3"], nodes["Inner4"]}) # test with a node inside the compound graph assert_valid_traversal([compound_graph, nodes["Inner5"]], set(compound_graph.get_nodes())) # invalid traversals assert_invalid_traversal([nodes["Inner1"], nodes["Outer1"]]) # mixed graphs assert_invalid_traversal([compound_graph, nodes["Outer1"]]) # compound and outer node assert_invalid_traversal(["/World"]) # invalid node assert_invalid_traversal(["/World/Testgraph"]) # non compound graph async def test_upstream_connections_works(self): """ Validate that upstream connections are collected correctly. """ stage = omni.usd.get_context().get_stage() # Test graph set up # [G1In1]-->[G1M1]-->[G1M2]--->[G1M4]--->[G1Out1] # [G1In2]---^ |---[G1M3]----| |--->[G1Out2] # # [G2In1]-->[G2M1]-->[G2Out1] # # [G3In1] controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("G1In1", "omni.graph.nodes.ConstantFloat"), ("G1In2", "omni.graph.nodes.ConstantFloat"), ("G1M1", "omni.graph.nodes.Add"), ("G1M2", "omni.graph.nodes.Add"), ("G1M3", "omni.graph.nodes.Add"), ("G1M4", "omni.graph.nodes.Add"), ("G1Out1", "omni.graph.nodes.Magnitude"), ("G1Out2", "omni.graph.nodes.Magnitude"), ("G2In1", "omni.graph.nodes.ConstantFloat"), ("G2M1", "omni.graph.nodes.Magnitude"), ("G2Out1", "omni.graph.nodes.Magnitude"), ("G3In1", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("G1In1.inputs:value", "G1M1.inputs:a"), ("G1In2.inputs:value", "G1M1.inputs:b"), ("G1M1.outputs:sum", "G1M2.inputs:a"), ("G1M1.outputs:sum", "G1M2.inputs:b"), ("G1M1.outputs:sum", "G1M3.inputs:a"), ("G1M1.outputs:sum", "G1M3.inputs:b"), ("G1M2.outputs:sum", "G1M4.inputs:a"), ("G1M3.outputs:sum", "G1M4.inputs:b"), ("G1M4.outputs:sum", "G1Out1.inputs:input"), ("G1M4.outputs:sum", "G1Out2.inputs:input"), ("G2In1.inputs:value", "G2M1.inputs:input"), ("G2M1.outputs:magnitude", "G2Out1.inputs:input"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) g1in1, g1in2, g1m1, _, g1m3, _, _, _, g2in1, g2m1, _, _ = prims # Validate the set of visited nodes expected = [g1m3, g1m1, g1in1, g1in2, g2m1, g2in1] visited = traverse_upstream_graph([g2m1, g1m3]) actual = [og.Controller.prim(n) for n in visited] self.assertCountEqual(expected, actual, "Unexpected set of visited nodes upstream") async def test_upstream_connections_can_include_compound_graph_prim(self): """Test that calling for uptream connections with compounds can include the compound graph prim.""" node_type = "omni.graph.nodes.Add" controller = og.Controller() keys = controller.Keys # Test graph set up # |============================| # [O1]->|->[I1]---->|I2|----->|I3|-->|--->|O2] # | | | | # | [I4]------------------->| # | [I5]->[I6] | # |============================| (_, _, _, nodes) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("Outer1", node_type), ("Outer2", node_type), ( "Compound", { keys.CREATE_NODES: [ ("Inner1", node_type), ("Inner2", node_type), ("Inner3", node_type), ("Inner4", node_type), ("Inner5", node_type), ("Inner6", node_type), ], keys.PROMOTE_ATTRIBUTES: [ ("Inner1.inputs:a", "inputs:value"), ("Inner3.outputs:sum", "outputs:one"), ("Inner4.outputs:sum", "outputs:two"), ], keys.CONNECT: [ ("Inner1.outputs:sum", "Inner2.inputs:b"), ("Inner2.outputs:sum", "Inner3.inputs:a"), ("Inner5.outputs:sum", "Inner6.inputs:a"), ], }, ), ], keys.CONNECT: [ ("Outer1.outputs:sum", "Compound.inputs:value"), ("Compound.outputs:one", "Outer2.inputs:a"), ], }, ) def assert_valid_traversal(items: List, expected_results: Set[og.Node]): """Helper method to validate traversal results.""" prims = [og.Controller.prim(i) for i in items] actual_set = traverse_upstream_graph(prims) self.assertEquals(expected_results, actual_set, "Unexpected set of visited nodes downstream") def assert_invalid_traversal(items): prims = [og.Controller.prim(i) for i in items] with self.assertRaises(og.OmniGraphError): traverse_upstream_graph(prims) compound_graph = nodes["Compound"].get_compound_graph_instance() # test traversal with compound graph assert_valid_traversal([nodes["Outer2"]], {nodes["Outer1"], nodes["Compound"], nodes["Outer2"]}) # test with just the compound graph assert_valid_traversal([compound_graph], {nodes["Inner1"], nodes["Inner2"], nodes["Inner3"], nodes["Inner4"]}) # test with a node inside the compound graph assert_valid_traversal([compound_graph, nodes["Inner6"]], set(compound_graph.get_nodes())) # invalid traversals assert_invalid_traversal([nodes["Inner1"], nodes["Outer2"]]) # mixed graphs assert_invalid_traversal([compound_graph, nodes["Outer2"]]) # compound and outer node assert_invalid_traversal(["/World"]) # invalid node assert_invalid_traversal(["/World/Testgraph"]) # non compound graph async def test_node_callback_works(self): """ Validate that the node predicate is applied correctly. """ stage = omni.usd.get_context().get_stage() # Test graph set up # [G1In1]-->[G1M1]-->[G1M2]--->[G1M4]--->[G1Out1] # [G1In2]---^ |---[G1M3]----| |--->[G1Out2] # # [G2In1]-->[G2M1]-->[G2Out1] # # [G3In1] controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("G1In1", "omni.graph.nodes.ConstantFloat"), ("G1In2", "omni.graph.nodes.ConstantFloat"), ("G1M1", "omni.graph.nodes.Add"), ("G1M2", "omni.graph.nodes.Add"), ("G1M3", "omni.graph.nodes.Add"), ("G1M4", "omni.graph.nodes.Add"), ("G1Out1", "omni.graph.nodes.Magnitude"), ("G1Out2", "omni.graph.nodes.Magnitude"), ("G2In1", "omni.graph.nodes.ConstantFloat"), ("G2M1", "omni.graph.nodes.Magnitude"), ("G2Out1", "omni.graph.nodes.Magnitude"), ("G3In1", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("G1In1.inputs:value", "G1M1.inputs:a"), ("G1In2.inputs:value", "G1M1.inputs:b"), ("G1M1.outputs:sum", "G1M2.inputs:a"), ("G1M1.outputs:sum", "G1M2.inputs:b"), ("G1M1.outputs:sum", "G1M3.inputs:a"), ("G1M1.outputs:sum", "G1M3.inputs:b"), ("G1M2.outputs:sum", "G1M4.inputs:a"), ("G1M3.outputs:sum", "G1M4.inputs:b"), ("G1M4.outputs:sum", "G1Out1.inputs:input"), ("G1M4.outputs:sum", "G1Out2.inputs:input"), ("G2In1.inputs:value", "G2M1.inputs:input"), ("G2M1.outputs:magnitude", "G2Out1.inputs:input"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) _, _, _, _, g1m3, _, _, _, _, g2m1, _, _ = prims custom_accumulator = [] def convert_to_prim(node): """Convert the visited node to Prim""" nonlocal custom_accumulator custom_accumulator.append(og.Controller.prim(node)) # Validate the downstream traversal visited = traverse_downstream_graph([g2m1, g1m3], node_callback=convert_to_prim) expected = [og.Controller.prim(n) for n in visited] self.assertCountEqual( expected, custom_accumulator, "Unexpected effect of the node callback in downstream traversal" ) # Validate the upstream traversal custom_accumulator = [] visited = traverse_upstream_graph([g2m1, g1m3], node_callback=convert_to_prim) expected = [og.Controller.prim(n) for n in visited] self.assertCountEqual( expected, custom_accumulator, "Unexpected effect of the node callback in upstream traversal" ) async def test_attribute_predicate_works(self): """Validate that the attribute callback allows filtering connections""" stage = omni.usd.get_context().get_stage() # Test graph set up # [OnCustomEvent1]====>[Counter]==================>[Delay] # [OnCustomEvent2]=====^ |-->[Negate] ^ # [ConstantFloat]--| # Where # "==>" : execution connection # "-->" : data connection controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("OnCustomEvent1", "omni.graph.action.OnCustomEvent"), ("OnCustomEvent2", "omni.graph.action.OnCustomEvent"), ("Counter", "omni.graph.action.Counter"), ("Delay", "omni.graph.action.Delay"), ("Duration", "omni.graph.nodes.ConstantFloat"), ("Negate", "omni.graph.nodes.Negate"), ], keys.CONNECT: [ ("OnCustomEvent1.outputs:execOut", "Counter.inputs:execIn"), ("OnCustomEvent2.outputs:execOut", "Counter.inputs:reset"), ("Counter.outputs:execOut", "Delay.inputs:execIn"), ("Counter.outputs:count", "Negate.inputs:input"), ("Duration.inputs:value", "Delay.inputs:duration"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) on_custom_event1, on_custom_event2, counter, delay, _, _ = prims def is_execution(attr: og.Attribute) -> bool: return attr and attr.get_resolved_type().role == og.AttributeRole.EXECUTION visited = traverse_downstream_graph([on_custom_event1], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {on_custom_event1, counter, delay} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes downstream") visited = traverse_upstream_graph([delay], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {delay, counter, on_custom_event1, on_custom_event2} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes upstream") async def test_graph_with_cycles_works(self): """Validate that the traversal functions work on graphs with cycles / loops""" stage = omni.usd.get_context().get_stage() # Test graph set up # # [OnStageEvent]===>[ForLoop]<====================================== # | ||============>[Delay]========>[Branch]=|| # |--------------------->[Compare]--^ # [ConstantInt]------^ # # Where # "==>" : execution connection # "-->" : data connection controller = og.Controller() keys = controller.Keys (_, nodes, _, _) = controller.edit( "/World/Testgraph", { keys.CREATE_NODES: [ ("OnStageEvent", "omni.graph.action.OnStageEvent"), ("ForLoop", "omni.graph.action.ForLoop"), ("Delay", "omni.graph.action.Delay"), ("ConstantInt", "omni.graph.nodes.ConstantInt"), ("Compare", "omni.graph.nodes.Compare"), ("Branch", "omni.graph.action.Branch"), ], keys.CONNECT: [ ("OnStageEvent.outputs:execOut", "ForLoop.inputs:execIn"), ("ForLoop.outputs:loopBody", "Delay.inputs:execIn"), ("ForLoop.outputs:index", "Compare.inputs:a"), ("Delay.outputs:finished", "Branch.inputs:execIn"), ("ConstantInt.inputs:value", "Compare.inputs:b"), ("Compare.outputs:result", "Branch.inputs:condition"), ("Branch.outputs:execTrue", "ForLoop.inputs:breakLoop"), ], }, ) prims = tuple(stage.GetPrimAtPath(n.get_prim_path()) for n in nodes) on_stage_event, for_loop, delay, constant_int, _, branch = prims def is_execution(attr: og.Attribute) -> bool: return attr and attr.get_resolved_type().role == og.AttributeRole.EXECUTION visited = traverse_downstream_graph([delay], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {delay, branch, for_loop} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes downstream") visited = traverse_upstream_graph([delay], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {delay, for_loop, branch, on_stage_event} self.assertSetEqual(expected, actual, "Unexpected sequence of nodes upstream") # The result of a traversal where the starting node has no matching attribute # is a set with only the node itself visited = traverse_downstream_graph([constant_int], is_execution) actual = {og.Controller.prim(n) for n in visited} expected = {constant_int} self.assertSetEqual(expected, actual, "Unexpected traversal when no connections are valid")
21,678
Python
44.64
118
0.486853
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_attribute_template_api.py
"""Tests related to the AttributeTemplate python APIs""" import tempfile from pathlib import Path from typing import Tuple import carb import numpy as np import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn import omni.kit.test import omni.usd from pxr import Gf, Sdf, Vt # test data for metadata on attribute templates VALID_ATTRIBUTE_OGN_KEYS_AND_SAMPLES = { ogn.MetadataKeys.ALLOW_MULTI_INPUTS: "1", ogn.MetadataKeys.ALLOWED_TOKENS: "A,B,C", ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"A": "1", "B": "2", "C": "3"}', ogn.MetadataKeys.DESCRIPTION: "TestDescription", ogn.MetadataKeys.HIDDEN: "1", ogn.MetadataKeys.OPTIONAL: "1", ogn.MetadataKeys.OUTPUT_ONLY: "1", ogn.MetadataKeys.LITERAL_ONLY: "1", ogn.MetadataKeys.UI_NAME: "DisplayName", } class TestAttributeTemplateAPI(ogts.OmniGraphTestCase): """Tests that validate the attribute template API""" _simple_test_file = "TestCompoundGraph.usda" @classmethod def setUpClass(cls): # this is required when running a single test to make expectedError work correctly...not sure why carb.log_warn("This class expects error. This preflushes to avoid problems with ExpectedError") def validate_connections_match_usd(self, attribute: ogu.AttributeTemplate, path_to_rel: str): """ Helper that tests whether the connection list on the node type matches the corresponding USD relationship """ base_path = "/World/Compounds/TestType/Graph" stage = omni.usd.get_context().get_stage() relationship = stage.GetRelationshipAtPath(f"/World/Compounds/TestType.{path_to_rel}") self.assertTrue(relationship.IsValid()) # compare sets as the order isn't guaranteed attr_set = {Sdf.Path(f"{base_path}/{x}") for x in attribute.get_connections()} rel_set = set(relationship.GetTargets()) self.assertEqual(attr_set, rel_set) async def test_port_type_property(self): """ Tests the port type attribute on AttributeTemplates """ compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") for i in range(1, 20): compound_node_type.add_input(f"input_{i}", "int", True) compound_node_type.add_output(f"output_{i}", "float", True) for i in range(1, 20): input_type = compound_node_type.find_input(f"input_{i}") output_type = compound_node_type.find_output(f"output_{i}") self.assertEquals(input_type.port_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.assertEquals(output_type.port_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) async def test_extended_type_property(self): """ Test the attribute extended type property """ compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") regular_input = compound_node_type.add_input("input_0", "int", True, 1) union_input = compound_node_type.add_extended_input( "input_1", "int, float", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_input = compound_node_type.add_extended_input( "input_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) regular_output = compound_node_type.add_output("output_0", "int", True, 1) union_output = compound_node_type.add_extended_output( "output_1", "int, float", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_output = compound_node_type.add_extended_output( "output_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertTrue(regular_input.is_valid()) self.assertTrue(union_input.is_valid()) self.assertTrue(any_input.is_valid()) self.assertTrue(regular_output.is_valid()) self.assertTrue(union_output.is_valid()) self.assertTrue(any_output.is_valid()) self.assertEquals(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEquals(union_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEquals(any_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertEquals(regular_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEquals(union_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEquals(any_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) async def test_get_types_method(self): """Test the get types methods returns the expected list values""" compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") regular_input = compound_node_type.add_input("input_0", "int", True, 1) union_input = compound_node_type.add_extended_input( "input_1", "int, float", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_input = compound_node_type.add_extended_input( "input_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) regular_output = compound_node_type.add_output("output_0", "float", True, 1) union_output = compound_node_type.add_extended_output( "output_1", "double[2], int[], normalf[3]", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION ) any_output = compound_node_type.add_extended_output( "output_2", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertTrue(regular_input.is_valid()) self.assertTrue(union_input.is_valid()) self.assertTrue(any_input.is_valid()) self.assertTrue(regular_output.is_valid()) self.assertTrue(union_output.is_valid()) self.assertTrue(any_output.is_valid()) self.assertEqual(regular_input.get_types(), [og.Type(og.BaseDataType.INT)]) self.assertEqual(regular_output.get_types(), [og.Type(og.BaseDataType.FLOAT)]) self.assertEqual(union_input.get_types(), [og.Type(og.BaseDataType.INT), og.Type(og.BaseDataType.FLOAT)]) self.assertEqual( union_output.get_types(), [ og.Type(og.BaseDataType.DOUBLE, 2), og.Type(og.BaseDataType.INT, 1, 1), og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NORMAL), ], ) self.assertEqual(any_input.get_types(), []) self.assertEqual(any_output.get_types(), []) async def test_attribute_template_set_type(self): """Tests the set type and set extended type calls""" stage = omni.usd.get_context().get_stage() compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") prim = stage.GetPrimAtPath("/World/Compounds/TestType") regular_input = compound_node_type.add_input("input_0", "int", True, 1) regular_output = compound_node_type.add_output("output_0", "int", True, 2) input_rel = prim.GetRelationship("omni:graph:input:input_0") output_rel = prim.GetRelationship("omni:graph:output:output_0") self.assertTrue(regular_input.get_types(), [og.Type(og.BaseDataType.INT)]) self.assertTrue(regular_output.get_types(), [og.Type(og.BaseDataType.INT)]) self.assertTrue(input_rel.IsValid()) self.assertTrue(output_rel.IsValid()) self.assertEqual(input_rel.GetCustomDataByKey("omni:graph:default"), 1) self.assertEqual(output_rel.GetCustomDataByKey("omni:graph:default"), 2) # set to union or any type and validate the key is removed regular_input.set_extended_type(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, "numerics") regular_output.set_extended_type(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertEqual(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) self.assertEqual(regular_output.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY) self.assertGreater(len(regular_input.get_types()), 5) self.assertEqual(regular_output.get_types(), []) self.assertIsNone(input_rel.GetCustomDataByKey("omni:graph:default")) self.assertIsNone(output_rel.GetCustomDataByKey("omni:graph:default")) self.assertEqual(input_rel.GetCustomDataByKey("omni:graph:type"), "numerics") self.assertIsNone(output_rel.GetCustomDataByKey("omni:graph:type")) # validate setting a regular input with the wrong method has no effect with ogts.ExpectedError(): regular_input.set_extended_type(og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "int") self.assertEqual(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION) regular_input.set_type(og.Type(og.BaseDataType.FLOAT, 3, 1), [(1, 2, 3), (4, 5, 6)]) self.assertEqual(regular_input.extended_type, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR) self.assertEqual( input_rel.GetCustomDataByKey("omni:graph:default"), Vt.Vec3fArray([Gf.Vec3f(1, 2, 3), Gf.Vec3f(4, 5, 6)]) ) self.assertEqual(input_rel.GetCustomDataByKey("omni:graph:type"), "float[3][]") regular_output.set_type(og.Type(og.BaseDataType.FLOAT, 2)) self.assertEqual(output_rel.GetCustomDataByKey("omni:graph:default"), None) self.assertEqual(output_rel.GetCustomDataByKey("omni:graph:type"), "float[2]") async def test_connect_by_path(self): """Test the connect by path API call""" stage = omni.usd.get_context().get_stage() compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") prim = stage.GetPrimAtPath("/World/Compounds/TestType") graph_path = prim.GetPath().AppendChild("Graph") (_, (_add_node1, _add_node2), _, _) = og.Controller.edit( str(graph_path), {og.Controller.Keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add")]}, ) node_path = graph_path.AppendChild("add_node") input_1 = compound_node_type.add_extended_input( "input_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) # invalid Paths will throw a value error with self.assertRaises(ValueError): input_1.connect_by_path(None) with self.assertRaises(ValueError): input_1.connect_by_path(2.0) with self.assertRaises(ValueError): input_1.connect_by_path("PATH WITH INVALID IDENTIFIERS - !@#$%^") # valid paths that are not part of the CNT graph produces errors and return false. with ogts.ExpectedError(): self.assertFalse(input_1.connect_by_path("/World")) # valid path, not part of the graph with ogts.ExpectedError(): self.assertFalse(input_1.connect_by_path(graph_path)) # valid SDFPath, not child of the graph full_attr_path = node_path.AppendProperty("inputs:a") rel_attr_path = "add.inputs:b" self.assertTrue(input_1.connect_by_path(full_attr_path)) self.assertTrue(input_1.connect_by_path(rel_attr_path)) self.assertEqual(len(input_1.get_connections()), 2) # existing connections don't append self.assertFalse(input_1.connect_by_path(node_path.AppendProperty("inputs:a"))) self.assertEqual(len(input_1.get_connections()), 2) output_1 = compound_node_type.add_extended_output( "output_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertTrue(output_1.connect_by_path(node_path.AppendProperty("outputs:sum"))) self.assertEqual(len(output_1.get_connections()), 1) self.assertTrue(output_1.connect_by_path("Add2.outputs:sum")) self.assertEqual(len(output_1.get_connections()), 1) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") def create_test_node_with_input_and_output(self) -> Tuple[ogu.AttributeTemplate, ogu.AttributeTemplate]: """Creates a comound_node_type with two attributes with connections""" compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") graph_path = "/World/Compounds/TestType/Graph" (_, (_add_node1, _add_node2), _, _) = og.Controller.edit( graph_path, {og.Controller.Keys.CREATE_NODES: [("Add", "omni.graph.nodes.Add"), ("Add2", "omni.graph.nodes.Add")]}, ) input_1 = compound_node_type.add_extended_input( "input_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertEqual(input_1.get_connections(), []) input_1.connect_by_path("/World/Compounds/TestType/Graph/Add.inputs:a") input_1.connect_by_path("Add.inputs:b") input_1.connect_by_path("Add2.inputs:a") input_1.connect_by_path("Add2.inputs:b") output_1 = compound_node_type.add_extended_output( "output_1", None, True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY ) self.assertEqual(output_1.get_connections(), []) output_1.connect_by_path("Add.outputs:sum") return (input_1, output_1) async def test_get_connections(self): """ Test the get_connection member function returns the expected connection values """ (input_1, output_1) = self.create_test_node_with_input_and_output() self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") self.assertEqual(output_1.get_connections(), ["Add.outputs:sum"]) output_1.connect_by_path("Add2.outputs:sum") self.assertEqual(input_1.get_connections(), ["Add.inputs:a", "Add.inputs:b", "Add2.inputs:a", "Add2.inputs:b"]) self.assertEqual(output_1.get_connections(), ["Add2.outputs:sum"]) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") async def test_disconnect_all(self): """Test the disconnect_all member function""" (input_1, output_1) = self.create_test_node_with_input_and_output() self.assertNotEqual(input_1.get_connections(), []) self.assertNotEqual(output_1.get_connections(), []) input_1.disconnect_all() self.assertEqual(input_1.get_connections(), []) input_1.disconnect_all() self.assertEqual(input_1.get_connections(), []) output_1.disconnect_all() self.assertEqual(output_1.get_connections(), []) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") self.validate_connections_match_usd(output_1, "omni:graph:output:output_1") async def test_disconnect_by_path(self): """Tests disconnect_by_path API call""" (input_1, _) = self.create_test_node_with_input_and_output() self.assertEqual(len(input_1.get_connections()), 4) # non existing path self.assertFalse(input_1.disconnect_by_path("Add.omni:graph:input:not_valid")) # existing absolute path self.assertTrue(input_1.disconnect_by_path("/World/Compounds/TestType/Graph/Add.inputs:b")) self.assertTrue(input_1.disconnect_by_path("Add2.inputs:b")) self.assertEqual(input_1.get_connections(), ["Add.inputs:a", "Add2.inputs:a"]) self.validate_connections_match_usd(input_1, "omni:graph:input:input_1") async def test_connections_are_set_when_loaded(self): """Tests that connections that are loaded from USD can be retrieved through the API""" (result, error) = await ogts.load_test_file(self._simple_test_file, use_caller_subdirectory=True) self.assertTrue(result, error) compound_node_type = ogu.find_compound_node_type_by_path("/World/Compounds/Compound") self.assertTrue(compound_node_type.is_valid()) input_a = compound_node_type.find_input("A") input_b = compound_node_type.find_input("B") output = compound_node_type.find_output("Value") self.assertTrue(input_a.is_valid()) self.assertTrue(input_b.is_valid()) self.assertTrue(output.is_valid()) self.assertEqual(input_a.get_connections(), ["Add_Node.inputs:a"]) self.assertEqual(input_b.get_connections(), ["Add_Node.inputs:b"]) self.assertEqual(output.get_connections(), ["Add_Node.outputs:sum"]) async def test_set_get_metadata(self): """Tests that validate the calls to set and retrieve metadata work as expected""" (input_1, output_1) = self.create_test_node_with_input_and_output() entries = VALID_ATTRIBUTE_OGN_KEYS_AND_SAMPLES for (key, value) in entries.items(): input_1.set_metadata(key, value) output_1.set_metadata(key, value) for (key, value) in entries.items(): self.assertTrue(input_1.get_metadata(key), value) self.assertTrue(output_1.get_metadata(key), value) # create a graph with the compound node and validate the values transfer (_, (node,), _, _) = og.Controller.edit( "/World/PushGraph", {og.Controller.Keys.CREATE_NODES: [("Node", "test.nodes.TestType")]} ) node_input = node.get_attribute("inputs:input_1") node_output = node.get_attribute("outputs:output_1") for (key, value) in entries.items(): self.assertEqual(node_input.get_metadata(key), value) self.assertEqual(node_output.get_metadata(key), value) async def test_set_get_metadata_reloads_from_file(self): """Tests that creating and setting metadata persists when the file reloads""" (input_1, output_1) = self.create_test_node_with_input_and_output() entries = VALID_ATTRIBUTE_OGN_KEYS_AND_SAMPLES for (key, value) in entries.items(): input_1.set_metadata(key, value) output_1.set_metadata(key, value) with tempfile.TemporaryDirectory() as tmpdirname: # save the file tmp_file_path = Path(tmpdirname) / "tmp.usda" result = omni.usd.get_context().save_as_stage(str(tmp_file_path)) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # reload the file back (result, error) = await ogts.load_test_file(str(tmp_file_path)) self.assertTrue(result, error) compound_node_type = ogu.find_compound_node_type_by_path("/World/Compounds/TestType") self.assertTrue(compound_node_type.is_valid()) input_1 = compound_node_type.find_input("input_1") output_1 = compound_node_type.find_output("output_1") self.assertTrue(input_1.is_valid()) self.assertTrue(output_1.is_valid()) for (key, value) in entries.items(): input_1.set_metadata(key, value) output_1.set_metadata(key, value) async def test_stress_test_add_input_output(self): """ Stress tests having many inputs and outputs on compound nodes. Validates that 'handles' maintain their correct object when internal movement of vectors is happening """ num_inputs = 1000 num_outputs = 1000 ogu.create_compound_node_type("TestType", "Graph", "test.nodes") node_type = og.get_node_type("test.nodes.TestType") self.assertTrue(node_type.is_valid()) compound_node_type = ogu.get_compound_node_type(node_type) self.assertTrue(compound_node_type.is_valid()) # build up a large number of inputs and outputs for i in range(0, num_inputs): compound_node_type.add_input(f"in_{i}", "int", True) for j in range(0, num_outputs): compound_node_type.add_output(f"out_{j}", "int", True) # validate the inputs and outputs return the correct object for i in range(0, num_inputs): input_attr = compound_node_type.find_input(f"in_{i}") self.assertTrue(input_attr.is_valid(), f"Failed at index {i}") self.assertEquals(input_attr.name, f"inputs:in_{i}") for j in range(0, num_outputs): output = compound_node_type.find_output(f"out_{j}") self.assertTrue(output.is_valid(), f"Failed at index {j}") self.assertEquals(output.name, f"outputs:out_{j}") # remove alternate inputs and outputs for i in range(1, num_inputs, 2): compound_node_type.remove_input_by_name(f"in_{i}") for j in range(1, num_outputs, 2): compound_node_type.remove_output_by_name(f"out_{j}") # verify everything is as expected. for i in range(0, num_inputs): input_attr = compound_node_type.find_input(f"in_{i}") if (i % 2) == 0: self.assertTrue(input_attr.is_valid(), f"Failed at index {i}") self.assertEquals(input_attr.name, f"inputs:in_{i}") else: self.assertFalse(input_attr.is_valid()) for j in range(0, num_outputs): output = compound_node_type.find_output(f"out_{j}") if (j % 2) == 0: self.assertTrue(output.is_valid(), f"Failed at index{j}") self.assertEquals(output.name, f"outputs:out_{j}") else: self.assertFalse(output.is_valid()) # ---------------------------------------------------------------------- async def test_default_data(self): """ Tests setting and getting default data through the attributetemplate ABI """ compound_node_type = ogu.create_compound_node_type("TestType", "Graph", "test.nodes") name_index = 0 def validate_type(og_type, data): nonlocal name_index input_name = f"input_{name_index}" name_index = name_index + 1 attr_input = compound_node_type.add_input(input_name, og_type.get_ogn_type_name(), True, data) actual_data = attr_input.get_default_data() expected_data = data # special case for half floats where the precision can fail verify_values due to loss of precision if og_type.base_type == og.BaseDataType.HALF: if og_type.array_depth > 0 or og_type.tuple_count > 1: expected_data = np.array(np.array(data, dtype=np.float16), dtype=np.float32) else: expected_data = float(np.half(data)) ogts.verify_values( expected_data, actual_data, f"Comparison failed {str(actual_data)} vs {str(expected_data)}" ) validate_type(og.Type(og.BaseDataType.BOOL), True) validate_type(og.Type(og.BaseDataType.BOOL), False) validate_type(og.Type(og.BaseDataType.BOOL, 1, 1), [True, False]) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.COLOR), (1, 0, 0)) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 1, og.AttributeRole.COLOR), [(1, 0, 0), (0, 1, 0)]) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.COLOR), (1, 0, 0)) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.COLOR), [(1, 0, 0), (0, 1, 0)]) validate_type(og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.COLOR), (1, 0, 0)) validate_type(og.Type(og.BaseDataType.HALF, 3, 1, og.AttributeRole.COLOR), [(1, 0, 0), (0, 1, 0)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.COLOR), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 1, og.AttributeRole.COLOR), [(1, 0, 0, 1), (0, 1, 1, 0)]) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.COLOR), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 1, og.AttributeRole.COLOR), [(1, 0, 0, 1), (0, 1, 1, 0)]) validate_type(og.Type(og.BaseDataType.HALF, 4, 0, og.AttributeRole.COLOR), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.HALF, 4, 1, og.AttributeRole.COLOR), [(1, 0, 0, 1), (0, 1, 1, 0)]) validate_type(og.Type(og.BaseDataType.DOUBLE), 1.5) validate_type(og.Type(og.BaseDataType.DOUBLE, 2), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.DOUBLE, 2, 1), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 3), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 1), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 4), (1.5, 1.6, 1.7, 1.8)) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 1), [(1.5, 1.6, 1.7, 1.8), (2.5, 2.6, 2.7, 2.8)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 1, 1), [1.5, 1.6, 1.7]) validate_type(og.Type(og.BaseDataType.FLOAT), 1.5) validate_type(og.Type(og.BaseDataType.FLOAT, 2), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.FLOAT, 2, 1), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.FLOAT, 3), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 1), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.FLOAT, 4), (1.5, 1.6, 1.7, 1.8)) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 1), [(1.5, 1.6, 1.7, 1.8), (2.5, 2.6, 2.7, 2.8)]) validate_type(og.Type(og.BaseDataType.FLOAT, 1, 1), [1.5, 1.6, 1.7]) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.FRAME), ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 1, og.AttributeRole.FRAME), [ ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ((5, 0, 0, 5), (6, 0, 0, 6), (7, 0, 0, 7), (8, 0, 0, 8)), ], ) validate_type(og.Type(og.BaseDataType.HALF), 1.5) validate_type(og.Type(og.BaseDataType.HALF, 2), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.HALF, 2, 1), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.HALF, 3), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.HALF, 3, 1), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.HALF, 4), (1.5, 1.6, 1.7, 1.8)) validate_type(og.Type(og.BaseDataType.HALF, 4, 1), [(1.5, 1.6, 1.7, 1.8), (2.5, 2.6, 2.7, 2.8)]) validate_type(og.Type(og.BaseDataType.HALF, 1, 1), [1.5, 1.6, 1.7]) validate_type(og.Type(og.BaseDataType.INT), 1) validate_type(og.Type(og.BaseDataType.INT, 2), (1, 2)) validate_type(og.Type(og.BaseDataType.INT, 2, 1), [(1, 2), (3, 4)]) validate_type(og.Type(og.BaseDataType.INT, 3), (1, 2, 3)) validate_type(og.Type(og.BaseDataType.INT, 3, 1), [(1, 2, 3), (3, 4, 5)]) validate_type(og.Type(og.BaseDataType.INT, 4), (1, 2, 3, 4)) validate_type(og.Type(og.BaseDataType.INT, 4, 1), [(1, 2, 3, 4), (3, 4, 5, 6)]) validate_type(og.Type(og.BaseDataType.INT64), 123456789012) validate_type(og.Type(og.BaseDataType.INT64, 1, 1), [123456789012, 345678901234]) validate_type(og.Type(og.BaseDataType.INT, 1, 1), [1, 2, 3, 4, 5, 6]) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.MATRIX), ((1, 2), (3, 4))) validate_type( og.Type(og.BaseDataType.DOUBLE, 4, 1, og.AttributeRole.MATRIX), [((1, 2), (3, 4)), ((5, 6), (7, 8))] ) validate_type(og.Type(og.BaseDataType.DOUBLE, 9, 0, og.AttributeRole.MATRIX), ((1, 2, 3), (4, 5, 6), (7, 8, 9))) validate_type( og.Type(og.BaseDataType.DOUBLE, 9, 1, og.AttributeRole.MATRIX), [((1, 2, 3), (4, 5, 6), (7, 8, 9)), ((0, 1, 2), (3, 4, 5), (6, 7, 8))], ) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX), ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ) validate_type( og.Type(og.BaseDataType.DOUBLE, 16, 1, og.AttributeRole.MATRIX), [ ((1, 0, 0, 1), (2, 0, 0, 2), (3, 0, 0, 3), (4, 0, 0, 4)), ((5, 0, 0, 5), (6, 0, 0, 6), (7, 0, 0, 7), (8, 0, 0, 8)), ], ) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.NORMAL), (0, 1, 0)) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 1, og.AttributeRole.NORMAL), [(1, 0.0, 0.0), (0, 1, 0.0)]) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NORMAL), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.NORMAL), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.NORMAL), (1.5, 1.6, 1.7)) validate_type(og.Type(og.BaseDataType.HALF, 3, 1, og.AttributeRole.NORMAL), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)]) validate_type(og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.POSITION), (1.5, 1.6, 1.7)) validate_type( og.Type(og.BaseDataType.DOUBLE, 3, 1, og.AttributeRole.POSITION), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)] ) validate_type(og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.POSITION), (1.5, 1.6, 1.7)) validate_type( og.Type(og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.POSITION), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)] ) validate_type(og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.POSITION), (1.5, 1.6, 1.7)) validate_type( og.Type(og.BaseDataType.HALF, 3, 1, og.AttributeRole.POSITION), [(1.5, 1.6, 1.7), (2.5, 2.6, 2.7)] ) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.QUATERNION), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.DOUBLE, 4, 1, og.AttributeRole.QUATERNION), [(1, 0, 0, 1), (0, 1, 0, 1)]) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.QUATERNION), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.FLOAT, 4, 1, og.AttributeRole.QUATERNION), [(1, 0, 0, 1), (0, 1, 0, 1)]) validate_type(og.Type(og.BaseDataType.HALF, 4, 0, og.AttributeRole.QUATERNION), (1, 0, 0, 1)) validate_type(og.Type(og.BaseDataType.HALF, 4, 1, og.AttributeRole.QUATERNION), [(1, 0, 0, 1), (0, 1, 0, 1)]) validate_type(og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT), "text") validate_type(og.Type(og.BaseDataType.DOUBLE, 2, 0, og.AttributeRole.TEXCOORD), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.DOUBLE, 2, 1, og.AttributeRole.TEXCOORD), [(1.5, 1.6), (2.5, 2.6)]) validate_type(og.Type(og.BaseDataType.FLOAT, 2, 0, og.AttributeRole.TEXCOORD), (1.5, 1.6)) validate_type(og.Type(og.BaseDataType.FLOAT, 2, 1, og.AttributeRole.TEXCOORD), [(1.5, 1.6), (2.5, 2.6)])
31,304
Python
52.421502
120
0.62369
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_auto_instancing.py
""" Tests for omnigraph instancing """ import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from pxr import OmniGraphSchemaTools, Sdf # ====================================================================== class TestAutoInstancing(ogts.OmniGraphTestCase): async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() timeline.set_fast_mode(True) # ---------------------------------------------------------------------- async def tick(self): # Auto instance merging happens globaly before any compute takes place, # but the decision of asking to be merged is a per-graph thing that can happen # at the beggining of each graph compute, when the pipeline is already running # So we need 2 frames in those tests to ensure that merging actually happens await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # ---------------------------------------------------------------------- def create_simple_graph(self, graph_path, prim_path, value: int): controller = og.Controller() keys = og.Controller.Keys # +------------+ +------------+ # | NewBundle |======>| InsertAttr | # +------------+ | | # ===>|val | # | +------------+ # | # | +---------------+ # | | WritePrimAttr | # +------+ | | | # |Const |=======>|value | # +------+ | | # | | # +------+ | | # |Const |=======>|path | # +------+ | | # | | # +------------+ | | # |ReadVariable|=======>|name | # +------------+ +---------------+ # # +--------------+ # |Tutorial State| # +--------------+ # The tutorial state allows to exercise internal states when using auto instancing # it does not need any connection to validate that it works as expected # create the target prim stage = omni.usd.get_context().get_stage() prim = stage.DefinePrim(prim_path) prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output2", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output3", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output4", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output5", Sdf.ValueTypeNames.Int).Set(0) # create the graph (graph, _, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("Path", "omni.graph.nodes.ConstantToken"), ("Value", "omni.graph.nodes.ConstantInt"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ("State", "omni.graph.tutorials.State"), ("NewBundle", "omni.graph.nodes.BundleConstructor"), ("Insert", "omni.graph.nodes.InsertAttribute"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "WritePrimAttr.inputs:name"), ("Path.inputs:value", "WritePrimAttr.inputs:primPath"), ("Value.inputs:value", "WritePrimAttr.inputs:value"), ("NewBundle.outputs_bundle", "Insert.inputs:data"), ("Value.inputs:value", "Insert.inputs:attrToInsert"), ], keys.CREATE_VARIABLES: [ ("attrib_name", og.Type(og.BaseDataType.TOKEN)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "attrib_name"), ("WritePrimAttr.inputs:usePath", True), ("Path.inputs:value", prim_path), ("Value.inputs:value", value), ("Insert.inputs:outputAttrName", "value"), ], }, ) # set the variable default value var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output") return graph # ---------------------------------------------------------------------- def create_instance_graph(self, graph_path, prim_root_path, inst_count, value: int): controller = og.Controller() keys = og.Controller.Keys # +------------+ +------------+ # | NewBundle |======>| InsertAttr | # +------------+ | | # ===>|val | # | +------------+ # | # | +---------------+ # | | WritePrimAttr | # +------+ | | | # |Const |=======>|value | # +------+ | | # | | # +------------+ | | # |GraphTarget |======>|path | # +------------+ | | # | | # +------------+ | | # |ReadVariable|=======>|name | # +------------+ +---------------+ # # +--------------+ # |Tutorial State| # +--------------+ (graph, _, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ReadVariable", "omni.graph.core.ReadVariable"), ("Target", "omni.graph.nodes.GraphTarget"), ("Value", "omni.graph.nodes.ConstantInt"), ("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"), ("State", "omni.graph.tutorials.State"), ("NewBundle", "omni.graph.nodes.BundleConstructor"), ("Insert", "omni.graph.nodes.InsertAttribute"), ], keys.CONNECT: [ ("ReadVariable.outputs:value", "WritePrimAttr.inputs:name"), ("Target.outputs:primPath", "WritePrimAttr.inputs:primPath"), ("Value.inputs:value", "WritePrimAttr.inputs:value"), ("NewBundle.outputs_bundle", "Insert.inputs:data"), ("Value.inputs:value", "Insert.inputs:attrToInsert"), ], keys.CREATE_VARIABLES: [ ("attrib_name", og.Type(og.BaseDataType.TOKEN)), ], keys.SET_VALUES: [ ("ReadVariable.inputs:variableName", "attrib_name"), ("WritePrimAttr.inputs:usePath", True), ("Value.inputs:value", value), ("Insert.inputs:outputAttrName", "value"), ], }, ) # set the variable default value var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output") # create instances stage = omni.usd.get_context().get_stage() for i in range(0, inst_count): prim_name = f"{prim_root_path}_{i}" prim = stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, graph_path) prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output2", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output3", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output4", Sdf.ValueTypeNames.Int).Set(0) prim.CreateAttribute("graph_output5", Sdf.ValueTypeNames.Int).Set(0) return graph # ---------------------------------------------------------------------- async def setup_stage(self, use_usd, use_og_inst): stage = omni.usd.get_context().get_stage() inst_count = 4 int_range = range(1, 10) if use_usd: # main template main_template_path = "/World/Template" main_template_prim = f"{main_template_path}/Prim" main_template_graph = f"{main_template_path}/Graph" if use_og_inst: graph = self.create_instance_graph(main_template_graph, main_template_prim, inst_count, 1) else: graph = self.create_simple_graph(main_template_graph, main_template_prim, 1) for i in int_range: smart_asset_path = f"/World/SmartAsset_{i}" instance_prim = stage.DefinePrim(smart_asset_path) instance_prim.GetReferences().AddReference("", main_template_path) # give a chance to the graph to be created await self.tick() # setup the overs for i in int_range: smart_asset_path = f"/World/SmartAsset_{i}" # keep the first value inherited from template if i != 1: attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Value").GetAttribute("inputs:value") attr.Set(i) if use_og_inst is False: attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Path").GetAttribute("inputs:value") attr.Set(f"/World/SmartAsset_{i}/Prim") else: for i in int_range: if use_og_inst: graph = self.create_instance_graph(f"/World/TestGraph_{i}", f"/World/Prim_{i}", inst_count, i) else: graph = self.create_simple_graph(f"/World/TestGraph_{i}", f"/World/Prim_{i}", i) return graph # ---------------------------------------------------------------------- def validate_results_and_reset( self, use_usd: bool, use_og_inst: bool, output: str = "graph_output", first_sa: int = 1, last_sa: int = 10, first_og_inst: int = 0, last_og_inst: int = 4, mult: int = 1, ): if use_usd: graph_path = "/World/SmartAsset_{asset}/Graph" base_path = "/World/SmartAsset_{asset}/Prim" base_path_og = "/World/SmartAsset_{asset}/Prim_{inst}" else: graph_path = "/World/TestGraph_{asset}" base_path = "/World/Prim_{asset}" base_path_og = "/World/Prim_{asset}_{inst}" # for internals states checks: # all graph instances must have a different hundreds (ie. each has its own state) # all graph instances must have a same mode 100 (ie. each one has executed against its own state) state_hundreds_last_val = -1 state_last_mod100 = -1 stage = omni.usd.get_context().get_stage() found_master_sa = False for i in range(first_sa, last_sa): graph = og.Controller.graph(graph_path.format(asset=i)) state_out = og.Controller.attribute(graph_path.format(asset=i) + "/State.outputs:monotonic") insert_node = og.Controller.node(graph_path.format(asset=i) + "/Insert") self.assertTrue(graph.is_auto_instanced()) inst_count = graph.get_instance_count() if use_og_inst: if found_master_sa: self.assertTrue(inst_count == 4) else: if inst_count != 4: self.assertTrue(inst_count == 36) found_master_sa = True for j in range(first_og_inst, last_og_inst): prim_path = base_path_og.format(asset=i, inst=j) attr = stage.GetPrimAtPath(prim_path).GetAttribute(output) self.assertEqual(attr.Get(), i * mult) attr.Set(0) state_val = state_out.get(instance=j) self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data", j) bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), i * mult) else: if found_master_sa: self.assertTrue(inst_count == 0) else: if inst_count != 0: self.assertTrue(inst_count == 9) found_master_sa = True prim_path = base_path.format(asset=i) attr = stage.GetPrimAtPath(prim_path).GetAttribute(output) self.assertEqual(attr.Get(), i * mult) attr.Set(0) state_val = state_out.get() self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data") bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), i * mult) # ---------------------------------------------------------------------- async def test_auto_instance_no_usd_without_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation await self.setup_stage(False, False) await self.tick() self.validate_results_and_reset(False, False) # ---------------------------------------------------------------------- async def test_auto_instance_no_usd_with_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation where asset have OG instancing await self.setup_stage(False, True) await self.tick() self.validate_results_and_reset(False, True) # ---------------------------------------------------------------------- async def test_auto_instance_usd_without_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation await self.setup_stage(True, False) await self.tick() self.validate_results_and_reset(True, False) # ---------------------------------------------------------------------- async def test_auto_instance_usd_with_og_instancing(self): # Tests that we get a vectorized compute in smart asset situation where asset have OG instancing await self.setup_stage(True, True) await self.tick() self.validate_results_and_reset(True, True) # ---------------------------------------------------------------------- async def test_auto_instance_variable_without_og_instancing(self): # Tests that variable changes are taken into account template = await self.setup_stage(True, False) # set the template to write to 2nd output var = template.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output2") await self.tick() self.validate_results_and_reset(True, False, "graph_output2") # change them 1 by 1 to write to 1st output for i in range(1, 10): graph = og.Controller.graph(f"/World/SmartAsset_{i}/Graph") var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output3") await self.tick() self.validate_results_and_reset(True, False, "graph_output3", 1, i + 1) if i != 9: self.validate_results_and_reset(True, False, "graph_output2", i + 1, 10) # ---------------------------------------------------------------------- async def test_auto_instance_variable_with_og_instancing(self): # Tests that variable changes are taken into account stage = omni.usd.get_context().get_stage() template = await self.setup_stage(True, True) await self.tick() self.validate_results_and_reset(True, True, "graph_output") # set the template to write to out2 template_var = template.find_variable("attrib_name") og.Controller.set_variable_default_value(template_var, "graph_output2") await self.tick() self.validate_results_and_reset(True, True, "graph_output2") # change first half of the OG template instances to write to out3 for i in range(0, 2): prim_path = f"/World/Template/Prim_{i}" prim = stage.GetPrimAtPath(prim_path) variable = prim.CreateAttribute("graph:variable:attrib_name", Sdf.ValueTypeNames.Token) variable.Set("graph_output3") await self.tick() self.validate_results_and_reset(True, True, "graph_output3", 1, 10, 0, 2) self.validate_results_and_reset(True, True, "graph_output2", 1, 10, 2, 4) # override half SA/Graph to write to out4 for i in range(1, 5): graph = og.Controller.graph(f"/World/SmartAsset_{i}/Graph") var = graph.find_variable("attrib_name") og.Controller.set_variable_default_value(var, "graph_output4") await self.tick() # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 1, 5, 0, 2) # COMES FROM: SA/Graph self.validate_results_and_reset(True, True, "graph_output4", 1, 5, 2, 4) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 5, 10, 0, 2) # COMES FROM: Template/Graph self.validate_results_and_reset(True, True, "graph_output2", 5, 10, 2, 4) # Apply SA/OG_inst override to all known provenance for i in [1, 2, 5, 6]: for j in [0, 2]: prim_path = f"/World/SmartAsset_{i}/Prim_{j}" prim = stage.GetPrimAtPath(prim_path) variable = prim.CreateAttribute("graph:variable:attrib_name", Sdf.ValueTypeNames.Token) variable.Set("graph_output5") await self.tick() # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 1, 3, 0, 1) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 1, 3, 1, 2) # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 1, 3, 2, 3) # COMES FROM: SA/Graph self.validate_results_and_reset(True, True, "graph_output4", 1, 3, 3, 4) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 3, 5, 0, 2) # COMES FROM: SA/Graph self.validate_results_and_reset(True, True, "graph_output4", 3, 5, 2, 4) # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 5, 7, 0, 1) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 5, 7, 1, 2) # COMES FROM: SA/OG_inst self.validate_results_and_reset(True, True, "graph_output5", 5, 7, 2, 3) # COMES FROM: Template/Graph self.validate_results_and_reset(True, True, "graph_output2", 5, 7, 3, 4) # COMES FROM: Template/OG_inst self.validate_results_and_reset(True, True, "graph_output3", 7, 10, 0, 2) # COMES FROM: Template/Graph self.validate_results_and_reset(True, True, "graph_output2", 7, 10, 2, 4) # ---------------------------------------------------------------------- async def test_auto_instance_value_without_og_instancing(self): # Tests that value changes are taken into account stage = omni.usd.get_context().get_stage() await self.setup_stage(True, False) await self.tick() self.validate_results_and_reset(True, False) for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Value").GetAttribute("inputs:value") attr.Set(i * 10) await self.tick() self.validate_results_and_reset(True, False, "graph_output", 1, 5, mult=10) self.validate_results_and_reset(True, False, "graph_output", 5, 10) # same, but through OG directly for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = og.Controller.attribute(f"{smart_asset_path}/Graph/Value.inputs:value") attr.set(i * 20) await self.tick() self.validate_results_and_reset(True, False, "graph_output", 1, 5, mult=20) self.validate_results_and_reset(True, False, "graph_output", 5, 10) # ---------------------------------------------------------------------- async def test_auto_instance_value_with_og_instancing(self): # Tests that a value change is taken into account stage = omni.usd.get_context().get_stage() await self.setup_stage(True, True) await self.tick() self.validate_results_and_reset(True, True) for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = stage.GetPrimAtPath(f"{smart_asset_path}/Graph/Value").GetAttribute("inputs:value") attr.Set(i * 10) await self.tick() self.validate_results_and_reset(True, True, "graph_output", 1, 5, mult=10) self.validate_results_and_reset(True, True, "graph_output", 5, 10) # same, but through OG directly for i in range(1, 5): smart_asset_path = f"/World/SmartAsset_{i}" attr = og.Controller.attribute(f"{smart_asset_path}/Graph/Value.inputs:value") attr.set(i * 20) await self.tick() self.validate_results_and_reset(True, True, "graph_output", 1, 5, mult=20) self.validate_results_and_reset(True, True, "graph_output", 5, 10) # ---------------------------------------------------------------------- def _check_value_and_reset(self, val1, val2, with_inst): stage = omni.usd.get_context().get_stage() states_out = [ og.Controller.attribute("/World/Graph1/State.outputs:monotonic"), og.Controller.attribute("/World/Graph2/State.outputs:monotonic"), ] # for internals states checks: # all graph instances must have a different hundreds (ie. each has its own state) # all graph instances must have a same mode 100 (ie. each one has executed against its own state) state_hundreds_last_val = -1 state_last_mod100 = -1 if with_inst: for i in range(0, 4): attr = stage.GetPrimAtPath(f"/World/Prim1_{i}").GetAttribute("graph_output") self.assertEqual(attr.Get(), val1) attr.Set(0) attr = stage.GetPrimAtPath(f"/World/Prim2_{i}").GetAttribute("graph_output") self.assertEqual(attr.Get(), val2) attr.Set(0) for state_out in states_out: state_val = state_out.get(instance=i) self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 # bundle for graph 1 graph = og.Controller.graph("/World/Graph1") insert_node = og.Controller.node("/World/Graph1/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data", i) bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val1) # bundle for graph 2 graph = og.Controller.graph("/World/Graph2") insert_node = og.Controller.node("/World/Graph2/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data", i) bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val2) else: attr = stage.GetPrimAtPath("/World/Prim1").GetAttribute("graph_output") self.assertEqual(attr.Get(), val1) attr.Set(0) attr = stage.GetPrimAtPath("/World/Prim2").GetAttribute("graph_output") self.assertEqual(attr.Get(), val2) attr.Set(0) for state_out in states_out: state_val = state_out.get() self.assertNotEqual(state_val // 100, state_hundreds_last_val) state_hundreds_last_val = state_val // 100 if state_last_mod100 != -1: self.assertEqual(state_val % 100, state_last_mod100) state_last_mod100 = state_val % 100 # bundle for graph 1 graph = og.Controller.graph("/World/Graph1") insert_node = og.Controller.node("/World/Graph1/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data") bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val1) # bundle for graph 2 graph = og.Controller.graph("/World/Graph2") insert_node = og.Controller.node("/World/Graph2/Insert") bundle_out = graph.get_default_graph_context().get_output_bundle(insert_node, "outputs_data") bundle_attrib = bundle_out.get_attribute_by_name("value") self.assertEqual(bundle_attrib.get(), val2) # ---------------------------------------------------------------------- async def _change_check_reset(self, val1, val2, with_inst, with_usd): if with_usd: stage = omni.usd.get_context().get_stage() val_g1 = stage.GetPrimAtPath("/World/Graph1/Value").GetAttribute("inputs:value") val_g2 = stage.GetPrimAtPath("/World/Graph2/Value").GetAttribute("inputs:value") val_g1.Set(val1) val_g2.Set(val2) else: val_g1 = og.Controller.attribute("/World/Graph1/Value.inputs:value") val_g2 = og.Controller.attribute("/World/Graph2/Value.inputs:value") val_g1.set(val1) val_g2.set(val2) await self.tick() self._check_value_and_reset(val1, val2, with_inst) # ---------------------------------------------------------------------- async def _instantiation_test(self, use_og_inst): # create the graphs if use_og_inst: inst_count = 4 graph1 = self.create_instance_graph("/World/Graph1", "/World/Prim1", inst_count, 1) graph2 = self.create_instance_graph("/World/Graph2", "/World/Prim2", inst_count, 2) else: inst_count = 0 graph1 = self.create_simple_graph("/World/Graph1", "/World/Prim1", 1) graph2 = self.create_simple_graph("/World/Graph2", "/World/Prim2", 2) # add a variable to the first one graph1.create_variable("_tmp_", og.Type(og.BaseDataType.TOKEN)) # run a frame await self.tick() # check that the call was not vectorized self.assertFalse(graph1.is_auto_instanced()) self.assertTrue(graph1.get_instance_count() == inst_count) self.assertFalse(graph2.is_auto_instanced()) self.assertTrue(graph2.get_instance_count() == inst_count) # check results self._check_value_and_reset(1, 2, use_og_inst) # change values await self._change_check_reset(3, 4, use_og_inst, True) await self._change_check_reset(5, 6, use_og_inst, False) # add the same variable to graph2 graph2.create_variable("_tmp_", og.Type(og.BaseDataType.TOKEN)) # run a frame await self.tick() # check that the call is now vectorized self.assertTrue(graph1.is_auto_instanced()) self.assertTrue(graph2.is_auto_instanced()) ic1 = graph1.get_instance_count() ic2 = graph2.get_instance_count() if use_og_inst: self.assertTrue( (ic1 == 2 * inst_count and ic2 == inst_count) or (ic1 == inst_count and ic2 == 2 * inst_count) ) else: self.assertTrue((ic1 == 2 and ic2 == 0) or (ic1 == 0 and ic2 == 2)) # check results self._check_value_and_reset(5, 6, use_og_inst) # change values await self._change_check_reset(7, 8, use_og_inst, True) await self._change_check_reset(9, 10, use_og_inst, False) # force each graph to not use auto instancing for g in [graph1, graph2]: g.set_auto_instancing_allowed(False) await self.tick() # check that the call was not vectorized self.assertFalse(graph1.is_auto_instanced()) self.assertTrue(graph1.get_instance_count() == inst_count) self.assertFalse(graph2.is_auto_instanced()) self.assertTrue(graph2.get_instance_count() == inst_count) # check that it works # this also validates that the graph/bundle data has been properly migrated between master/slave self._check_value_and_reset(9, 10, use_og_inst) # change values await self._change_check_reset(11, 12, use_og_inst, True) await self._change_check_reset(13, 14, use_og_inst, False) # activate back auto instancing g.set_auto_instancing_allowed(True) await self.tick() # check that the call is now vectorized self.assertTrue(graph1.is_auto_instanced()) self.assertTrue(graph2.is_auto_instanced()) ic1 = graph1.get_instance_count() ic2 = graph2.get_instance_count() if use_og_inst: self.assertTrue( (ic1 == 2 * inst_count and ic2 == inst_count) or (ic1 == inst_count and ic2 == 2 * inst_count) ) else: self.assertTrue((ic1 == 2 and ic2 == 0) or (ic1 == 0 and ic2 == 2)) # check that it works self._check_value_and_reset(13, 14, use_og_inst) # change values await self._change_check_reset(15, 16, use_og_inst, True) # back to initial value (for next loop or next test) await self._change_check_reset(9, 10, use_og_inst, False) # add a new variable to graph1 graph1.create_variable("_tmp2_", og.Type(og.BaseDataType.TOKEN)) # run a frame await self.tick() # check that the call is now back to non-vectorized self.assertFalse(graph1.is_auto_instanced()) self.assertTrue(graph1.get_instance_count() == inst_count) self.assertFalse(graph2.is_auto_instanced()) self.assertTrue(graph2.get_instance_count() == inst_count) # check results self._check_value_and_reset(9, 10, use_og_inst) # change values await self._change_check_reset(11, 12, use_og_inst, True) await self._change_check_reset(13, 14, use_og_inst, False) # ---------------------------------------------------------------------- async def test_auto_instance_instantiation_without_og_instancing(self): # Tests that a graph modification can make it an auto instance await self._instantiation_test(False) # ---------------------------------------------------------------------- async def test_auto_instance_instantiation_with_og_instancing(self): # Tests that a graph modification can (un)make it an auto instance await self._instantiation_test(True) # ---------------------------------------------------------------------- async def test_auto_instance_signature_same_attrib(self): # Tests that 2 graphs that have a node with same attribute names don't get merged # the BooleanOr and BoolenAnd node has the same set of attributes: # inputs:a, inputs:b and outputs:result # 2 different graphs with the same topology but different nodes shouldn't get merged controller = og.Controller() keys = og.Controller.Keys # create the graphs (graph1, _, _, _) = controller.edit( "/World/TestGraph1", { keys.CREATE_NODES: [ ("/World/TestGraph1/Operation", "omni.graph.nodes.BooleanOr"), ], keys.SET_VALUES: [ ("/World/TestGraph1/Operation.inputs:a", {"type": "bool", "value": False}), ("/World/TestGraph1/Operation.inputs:b", {"type": "bool", "value": True}), ], }, ) (graph2, _, _, _) = controller.edit( "/World/TestGraph2", { keys.CREATE_NODES: [ ("/World/TestGraph2/Operation", "omni.graph.nodes.BooleanAnd"), ], keys.SET_VALUES: [ ("/World/TestGraph2/Operation.inputs:a", {"type": "bool", "value": False}), ("/World/TestGraph2/Operation.inputs:b", {"type": "bool", "value": True}), ], }, ) # run a frame await self.tick() # check results self.assertFalse(graph1.is_auto_instanced()) self.assertFalse(graph2.is_auto_instanced()) self.assertEqual(controller.attribute("/World/TestGraph1/Operation.outputs:result").get(), True) self.assertEqual(controller.attribute("/World/TestGraph2/Operation.outputs:result").get(), False) # ---------------------------------------------------------------------- async def test_auto_instance_signature_different_connection(self): # Tests that 2 graphs that have the same set of attributes with different connections don't get merged controller = og.Controller() keys = og.Controller.Keys # create the graphs (graph1, _, _, _) = controller.edit( "/World/TestGraph1", { keys.CREATE_NODES: [ ("Sub", "omni.graph.nodes.Subtract"), ("C1", "omni.graph.nodes.ConstantDouble"), ("C2", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("C1.inputs:value", "Sub.inputs:a"), ("C2.inputs:value", "Sub.inputs:b"), ], keys.SET_VALUES: [ ("C1.inputs:value", 10), ("C2.inputs:value", 5), ], }, ) # connected the other way around (graph2, _, _, _) = controller.edit( "/World/TestGraph2", { keys.CREATE_NODES: [ ("/World/TestGraph2/Sub", "omni.graph.nodes.Subtract"), ("/World/TestGraph2/C1", "omni.graph.nodes.ConstantDouble"), ("/World/TestGraph2/C2", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("/World/TestGraph2/C1.inputs:value", "/World/TestGraph2/Sub.inputs:b"), ("/World/TestGraph2/C2.inputs:value", "/World/TestGraph2/Sub.inputs:a"), ], keys.SET_VALUES: [ ("/World/TestGraph2/C1.inputs:value", 10), ("/World/TestGraph2/C2.inputs:value", 5), ], }, ) # run a frame await self.tick() # check results self.assertFalse(graph1.is_auto_instanced()) self.assertFalse(graph2.is_auto_instanced()) self.assertEqual(controller.attribute("/World/TestGraph1/Sub.outputs:difference").get(), 5) self.assertEqual(controller.attribute("/World/TestGraph2/Sub.outputs:difference").get(), -5)
37,017
Python
45.042289
116
0.520572
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_compound_nodes.py
# noqa: PLC0302 import itertools import math import os import re import tempfile from typing import List, Tuple import omni.graph.core as og import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn import omni.kit.test import omni.usd from pxr import OmniGraphSchema, Sdf DESCRIPTION_METADATA_KEY = f"omni:graph:{ogn.MetadataKeys.DESCRIPTION}" DISPLAYNAME_METADATA_KEY = f"omni:graph:{ogn.MetadataKeys.UI_NAME}" # ------------------------------------------------------------------------ def get_node(graph: og.Graph, node_name: str) -> og.Node: return graph.get_node(graph.get_path_to_graph() + "/" + node_name) # ------------------------------------------------------------------------ def get_node_type_from_schema_prim(prim: OmniGraphSchema.OmniGraphCompoundNodeType) -> str: """Returns the node type from an omni graph prim""" return f"{prim.GetOmniGraphNamespaceAttr().Get()}.{prim.GetPrim().GetPath().name}" # ------------------------------------------------------------------------ class TestCompoundNodes(ogts.OmniGraphTestCase): _simple_test_file = "TestCompoundGraph.usda" _test_file_with_reference = "TestCompoundWithExternalReference.usda" _test_file_with_default_values = "TestCompoundDefaultValues.usda" _test_preschema_file = "TestPreSchemaCompoundNode.usda" _test_graph_path = "/World/TestGraph" _node_library_test_file = os.path.join(os.path.dirname(__file__), "data", "TestNodeLibrary.usda") _library_compound_paths = [ "/World/Compounds/Madd", "/World/Compounds/DebugString", "/World/Compounds/Deg2Rad", "/World/Compounds/CelciusToFahrenheit", ] # ------------------------------------------------------------------------- def get_compound_folder(self): return ogu.get_default_compound_node_type_folder() def get_compound_path(self): return f"{self.get_compound_folder()}/Compound" def get_compound_graph_path(self): return f"{self.get_compound_path()}/Graph" # ------------------------------------------------------------------------- async def tearDown(self): omni.timeline.get_timeline_interface().stop() await super().tearDown() # ------------------------------------------------------------------------- async def test_load_file_with_compound_node_def(self): """ Tests that a usd file containing a compound node definition loads the compound node and adds it to the node database """ (result, error) = await ogts.load_test_file(self._simple_test_file, use_caller_subdirectory=True) self.assertTrue(result, error) # load the node type by path node_type = og.get_node_type(self.get_compound_path()) self.assertIsNotNone(node_type) expected_node_type = "local.nodes." + self.get_compound_path().rsplit("/", maxsplit=1)[-1] self.assertEquals(node_type.get_node_type(), expected_node_type) metadata = node_type.get_all_metadata() # verify it has expected metadata self.assertEquals(metadata["__categories"], "Compounds") self.assertEquals(metadata["uiName"], "Compound") self.assertEquals(metadata["tags"], "Compounds") # ------------------------------------------------------------------------- async def test_usd_changes_reflect_in_node_type(self): """ Tests that changing OmniGraphCompoundNodeType values are reflected in the compound node """ stage = omni.usd.get_context().get_stage() ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) # Change the schema_prim values schema_prim = OmniGraphSchema.OmniGraphCompoundNodeType(stage.GetPrimAtPath(self.get_compound_path())) schema_prim.GetOmniGraphCategoriesAttr().Set(["CatA", "CatB"]) schema_prim.GetOmniGraphDescriptionAttr().Set("Changed description") schema_prim.GetOmniGraphTagsAttr().Set(["TagA", "TagB"]) schema_prim.GetOmniGraphUiNameAttr().Set("FakeUIName") # validate they are changed in the node type node_type = og.get_node_type(self.get_compound_path()) metadata = node_type.get_all_metadata() self.assertEquals(metadata["__categories"], "CatA,CatB") self.assertEquals(metadata["tags"], "CatA,CatB") self.assertEquals(metadata["__description"], "Changed description") self.assertEquals(metadata["uiName"], "FakeUIName") # ------------------------------------------------------------------------- async def test_create_node_types_save_and_load(self): """Tests that a created node types save to USD and reload correctly""" stage = omni.usd.get_context().get_stage() # create a compound node ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) with tempfile.TemporaryDirectory() as tmpdirname: # save the file tmp_file_path = os.path.join(tmpdirname, "tmp.usda") result = omni.usd.get_context().save_as_stage(tmp_file_path) self.assertTrue(result) # refresh the stage await omni.usd.get_context().new_stage_async() # validate the node type was unloaded with the stage self.assertFalse(og.get_node_type(self.get_compound_path()).is_valid()) # reload the file back (result, error) = await ogts.load_test_file(tmp_file_path) self.assertTrue(result, error) # load the node type by path node_type = og.get_node_type(self.get_compound_path()) self.assertIsNotNone(node_type) expected_node_type = "local.nodes." + self.get_compound_path().rsplit("/", maxsplit=1)[-1] self.assertEquals(node_type.get_node_type(), expected_node_type) # ------------------------------------------------------------------------- def _create_and_test_graph_from_add_compound( self, compound_path, input_a="input_a", input_b="input_b", output="value", should_add: bool = True ) -> og.Graph: """Create and test a graph around a simple compound of an add node""" # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound", compound_path), ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("Constant_a.inputs:value", f"Compound.inputs:{input_a}"), ("Constant_b.inputs:value", f"Compound.inputs:{input_b}"), ], keys.SET_VALUES: [("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0)], }, ) self.assertTrue(nodes[0].get_attribute_exists(f"inputs:{input_a}")) self.assertTrue(nodes[0].get_attribute_exists(f"inputs:{input_b}")) self.assertTrue(nodes[0].get_attribute_exists(f"outputs:{output}")) graph.evaluate() result = nodes[0].get_attribute(f"outputs:{output}").get() if should_add: self.assertEquals(result, 3.0) return graph # ------------------------------------------------------------------------ def _create_graph_with_compound_node(self, compound_path: str) -> Tuple[og.Graph, og.Node]: """Create a graph that simply uses the compound node type specified.""" keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self._test_graph_path, {keys.CREATE_NODES: [("Compound", compound_path)]} ) return (graph, nodes[0]) # ------------------------------------------------------------------------ def _create_test_compound( self, compound_name, graph_name="Graph", namespace="local.nodes.", compound_dir=None, evaluator_type=None ): """Creates a compound node/graph that wraps an add node""" # create a compound node (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type=evaluator_type, ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_path = f"{graph_path}/Add_Node" node_type = get_node_type_from_schema_prim(schema_prim) # Create a node in the sub graph og.cmds.CreateNode( graph=og.get_graph_by_path(graph_path), node_path=node_path, node_type="omni.graph.nodes.Add", create_usd=True, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_a", attribute_path=Sdf.Path(f"{node_path}.inputs:a") ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_b", attribute_path=Sdf.Path(f"{node_path}.inputs:b") ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="value", attribute_path=Sdf.Path(f"{node_path}.outputs:sum") ) # ------------------------------------------------------------------------- async def test_create_and_use_compound_node(self): """Tests manual creation, assignment and evaluation of a compound node""" self._create_test_compound("Compound") self._create_and_test_graph_from_add_compound(f"{self.get_compound_folder()}/Compound") # ------------------------------------------------------------------------- async def test_create_and_use_compound_node_with_qualifiedname(self): """Tests that graphs can be referenced by the qualified name""" self._create_test_compound("Compound") self._create_and_test_graph_from_add_compound("local.nodes.Compound") # ------------------------------------------------------------------------- async def test_create_and_use_compound_node_with_namespace(self): """Tests that graphs can be referenced using a different namespace""" self._create_test_compound("Compound", "Graph", "test.nodes.") self._create_and_test_graph_from_add_compound("test.nodes.Compound") # ------------------------------------------------------------------------- async def test_create_and_rename_compound_node(self): """Tests created graphs can handle""" self._create_test_compound("Compound", "Graph") graph = self._create_and_test_graph_from_add_compound("local.nodes.Compound") stage = omni.usd.get_context().get_stage() # rename the compound node new_compound_path = f"{self.get_compound_folder()}/NewCompound" omni.kit.commands.execute("MovePrim", path_from=self.get_compound_path(), path_to=new_compound_path) await omni.kit.app.get_app().next_update_async() # validate the graph still updates node = graph.get_node(graph.get_path_to_graph() + "/Constant_a") node.get_attribute("inputs:value").set(2.0) graph.evaluate() node = graph.get_node(graph.get_path_to_graph() + "/Compound") self.assertEquals(node.get_attribute("outputs:value").get(), 4.0) # validate the node type is properly updated node = OmniGraphSchema.OmniGraphNode(stage.GetPrimAtPath(node.get_prim_path())) self.assertEquals("local.nodes.NewCompound", node.GetNodeTypeAttr().Get()) # ------------------------------------------------------------------------- async def test_change_compound_namespace(self): """Tests that changing the compound namespace is reflected in the nodes""" self._create_test_compound("Compound") graph = self._create_and_test_graph_from_add_compound(self.get_compound_path()) stage = omni.usd.get_context().get_stage() # change the node type namespace schema_prim = OmniGraphSchema.OmniGraphCompoundNodeType(stage.GetPrimAtPath(self.get_compound_path())) schema_prim.GetOmniGraphNamespaceAttr().Set("test.nodes") # validate the node type itself updates node = OmniGraphSchema.OmniGraphNode(stage.GetPrimAtPath(f"{self._test_graph_path}/Compound")) self.assertEquals("test.nodes.Compound", node.GetNodeTypeAttr().Get()) # validate the graph still updates node = graph.get_node(graph.get_path_to_graph() + "/Constant_a") node.get_attribute("inputs:value").set(2.0) graph.evaluate() node = graph.get_node(graph.get_path_to_graph() + "/Compound") self.assertEquals(node.get_attribute("outputs:value").get(), 4.0) # ------------------------------------------------------------------------- async def test_node_type_command_undo_redo(self): """Tests node type commands support undo/redo""" stage = omni.usd.get_context().get_stage() input_attribute_path = f"{self.get_compound_path()}.omni:graph:input:" output_attribute_path = f"{self.get_compound_path()}.omni:graph:output:" # create a compound node ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) self.assertTrue(stage.GetPrimAtPath(self.get_compound_graph_path()).IsValid()) omni.kit.undo.undo() self.assertFalse(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) self.assertFalse(stage.GetPrimAtPath(self.get_compound_graph_path()).IsValid()) omni.kit.undo.redo() self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) self.assertTrue(stage.GetPrimAtPath(self.get_compound_graph_path()).IsValid()) # Create a node in the sub graph og.cmds.CreateNode( graph=og.get_graph_by_path(self.get_compound_graph_path()), node_path=self.get_compound_graph_path() + "/Add_Node", node_type="omni.graph.nodes.Add", create_usd=True, ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=self.get_compound_path(), input_name="input_a", attribute_path=Sdf.Path(self.get_compound_path() + "/Graph/Add_Node.inputs:a"), ) self.assertTrue(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) omni.kit.undo.undo() self.assertFalse(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) omni.kit.undo.redo() self.assertTrue(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=self.get_compound_path(), output_name="value", attribute_path=Sdf.Path(self.get_compound_graph_path() + "/Add_Node.outputs:sum"), ) self.assertTrue(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) omni.kit.undo.undo() self.assertFalse(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) omni.kit.undo.redo() self.assertTrue(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) ogu.cmds.RemoveCompoundNodeTypeInput( node_type=self.get_compound_path(), input_name="input_a", ) self.assertFalse(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) omni.kit.undo.undo() self.assertTrue(stage.GetRelationshipAtPath(f"{input_attribute_path}input_a").IsValid()) ogu.cmds.RemoveCompoundNodeTypeOutput( node_type=self.get_compound_path(), output_name="value", ) self.assertFalse(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) omni.kit.undo.undo() self.assertTrue(stage.GetRelationshipAtPath(f"{output_attribute_path}value").IsValid()) # set up the second input and test to make sure the graph works ogu.cmds.CreateCompoundNodeTypeInput( node_type=self.get_compound_path(), input_name="input_b", attribute_path=Sdf.Path(self.get_compound_graph_path() + "/Add_Node.inputs:b"), ) self._create_and_test_graph_from_add_compound(self.get_compound_path()) # ------------------------------------------------------------------------- async def test_nested_compound_nodes(self): """Tests that nested compounds can be created and execute as expected""" # create an add compound for the inner node self._create_test_compound("innerCompound") inner_compound_path = f"{self.get_compound_folder()}/innerCompound" ogu.cmds.CreateCompoundNodeType(compound_name="outerCompound", graph_name="Graph") outer_compound_path = f"{self.get_compound_folder()}/outerCompound" outer_graph_path = f"{outer_compound_path}/Graph" outer_graph_node_path = f"{outer_graph_path}/Node" # Create a node in the sub graph that uses the inner compound og.cmds.CreateNode( graph=og.get_graph_by_path(outer_graph_path), node_path=outer_graph_node_path, node_type=inner_compound_path, create_usd=True, ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=outer_compound_path, input_name="a", attribute_path=Sdf.Path(f"{outer_graph_node_path}.inputs:input_a"), ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=outer_compound_path, input_name="b", attribute_path=Sdf.Path(f"{outer_graph_node_path}.inputs:input_b"), ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=outer_compound_path, output_name="result", attribute_path=Sdf.Path(f"{outer_graph_node_path}.outputs:value"), ) self._create_and_test_graph_from_add_compound(outer_compound_path, "a", "b", "result") # ------------------------------------------------------------------------- async def test_multiple_compounds_used(self): """Tests that multiple compounds of the same type can be used in a single graphs""" self._create_test_compound("Compound") # create a graph that uses the compound graph # ------------ ------------- # [Const a]->|Compound a| -------> |Compound b | # [Const b] | | [Const c]->| | # ------------ ------------- keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound_a", self.get_compound_path()), ("Compound_b", self.get_compound_path()), ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Constant_c", "omni.graph.nodes.ConstantDouble"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Compound_a.inputs:input_a"), ("Constant_b.inputs:value", "Compound_a.inputs:input_b"), ("Compound_a.outputs:value", "Compound_b.inputs:input_a"), ("Constant_c.inputs:value", "Compound_b.inputs:input_b"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) self.assertTrue(nodes[0].get_attribute_exists("inputs:input_a")) self.assertTrue(nodes[0].get_attribute_exists("inputs:input_b")) self.assertTrue(nodes[0].get_attribute_exists("outputs:value")) self.assertTrue(nodes[1].get_attribute_exists("inputs:input_a")) self.assertTrue(nodes[1].get_attribute_exists("inputs:input_b")) self.assertTrue(nodes[1].get_attribute_exists("outputs:value")) graph.evaluate() # check intermediate result result = nodes[0].get_attribute("outputs:value").get() self.assertEquals(result, 3.0) # check final result result = nodes[1].get_attribute("outputs:value").get() self.assertEquals(result, 6.0) # ------------------------------------------------------------------------- async def test_compound_graph_does_not_run(self): """ Tests that when creating a compound graph, the compound graph itself does not evaluate """ compound_name = "Compound" graph_name = "Graph" # create a compound node ogu.cmds.CreateCompoundNodeType(compound_name=compound_name, graph_name=graph_name) compound_path = f"{self.get_compound_folder()}/{compound_name}" graph_path = f"{compound_path}/{graph_name}" keys = og.Controller.Keys controller = og.Controller() (_, (time_node, to_string_node), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("Time", "omni.graph.nodes.ReadTime"), ("ToString", "omni.graph.nodes.ToString"), ], keys.CONNECT: [("Time.outputs:timeSinceStart", "ToString.inputs:value")], }, ) for _ in range(1, 5): await omni.kit.app.get_app().next_update_async() self.assertEquals(time_node.get_compute_count(), 0) self.assertEquals(to_string_node.get_compute_count(), 0) # ------------------------------------------------------------------------- async def test_replace_with_compound_command(self): """Tests the replace with compound command under different scenarios""" graph_path = "/World/Graph" def build_graph(graph_path: str) -> Tuple[og.Node]: # [ConstA] -----> [Add]---v # [ConstB] -------^ [Add]---v # [ConstC] ---------------^ [Add]--->[Magnitude] # [ReadTime] ---------------------^ keys = og.Controller.Keys controller = og.Controller() (_graph, nodes, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), # 0 ("Constant_b", "omni.graph.nodes.ConstantDouble"), # 1 ("Constant_c", "omni.graph.nodes.ConstantDouble"), # 2 ("ReadTime", "omni.graph.nodes.ReadTime"), # 3 ("Add1", "omni.graph.nodes.Add"), # 4 ("Add2", "omni.graph.nodes.Add"), # 5 ("Add3", "omni.graph.nodes.Add"), # 6 ("Abs", "omni.graph.nodes.Magnitude"), # 7 ], keys.CONNECT: [ ("Constant_a.inputs:value", "Add1.inputs:a"), ("Constant_b.inputs:value", "Add1.inputs:b"), ("Add1.outputs:sum", "Add2.inputs:a"), ("Constant_c.inputs:value", "Add2.inputs:b"), ("Add2.outputs:sum", "Add3.inputs:a"), ("ReadTime.outputs:timeSinceStart", "Add3.inputs:b"), ("Add3.outputs:sum", "Abs.inputs:input"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) # Workaround...SET_VALUES does not set values in USD, which is needed to retain # values when nodes are copied stage = omni.usd.get_context().get_stage() stage.GetAttributeAtPath(graph_path + "/Constant_a.inputs:value").Set(1.0) stage.GetAttributeAtPath(graph_path + "/Constant_b.inputs:value").Set(2.0) stage.GetAttributeAtPath(graph_path + "/Constant_c.inputs:value").Set(3.0) return nodes async def validate_graph(all_nodes: Tuple[og.Node], node_indices: List[int]): # let the graph evaluate and cache the output value, which # should increase with each tick output_node = all_nodes[-1] output_attr = output_node.get_attribute("outputs:magnitude") await omni.kit.app.get_app().next_update_async() self.assertGreater(output_node.get_compute_count(), 0) self.assertGreater(output_attr.get(), 6.0) last_val = output_attr.get() # replace the given node set with a compound node all_node_paths = [Sdf.Path(node.get_prim_path()) for node in all_nodes] nodes = [all_nodes[i] for i in node_indices] node_paths = [Sdf.Path(node.get_prim_path()) for node in nodes] og.cmds.ReplaceWithCompound(nodes=node_paths) # verify the compound node was created compound_path = node_paths[0].GetParentPath().AppendChild("compound") compound_node = og.get_node_by_path(str(compound_path)) self.assertTrue(compound_node.is_valid()) # if the last node is not the compound if 7 not in node_indices: # re-fetch the node from a path, the previous og.node may have been invalidated abs_path = og.get_node_by_path(str(all_node_paths[7])) output_attr = abs_path.get_attribute("outputs:magnitude") await omni.kit.app.get_app().next_update_async() # note: the compute count gets reset when the replace with compound, so validate it has advanced self.assertGreater(abs_path.get_compute_count(), 0) self.assertGreater(output_attr.get(), last_val) else: self.assertGreater(compound_node.get_compute_count(), 0) # validate all nodes in the subgraph computed graph_path = compound_path.AppendChild("Graph") compound_graph = og.get_graph_by_path(str(graph_path)) self.assertTrue(compound_graph.is_valid()) compound_nodes = compound_graph.get_nodes() self.assertGreater(len(compound_nodes), 0) for compound_node in compound_nodes: # Quick check for constant nodes. TODO: Add a more robust method to # check for such nodes (check if a node has the "pure" scheduling # hint and only runtime-constant input attributes)? if "omni.graph.nodes.Constant" in compound_node.get_type_name(): self.assertEqual(compound_node.get_compute_count(), 0) else: self.assertGreater(compound_node.get_compute_count(), 0) # add nodes await validate_graph(build_graph(graph_path + "0"), [4, 5, 6]) # first two inputs + first add await validate_graph(build_graph(graph_path + "1"), [0, 1, 4]) # last const + read time + last two adds await validate_graph(build_graph(graph_path + "2"), [2, 3, 5, 6]) # all nodes except the last await validate_graph(build_graph(graph_path + "3"), [0, 1, 2, 3, 4, 5, 6]) # ------------------------------------------------------------------------- async def _load_node_library(self): stage = omni.usd.get_context().get_stage() root_layer = stage.GetRootLayer() # insert a subLayer with material.usda which contains just one material prim omni.kit.commands.execute( "CreateSublayer", layer_identifier=root_layer.identifier, sublayer_position=0, new_layer_path=self._node_library_test_file, transfer_root_content=False, create_or_insert=False, ) await omni.kit.app.get_app().next_update_async() # ------------------------------------------------------------------------- async def _unload_node_library(self): stage = omni.usd.get_context().get_stage() root_layer = stage.GetRootLayer() omni.kit.commands.execute("RemoveSublayer", layer_identifier=root_layer.identifier, sublayer_position=0) await omni.kit.app.get_app().next_update_async() # ------------------------------------------------------------------------ def _validate_library_nodes_loaded(self, are_loaded: bool): stage = omni.usd.get_context().get_stage() for path in self._library_compound_paths: prim = stage.GetPrimAtPath(Sdf.Path(path)) prim_loaded_and_valid = bool(prim) and prim.IsA(OmniGraphSchema.OmniGraphCompoundNodeType) self.assertEquals(are_loaded, prim_loaded_and_valid, f"Failed with {path}") self.assertEquals(are_loaded, og.get_node_type(path).is_valid()) # ------------------------------------------------------------------------- async def test_compound_nodes_load_from_layer(self): """ Tests that node libraries loaded from a separate layer correctly load and unload """ # load the library await self._load_node_library() self._validate_library_nodes_loaded(True) # unload await self._unload_node_library() self._validate_library_nodes_loaded(False) # reload the library await self._load_node_library() self._validate_library_nodes_loaded(True) # unload the whole stage await omni.usd.get_context().new_stage_async() self._validate_library_nodes_loaded(False) # ----------------------------------------------------------------------- async def test_compound_node_can_reference_layer(self): """ Tests that a compound node that references a compound graph located in a layer """ await self._load_node_library() # builds the graph # [const]-->[compound]------->[magnitude] # [const]---^ ^ # [const]------| keys = og.Controller.Keys controller = og.Controller() (_graph, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Constant_c", "omni.graph.nodes.ConstantDouble"), ("Madd", "/World/Compounds/Madd"), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Madd.inputs:a"), ("Constant_b.inputs:value", "Madd.inputs:b"), ("Constant_c.inputs:value", "Madd.inputs:c"), ("Madd.outputs:sum", "Abs.inputs:input"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) await omni.kit.app.get_app().next_update_async() for node in nodes: # Quick check for constant nodes. TODO: Add a more robust method to # check for such nodes (check if a node has the "pure" scheduling # hint and only runtime-constant input attributes)? if not node.is_compound_node() and "omni.graph.nodes.Constant" not in node.get_type_name(): self.assertGreater(node.get_compute_count(), 0, f"Expected {node.get_prim_path()} to be computed") attr = nodes[4].get_attribute("outputs:magnitude") self.assertEquals(attr.get(), 1.0 * 2.0 + 3.0) # ------------------------------------------------------------------------- async def test_compound_from_reference_runs(self): """ Tests that a graph containing a compound node with an external reference can be loaded and run """ # Loads a graph on disk that looks like: # where the compound references a graph from the TestNodeLibrary.usda (madd) # [const]-->[compound]------->[magnitude] # [const]---^ ^ # [const]------| (result, error) = await ogts.load_test_file(self._test_file_with_reference, use_caller_subdirectory=True) self.assertTrue(result, error) await omni.kit.app.get_app().next_update_async() graph = og.get_graph_by_path("/World/PushGraph") nodes = graph.get_nodes() self.assertGreater(len(nodes), 4, "Expected at least 5 nodes") for node in nodes: # Quick check for constant nodes. TODO: Add a more robust method to # check for such nodes (check if a node has the "pure" scheduling # hint and only runtime-constant input attributes)? if not node.is_compound_node() and "omni.graph.nodes.Constant" not in node.get_type_name(): self.assertGreater(node.get_compute_count(), 0, f"Expected {node.get_prim_path()} to be computed") output = og.get_node_by_path("/World/PushGraph/magnitude") attr = output.get_attribute("outputs:magnitude") self.assertEquals(attr.get(), 1.0 * 2.0 + 3.0) # ------------------------------------------------------------------------- async def test_nested_reference_compound(self): """ Tests that a nested compound node loaded from a compound library runs """ await self._load_node_library() keys = og.Controller.Keys controller = og.Controller() (_graph, (_constant, convert), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Convert", "/World/Compounds/CelciusToFahrenheit"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Convert.inputs:a"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ], }, ) await omni.kit.app.get_app().next_update_async() self.assertEquals(convert.get_attribute("outputs:value").get(), 33.8) # ------------------------------------------------------------------------- async def test_fan_out_to_compounds(self): """Tests that fan out into multiple compound nodes""" await self._load_node_library() # [Const] -> [Compound] -> [Add] # -> [Compound] -> keys = og.Controller.Keys controller = og.Controller() (_, (_, compound_a, compound_b, add), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Convert_a", "/World/Compounds/Deg2Rad"), ("Convert_b", "/World/Compounds/Deg2Rad"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Convert_a.inputs:a"), ("Constant_a.inputs:value", "Convert_b.inputs:a"), ("Convert_a.outputs:result", "Add.inputs:a"), ("Convert_b.outputs:result", "Add.inputs:b"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 180), ], }, ) await omni.kit.app.get_app().next_update_async() self.assertEquals(compound_a.get_attribute("outputs:result").get(), math.pi) self.assertEquals(compound_b.get_attribute("outputs:result").get(), math.pi) self.assertEquals(add.get_attribute("outputs:sum").get(), math.pi * 2.0) # ------------------------------------------------------------------------- async def test_fan_out_from_compounds(self): """Tests that fan out from a compound node works""" await self._load_node_library() # [Const] -> [Compound] -> [Abs] # -> [Abs] keys = og.Controller.Keys controller = og.Controller() (_, (_, _, abs_a, abs_b), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Convert_a", "/World/Compounds/Deg2Rad"), ("Abs_a", "omni.graph.nodes.Magnitude"), ("Abs_b", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Convert_a.inputs:a"), ("Convert_a.outputs:result", "Abs_a.inputs:input"), ("Convert_a.outputs:result", "Abs_b.inputs:input"), ], keys.SET_VALUES: [("Constant_a.inputs:value", 180)], }, ) await omni.kit.app.get_app().next_update_async() self.assertEquals(abs_a.get_attribute("outputs:magnitude").get(), math.pi) self.assertEquals(abs_b.get_attribute("outputs:magnitude").get(), math.pi) # ------------------------------------------------------------------------- async def test_register_compound_with_node_type_conflict(self): """ Tests that compound nodes registered with the same as built-in nodes produces error and does NOT override the default node usage """ # Create the compound node with ogts.ExpectedError(): self._create_test_compound("Add", "Graph", "omni.graph.nodes") # Validate the compound is still created stage = omni.usd.get_context().get_stage() self.assertTrue(stage.GetPrimAtPath(self.get_compound_folder() + "/Add_01").IsValid()) self.assertTrue(stage.GetPrimAtPath(self.get_compound_folder() + "/Add_01/Graph").IsValid()) # Validate the built-in node type is actually used keys = og.Controller.Keys controller = og.Controller() (graph, (_, _, add), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Add.inputs:a"), ("Constant_b.inputs:value", "Add.inputs:b"), ], keys.SET_VALUES: [("Constant_a.inputs:value", 1), ("Constant_b.inputs:value", 2)], }, ) await controller.evaluate(graph) self.assertEquals(add.get_attribute("outputs:sum").get(), 3) # ------------------------------------------------------------------------- async def test_register_compound_with_compound_conflict(self): """Tests errors when registering multiple compounds with the same name""" self._create_test_compound("Compound") with ogts.ExpectedError(): self._create_test_compound(compound_name="Compound", compound_dir=Sdf.Path("/World/Compound/SubDir")) self._create_and_test_graph_from_add_compound("local.nodes.Compound") # ------------------------------------------------------------------------- async def test_create_node_type_prevents_duplicates(self): """Tests that CreateNodeType prevents duplicates through renaming""" ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") ogu.cmds.CreateCompoundNodeType(compound_name="Add", graph_name="Graph", namespace="omni.graph.nodes") stage = omni.usd.get_context().get_stage() folder = stage.GetPrimAtPath(self.get_compound_folder()) self.assertEquals(len(folder.GetChildren()), 3) self.assertTrue(stage.GetPrimAtPath(self.get_compound_folder() + "/Compound").IsValid()) self.assertFalse(stage.GetPrimAtPath(self.get_compound_folder() + "/Add").IsValid()) # -------------------------------------------------------------------------- async def test_create_node_type_with_existing_node_name(self): """ Tests that creating a node type with a name conflict on an existing node in the graph functions does not break """ keys = og.Controller.Keys controller = og.Controller() (graph, (const_a, const_b, _, add, add_01), _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Constant_a", "omni.graph.nodes.ConstantDouble"), ("Constant_b", "omni.graph.nodes.ConstantDouble"), ("Constant_c", "omni.graph.nodes.ConstantDouble"), ("Add", "omni.graph.nodes.Add"), ("Add_01", "omni.graph.nodes.Add"), ], keys.CONNECT: [ ("Constant_a.inputs:value", "Add.inputs:a"), ("Constant_b.inputs:value", "Add.inputs:b"), ("Add.outputs:sum", "Add_01.inputs:a"), ("Constant_c.inputs:value", "Add_01.inputs:b"), ], keys.SET_VALUES: [ ("Constant_a.inputs:value", 1.0), ("Constant_b.inputs:value", 2.0), ("Constant_c.inputs:value", 3.0), ], }, ) await og.Controller.evaluate(graph) self.assertEquals(add_01.get_attribute("outputs:sum").get(), 6.0) # replace the nodes with a node type that has the same name as an existing node node_paths = [Sdf.Path(node.get_prim_path()) for node in [const_a, const_b, add]] og.cmds.ReplaceWithCompound(nodes=node_paths, compound_name="Add_01") # validate add_01 = get_node(graph, "Add_01") compound_node = next(filter(lambda node: node.is_compound_node(), graph.get_nodes()), None) self.assertFalse(get_node(graph, "Constant_a").is_valid()) self.assertFalse(get_node(graph, "Constant_b").is_valid()) self.assertTrue(get_node(graph, "Constant_c").is_valid()) self.assertTrue(add_01.is_valid()) self.assertIsNotNone(compound_node) self.assertNotEquals(Sdf.Path(compound_node.get_prim_path()).name, "Add_01") # validate the graph await og.Controller.evaluate(graph) self.assertEquals(add_01.get_attribute("outputs:sum").get(), 6.0) # -------------------------------------------------------------------------- async def test_is_compound_node_type(self): """Simple test that validates nodetype.is_compound_node""" await self._load_node_library() # C++ nodes self.assertFalse(og.get_node_type("omni.graph.test.Add2IntegerArrays").is_compound_node_type()) self.assertFalse(og.get_node_type("omni.graph.test.ComputeErrorCpp").is_compound_node_type()) # python nodes self.assertFalse(og.get_node_type("omni.graph.test.ComputeErrorPy").is_compound_node_type()) self.assertFalse(og.get_node_type("omni.graph.test.TestAllDataTypesPy").is_compound_node_type()) # compound nodes self.assertTrue(og.get_node_type("local.nodes.Madd").is_compound_node_type()) self.assertTrue(og.get_node_type("local.nodes.DebugString").is_compound_node_type()) self.assertTrue(og.get_node_type("local.nodes.Deg2Rad").is_compound_node_type()) self.assertTrue(og.get_node_type("local.nodes.CelciusToFahrenheit").is_compound_node_type()) # -------------------------------------------------------------------------- async def test_compound_nodes_trigger_graph_registry_events(self): """Tests that changing compound node values triggers appropriate graph registry events""" node_type_t = OmniGraphSchema.OmniGraphCompoundNodeType await self._load_node_library() events = [] def on_changed(event): nonlocal events events.append(event) sub = og.GraphRegistry().get_event_stream().create_subscription_to_pop(on_changed) self.assertIsNotNone(sub) stage = omni.usd.get_context().get_stage() prims = [node_type_t(stage.GetPrimAtPath(path)) for path in self._library_compound_paths] for prim in prims: prim.GetOmniGraphCategoriesAttr().Set(["NewCategory"]) await omni.kit.app.get_app().next_update_async() self.assertEquals(len(events), len(self._library_compound_paths)) self.assertTrue(all(e.type == int(og.GraphRegistryEvent.NODE_TYPE_CATEGORY_CHANGED) for e in events)) events = [] for prim in prims: prim.GetOmniGraphNamespaceAttr().Set("other.namespace") await omni.kit.app.get_app().next_update_async() # Double the count because there will be two events per compound (node type added, namespace changed) self.assertEquals(len(events), len(self._library_compound_paths) * 2) add_events = [ int(og.GraphRegistryEvent.NODE_TYPE_NAMESPACE_CHANGED), int(og.GraphRegistryEvent.NODE_TYPE_ADDED), ] self.assertTrue(all(e.type in add_events for e in events)) sub = None # -------------------------------------------------------------------------- async def test_is_compound_graph(self): """Tests is_compound_graph returns true for compounds graphs""" (result, error) = await ogts.load_test_file(self._test_file_with_reference, use_caller_subdirectory=True) self.assertTrue(result, error) await omni.kit.app.get_app().next_update_async() graph = og.get_graph_by_path("/World/PushGraph") self.assertTrue(graph.is_valid()) self.assertFalse(graph.is_compound_graph()) graph = og.get_graph_by_path("/World/PushGraph/madd/Graph") self.assertTrue(graph.is_valid()) self.assertTrue(graph.is_compound_graph()) # --------------------------------------------------------------------- def _create_lazy_compound( self, compound_name, evaluator_type, graph_name="Graph", namespace="local.nodes.", compound_dir=None ): """Creates a compound node/graph that wraps an add node The output is the time from a ReadTime node """ # Create a compound node/graph that can be used to evaluate lazy graphs (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type=evaluator_type, ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_path = f"{graph_path}/ReadTime_Node" node_type = get_node_type_from_schema_prim(schema_prim) # Create a node in the sub graph og.cmds.CreateNode( graph=og.get_graph_by_path(graph_path), node_path=node_path, node_type="omni.graph.nodes.ReadTime", create_usd=True, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="value", attribute_path=Sdf.Path(f"{node_path}.outputs:timeSinceStart") ) # ------------------------------------------------------------------------- def _create_evaluation_graph( self, compound_name, evaluator_type, graph_name="Graph", namespace="local.nodes.", compound_dir=None ): """ Creates a compound node for an evaluation graph The underlying graph is [OnImpulse]->[TickCounter] and outputs the tick count """ (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type=evaluator_type, ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_path = f"{graph_path}/TickCounter" node_type = get_node_type_from_schema_prim(schema_prim) keys = og.Controller.Keys controller = og.Controller() (_, (_impulse, _counter), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnImpulse", "omni.graph.action.OnImpulseEvent"), ("TickCounter", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"), ], keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False), ("OnImpulse.state:enableImpulse", True)], }, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="value", attribute_path=Sdf.Path(f"{node_path}.outputs:count") ) # ------------------------------------------------------------------------- async def __evaluate_graph_types(self, compound_type: str, runner_type: str): """Tests that graphs can be referenced using a different namespace""" if compound_type == "execution": self._create_evaluation_graph("Compound", compound_type) else: self._create_lazy_compound("Compound", compound_type) # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (graph, (_compound, abs_node), _, _) = controller.edit( {"graph_path": self._test_graph_path, "evaluator_name": runner_type}, { keys.CREATE_NODES: [ ("Compound", f"{self.get_compound_folder()}/Compound"), ("Abs", "omni.graph.nodes.Magnitude"), ], keys.CONNECT: [ ("Compound.outputs:value", "Abs.inputs:input"), ], }, ) await omni.kit.app.get_app().next_update_async() await og.Controller.evaluate(graph) result = abs_node.get_attribute("outputs:magnitude").get() return result > 0.0 # ------------------------------------------------------------------------- async def test_intermix_evaluator_types_in_compounds(self): """ Tests mixing evaluator types of graphs with compounds This test uses a compound with a given evaluator type and a single output connected to an outer graph """ # play the timeline so readtime nodes get updated omni.timeline.get_timeline_interface().play() outer_graph_modes = ["push", "dirty_push"] compound_modes = ["push", "dirty_push", "execution"] for (graph_type, compound_type) in itertools.product(outer_graph_modes, compound_modes): with self.subTest(compound_type=compound_type, graph_type=graph_type): success = await self.__evaluate_graph_types(compound_type, graph_type) self.assertTrue(success, f"Graph Type: '{graph_type}' with Compound Type: '{compound_type}'") await omni.usd.get_context().new_stage_async() # ------------------------------------------------------------------------- async def test_evaluator_types_in_compounds(self): """ Test different evaluator types of graphs with compounds that have inputs and outputs where the outer graph is a push graph """ compound_modes = ["push", "dirty_push", "execution"] for compound_type in compound_modes: with self.subTest(compound_type=compound_type): self._create_test_compound("Compound", evaluator_type=compound_type) should_add = compound_type in ("push", "dirty_push") self._create_and_test_graph_from_add_compound( f"{self.get_compound_folder()}/Compound", should_add=should_add ) await omni.usd.get_context().new_stage_async() # ---------------------------------------------------------------------------- async def test_deleted_compound_graph(self): """Basic test that validates a deleted compound doesn't cause a crash""" stage = omni.usd.get_context().get_stage() self._create_test_compound("Compound") graph = self._create_and_test_graph_from_add_compound("local.nodes.Compound") omni.kit.commands.execute("DeletePrims", paths=[self.get_compound_path()]) self.assertFalse(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) graph.evaluate() # ---------------------------------------------------------------------------- async def test_create_node_type_attributes_with_fixed_types(self): """ Tests the CreateNodeTypeInput and CreateNodeTypeOutput with predefined types, including extended types and validates the attributes are correctly created on the resulting node instances """ stage = omni.usd.get_context().get_stage() (_, schema_prim) = ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) node_type = get_node_type_from_schema_prim(schema_prim) og_types = [ og.AttributeType.type_from_ogn_type_name(type_name) for type_name in ogn.supported_attribute_type_names() ] str_inputs = ogn.supported_attribute_type_names() + list(ogn.ATTRIBUTE_UNION_GROUPS.keys()) # create attributes both from og.Type and ogn type strings (including "union" types) for idx, og_type in enumerate(og_types): name = re.sub(r"\W", "_", og_type.get_ogn_type_name()) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name=f"input_{name}_{idx}", attribute_path=None, default_type=og_type ) if og_type.role not in [og.AttributeRole.BUNDLE, og.AttributeRole.TARGET]: ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name=f"output_{name}_{idx}", attribute_path=None, default_type=og_type ) for idx, str_type in enumerate(str_inputs): name = re.sub(r"\W", "_", str_type) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name=f"input_s_{name}_{idx}", attribute_path=None, default_type=str_type ) if str_type not in ["bundle", "target"]: ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name=f"output_s_{name}_{idx}", attribute_path=None, default_type=str_type, ) # validate bundles don't work omni.kit.commands.set_logging_enabled(False) (result, _) = ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_bundle_a", attribute_path=None, default_type="bundle" ) self.assertFalse(result) (result, _) = ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_bundle_b", attribute_path=None, default_type=og.Type(og.BaseDataType.PRIM, 1, 0, og.AttributeRole.BUNDLE), ) self.assertFalse(result) omni.kit.commands.set_logging_enabled(True) # validate specifying no path or default_type still creates inputs and outputs ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_empty", attribute_path=None, default_type=None ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_empty", attribute_path=None, default_type=None ) # validate creation with list style unions float_type_subset = [ og.Type(og.BaseDataType.FLOAT), og.Type(og.BaseDataType.FLOAT, 2), og.Type(og.BaseDataType.FLOAT, 3), ] ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_union", attribute_path=None, default_type=float_type_subset ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_union", attribute_path=None, default_type=float_type_subset ) # create a graph that uses the compound graph (_, compound_node) = self._create_graph_with_compound_node(f"{self.get_compound_folder()}/Compound") # validate the attributes on the node have been created, and the resolved type matches where there is a regular type for idx, og_type in enumerate(og_types): name = re.sub(r"\W", "_", og_type.get_ogn_type_name()) input_name = f"inputs:input_{name}_{idx}" self.assertTrue(compound_node.get_attribute(input_name).is_valid(), input_name) self.assertEquals(compound_node.get_attribute(input_name).get_resolved_type(), og_type) if og_type.role not in [og.AttributeRole.BUNDLE, og.AttributeRole.TARGET]: output_name = f"outputs:output_{name}_{idx}" self.assertTrue(compound_node.get_attribute(output_name).is_valid(), output_name) self.assertEquals(compound_node.get_attribute(output_name).get_resolved_type(), og_type) for idx, str_type in enumerate(str_inputs): name = re.sub(r"\W", "_", str_type) input_name = f"inputs:input_s_{name}_{idx}" self.assertTrue(compound_node.get_attribute(input_name).is_valid(), input_name) if str_type not in ["bundle", "target"]: output_name = f"outputs:output_s_{name}_{idx}" self.assertTrue(compound_node.get_attribute(output_name).is_valid(), output_name) # empty inputs and outputs create self.assertTrue(compound_node.get_attribute("inputs:input_empty").is_valid()) self.assertTrue(compound_node.get_attribute("outputs:output_empty").is_valid()) # list-style unions self.assertTrue(compound_node.get_attribute("inputs:input_union").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertTrue(compound_node.get_attribute("outputs:output_union").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) # ---------------------------------------------------------------------------- async def test_create_node_type_attributes_with_fixed_types_and_connections(self): """ Tests CreateNodeTypeInput and CreateNodeTypeOutput when both an attribute_path and a fixed types are applied """ # create a compound node stage = omni.usd.get_context().get_stage() (_, schema_prim) = ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) node_path = f"{self.get_compound_graph_path()}/Node" union_path = f"{self.get_compound_graph_path()}/UnionNode" union_path_2 = f"{self.get_compound_graph_path()}/UnionNodeTwo" node_type = get_node_type_from_schema_prim(schema_prim) input_prefix = f"{node_path}.inputs:" output_prefix = f"{node_path}.outputs:" # Create a node in the sub graph that has many fixed types og.cmds.CreateNode( graph=og.get_graph_by_path(self.get_compound_graph_path()), node_path=node_path, node_type="omni.graph.test.TestAllDataTypes", create_usd=True, ) # And nodes with union types for path in [union_path, union_path_2]: og.cmds.CreateNode( graph=og.get_graph_by_path(self.get_compound_graph_path()), node_path=path, node_type="omni.graph.nodes.Add", create_usd=True, ) # attributes where the types match ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_bool", attribute_path=Sdf.Path(f"{input_prefix}a_bool"), default_type="bool", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_bool", attribute_path=Sdf.Path(f"{output_prefix}a_bool"), default_type="bool", ) # attributes where the defined type is a union, and the attribute type is not ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_float", attribute_path=Sdf.Path(f"{input_prefix}a_float"), default_type="numerics", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_float", attribute_path=Sdf.Path(f"{output_prefix}a_float"), default_type="numerics", ) # attributes where the defined type is fixed, and the attribute type is a union ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_double", attribute_path=Sdf.Path(f"{union_path}.inputs:a"), default_type="double", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_double", attribute_path=Sdf.Path(f"{union_path}.outputs:sum"), default_type="double", ) # attributes where the types don't match with ogts.ExpectedError(): ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_float_2", attribute_path=Sdf.Path(f"{input_prefix}a_token"), default_type="float[2]", ) with ogts.ExpectedError(): ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_float_2", attribute_path=Sdf.Path(f"{output_prefix}a_token"), default_type="float[2]", ) # union to union ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_union", attribute_path=Sdf.Path(f"{union_path}.inputs:b"), default_type="numerics", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_union", attribute_path=Sdf.Path(f"{union_path_2}.outputs:sum"), default_type="numerics", ) # create a graph that uses the compound graph (_, compound_node) = self._create_graph_with_compound_node(f"{self.get_compound_folder()}/Compound") # types match exactly self.assertTrue(compound_node.get_attribute("inputs:input_bool").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_bool").get_resolved_type(), og.Type(og.BaseDataType.BOOL) ) self.assertTrue(compound_node.get_attribute("outputs:output_bool").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_bool").get_resolved_type(), og.Type(og.BaseDataType.BOOL) ) # definition is a union, target is fixed self.assertTrue(compound_node.get_attribute("inputs:input_float").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_float").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertTrue(compound_node.get_attribute("outputs:output_float").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_float").get_resolved_type(), og.Type(og.BaseDataType.FLOAT) ) # definition is fixed, target is a union self.assertTrue(compound_node.get_attribute("inputs:input_double").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_double").get_resolved_type(), og.Type(og.BaseDataType.DOUBLE) ) self.assertTrue(compound_node.get_attribute("outputs:output_double").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_double").get_resolved_type(), og.Type(og.BaseDataType.DOUBLE) ) # attributes where the types don't match self.assertTrue(compound_node.get_attribute("inputs:input_float_2").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_float_2").get_resolved_type(), og.Type(og.BaseDataType.FLOAT, 2, 0), ) self.assertTrue(compound_node.get_attribute("outputs:output_float_2").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_float_2").get_resolved_type(), og.Type(og.BaseDataType.FLOAT, 2, 0), ) # both are unions self.assertTrue(compound_node.get_attribute("inputs:input_union").is_valid()) self.assertEquals( compound_node.get_attribute("inputs:input_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) self.assertTrue(compound_node.get_attribute("outputs:output_union").is_valid()) self.assertEquals( compound_node.get_attribute("outputs:output_union").get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN) ) # ---------------------------------------------------------------------------- async def test_compound_node_input_output_metadata(self): """ Validate that metadata created on the input/outputs of a Compound Node Type gets transferred to created nodes from those compounds """ stage = omni.usd.get_context().get_stage() (_, schema_prim) = ogu.cmds.CreateCompoundNodeType(compound_name="Compound", graph_name="Graph") self.assertTrue(stage.GetPrimAtPath(self.get_compound_path()).IsValid()) node_type = get_node_type_from_schema_prim(schema_prim) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="input_a", attribute_path=None, default_type="int", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="output_a", attribute_path=None, default_type="int", ) # get the relationship created as the type input and output input_rel = schema_prim.GetPrim().GetRelationship("omni:graph:input:input_a") output_rel = schema_prim.GetPrim().GetRelationship("omni:graph:output:output_a") self.assertTrue(input_rel.IsValid()) self.assertTrue(output_rel.IsValid()) # set the metadata on the relationships. input_rel.SetCustomDataByKey(DESCRIPTION_METADATA_KEY, "InputDescription") input_rel.SetCustomDataByKey(DISPLAYNAME_METADATA_KEY, "InputDisplayName") output_rel.SetCustomDataByKey(DESCRIPTION_METADATA_KEY, "OutputDescription") output_rel.SetCustomDataByKey(DISPLAYNAME_METADATA_KEY, "OutputDisplayName") # create a graph that uses the compound node type keys = og.Controller.Keys controller = og.Controller() (_, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound", f"{self.get_compound_folder()}/Compound"), ] }, ) node = nodes[0] # Validate that the resulting node contains the metadata transfered when the node is created input_attr = node.get_attribute("inputs:input_a") output_attr = node.get_attribute("outputs:output_a") self.assertEquals("InputDescription", input_attr.get_metadata(ogn.MetadataKeys.DESCRIPTION)) self.assertEquals("InputDisplayName", input_attr.get_metadata(ogn.MetadataKeys.UI_NAME)) self.assertEquals("OutputDescription", output_attr.get_metadata(ogn.MetadataKeys.DESCRIPTION)) self.assertEquals("OutputDisplayName", output_attr.get_metadata(ogn.MetadataKeys.UI_NAME)) # ------------------------------------------------------------------------- def assert_attribute_value(self, actual, expected): """ Helper method that deals with values returned from attributes, where lists may actually be numpy arrays. """ ogts.verify_values(expected, actual, f"Comparison failed {str(actual)} vs {str(expected)}") # ---------------------------------------------------------------------------- async def test_compound_node_input_defaults(self): """ Test that validates compound nodes that carry default values in their metadata initialize nodes with the default values. This validates the attribute is correctly loaded with the typed default value in the metadata of node type definition """ (result, error) = await ogts.load_test_file(self._test_file_with_default_values, use_caller_subdirectory=True) self.assertTrue(result, error) compound_node_type = ogu.find_compound_node_type_by_path("/World/Compounds/Compound") self.assert_attribute_value(compound_node_type.find_input("a_bool").get_default_data(), 0) self.assert_attribute_value(compound_node_type.find_input("a_bool_array").get_default_data(), [0, 1]) self.assert_attribute_value( compound_node_type.find_input("a_colord_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_colord_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_colord_4").get_default_data(), [0.01625, 0.14125, 0.26625, 0.39125] ) self.assert_attribute_value( compound_node_type.find_input("a_colord_4_array").get_default_data(), [[0.01625, 0.14125, 0.26625, 0.39125], [0.39125, 0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_4").get_default_data(), [0.125, 0.25, 0.375, 0.5] ) self.assert_attribute_value( compound_node_type.find_input("a_colorf_4_array").get_default_data(), [[0.125, 0.25, 0.375, 0.5], [0.5, 0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_colorh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_colorh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value( compound_node_type.find_input("a_colorh_4").get_default_data(), [0.5, 0.625, 0.75, 0.875] ) self.assert_attribute_value( compound_node_type.find_input("a_colorh_4_array").get_default_data(), [[0.5, 0.625, 0.75, 0.875], [0.875, 0.75, 0.625, 0.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_double").get_default_data(), 4.125) self.assert_attribute_value(compound_node_type.find_input("a_double_2").get_default_data(), [4.125, 4.25]) self.assert_attribute_value( compound_node_type.find_input("a_double_2_array").get_default_data(), [[4.125, 4.25], [2.125, 2.25]] ) self.assert_attribute_value( compound_node_type.find_input("a_double_3").get_default_data(), [4.125, 4.25, 4.375] ) self.assert_attribute_value( compound_node_type.find_input("a_double_3_array").get_default_data(), [[4.125, 4.25, 4.375], [2.125, 2.25, 2.375]], ) self.assert_attribute_value( compound_node_type.find_input("a_double_4").get_default_data(), [4.125, 4.25, 4.375, 4.5] ) self.assert_attribute_value( compound_node_type.find_input("a_double_4_array").get_default_data(), [[4.125, 4.25, 4.375, 4.5], [2.125, 2.25, 2.375, 2.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_double_array").get_default_data(), [4.125, 2.125]) self.assert_attribute_value(compound_node_type.find_input("a_execution").get_default_data(), 0) self.assert_attribute_value(compound_node_type.find_input("a_float").get_default_data(), 4.5) self.assert_attribute_value(compound_node_type.find_input("a_float_2").get_default_data(), [4.5, 4.625]) self.assert_attribute_value( compound_node_type.find_input("a_float_2_array").get_default_data(), [[4.5, 4.625], [2.5, 2.625]] ) self.assert_attribute_value(compound_node_type.find_input("a_float_3").get_default_data(), [4.5, 4.625, 4.75]) self.assert_attribute_value( compound_node_type.find_input("a_float_3_array").get_default_data(), [[4.5, 4.625, 4.75], [2.5, 2.625, 2.75]], ) self.assert_attribute_value( compound_node_type.find_input("a_float_4").get_default_data(), [4.5, 4.625, 4.75, 4.875] ) self.assert_attribute_value( compound_node_type.find_input("a_float_4_array").get_default_data(), [[4.5, 4.625, 4.75, 4.875], [2.5, 2.625, 2.75, 2.875]], ) self.assert_attribute_value(compound_node_type.find_input("a_float_array").get_default_data(), [4.5, 2.5]) self.assert_attribute_value( compound_node_type.find_input("a_frame_4").get_default_data(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], ) self.assert_attribute_value( compound_node_type.find_input("a_frame_4_array").get_default_data(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value(compound_node_type.find_input("a_half").get_default_data(), 2.5) self.assert_attribute_value(compound_node_type.find_input("a_half_2").get_default_data(), [2.5, 2.625]) self.assert_attribute_value( compound_node_type.find_input("a_half_2_array").get_default_data(), [[2.5, 2.625], [4.5, 4.625]] ) self.assert_attribute_value(compound_node_type.find_input("a_half_3").get_default_data(), [2.5, 2.625, 2.75]) self.assert_attribute_value( compound_node_type.find_input("a_half_3_array").get_default_data(), [[2.5, 2.625, 2.75], [4.5, 4.625, 4.75]] ) self.assert_attribute_value( compound_node_type.find_input("a_half_4").get_default_data(), [2.5, 2.625, 2.75, 2.875] ) self.assert_attribute_value( compound_node_type.find_input("a_half_4_array").get_default_data(), [[2.5, 2.625, 2.75, 2.875], [4.5, 4.625, 4.75, 4.875]], ) self.assert_attribute_value(compound_node_type.find_input("a_half_array").get_default_data(), [2.5, 4.5]) self.assert_attribute_value(compound_node_type.find_input("a_int").get_default_data(), -32) self.assert_attribute_value(compound_node_type.find_input("a_int64").get_default_data(), -46) self.assert_attribute_value(compound_node_type.find_input("a_int64_array").get_default_data(), [-46, -64]) self.assert_attribute_value(compound_node_type.find_input("a_int_2").get_default_data(), [-32, -31]) self.assert_attribute_value( compound_node_type.find_input("a_int_2_array").get_default_data(), [[-32, -31], [-23, -22]] ) self.assert_attribute_value(compound_node_type.find_input("a_int_3").get_default_data(), [-32, -31, -30]) self.assert_attribute_value( compound_node_type.find_input("a_int_3_array").get_default_data(), [[-32, -31, -30], [-23, -22, -21]] ) self.assert_attribute_value(compound_node_type.find_input("a_int_4").get_default_data(), [-32, -31, -30, -29]) self.assert_attribute_value( compound_node_type.find_input("a_int_4_array").get_default_data(), [[-32, -31, -30, -29], [-23, -22, -21, -20]], ) self.assert_attribute_value(compound_node_type.find_input("a_int_array").get_default_data(), [-32, -23]) self.assert_attribute_value(compound_node_type.find_input("a_matrixd_2").get_default_data(), [[1, 0], [0, 1]]) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_2_array").get_default_data(), [[[1, 0], [0, 1]], [[2, 3], [3, 2]]] ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_3").get_default_data(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]] ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_3_array").get_default_data(), [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[2, 3, 3], [3, 2, 3], [3, 3, 2]]], ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_4").get_default_data(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], ) self.assert_attribute_value( compound_node_type.find_input("a_matrixd_4_array").get_default_data(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value( compound_node_type.find_input("a_normald_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_normald_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_normalf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_normalf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_normalh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_normalh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_objectId").get_default_data(), 46) self.assert_attribute_value(compound_node_type.find_input("a_objectId_array").get_default_data(), [46, 64]) self.assert_attribute_value(compound_node_type.find_input("a_path").get_default_data(), "/This/Is") self.assert_attribute_value( compound_node_type.find_input("a_pointd_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_pointd_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_pointf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_pointf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_pointh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_pointh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value( compound_node_type.find_input("a_quatd_4").get_default_data(), [0.01625, 0.14125, 0.26625, 0.78] ) self.assert_attribute_value( compound_node_type.find_input("a_quatd_4_array").get_default_data(), [[0.01625, 0.14125, 0.26625, 0.78], [0.14125, 0.26625, 0.39125, 0.51625]], ) self.assert_attribute_value( compound_node_type.find_input("a_quatf_4").get_default_data(), [0.125, 0.25, 0.375, 0.5] ) self.assert_attribute_value( compound_node_type.find_input("a_quatf_4_array").get_default_data(), [[0.125, 0.25, 0.375, 0.5], [0.25, 0.375, 0.5, 0.625]], ) self.assert_attribute_value(compound_node_type.find_input("a_quath_4").get_default_data(), [0, 0.25, 0.5, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_quath_4_array").get_default_data(), [[0, 0.25, 0.5, 0.75], [0.125, 0.375, 0.625, 0.875]], ) self.assert_attribute_value(compound_node_type.find_input("a_string").get_default_data(), "Anakin") self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_2").get_default_data(), [0.01625, 0.14125] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_2_array").get_default_data(), [[0.01625, 0.14125], [0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordd_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(compound_node_type.find_input("a_texcoordf_2").get_default_data(), [0.125, 0.25]) self.assert_attribute_value( compound_node_type.find_input("a_texcoordf_2_array").get_default_data(), [[0.125, 0.25], [0.25, 0.125]] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_texcoordh_2").get_default_data(), [0.5, 0.625]) self.assert_attribute_value( compound_node_type.find_input("a_texcoordh_2_array").get_default_data(), [[0.5, 0.625], [0.625, 0.5]] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordh_3").get_default_data(), [0.5, 0.625, 0.75] ) self.assert_attribute_value( compound_node_type.find_input("a_texcoordh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) self.assert_attribute_value(compound_node_type.find_input("a_timecode").get_default_data(), 5) self.assert_attribute_value(compound_node_type.find_input("a_timecode_array").get_default_data(), [5, 6]) self.assert_attribute_value(compound_node_type.find_input("a_token").get_default_data(), "Ahsoka") self.assert_attribute_value( compound_node_type.find_input("a_token_array").get_default_data(), ["Ahsoka", "Tano"] ) self.assert_attribute_value(compound_node_type.find_input("a_uchar").get_default_data(), 12) self.assert_attribute_value(compound_node_type.find_input("a_uchar_array").get_default_data(), [12, 8]) self.assert_attribute_value(compound_node_type.find_input("a_uint").get_default_data(), 32) self.assert_attribute_value(compound_node_type.find_input("a_uint64").get_default_data(), 46) self.assert_attribute_value(compound_node_type.find_input("a_uint64_array").get_default_data(), [46, 64]) self.assert_attribute_value(compound_node_type.find_input("a_uint_array").get_default_data(), [32, 23]) self.assert_attribute_value( compound_node_type.find_input("a_vectord_3").get_default_data(), [0.01625, 0.14125, 0.26625] ) self.assert_attribute_value( compound_node_type.find_input("a_vectord_3_array").get_default_data(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value( compound_node_type.find_input("a_vectorf_3").get_default_data(), [0.125, 0.25, 0.375] ) self.assert_attribute_value( compound_node_type.find_input("a_vectorf_3_array").get_default_data(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]], ) self.assert_attribute_value(compound_node_type.find_input("a_vectorh_3").get_default_data(), [0.5, 0.625, 0.75]) self.assert_attribute_value( compound_node_type.find_input("a_vectorh_3_array").get_default_data(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]], ) # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (_, nodes, _, _) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ("Compound", f"{self.get_compound_folder()}/Compound"), ] }, ) node = nodes[0] # validate that the generated nodes have the proper default set as well. self.assert_attribute_value(node.get_attribute("inputs:a_bool").get(), 0) self.assert_attribute_value(node.get_attribute("inputs:a_bool_array").get(), [0, 1]) self.assert_attribute_value(node.get_attribute("inputs:a_colord_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_colord_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_colord_4").get(), [0.01625, 0.14125, 0.26625, 0.39125]) self.assert_attribute_value( node.get_attribute("inputs:a_colord_4_array").get(), [[0.01625, 0.14125, 0.26625, 0.39125], [0.39125, 0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_colorf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_colorf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_colorf_4").get(), [0.125, 0.25, 0.375, 0.5]) self.assert_attribute_value( node.get_attribute("inputs:a_colorf_4_array").get(), [[0.125, 0.25, 0.375, 0.5], [0.5, 0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_colorh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_colorh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_colorh_4").get(), [0.5, 0.625, 0.75, 0.875]) self.assert_attribute_value( node.get_attribute("inputs:a_colorh_4_array").get(), [[0.5, 0.625, 0.75, 0.875], [0.875, 0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_double").get(), 4.125) self.assert_attribute_value(node.get_attribute("inputs:a_double_2").get(), [4.125, 4.25]) self.assert_attribute_value(node.get_attribute("inputs:a_double_2_array").get(), [[4.125, 4.25], [2.125, 2.25]]) self.assert_attribute_value(node.get_attribute("inputs:a_double_3").get(), [4.125, 4.25, 4.375]) self.assert_attribute_value( node.get_attribute("inputs:a_double_3_array").get(), [[4.125, 4.25, 4.375], [2.125, 2.25, 2.375]] ) self.assert_attribute_value(node.get_attribute("inputs:a_double_4").get(), [4.125, 4.25, 4.375, 4.5]) self.assert_attribute_value( node.get_attribute("inputs:a_double_4_array").get(), [[4.125, 4.25, 4.375, 4.5], [2.125, 2.25, 2.375, 2.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_double_array").get(), [4.125, 2.125]) self.assert_attribute_value(node.get_attribute("inputs:a_execution").get(), 0) self.assert_attribute_value(node.get_attribute("inputs:a_float").get(), 4.5) self.assert_attribute_value(node.get_attribute("inputs:a_float_2").get(), [4.5, 4.625]) self.assert_attribute_value(node.get_attribute("inputs:a_float_2_array").get(), [[4.5, 4.625], [2.5, 2.625]]) self.assert_attribute_value(node.get_attribute("inputs:a_float_3").get(), [4.5, 4.625, 4.75]) self.assert_attribute_value( node.get_attribute("inputs:a_float_3_array").get(), [[4.5, 4.625, 4.75], [2.5, 2.625, 2.75]] ) self.assert_attribute_value(node.get_attribute("inputs:a_float_4").get(), [4.5, 4.625, 4.75, 4.875]) self.assert_attribute_value( node.get_attribute("inputs:a_float_4_array").get(), [[4.5, 4.625, 4.75, 4.875], [2.5, 2.625, 2.75, 2.875]] ) self.assert_attribute_value(node.get_attribute("inputs:a_float_array").get(), [4.5, 2.5]) self.assert_attribute_value( node.get_attribute("inputs:a_frame_4").get(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] ) self.assert_attribute_value( node.get_attribute("inputs:a_frame_4_array").get(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value(node.get_attribute("inputs:a_half").get(), 2.5) self.assert_attribute_value(node.get_attribute("inputs:a_half_2").get(), [2.5, 2.625]) self.assert_attribute_value(node.get_attribute("inputs:a_half_2_array").get(), [[2.5, 2.625], [4.5, 4.625]]) self.assert_attribute_value(node.get_attribute("inputs:a_half_3").get(), [2.5, 2.625, 2.75]) self.assert_attribute_value( node.get_attribute("inputs:a_half_3_array").get(), [[2.5, 2.625, 2.75], [4.5, 4.625, 4.75]] ) self.assert_attribute_value(node.get_attribute("inputs:a_half_4").get(), [2.5, 2.625, 2.75, 2.875]) self.assert_attribute_value( node.get_attribute("inputs:a_half_4_array").get(), [[2.5, 2.625, 2.75, 2.875], [4.5, 4.625, 4.75, 4.875]] ) self.assert_attribute_value(node.get_attribute("inputs:a_half_array").get(), [2.5, 4.5]) self.assert_attribute_value(node.get_attribute("inputs:a_int").get(), -32) self.assert_attribute_value(node.get_attribute("inputs:a_int64").get(), -46) self.assert_attribute_value(node.get_attribute("inputs:a_int64_array").get(), [-46, -64]) self.assert_attribute_value(node.get_attribute("inputs:a_int_2").get(), [-32, -31]) self.assert_attribute_value(node.get_attribute("inputs:a_int_2_array").get(), [[-32, -31], [-23, -22]]) self.assert_attribute_value(node.get_attribute("inputs:a_int_3").get(), [-32, -31, -30]) self.assert_attribute_value( node.get_attribute("inputs:a_int_3_array").get(), [[-32, -31, -30], [-23, -22, -21]] ) self.assert_attribute_value(node.get_attribute("inputs:a_int_4").get(), [-32, -31, -30, -29]) self.assert_attribute_value( node.get_attribute("inputs:a_int_4_array").get(), [[-32, -31, -30, -29], [-23, -22, -21, -20]] ) self.assert_attribute_value(node.get_attribute("inputs:a_int_array").get(), [-32, -23]) self.assert_attribute_value(node.get_attribute("inputs:a_matrixd_2").get(), [[1, 0], [0, 1]]) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_2_array").get(), [[[1, 0], [0, 1]], [[2, 3], [3, 2]]] ) self.assert_attribute_value(node.get_attribute("inputs:a_matrixd_3").get(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_3_array").get(), [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[2, 3, 3], [3, 2, 3], [3, 3, 2]]], ) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_4").get(), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] ) self.assert_attribute_value( node.get_attribute("inputs:a_matrixd_4_array").get(), [ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[2, 3, 3, 3], [3, 2, 3, 3], [3, 3, 2, 3], [3, 3, 3, 2]], ], ) self.assert_attribute_value(node.get_attribute("inputs:a_normald_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_normald_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_normalf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_normalf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_normalh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_normalh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_objectId").get(), 46) self.assert_attribute_value(node.get_attribute("inputs:a_objectId_array").get(), [46, 64]) self.assert_attribute_value(node.get_attribute("inputs:a_path").get(), "/This/Is") self.assert_attribute_value(node.get_attribute("inputs:a_pointd_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_pointd_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_pointf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_pointf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_pointh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_pointh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_quatd_4").get(), [0.01625, 0.14125, 0.26625, 0.78]) self.assert_attribute_value( node.get_attribute("inputs:a_quatd_4_array").get(), [[0.01625, 0.14125, 0.26625, 0.78], [0.14125, 0.26625, 0.39125, 0.51625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_quatf_4").get(), [0.125, 0.25, 0.375, 0.5]) self.assert_attribute_value( node.get_attribute("inputs:a_quatf_4_array").get(), [[0.125, 0.25, 0.375, 0.5], [0.25, 0.375, 0.5, 0.625]] ) self.assert_attribute_value(node.get_attribute("inputs:a_quath_4").get(), [0, 0.25, 0.5, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_quath_4_array").get(), [[0, 0.25, 0.5, 0.75], [0.125, 0.375, 0.625, 0.875]] ) self.assert_attribute_value(node.get_attribute("inputs:a_string").get(), "Anakin") self.assert_attribute_value(node.get_attribute("inputs:a_texcoordd_2").get(), [0.01625, 0.14125]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordd_2_array").get(), [[0.01625, 0.14125], [0.14125, 0.01625]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordd_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordd_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordf_2").get(), [0.125, 0.25]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordf_2_array").get(), [[0.125, 0.25], [0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordh_2").get(), [0.5, 0.625]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordh_2_array").get(), [[0.5, 0.625], [0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_texcoordh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_texcoordh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) self.assert_attribute_value(node.get_attribute("inputs:a_timecode").get(), 5) self.assert_attribute_value(node.get_attribute("inputs:a_timecode_array").get(), [5, 6]) self.assert_attribute_value(node.get_attribute("inputs:a_token").get(), "Ahsoka") self.assert_attribute_value(node.get_attribute("inputs:a_token_array").get(), ["Ahsoka", "Tano"]) self.assert_attribute_value(node.get_attribute("inputs:a_uchar").get(), 12) self.assert_attribute_value(node.get_attribute("inputs:a_uchar_array").get(), [12, 8]) self.assert_attribute_value(node.get_attribute("inputs:a_uint").get(), 32) self.assert_attribute_value(node.get_attribute("inputs:a_uint64").get(), 46) self.assert_attribute_value(node.get_attribute("inputs:a_uint64_array").get(), [46, 64]) self.assert_attribute_value(node.get_attribute("inputs:a_uint_array").get(), [32, 23]) self.assert_attribute_value(node.get_attribute("inputs:a_vectord_3").get(), [0.01625, 0.14125, 0.26625]) self.assert_attribute_value( node.get_attribute("inputs:a_vectord_3_array").get(), [[0.01625, 0.14125, 0.26625], [0.26625, 0.14125, 0.01625]], ) self.assert_attribute_value(node.get_attribute("inputs:a_vectorf_3").get(), [0.125, 0.25, 0.375]) self.assert_attribute_value( node.get_attribute("inputs:a_vectorf_3_array").get(), [[0.125, 0.25, 0.375], [0.375, 0.25, 0.125]] ) self.assert_attribute_value(node.get_attribute("inputs:a_vectorh_3").get(), [0.5, 0.625, 0.75]) self.assert_attribute_value( node.get_attribute("inputs:a_vectorh_3_array").get(), [[0.5, 0.625, 0.75], [0.75, 0.625, 0.5]] ) def _create_test_action_compound( self, compound_name, graph_name="Graph", namespace="local.nodes.", compound_dir=None ): """Creates a compound node/graph that wraps an add node""" # create a compound node (success, schema_prim) = ogu.cmds.CreateCompoundNodeType( compound_name=compound_name, graph_name=graph_name, namespace=namespace, folder=compound_dir, evaluator_type="execution", ) if not success: raise og.OmniGraphError("CreateNodeType failed") compound_path = str(schema_prim.GetPrim().GetPath()) graph_path = f"{compound_path}/{graph_name}" node_type = get_node_type_from_schema_prim(schema_prim) keys = og.Controller.Keys controller = og.Controller() (_, _, _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Branch", "omni.graph.action.Branch"), ("WriteTrue", "omni.graph.nodes.WritePrimAttribute"), ("WriteFalse", "omni.graph.nodes.WritePrimAttribute"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "Branch.inputs:execIn"), ("Branch.outputs:execTrue", "WriteTrue.inputs:execIn"), ("Branch.outputs:execFalse", "WriteFalse.inputs:execIn"), ], keys.CREATE_PRIMS: [("/World/Prim", {"val": ("double", 0.0)})], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("WriteTrue.inputs:name", "val"), ("WriteTrue.inputs:primPath", "/World/Prim"), ("WriteTrue.inputs:usePath", True), ("WriteFalse.inputs:name", "val"), ("WriteFalse.inputs:primPath", "/World/Prim"), ("WriteFalse.inputs:usePath", True), ], }, ) # assign inputs and outputs ogu.cmds.CreateCompoundNodeTypeInput(node_type=node_type, input_name="execIn", default_type="execution") ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="valTrue", attribute_path=Sdf.Path(f"{graph_path}/WriteTrue.inputs:value"), default_type="double", ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="valFalse", attribute_path=Sdf.Path(f"{graph_path}/WriteFalse.inputs:value"), default_type="double", ) ogu.cmds.CreateCompoundNodeTypeInput( node_type=node_type, input_name="condition", attribute_path=Sdf.Path(f"{graph_path}/Branch.inputs:condition"), default_type="bool", ) ogu.cmds.CreateCompoundNodeTypeOutput( node_type=node_type, output_name="execOut", attribute_path=Sdf.Path(f"{graph_path}/WriteTrue.outputs:execOut"), default_type="execution", ) return (compound_path, graph_path) async def test_action_compounds(self): """ Test Action Graph compound nodes """ compound_path, _ = self._create_test_action_compound("ExecCompound") self._create_test_compound("PushCompound") stage = omni.usd.get_context().get_stage() push_compound_path = f"{self.get_compound_folder()}/PushCompound" # create a graph that uses the compound graph keys = og.Controller.Keys controller = og.Controller() (graph, (exec_node, push_node, _, _, _, _), _, _) = controller.edit( {"graph_path": self._test_graph_path, "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("ExecCompound", compound_path), ("PushCompound", push_compound_path), ("OnTick", "omni.graph.action.OnTick"), ("Constant1", "omni.graph.nodes.ConstantDouble"), ("Constant2", "omni.graph.nodes.ConstantDouble"), ("ConstantBool", "omni.graph.nodes.ConstantBool"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "ExecCompound.inputs:execIn"), ("Constant1.inputs:value", "PushCompound.inputs:input_a"), ("Constant2.inputs:value", "PushCompound.inputs:input_b"), ("PushCompound.outputs:value", "ExecCompound.inputs:valTrue"), ("Constant2.inputs:value", "ExecCompound.inputs:valFalse"), ("ConstantBool.inputs:value", "ExecCompound.inputs:condition"), ], keys.SET_VALUES: [ ("Constant1.inputs:value", 1.0), ("Constant2.inputs:value", 2.0), ("ConstantBool.inputs:value", False), ("OnTick.inputs:onlyPlayback", False), ], }, ) await og.Controller.evaluate(graph) self.assertTrue(bool(exec_node.get_compound_graph_instance())) self.assertEqual(len(exec_node.get_compound_graph_instance().get_nodes()), 4) self.assertTrue(bool(push_node.get_compound_graph_instance())) stage = omni.usd.get_context().get_stage() self.assertEqual(stage.GetAttributeAtPath("/World/Prim.val").Get(), 2.0) # Set the Branch to go to WriteTrue, which will take the value from PushCompound.outputs:value # which should be 1.0 + 2.0 controller.edit(self._test_graph_path, {keys.SET_VALUES: ("ConstantBool.inputs:value", True)}) await og.Controller.evaluate(graph) self.assertEqual(stage.GetAttributeAtPath("/World/Prim.val").Get(), 3.0) # ------------------------------------------------------------------------- async def test_compound_node_upgrade_to_schema_api(self): """ Tests that loading a file with a compound node generated prior to the introduction of compoundNodeAPI gets properly migrated. """ # The preschema file contains a graph with a simple compound node # [Constant]->| Compound Node |->[Absolute] # [Constant]->| | # # With a compound defined as # [Add]->[Absolute] # The constants are set to 1 and 2, so the result trivially evaluates to 3 (result, error) = await ogts.load_test_file(self._test_preschema_file, use_caller_subdirectory=True) self.assertTrue(result, error) stage = omni.usd.get_context().get_stage() graph_prim_path = "/World/PushGraph" compound_path = f"{graph_prim_path}/Compound" result_path = f"{graph_prim_path}/absolute_01.outputs:absolute" # validate the graph evaluates as expeected graph = og.Controller.graph(graph_prim_path) await og.Controller.evaluate(graph) self.assertTrue(graph.is_valid()) attr = og.Controller.attribute(result_path) self.assertTrue(attr.is_valid()) self.assertEqual(3, og.Controller.get(attr)) # validate the compound node USD is upgraded as expected compound_node_prim = stage.GetPrimAtPath(compound_path) self.assertTrue(compound_node_prim.IsValid()) # the old relationship has been removed, and replaced with the schemaAPI self.assertFalse(compound_node_prim.GetRelationship("omni:graph:compound").IsValid()) self.assertTrue(compound_node_prim.HasAPI(OmniGraphSchema.CompoundNodeAPI)) schema_api = OmniGraphSchema.CompoundNodeAPI(compound_node_prim) self.assertGreater(len(schema_api.GetCompoundGraphRel().GetTargets()), 0) self.assertEqual(schema_api.GetCompoundTypeAttr().Get(), "nodetype") # ------------------------------------------------------------------------- async def test_enter_compound(self): """ Test that querying a node in a compound subgraph will pass validation. This exercises a code-path that is used by kit-graphs when you double-click and enter a compound. The graph itself remains the top-level graph (as this is set in the graph model), but we are able to step in and look at nodes in a child graph """ self._create_test_compound("Compound") self._create_and_test_graph_from_add_compound(f"{self.get_compound_folder()}/Compound") # Verify that we do not get an error in ObjectLookup __verify_graph node = og.Controller.node( f"{self._test_graph_path}/Compound/Graph/Add_Node", og.get_graph_by_path(self._test_graph_path) ) self.assertTrue(node.is_valid()) # ------------------------------------------------------------------------- async def test_get_owning_compound_node_api(self): """ Tests the og.graph.get_owning_compound_node_api available on og.Graph. """ controller = og.Controller(update_usd=True) keys = controller.Keys # Simple graph with nested compounds (graph, (compound_1, compound_2), _, node_map) = controller.edit( self._test_graph_path, { keys.CREATE_NODES: [ ( "Compound1", { keys.CREATE_NODES: [ ("Add1", "omni.graph.nodes.Add"), ( "Compound3", { keys.CREATE_NODES: [ ("Add3", "omni.graph.nodes.Add"), ] }, ), ], }, ), ( "Compound2", { keys.CREATE_NODES: [ ("Add2", "omni.graph.nodes.Add"), ] }, ), ], }, ) self.assertTrue(graph.is_valid()) self.assertFalse(graph.get_owning_compound_node().is_valid()) compound_graph_1 = compound_1.get_compound_graph_instance() compound_graph_2 = compound_2.get_compound_graph_instance() self.assertTrue(compound_graph_1.is_valid()) self.assertTrue(compound_graph_2.is_valid()) compound_3 = node_map["Compound3"] self.assertTrue(compound_3.is_valid()) compound_graph_3 = compound_3.get_compound_graph_instance() self.assertTrue(compound_graph_3.is_valid()) self.assertEqual(compound_graph_1.get_owning_compound_node(), compound_1) self.assertEqual(compound_graph_2.get_owning_compound_node(), compound_2) self.assertEqual(compound_graph_3.get_owning_compound_node(), compound_3) self.assertEqual(compound_3.get_graph().get_owning_compound_node(), compound_1) self.assertFalse(compound_1.get_graph().get_owning_compound_node().is_valid()) add1 = node_map["Add1"] self.assertEquals(add1.get_graph().get_owning_compound_node(), compound_1) add2 = node_map["Add2"] self.assertEquals(add2.get_graph().get_owning_compound_node(), compound_2) add3 = node_map["Add3"] self.assertEquals(add3.get_graph().get_owning_compound_node(), compound_3)
112,982
Python
47.573947
124
0.566913
omniverse-code/kit/exts/omni.graph.test/omni/graph/test/tests/test_maneuver_nodes.py
"""Misc collection of tests for nodes in this extension""" from typing import List import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.timeline import omni.usd from pxr import Gf, Sdf, Usd, UsdGeom # Result of this does not match the matrix by generating attributes individually def _generate_random_transform_matrix(): translate = Gf.Vec3d((np.random.rand(3) * 300).tolist()) euler = Gf.Vec3d((np.random.rand(3) * 360).tolist()) scale = Gf.Vec3d((np.random.rand(3) * 5).tolist()) rotation = ( Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2]) * Gf.Rotation(Gf.Vec3d.YAxis(), euler[1]) * Gf.Rotation(Gf.Vec3d.XAxis(), euler[0]) ) return Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate) def _generate_random_prim_transform_attributes(prim, use_orient, want_rotation): translate = Gf.Vec3d((np.random.random_integers(-100, 100, 3)).tolist()) euler = Gf.Vec3d((np.random.random_integers(0, 720, 3)).tolist()) if want_rotation else Gf.Vec3d() scale = Gf.Vec3d((np.random.random_integers(1, 10, 3)).tolist()) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(translate) prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(scale) if use_orient: rotation = ( ( Gf.Rotation(Gf.Vec3d.XAxis(), euler[0]) * Gf.Rotation(Gf.Vec3d.YAxis(), euler[1]) * Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2]) ) if want_rotation else Gf.Rotation().SetIdentity() ) quat = rotation.GetQuat() prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set(quat) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:orient", "xformOp:scale"] ) else: prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(euler) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] ) return translate, euler, scale # TODO: fix the bug in OM-46746 related to non-uniform scale in parent def _generate_test_prims(stage, suffix: str, use_orient=True, want_rotation=True) -> List[Usd.Prim]: # No Hierarchy case source1 = stage.DefinePrim(f"/World/Cube{suffix}1", "Cube") _generate_random_prim_transform_attributes(source1, use_orient, want_rotation) # source1.GetAttribute("xformOp:scale").Set(Gf.Vec3d(1, 1, 1)) xform1 = stage.DefinePrim(f"/World/xform{suffix}1", "Cone") _generate_random_prim_transform_attributes(xform1, use_orient, want_rotation) xform1.GetAttribute("xformOp:scale").Set(Gf.Vec3d(1, 1, 1)) source2 = stage.DefinePrim(f"{xform1.GetPath()}/Cube{suffix}2", "Cube") _generate_random_prim_transform_attributes(source2, use_orient, want_rotation) xform2 = stage.DefinePrim(f"{xform1.GetPath()}/xform{suffix}2", "Xform") _generate_random_prim_transform_attributes(xform2, use_orient, want_rotation) xform2.GetAttribute("xformOp:scale").Set(Gf.Vec3d(1, 1, 1)) source3 = stage.DefinePrim(f"{xform2.GetPath()}/Cube{suffix}3", "Cube") _generate_random_prim_transform_attributes(source3, use_orient, want_rotation) # Negative Scale case source4 = stage.DefinePrim(f"/World/Cube{suffix}4", "Cube") _generate_random_prim_transform_attributes(source4, use_orient, want_rotation) source4.GetAttribute("xformOp:scale").Set(Gf.Vec3d(np.random.uniform(-2, 2, 3).tolist())) return [source1, source2, source3] def _add_inputs_prim(stage, node: og.Node, src_prim: Usd.Prim, attrib: str): """Connect the given prim to the given Node's input attrib""" omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{node.get_prim_path()}.inputs:{attrib}"), target=src_prim.GetPath(), ) def _remove_inputs_prim(stage, node: og.Node, target_prim: Usd.Prim, attrib: str): """Remove the given prim to the given Node's input attrib""" omni.kit.commands.execute( "RemoveRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{node.get_prim_path()}.inputs:{attrib}"), target=target_prim.GetPath(), ) # ====================================================================== class TestManeuverNodes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises nodes""" TEST_GRAPH_PATH = "/World/TestGraph" max_tries = 10 # max times to check if we have converged updates_per_try = 5 # number of frames to wait between checks async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) timeline = omni.timeline.get_timeline_interface() timeline.set_start_time(1.0) timeline.set_end_time(10.0) fps = 24.0 timeline.set_time_codes_per_second(fps) timeline.set_fast_mode(True) await omni.kit.app.get_app().next_update_async() np.random.seed(12345) # ------------------------------------------------------------------------ async def next_try_async(self): for _ in range(self.updates_per_try): await omni.kit.app.get_app().next_update_async() # ------------------------------------------------------------------------ async def test_move_to_target(self): """Test OgnMoveToTarget node""" keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() for use_orient_src, use_orient_target in [(True, True), (True, False)]: controller = og.Controller() sources = _generate_test_prims(stage, "Source", use_orient=use_orient_src) # We don't support interpolation rotation without orient want_rotation = use_orient_src targets = _generate_test_prims(stage, "Target", use_orient=use_orient_target, want_rotation=want_rotation) (graph, (_, move_to_target_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("MoveToTarget", "omni.graph.nodes.MoveToTarget"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "MoveToTarget.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("MoveToTarget.inputs:speed", 5), ], }, ) def check_progress(src: Usd.Prim, target: Usd.Prim) -> bool: xform_cache = UsdGeom.XformCache() final_transform = xform_cache.GetLocalToWorldTransform(src) target_transform = xform_cache.GetLocalToWorldTransform(target) ok = Gf.IsClose(target_transform.Transform(Gf.Vec3d()), final_transform.Transform(Gf.Vec3d()), 0.0001) if ok: rot = target_transform.ExtractRotation().Decompose( Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis() ) rot2 = final_transform.ExtractRotation().Decompose( Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis() ) ok = Gf.IsClose(rot, rot2, 0.0001) if ok: ok = ( Gf.IsClose( target_transform.Transform(Gf.Vec3d.XAxis()).GetLength(), final_transform.Transform(Gf.Vec3d.XAxis()).GetLength(), 0.0001, ) and Gf.IsClose( target_transform.Transform(Gf.Vec3d.YAxis()).GetLength(), final_transform.Transform(Gf.Vec3d.YAxis()).GetLength(), 0.0001, ) and Gf.IsClose( target_transform.Transform(Gf.Vec3d.ZAxis()).GetLength(), final_transform.Transform(Gf.Vec3d.ZAxis()).GetLength(), 0.0001, ) ) if ok: return True return False for src in sources: for target in targets: _add_inputs_prim(stage, move_to_target_node, src, "sourcePrim") _add_inputs_prim(stage, move_to_target_node, target, "targetPrim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() if check_progress(src, target): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, move_to_target_node, src, "sourcePrim") _remove_inputs_prim(stage, move_to_target_node, target, "targetPrim") omni.kit.commands.execute("DeletePrims", paths=[graph.get_path_to_graph()]) # ------------------------------------------------------------------------ async def test_move_to_transform(self): """Test OgnMoveToTransform node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_transform = _generate_random_transform_matrix() (_, (_, move_to_transform_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("MoveToTransform", "omni.graph.nodes.MoveToTransform"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "MoveToTransform.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("MoveToTransform.inputs:speed", 5), ("MoveToTransform.inputs:target", target_transform), ], }, ) for src in sources: _add_inputs_prim(stage, move_to_transform_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() src_xformable = UsdGeom.Xformable(src) # Move To Transform only moves to Local Transform final_transform = src_xformable.GetLocalTransformation() if Gf.IsClose(target_transform, final_transform, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, move_to_transform_node, src, "prim") # # ------------------------------------------------------------------------ async def test_scale_to_size(self): """Test OgnScaleToSize node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_scale = Gf.Vec3f(np.random.rand(3).tolist()) (_, (_, scale_to_size_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("ScaleToSize", "omni.graph.nodes.ScaleToSize"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "ScaleToSize.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("ScaleToSize.inputs:speed", 5), ("ScaleToSize.inputs:target", target_scale), ], }, ) for src in sources: _add_inputs_prim(stage, scale_to_size_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() final_scale = UsdGeom.XformCommonAPI(src).GetXformVectors(Usd.TimeCode.Default())[2] if Gf.IsClose(target_scale, final_scale, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, scale_to_size_node, src, "prim") # # ------------------------------------------------------------------------ async def test_translate_to_location(self): """Test OgnTranslateToLocation node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() await omni.kit.app.get_app().next_update_async() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_translation = Gf.Vec3d(np.random.rand(3).tolist()) (_, (_, translate_to_location_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("TranslateToLocation", "omni.graph.nodes.TranslateToLocation"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "TranslateToLocation.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("TranslateToLocation.inputs:speed", 5), ("TranslateToLocation.inputs:target", target_translation), ], }, ) for src in sources: _add_inputs_prim(stage, translate_to_location_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() final_translation = UsdGeom.XformCommonAPI(src).GetXformVectors(Usd.TimeCode.Default())[0] if Gf.IsClose(target_translation, final_translation, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, translate_to_location_node, src, "prim") # ------------------------------------------------------------------------ async def test_translate_to_target(self): """Test OgnTranslateToTarget node""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") targets = _generate_test_prims(stage, "Target") (_, (_, translate_to_target_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("TranslateToTarget", "omni.graph.nodes.TranslateToTarget"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "TranslateToTarget.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("TranslateToTarget.inputs:speed", 5), ], }, ) for src in sources: for target in targets: _add_inputs_prim(stage, translate_to_target_node, src, "sourcePrim") _add_inputs_prim(stage, translate_to_target_node, target, "targetPrim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() xform_cache = UsdGeom.XformCache() final_translation = Gf.Transform(xform_cache.GetLocalToWorldTransform(src)).GetTranslation() target_translation = Gf.Transform(xform_cache.GetLocalToWorldTransform(target)).GetTranslation() if Gf.IsClose(target_translation, final_translation, 0.00001): done = True break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, translate_to_target_node, src, "sourcePrim") _remove_inputs_prim(stage, translate_to_target_node, target, "targetPrim") # # ------------------------------------------------------------------------ async def test_rotate_to_orientation(self): """Test OgnRotateToOrientation node using orientation""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") target_rotation = Gf.Vec3f((np.random.rand(3) * 360).tolist()) (_, (_, rotate_to_orientation_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("RotateToOrientation", "omni.graph.nodes.RotateToOrientation"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "RotateToOrientation.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("RotateToOrientation.inputs:speed", 3), ("RotateToOrientation.inputs:target", target_rotation), ], }, ) for src in sources: _add_inputs_prim(stage, rotate_to_orientation_node, src, "prim") timeline.play() done = False for _ in range(self.max_tries): await self.next_try_async() final_rotation = UsdGeom.XformCommonAPI(src).GetXformVectors(Usd.TimeCode.Default())[1] for value in zip(target_rotation, final_rotation): target_angle = np.mod(value[0], 360) final_angle = np.mod(value[1], 360) if Gf.IsClose(target_angle, final_angle, 0.0001): done = True if done: break self.assertTrue(done, "source never reached target") _remove_inputs_prim(stage, rotate_to_orientation_node, src, "prim") # ------------------------------------------------------------------------ async def test_rotate_to_target(self): """Test OgnRotateToTarget node using orientation""" controller = og.Controller() keys = og.Controller.Keys timeline = omni.timeline.get_timeline_interface() usd_context = omni.usd.get_context() stage = usd_context.get_stage() sources = _generate_test_prims(stage, "Source") targets = _generate_test_prims(stage, "Target") (_, (_, rotate_to_target_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("RotateToTarget", "omni.graph.nodes.RotateToTarget"), ], keys.CONNECT: [ ("OnTick.outputs:tick", "RotateToTarget.inputs:execIn"), ], keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", True), ("RotateToTarget.inputs:speed", 3), ], }, ) for src in sources: for target in targets: _add_inputs_prim(stage, rotate_to_target_node, src, "sourcePrim") _add_inputs_prim(stage, rotate_to_target_node, target, "targetPrim") done = False timeline.play() for _ in range(self.max_tries): await self.next_try_async() xform_cache = UsdGeom.XformCache() target_translation = ( Gf.Transform(xform_cache.GetLocalToWorldTransform(target)).GetRotation().GetQuaternion() ) final_translation = ( Gf.Transform(xform_cache.GetLocalToWorldTransform(src)).GetRotation().GetQuaternion() ) if Gf.IsClose(target_translation.GetReal(), final_translation.GetReal(), 0.00001) and Gf.IsClose( target_translation.GetImaginary(), final_translation.GetImaginary(), 0.00001 ): done = True break _remove_inputs_prim(stage, rotate_to_target_node, src, "sourcePrim") _remove_inputs_prim(stage, rotate_to_target_node, target, "targetPrim") self.assertTrue(done, "source never reached target")
22,289
Python
42.450292
118
0.529858
omniverse-code/kit/exts/omni.graph.test/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.18.0] - 2022-11-15 ### Added - Additional test to exercise simple dynamic attribute values ## [0.17.0] - 2022-11-09 ### Added - Test node and script for verifying location of dynamic attribute memory ## [0.16.1] - 2022-10-18 ### Added - Test against crashing when new UsdContext is created. ## [0.16.0] - 2022-09-28 ### Added - Test for argument flattening utility ### Fixed - Obsolete branding - Obsolete test configurations ## [0.15.1] - 2022-09-27 ### Fixed - Lint errors that crept in ## [0.15.0] - 2022-09-06 ### Removed - Tests and dependencies related to UI and RTX ### Changed - Test node type that used the omni.graph.ui extension to one that does not ## [0.14.1] - 2022-08-31 ### Fixed - Refactored out use of a deprecated class ## [0.14.0] - 2022-08-30 ### Added - Test for reading nodes with all data types, and sample test files with such nodes ### Fixed - Linting errors ## [0.13.9] - 2022-08-17 ### Changed - Restored the fixed failing test to the test suite ## [0.13.8] - 2022-08-16 ### Removed - References to obsolete ABI methods ## [0.13.7] - 2022-08-09 ### Fixed - Applied formatting to all of the Python files ## [0.13.6] - 2022-08-03 ### Fixed - Compilation errors related to deprecation of methods in ogn bundle. ## [0.13.5] - 2022-07-27 ### Fixed - All of the lint errors reported on the Python files in this extension ## [0.13.4] - 2022-07-21 ### Changed - Undo revert ## [0.13.3] - 2022-07-18 ### Changed - Reverted the changes in 0.13.2 ## [0.13.2] - 2022-07-15 ### Changed - Removed LatentTest node, modified tests ## [0.13.1] - 2022-07-11 ### Fixed - OgnComputeErrorPy node was importing the _internal class directly, which some of our linux build systems do not like. ## [0.13.0] - 2022-07-08 ### Added - Test of attribute deprecation API. ## [0.12.0] - 2022-07-07 ### Changed - Refactored imports from omni.graph.tools to get the new locations ### Added - Test for public API consistency ## [0.11.0] - 2022-06-28 ### Added - Test to verify that CHANGELOG and extension.toml versions match ## [0.10.0] - 2022-06-17 ### Added - Tests for changing graph settings from USD ## [0.9.0] - 2022-06-13 ### Added - Tests for evaluation mode setting ### Changed - Evaluation mode added to settings tests ## [0.8.0] - 2022-06-13 ### Added - New test to verify that C++ and Python node duplication propagate attribute values ## [0.7.0] - 2022-06-08 ### Added - Added gpuinterop vertex deformation test ## [0.6.0] - 2022-06-07 ### Added - Test for CPU-GPU pointer access in the controller interface ## [0.5.1] - 2022-06-06 ### Fixed - Fixed extension dependencies and restored flaky test ## [0.5.0] - 2022-05-27 ### Added - Added a new test for accessing multiple schema-based graphs in a single scene ## [0.4.1] - 2022-05-26 ### Changed - Re-enabled test_graphs_in_sublayer_load, test_variable_commands and test_variables_create_remove_stress_test ## [0.4.0] - 2022-04-29 ### Removed - Removed obsolete tests and test files ### Changed - Made tests derive from OmniGraphTestCase and use the new og.Settings ## [0.3.0] - 2022-04-25 ### Changed - Stopped generating the pointless USD and docs for the test nodes ### Fixed - Fixed reference to extension.toml in the docs to point to the correct line and use an explicit language ## [0.2.4] - 2022-04-20 ### Added - Test for undoing prim deletions. ## [0.2.3] - 2022-04-11 ### Added - Test for connection callbacks ### Changed - Consolidated various callback tests into test_callbacks.py ## [0.2.2] - 2022-03-16 ### Changed - Previously disabled tests have been re-enabled with new _enabledLegacyPrimConnections_ setting. ## [0.2.1] - 2022-03-08 ### Changed - Modified registration test to match the new style used as of *omni.graph.core 2.23.3* ## [0.2.0] - 2022-03-01 ### Changed - Moved *expected_errors.py* to omni.graph so that it can be more generally accessible ## [0.1.0] - 2021-03-01 ### Changed - Renamed from omni.graph.tests to avoid conflict with automatic test detection
4,259
Markdown
24.2071
119
0.694764
omniverse-code/kit/exts/omni.graph.test/docs/README.md
# OmniGraph Integration Testing [omni.graph.test] This extension contains support for tests that span multiple OmniGraph extensions. ## Published Documentation The automatically-published user guide from this repo can be viewed :ref:`here<index.rst>`
254
Markdown
30.874996
90
0.807087
omniverse-code/kit/exts/omni.graph.test/docs/index.rst
.. _omni.graph.test: OmniGraph Integration Testing ############################# .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.test,**Documentation Generated**: |today| In order to effectively test the OmniGraph access to nodes and scripts that are not necessary for the graph to operate correctly. In order to minimize the unnecessary files, yet still have nodes and files explicitly for testing, all of that functionality has been broken out into this extension. Dependencies ============ As the purpose of this extension is to provide testing facilities for all of OmniGraph it will have load dependencies on all of the `omni.graph.*` extensions. If any new ones are added they should be added to the dependencies in the file ``config/extension.toml``. Data Files ========== Three types of data files are accessed in this extension: 1. Generic data files, created in other extensions for use by the user (e.g. compound node definitions) 2. Example files, created to illustrate how to use certain nodes but not intended for general use 3. Test files, used only for the purpose of loading to test certain features The ``data/`` subdirectories in this extension contains the latter of those three. The other files live in the lowest level extension in which they are legal (e.g. if they contain a node from `omni.graph.nodes` then they will live in that extension). As this extension has dependencies on all of the OmniGraph extensions it will have access to all of their data files as well. Node Files ========== Most nodes will come from other extensions. Some nodes are created explicitly for testing purposes. These will appear in this extension and should not be used for any other purpose. Import Example -------------- This simple example shows how the test files from the `omni.graph.examples.python` extension were imported and enabled in this extension. The first step was to move the required files into the directory tree: .. code-block:: text omni.graph.test/ ├── python/ └── tests/ ├──── test_omnigraph_simple.py └── data/ ├──── TestEventTrigger.usda └──── TestExecutionConnections.usda .. note:: The two .usda files contain only nodes from the `omni.graph.examples.python` extension and are solely used for test purposes. That is why they could be moved into the extension's test directory. Next the standard automatic test detection file was added to ``omni.graph.test/python/tests/__init__.py`` .. literalinclude:: ../python/tests/__init__.py :linenos: :language: python Finally, the `config/extension.toml` had additions made to inform it of the dependency on the new extension: .. literalinclude:: ../config/extension.toml :language: toml :linenos: :emphasize-lines: 34 .. toctree:: :maxdepth: 1 CHANGELOG
2,893
reStructuredText
35.175
117
0.720014
omniverse-code/kit/exts/omni.kit.renderer.core/omni/kit/renderer_test/__init__.py
from ._renderer_test import * # Cached interface instance pointer def get_renderer_test_interface() -> IRendererTest: if not hasattr(get_renderer_test_interface, "renderer_test"): get_renderer_test_interface.renderer_test = acquire_renderer_test_interface() return get_renderer_test_interface.renderer_test
325
Python
35.222218
85
0.756923
omniverse-code/kit/exts/omni.kit.widget.path_field/config/extension.toml
[package] title = "Kit Path Field Widget v2.0.4" version = "2.0.4" category = "Internal" description = "String field widget with tooltips for branching" authors = ["NVIDIA"] slackids = ["UQY4RMR3N"] repository = "" keywords = ["kit", "ui"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.widget.path_field" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ]
513
TOML
19.559999
63
0.666667
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/style.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui UI_STYLES = {} UI_STYLES["NvidiaLight"] = { "ScrollingFrame": {"background_color": 0xFF535354, "margin": 0, "padding": 0}, "Rectangle": {"background_color": 0xFF535354}, "InputField": {"background_color": 0xFF535354, "color": 0xFFD6D6D6, "padding": 0}, "BreadCrumb": {"background_color": 0x0, "padding": 0}, "BreadCrumb.Label": {"color": 0xFFD6D6D6}, "BreadCrumb:hovered": {"background_color": 0xFFCFCCBF}, "BreadCrumb.Label:hovered": {"color": 0xFF2A2825}, "BreadCrumb:selected": {"background_color": 0xFF535354}, "Tooltips.Menu": {"background_color": 0xFFE0E0E0, "border_color": 0xFFE0E0E0, "border_width": 0.5}, "Tooltips.Item": {"background_color": 0xFF535354, "padding": 4}, "Tooltips.Item:hovered": {"background_color": 0xFF6E6E6E}, "Tooltips.Item:checked": {"background_color": 0xFF6E6E6E}, "Tooltips.Item.Label": {"color": 0xFFD6D6D6, "alignment": ui.Alignment.LEFT}, "Tooltips.Spacer": {"background_color": 0x0, "color": 0x0, "alignment": ui.Alignment.LEFT, "padding": 0}, } UI_STYLES["NvidiaDark"] = { "ScrollingFrame": {"background_color": 0xFF23211F, "margin": 0, "padding": 0}, "InputField": {"background_color": 0x0, "color": 0xFF9E9E9E, "padding": 0, "margin": 0}, "BreadCrumb": {"background_color": 0x0, "padding": 0}, "BreadCrumb:hovered": {"background_color": 0xFF8A8777}, "BreadCrumb:selected": {"background_color": 0xFF8A8777}, "BreadCrumb.Label": {"color": 0xFF9E9E9E}, "BreadCrumb.Label:hovered": {"color": 0xFF2A2825}, "Tooltips.Menu": {"background_color": 0xDD23211F, "border_color": 0xAA8A8777, "border_width": 0.5}, "Tooltips.Item": {"background_color": 0x0, "padding": 4}, "Tooltips.Item:hovered": {"background_color": 0xFF8A8777}, "Tooltips.Item:checked": {"background_color": 0xFF8A8777}, "Tooltips.Item.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT}, "Tooltips.Item.Label:hovered": {"color": 0xFF2A2825}, "Tooltips.Item.Label:checked": {"color": 0xFF2A2825}, "Tooltips.Spacer": { "background_color": 0x0, "color": 0x0, "alignment": ui.Alignment.LEFT, "padding": 0, "margin": 0, }, }
2,646
Python
48.018518
109
0.675359
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import omni.kit.app import omni.ui as ui from typing import List from .style import UI_STYLES from carb.input import KeyboardInput as Key from functools import partial class DelayedFocus: """A helper to run focus_keyboard the next frame""" def __init__(self, field: ui.StringField): self.__task = None self.__field = field def destroy(self): if self.__task and not self.__task.done(): self.__task.cancel() self.__task = None self.__field = None def focus_keyboard(self): """Execute frame.focus_keyboard in the next frame""" # Update in the next frame. if self.__task is None or self.__task.done(): self.__task = asyncio.ensure_future(self.__delayed_do()) async def __delayed_do(self): # Wait one frame await omni.kit.app.get_app().next_update_async() self.__field.focus_keyboard() class PathFieldModel(ui.AbstractValueModel): def __init__(self, parent: ui.Widget, theme: str, **kwargs): super().__init__() self._parent = parent self._window = None self._field = None self._tooltips_frame = None self._tooltips = None self._tooltip_items = [] self._num_tooltips = 0 self._path = None # Always ends with separator character! self._branches = [] self._focus = None self._style = UI_STYLES[theme] self._apply_path_handler = kwargs.get("apply_path_handler", None) self._apply_path_on_branch_changed = False self._current_path_provider = kwargs.get("current_path_provider", None) self._branching_options_provider = kwargs.get("branching_options_provider", None) # OBSOLETE self._branching_options_handler = kwargs.get("branching_options_handler", None) self._tooltips_max_visible = kwargs.get("tooltips_max_visible", 10) self._separator = kwargs.get("separator", "/") self._is_paste = False def set_value(self, value: str): print("Warning: Method 'set_value' is provided for compatibility only and should not be used.") def get_value_as_string(self) -> str: # Return empty string to parent widget return "" def set_path(self, path: str): self._path = path def set_branches(self, branches: [str]): if branches: self._branches = branches else: self._branches = [] def begin_edit(self): if not (self._window and self._window.visible): self._build_ui() # Reset path in case we inadvertently deleted it if self._current_path_provider: input_str = self._current_path_provider() else: input_str = "" self._field.model.set_value(input_str) def _build_ui(self): # Create and show the window with field and list of tips window_args = { "flags": ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND | ui.WINDOW_FLAGS_NO_MOVE, "auto_resize": True, "padding_x": 0, "padding_y": 0, "spacing": 0, } self._window = ui.Window("0", **window_args) with self._window.frame: width = self._parent.computed_content_width with ui.VStack(height=0, style=self._style): with ui.ZStack(): ui.Rectangle() # Use scrolling frame to confine width in case of long inputs with ui.ScrollingFrame( width=width, height=20, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"background_color": 0x0}, ): with ui.HStack(spacing=0): ui.Spacer(width=3) input = ui.SimpleStringModel() input.add_value_changed_fn(lambda m: self._update_tooltips()) with ui.Placer(stable_size=True, offset_x=6, offset_y=3): self._field = ui.StringField(input, style_type_name_override="InputField") # TODO: It's a workaround. We need to find out # why we need delayed focus here and why # self._field.focus_keyboard doesn't work. self._focus = DelayedFocus(self._field) self._focus.focus_keyboard() # Reserve for tooltips self._tooltips_frame = ui.Frame() # Process pre-defined set of key presses self._window.set_key_pressed_fn(self._on_key_pressed) self._place_window() def _on_key_pressed(self, key: int, key_mod: int, key_down: bool): """ Process keys on release. """ key = Key(key) # Convert to enumerated type if key_down: if key == Key.V and key_mod == 2: # We need it to avoid the connection to the server if the # string is pasted self._is_paste = True return if self._is_paste: self._is_paste = False do_apply_path = False if key == Key.ESCAPE: do_apply_path = True self._hide_window() elif key in [Key.TAB, Key.RIGHT, Key.ENTER]: if self._tooltips and self._tooltip_items: index = self._tooltips.model.get_value_as_int() self._extend_path_by_selected_branch(index) if key == Key.ENTER: do_apply_path = True self._hide_window() elif self._apply_path_on_branch_changed: do_apply_path = True elif key == Key.LEFT: self._shrink_path_by_tail_branch() if self._apply_path_on_branch_changed: do_appy_path = True elif key == Key.DOWN: if self._tooltips and self._num_tooltips > 0: value = self._tooltips.model.get_value_as_int() self._tooltips.model.set_value((value + 1) % self._num_tooltips) elif key == Key.UP: if self._tooltips and self._num_tooltips > 0: value = self._tooltips.model.get_value_as_int() self._tooltips.model.set_value(value - 1 if value >= 1 else self._num_tooltips - 1) else: # Skip all other keys pass if do_apply_path and self._apply_path_handler: try: self._apply_path_handler(self._field.model.get_value_as_string()) except Exception: pass def _update_tooltips(self): """Generates list of tips""" if not self._field: return cur_path = self._path or "" input_str = self._field.model.get_value_as_string() # TODO: This is a hack to avoid the connection to the server if the # string is pasted. When we paste full path, we don't want to wait for # the server connection. if self._is_paste: self.set_path(input_str) return splits = input_str.rsplit(self._separator, 1) match_str = splits[1] if len(splits) > 1 else splits[0] # Alternatively: match_str = input_str.replace(cur_path, "").lower().rstrip(self._separator) if not input_str.startswith(cur_path) or self._separator in input_str[len(cur_path) :]: # Off the current path, need to update both path and branches before continuing. if self._branching_options_handler: new_path = splits[0] new_path += self._separator if new_path else "" self.set_path(new_path) return self._branching_options_handler(new_path, partial(self._update_tooltips_menu, match_str, True)) else: self._update_tooltips_menu(match_str, False, None) def _update_tooltips_menu(self, match_str: str, update_branches: bool, branches: List[str]): if update_branches: self.set_branches(branches) self._num_tooltips = 0 self._tooltip_items.clear() with self._tooltips_frame: with ui.HStack(): with ui.HStack(mouse_pressed_fn=lambda x, y, b, _: self._hide_window()): ui.Spacer(width=6) ui.Label(self._path or "", width=0, style_type_name_override="Tooltips.Spacer") with ui.ZStack(): ui.Rectangle(style_type_name_override="Tooltips.Menu") with ui.VStack(): self._tooltips = ui.RadioCollection() self._tooltip_items.clear() # Pre-pend an empty branch to pick none for branch in [" "] + self._branches: if self._num_tooltips >= self._tooltips_max_visible: break if not match_str or (branch and branch.lower().startswith(match_str.lower())): item = ui.RadioButton( text=branch, height=20, radio_collection=self._tooltips, style_type_name_override="Tooltips.Item", ) item.set_clicked_fn(partial(self._extend_path_by_selected_branch, self._num_tooltips)) self._tooltip_items.append(item) self._num_tooltips += 1 self._tooltips.model.set_value(0) with ui.HStack(mouse_pressed_fn=lambda x, y, b, _: self._hide_window()): ui.Spacer(style_type_name_override="Tooltips.Spacer") self._place_window() def _extend_path_by_selected_branch(self, index: int): index = min(index, len(self._tooltip_items) - 1) if not self._tooltip_items[index].visible: return branch = self._tooltip_items[index].text.strip() if branch: # Skip empty strings, incl. one we introduced. Don't allow ending with 2 copies of separator. new_path = self._path + (branch + self._separator if not branch.endswith(self._separator) else branch) else: new_path = self._path if self._field: self._field.model.set_value(new_path) def _shrink_path_by_tail_branch(self): input_str = self._field.model.get_value_as_string() splits = input_str.rstrip(self._separator).rsplit(self._separator, 1) if len(splits) > 1 and splits[1]: new_path = splits[0] + self._separator else: new_path = "" if self._field: self._field.model.set_value(new_path) def _place_window(self): if self._parent: self._window.position_x = self._parent.screen_position_x - 1 self._window.position_y = self._parent.screen_position_y + 1 def _hide_window(self): if self._window: self._window.visible = False def destroy(self): self._field = None self._tootip_items = None self._tooltips = None self._tooltips_frame = None self._parent = None self._window = None if self._focus: self._focus.destroy() self._focus = None
12,213
Python
38.785016
118
0.547122
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/widget.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 platform import sys, os import omni.ui as ui from .model import PathFieldModel from .style import UI_STYLES class PathField: """ Main class for the PathField widget. This widget is a UI alternative to omni.ui.StringField for navigating tree views with the keyboard. As the user navigates the tree using TAB, Backspace, and Arrow keys, they are constantly provided branching options via auto-filtered tooltips. Args: None Keyword Args: apply_path_handler (Callable): This function is called when the user hits Enter on the input field, signaling that they want to apply the path. This handler is expected to update the caller's app accordingly. Function signature: void apply_path_handler(path: str) branching_options_handler (Callable): This function is required to provide a list of possible branches whenever prompted with a path. For example, if path = "C:", then the list of values produced might be ["Program Files", "temp", ..., "Users"]. Function signature: list(str) branching_options_provider(path: str, callback: func) separator (str): Character used to split a path into list of branches. Default '/'. """ def __init__(self, **kwargs): import carb.settings self._scrolling_frame = None self._input_frame = None self._path = None self._path_model = None self._breadcrumbs = [] self._theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" self._style = UI_STYLES[self._theme] self._apply_path_handler = kwargs.get("apply_path_handler", None) self._branching_options_handler = kwargs.get("branching_options_handler", None) self._branching_options_provider = kwargs.get("branching_options_provider", None) # OBSOLETE self._separator = kwargs.get("separator", "/") self._prefix_separator = kwargs.get("prefix_separator", None) self._build_ui() @property def path(self) -> str: """str: Returns the current path as entered in the field box.""" return self._path def _parse_path(self, full_path: str): if not full_path: return None, None prefix, path = "", full_path if self._prefix_separator: splits = full_path.split(self._prefix_separator, 1) if len(splits) == 2: prefix = f"{splits[0]}{self._prefix_separator}" path = splits[1] return prefix, path def set_path(self, full_path: str): """ Sets the path. Args: path (str): The full path name. """ if not full_path: return prefix, path = self._parse_path(full_path) # Make sure path string is properly formatted - it should end with # exactly 1 copy of the separator character. if path: path = f"{path.rstrip(self._separator)}{self._separator}" self._path = f"{prefix}{path}" self._update_breadcrumbs(self._path) def _build_ui(self): # Use a scrolling frame to prevent long paths from exploding width inut box self._scrolling_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style=self._style, style_type_name_override="ScrollingFrame", ) with self._scrolling_frame: self._build_input_field() def _build_input_field(self): self._path_model = PathFieldModel( self._scrolling_frame, self._theme, show_max_suggestions=10, apply_path_handler=self._apply_path_handler, branching_options_handler=self._branching_options_handler, current_path_provider=lambda: self._path or "", ) with ui.ZStack(style=self._style): ui.Rectangle() with ui.HStack(height=20): ui.Spacer(width=3) self._input_frame = ui.Frame() field = ui.StringField(self._path_model, style_type_name_override="InputField", identifier="filepicker_directory_path") self._update_breadcrumbs(self._path) def _update_breadcrumbs(self, path: str): def on_breadcrumb_clicked(button: ui.RadioButton): if button and self._apply_path_handler: self._apply_path_handler(button.name) def create_breadcrumb(label: str, path: str): breadcrumb = ui.Button(text="", style_type_name_override="BreadCrumb") # HACK Alert: We're hijacking the name attr to store the fullpath. # Alternatively subclass from ui.Button and add a fullpath attr. breadcrumb.text = label breadcrumb.name = path breadcrumb.set_clicked_fn(lambda b=breadcrumb: on_breadcrumb_clicked(b)), separator = ui.Label(self._separator, style_type_name_override="BreadCrumb.Label") return (breadcrumb, separator) self._breadcrumbs.clear() prefix, path = self._parse_path(path) accum_path = "" with self._input_frame: with ui.HStack(width=0, spacing=0, style=self._style): ui.Spacer(width=5) if prefix: accum_path += prefix self._breadcrumbs.append(create_breadcrumb(accum_path, accum_path)) _, separator = self._breadcrumbs[-1] separator.visible = False if path: for token in path.rstrip(self._separator).split(self._separator): accum_path += token self._breadcrumbs.append(create_breadcrumb(token, accum_path)) accum_path += self._separator # For extremely long paths, scroll to the last breadcrumb if self._breadcrumbs: breadcrumb, _ = self._breadcrumbs[-1] breadcrumb.scroll_here_x(0) def destroy(self): """Destructor.""" self._path_model = None self._breadcrumbs = None self._input_frame = None self._scrolling_frame = None
6,771
Python
40.292683
135
0.616453
omniverse-code/kit/exts/omni.kit.widget.path_field/omni/kit/widget/path_field/tests/test_breadcrumbs.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from unittest.mock import Mock, patch from ..widget import PathField class TestBreadCrumbs(omni.kit.test.AsyncTestCase): """Testing PathField.set_path""" async def setUp(self): self.test_paths = { "omniverse://ov-test/NVIDIA/Samples": ["omniverse://", "ov-test", "NVIDIA", "Samples"], "my-computer://C:/Users/jack": ["my-computer://", "C:", "Users", "jack"], "my-computer:///home/jack": ["my-computer://", "", "home", "jack"], "C:/Users/jack": ["C:", "Users", "jack"], "/": [""], "/home/jack": ["", "home", "jack"], } async def tearDown(self): pass async def test_breadcrumbs_succeeds(self): """Testing PathField.set_path correctly initializes breacrumbs""" mock_path_handler = Mock() under_test = PathField(separator="/", prefix_separator="://", apply_path_handler=mock_path_handler) for path, expected in self.test_paths.items(): under_test.set_path(path) expected_path = "" for breadcrumb, _ in under_test._breadcrumbs: expected_step = expected.pop(0) expected_path += expected_step # Confirm when breadcrumb clicked, it triggers callback with expected path breadcrumb.call_clicked_fn() mock_path_handler.assert_called_with(expected_path) expected_path += "/" if not expected_step.endswith("://") else ""
1,952
Python
42.399999
107
0.620389
omniverse-code/kit/exts/omni.kit.widget.path_field/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [2.0.4] - 2022-11-09 ### Changes - Fix to toml file ## [2.0.3] - 2021-06-16 ### Changes - Fixes double "//" at the end of the path string. ## [2.0.2] - 2021-04-23 ### Changes - Fix to breadcrumbs on Linux returning incorrect paths resulting in Connection Errors. ## [2.0.1] - 2021-02-10 ### Changes - Updated StyleUI handling ## [2.0.0] - 2020-01-03 ### Updated - Refactored for async directory listing to improve overall stability in case of network delays. ### Added - Keyword Arg: 'branching_options_handler' ### Deleted - Keyword Arg: 'branching_options_provider' ## [0.1.6] - 2020-11-20 ### Added - Don't Execute "apply path" on directory changes, only when user hits Esc or Enter key. ## [0.1.5] - 2020-11-20 ### Added - Fixes occasionally jumbled-up breadcrumbs. ## [0.1.4] - 2020-09-18 ### Added - Initial commit to master.
938
Markdown
22.474999
96
0.673774
omniverse-code/kit/exts/omni.kit.widget.path_field/docs/index.rst
omni.kit.widget.path_field ########################## A UI alternative to omni.ui.StringField for smarter path traversal (think filesystem paths). .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.widget.path_field :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: .. autoclass:: PathField :members:
386
reStructuredText
18.349999
92
0.632124
omniverse-code/kit/exts/omni.kit.window.stageviewer/config/extension.toml
[package] version = "1.0.5" category = "Internal" feature = true title = "Stage Viewer" description="Adds context menu in the Content Browser that allows to inspect stages." changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.widget.stage" = {} [[python.module]] name = "omni.kit.window.stageviewer" # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.window.stageviewer.tests" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", "omni.kit.window.content_browser", ] stdoutFailPatterns.exclude = [ "*Failed to acquire interface*while unloading all plugins*" ]
790
TOML
21.599999
85
0.703797
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/stageviewer_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.ext from .content_menu import content_available from .content_menu import ContentMenu class StageViewerExtension(omni.ext.IExt): def on_startup(self, ext_id): # Setup a callback when any extension is loaded/unloaded 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.window.stageviewer" ) self.__context_menu = None self._on_event(None) def _on_event(self, event): """Called when any extension is loaded/unloaded""" if self.__context_menu: if not content_available(): self.__context_menu.destroy() self.__context_menu = None else: if content_available(): self.__context_menu = ContentMenu() def on_shutdown(self): self.__extensions_subscription = None if self.__context_menu: self.__context_menu.destroy() self.__context_menu = None
1,562
Python
34.522726
106
0.663252
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/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 .stageviewer import ViewerWindows from .stageviewer_utils import is_extension_loaded from omni.kit.ui import get_custom_glyph_code def content_available(): """ Returns True if the extension "omni.kit.window.content_browser" is loaded. """ return is_extension_loaded("omni.kit.window.content_browser") class ContentMenu: """ When this object is alive, Content Browser has the additional context menu with the items that allow to view usd files. """ def __init__(self): self._content_window = None self.__view_menu_subscription = None if content_available(): import omni.kit.window.content_browser as content self._content_window = content.get_content_window() if self._content_window: self.__view_menu_subscription = self._content_window.add_context_menu( "Inspect", "show.svg", self._on_show_triggered, self._is_show_visible ) def _is_show_visible(self, content_url): '''True if we can show the menu item "View Image"''' for ext in ["usd", "usda"]: if content_url.endswith(f".{ext}"): return True return False def _on_show_triggered(self, menu, value): """Start watching for the layer and run the editor""" ViewerWindows().open_window(value) def destroy(self): """Stop all watchers and remove the menu from the content browser""" if self.__view_menu_subscription: self._content_window.delete_context_menu(self.__view_menu_subscription) self.__view_menu_subscription = None self._content_window = None ViewerWindows().close_all()
2,165
Python
36.344827
89
0.661894
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/stageviewer.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from omni.kit.widget.stage import StageWidget from pxr import Usd from .singleton import Singleton @Singleton class ViewerWindows: """This object keeps all the Stage Viewer windows""" def __init__(self): self.__windows = {} def open_window(self, filepath): """Open StageViewer window with the stage file opened in it""" if filepath in self.__windows: self.__windows[filepath].visible = True else: stage = Usd.Stage.Open(filepath, Usd.Stage.LoadNone) if not stage: return window = StageViewer(stage) # When window is closed, remove it from the list window.set_visibility_changed_fn(lambda _, f=filepath: self.close(f)) self.__windows[filepath] = window def close(self, filepath): """Close and remove specific window""" self.__windows[filepath].destroy() self.__windows[filepath] = None del self.__windows[filepath] def close_all(self): """Close and remove all windows""" self.__windows = {} class StageViewer(ui.Window): """The Stage window that displays a custom stage""" def __init__(self, stage: Usd.Stage, **kwargs): if stage: name = stage.GetRootLayer().identifier else: name = "None" kwargs["flags"] = ui.WINDOW_FLAGS_NO_SCROLLBAR kwargs["width"] = 600 kwargs["height"] = 800 super().__init__(f"Stage {name}", **kwargs) with self.frame: # We only show the Type column self.__stage_widget = StageWidget(stage, columns_accepted=["Type"], lazy_payloads=True) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ self.__stage_widget.destroy() self.__stage_widget = None super().destroy()
2,426
Python
32.708333
99
0.631492
omniverse-code/kit/exts/omni.kit.window.stageviewer/omni/kit/window/stageviewer/tests/stageviewer_test.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from ..stageviewer import StageViewer from ..content_menu import ContentMenu from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import Usd from pxr import UsdGeom import omni.kit.app import omni.kit.commands import omni.ui as ui import omni.usd CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data") class TestStageviewer(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): # New stage with a sphere stage = Usd.Stage.CreateInMemory("test.usda") UsdGeom.Sphere.Define(stage, "/Sphere") window = await self.create_test_window() stageviewer = StageViewer(stage) stageviewer.flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE stageviewer.position_x = 0 stageviewer.position_y = 0 stageviewer.width = 256 stageviewer.height = 256 for _ in range(2): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir) stageviewer.destroy() async def test_context_menu(self): """This is to test that the content menu is shown when it is a usd file""" context_menu = ContentMenu() for _ in range(2): await omni.kit.app.get_app().next_update_async() file_name = f"{self._golden_img_dir}/empty.usd".replace("\\", "/") result = context_menu._is_show_visible(file_name) self.assertTrue(result, True) context_menu.destroy()
2,295
Python
34.323076
115
0.67756
omniverse-code/kit/exts/omni.kit.window.stageviewer/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.5] - 2022-11-18 ### Fixed - Fix test on Linux ## [1.0.4] - 2022-07-05 ### Changed - Added more test to increase the test coverage ## [1.0.3] - 2022-04-06 ### Fixed - Message "Failed to acquire interface while unloading all plugins" ## [1.0.2] - 2021-06-16 ### Changed - Load payloads when the user expands the tree ## [1.0.1] - 2020-11-12 ### Changed - Fixed exception in Create ## [1.0.0] - 2020-09-16 ### Added - Adds context menu in the Content Browser
564
Markdown
19.178571
80
0.656028
omniverse-code/kit/exts/omni.kit.multinode/config/extension.toml
[package] title = "Kit Multi-Node Setup" version = "0.1.0" authors = ["NVIDIA"] [dependencies] "omni.kit.renderer.core" = {} [[native.plugin]] path = "bin/omni.kit.multinode.plugin" [[test]] waiver = "Extension is tested externally"
235
TOML
17.153845
41
0.685106
omniverse-code/kit/exts/omni.kit.widget.settings/config/extension.toml
[package] title = "Settings Widget" description = "Settings Widget" version = "1.0.1" category = "Internal" authors = ["NVIDIA"] repository = "" keywords = ["settings", "ui"] changelog = "docs/CHANGELOG.md" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.commands" = {} [[python.module]] name = "omni.kit.widget.settings" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture", ]
623
TOML
18.499999
93
0.666132
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/settings_widget.py
from enum import Enum from typing import Tuple, Union import carb import carb.settings import omni.ui as ui from .settings_model import ( SettingModel, SettingsComboItemModel, VectorFloatSettingsModel, VectorIntSettingsModel, AssetPathSettingsModel, RadioButtonSettingModel, ) from .settings_widget_builder import SettingsWidgetBuilder from omni.kit.widget.searchable_combobox import build_searchable_combo_widget import omni.kit.app class SettingType(Enum): """ Supported setting types """ FLOAT = 0 INT = 1 COLOR3 = 2 BOOL = 3 STRING = 4 DOUBLE3 = 5 INT2 = 6 DOUBLE2 = 7 ASSET = 8 class SettingWidgetType(Enum): """ Supported setting UI widget types """ FLOAT = 0 INT = 1 COLOR3 = 2 BOOL = 3 STRING = 4 DOUBLE3 = 5 INT2 = 6 DOUBLE2 = 7 ASSET = 8 COMBOBOX = 9 RADIOBUTTON = 10 # This is for backward compatibility - Using deprecated SettingType - omni.kit.widget.settings.deprecated.SettingType INT_WIDGET_TPYE_MAP = { 0: SettingWidgetType.FLOAT, 1: SettingWidgetType.INT, 2: SettingWidgetType.COLOR3, 3: SettingWidgetType.BOOL, 4: SettingWidgetType.STRING, 5: SettingWidgetType.DOUBLE3, 6: SettingWidgetType.INT2, 7: SettingWidgetType.DOUBLE2, 8: SettingWidgetType.ASSET, 9: SettingWidgetType.COMBOBOX, 10: SettingWidgetType.RADIOBUTTON, } # TODO: Section will be moved to some location like omni.ui.settings # ############################################################################################# def create_setting_widget( setting_path: str, setting_type: SettingType, range_from=0, range_to=0, speed=1, **kwargs ) -> Tuple[ui.Widget, ui.AbstractValueModel]: """ Create a UI widget connected with a setting. If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`. Args: setting_path: Path to the setting to show and edit. setting_type: Type of the setting to expect. range_from: Limit setting value lower bound. range_to: Limit setting value upper bound. speed: Range speed Returns: :class:`ui.Widget` and :class:`ui.AbstractValueModel` connected with the setting on the path specified. """ widget = None model = None if isinstance(setting_type, int): setting_type = INT_WIDGET_TPYE_MAP.get(setting_type) # The string "ASSET" is for backward compatibility if not isinstance(setting_type, Enum) and setting_type != "ASSET": carb.log_warn(f"Unsupported setting widget type {setting_type} for {setting_path}") return None, None # Create widget to be used for particular type. if setting_type == SettingWidgetType.COMBOBOX: setting_is_index = kwargs.pop("setting_is_index", True) widget, model = SettingsWidgetBuilder.createComboboxWidget(setting_path, setting_is_index=setting_is_index, additional_widget_kwargs=kwargs) elif setting_type == SettingWidgetType.RADIOBUTTON: model = RadioButtonSettingModel(setting_path) widget = SettingsWidgetBuilder.createRadiobuttonWidget(model, setting_path, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.INT, SettingWidgetType.INT]: model = SettingModel(setting_path, draggable=True) if model.get_value_as_int() is not None: widget = SettingsWidgetBuilder.createIntWidget(model, range_from, range_to, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.FLOAT, SettingWidgetType.FLOAT]: model = SettingModel(setting_path, draggable=True) if model.get_value_as_float() is not None: widget = SettingsWidgetBuilder.createFloatWidget(model, range_from, range_to, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.BOOL, SettingWidgetType.BOOL]: model = SettingModel(setting_path) if model.get_value_as_bool() is not None: widget = SettingsWidgetBuilder.createBoolWidget(model, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.STRING, SettingWidgetType.STRING]: model = SettingModel(setting_path) if model.get_value_as_string() is not None: widget = ui.StringField(**kwargs) elif setting_type in [SettingType.COLOR3, SettingWidgetType.COLOR3]: model = VectorFloatSettingsModel(setting_path, 3) widget = SettingsWidgetBuilder.createColorWidget(model, comp_count=3, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.DOUBLE2, SettingWidgetType.DOUBLE2]: model = VectorFloatSettingsModel(setting_path, 2) widget = SettingsWidgetBuilder.createDoubleArrayWidget(model, range_from, range_to, comp_count=2, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.DOUBLE3, SettingWidgetType.DOUBLE3]: model = VectorFloatSettingsModel(setting_path, 3) widget = SettingsWidgetBuilder.createDoubleArrayWidget(model, range_from, range_to, comp_count=3, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.INT2, SettingWidgetType.INT2]: model = VectorIntSettingsModel(setting_path, 2) widget = SettingsWidgetBuilder.createIntArrayWidget(model, range_from, range_to, comp_count=2, additional_widget_kwargs=kwargs) elif setting_type in [SettingType.ASSET, SettingWidgetType.ASSET, "ASSET"]: # The string "ASSET" is for backward compatibility model = AssetPathSettingsModel(setting_path) widget = SettingsWidgetBuilder.createAssetWidget(model, additional_widget_kwargs=kwargs) else: # pragma: no cover # Convenient way to extend new types of widget creation. build_widget_func = getattr(SettingsWidgetBuilder, f"create{setting_type.name.capitalize()}Widget", None) if build_widget_func: widget, model = build_widget_func(setting_path, additional_widget_kwargs=kwargs) else: carb.log_warn(f"Couldn't find widget for {setting_type} - {setting_path}") # Do we have any right now? return None, None if widget: try: widget.model = model except Exception: # pragma: no cover print(widget, "doesn't have model") if isinstance(widget, ui.Widget) and not widget.identifier: widget.identifier = setting_path return widget, model def create_setting_widget_combo( setting_path: str, items: Union[list, dict], setting_is_index: bool = True) -> Tuple[SettingsComboItemModel, ui.ComboBox]: """ Creating a Combo Setting widget. This function creates a combo box that shows a provided list of names and it is connected with setting by path specified. Underlying setting values are used from values of `items` dict. Args: setting_path: Path to the setting to show and edit. items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values. setting_is_index: True - setting_path value is index into items list (default) False - setting_path value is string in items list """ return SettingsWidgetBuilder.createComboboxWidget(setting_path, items=items, setting_is_index=setting_is_index) class SettingsSearchableCombo: def __init__(self, setting_path: str, key_value_pairs: dict, default_key: str): self._path = setting_path self._items = key_value_pairs key_index = -1 key_list = sorted(list(self._items.keys())) self._set_by_ui = False def on_combo_click(model): item_key = model.get_value_as_string() item_value = self._items[item_key] self._set_by_ui = True carb.settings.get_settings().set_string(self._path, item_value) self._component_combo = build_searchable_combo_widget(key_list, key_index, on_combo_click, widget_height=18, default_value=default_key) self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_setting_change) def destroy(self): self._component_combo.destroy() self._component_combo = None self._update_setting = None def get_key_from_value(self, value): idx = list(self._items.values()).index(value) key = list(self._items.keys())[idx] return key def get_current_key(self): current_value = carb.settings.get_settings().get_as_string(self._path) return self.get_key_from_value(current_value) def _on_setting_change(owner, item: carb.dictionary.Item, event_type): if owner._set_by_ui: owner._set_by_ui = False else: key = owner.get_current_key() owner._component_combo.set_text(new_text=key) #print(item)
9,063
Python
40.962963
148
0.681231
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/style.py
import carb.settings import omni.ui as ui def get_ui_style_name(): return carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" def get_style(): KIT_GREEN = 0xFF8A8777 BORDER_RADIUS = 1.5 FONT_SIZE = 14.0 ui_style = get_ui_style_name() if ui_style == "NvidiaLight": # pragma: no cover WINDOW_BACKGROUND_COLOR = 0xFF444444 BUTTON_BACKGROUND_COLOR = 0xFF545454 BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778 BUTTON_LABEL_DISABLED_COLOR = 0xFF606060 BUTTON_LABEL_COLOR = 0x7FD6D6D6 FRAME_TEXT_COLOR = 0xFF545454 FIELD_BACKGROUND = 0xFF545454 FIELD_SECONDARY = 0xFFABABAB FIELD_TEXT_COLOR = 0xFFD6D6D6 FIELD_TEXT_COLOR_READ_ONLY = 0xFF9C9C9C FIELD_TEXT_COLOR_HIDDEN = 0x01000000 COLLAPSABLEFRAME_BORDER_COLOR = 0x0 COLLAPSABLEFRAME_BACKGROUND_COLOR = 0x7FD6D6D6 COLLAPSABLEFRAME_TEXT_COLOR = 0xFF545454 COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFFC9C9C9 COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFFD6D6D6 COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFFCCCFBF COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR = 0xFFD6D6D6 COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR = 0xFFE6E6E6 LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD LABEL_MIXED_COLOR = 0xFFD6D6D6 LIGHT_FONT_SIZE = 14.0 LIGHT_BORDER_RADIUS = 3 style = { "Window": {"background_color": 0xFFE0E0E0}, "Button": {"background_color": 0xFFE0E0E0, "margin": 0, "padding": 3, "border_radius": 2}, "Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR}, "Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR}, "Button.Label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR}, "Button.Label": {"color": BUTTON_LABEL_COLOR}, "RadioButton": { "margin": 2, "border_radius": 2, "font_size": 16, "background_color": BUTTON_BACKGROUND_COLOR, "color": 0xFFFF0000, }, "RadioButton.Label": {"font_size": 16, "color": 0xFFC8C8C8}, "RadioButton:checked": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR, "color": 0xFF00FF00}, "RadioButton:pressed": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR, "color": 0xFF00FF00}, "RadioButton.Label:checked": {"color": 0xFFE8E8E8}, "Triangle::title": {"background_color": BUTTON_BACKGROUND_COLOR}, "ComboBox": { "font_size": LIGHT_FONT_SIZE, "color": 0xFFE6E6E6, "background_color": 0xFF545454, "secondary_color": 0xFF545454, "selected_color": 0xFFACACAF, "border_radius": LIGHT_BORDER_RADIUS * 2, }, "ComboBox:hovered": {"background_color": 0xFF545454}, "ComboBox:selected": {"background_color": 0xFF545454}, "Field::models": { "background_color": FIELD_BACKGROUND, "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS, "secondary_color": FIELD_SECONDARY, }, "Field::models_readonly": { "background_color": FIELD_BACKGROUND, "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR_READ_ONLY, "border_radius": LIGHT_BORDER_RADIUS, "secondary_color": FIELD_SECONDARY, }, "Field::models:pressed": {"background_color": 0xFFCECECE}, "Field": {"background_color": 0xFF535354, "color": 0xFFCCCCCC}, "Label": {"font_size": 12, "color": FRAME_TEXT_COLOR}, "Label::RenderLabel": {"font_size": LIGHT_FONT_SIZE, "color": FRAME_TEXT_COLOR}, "Label::label": { "font_size": LIGHT_FONT_SIZE, "background_color": FIELD_BACKGROUND, "color": FRAME_TEXT_COLOR, }, "Label::title": { "font_size": LIGHT_FONT_SIZE, "background_color": FIELD_BACKGROUND, "color": FRAME_TEXT_COLOR, }, "Slider::value": { "font_size": LIGHT_FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS, "background_color": BUTTON_BACKGROUND_HOVERED_COLOR, "secondary_color": KIT_GREEN, }, "CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F}, "CollapsableFrame": { "background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "color": COLLAPSABLEFRAME_TEXT_COLOR, "border_radius": LIGHT_BORDER_RADIUS, "border_color": 0x0, "border_width": 1, "font_size": LIGHT_FONT_SIZE, "padding": 6, }, "CollapsableFrame.Header": { "font_size": LIGHT_FONT_SIZE, "background_color": FRAME_TEXT_COLOR, "color": FRAME_TEXT_COLOR, }, "CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR}, "CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR}, "Label::vector_label": {"font_size": 14, "color": LABEL_VECTORLABEL_COLOR}, "Rectangle::reset_invalid": {"background_color": 0xFF505050, "border_radius": 2}, "Rectangle::reset": {"background_color": 0xFFA07D4F, "border_radius": 2}, "Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT}, "Rectangle": {"border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND}, "Line::check_line": {"color": KIT_GREEN}, } else: LABEL_COLOR = 0xFF8F8E86 FIELD_BACKGROUND = 0xFF23211F FIELD_TEXT_COLOR = 0xFFD5D5D5 FIELD_TEXT_COLOR_READ_ONLY = 0xFF5C5C5C FRAME_TEXT_COLOR = 0xFFCCCCCC WINDOW_BACKGROUND_COLOR = 0xFF444444 BUTTON_BACKGROUND_COLOR = 0xFF292929 BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778 BUTTON_LABEL_DISABLED_COLOR = 0xFF606060 LABEL_LABEL_COLOR = 0xFF9E9E9E LABEL_TITLE_COLOR = 0xFFAAAAAA LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD COLORWIDGET_BORDER_COLOR = 0xFF1E1E1E COMBOBOX_HOVERED_BACKGROUND_COLOR = 0xFF33312F COLLAPSABLEFRAME_BORDER_COLOR = 0x0 COLLAPSABLEFRAME_BACKGROUND_COLOR = 0xFF343432 COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFF23211F COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFF343432 COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFF2E2E2B COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B style = { "Window": {"background_color": WINDOW_BACKGROUND_COLOR}, "Button": {"background_color": WINDOW_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 4}, "RadioButton": { "margin": 2, "border_radius": 2, "font_size": 16, "background_color": 0xFF212121, "color": 0xFF444444, }, "RadioButton.Label": {"font_size": 16, "color": 0xFF777777}, "RadioButton:checked": {"background_color": 0xFF777777, "color": 0xFF222222}, "RadioButton.Label:checked": {"color": 0xFFDDDDDD}, "Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR}, "Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR}, "Button.Label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR}, "Triangle::title": {"background_color": 0xFFCCCCCC}, "Field::models": { "background_color": FIELD_BACKGROUND, "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, }, "Field::models_readonly": { "background_color": FIELD_BACKGROUND, "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR_READ_ONLY, "border_radius": BORDER_RADIUS, }, "Label": {"font_size": 14, "color": LABEL_COLOR}, "Label::label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR}, "Label::title": {"font_size": FONT_SIZE, "color": LABEL_TITLE_COLOR}, "ComboBox::renderer_choice": {"font_size": 16}, "ComboBox::choices": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND, "border_radius": BORDER_RADIUS, }, "ComboBox:hovered:choices": { "background_color": COMBOBOX_HOVERED_BACKGROUND_COLOR, "secondary_color": COMBOBOX_HOVERED_BACKGROUND_COLOR, }, "Slider::value": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": KIT_GREEN, }, "Slider::multivalue": { "font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR, "border_radius": BORDER_RADIUS, "background_color": FIELD_BACKGROUND, "secondary_color": KIT_GREEN, "draw_mode": ui.SliderDrawMode.HANDLE, }, "CheckBox::greenCheck": { "font_size": 12, "background_color": LABEL_LABEL_COLOR, "color": FIELD_BACKGROUND, "border_radius": BORDER_RADIUS, }, "CollapsableFrame": { "background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR, "border_radius": BORDER_RADIUS * 2, "padding": 4, "color": FRAME_TEXT_COLOR, }, "CollapsableFrame::groupFrame": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "border_radius": BORDER_RADIUS * 2, "padding": 2, }, "CollapsableFrame::groupFrame:hovered": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::groupFrame:pressed": { "background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame:hovered": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR, }, "CollapsableFrame::subFrame:pressed": { "background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR, "secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR, }, "CollapsableFrame.Header": { "font_size": FONT_SIZE, "background_color": FRAME_TEXT_COLOR, "color": FRAME_TEXT_COLOR, }, "CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR}, "CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR}, "ColorWidget": { "border_radius": BORDER_RADIUS, "border_color": COLORWIDGET_BORDER_COLOR, "border_width": 0.5, }, "Label::RenderLabel": {"font_size": 16, "color": FRAME_TEXT_COLOR}, "Rectangle::TopBar": { "border_radius": BORDER_RADIUS * 2, "background_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR, }, "Label::vector_label": {"font_size": 16, "color": LABEL_VECTORLABEL_COLOR}, "Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT}, "Rectangle::reset_invalid": {"background_color": 0xFF505050, "border_radius": 2}, "Rectangle::reset": {"background_color": 0xFFA07D4F, "border_radius": 2}, } return style
13,385
Python
47.151079
115
0.56526
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/__init__.py
from .style import get_style, get_ui_style_name from .settings_widget import create_setting_widget, create_setting_widget_combo, SettingType, SettingsSearchableCombo, SettingWidgetType from .settings_widget_builder import SettingsWidgetBuilder
244
Python
60.249985
136
0.848361
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/settings_widget_builder.py
import collections from functools import partial from pathlib import Path from typing import Tuple, Union, Any import carb import carb.settings import omni.kit.app import omni.kit.commands import omni.ui as ui from .settings_model import SettingsComboItemModel, RadioButtonSettingModel LABEL_HEIGHT = 18 HORIZONTAL_SPACING = 4 LABEL_WIDTH = 200 class SettingsWidgetBuilder: checkbox_alignment = None checkbox_alignment_set = False @staticmethod def _get_setting(setting_path: str, setting_name: str = "", default: Any = None) -> Any: """Get the configuration of an UI widget carb.settings. This method assumes the given "setting_path" points to a value that has the given "setting_name" setting lives aside with it as a sibling. Args: setting_path (str): The base setting path. setting_name (str): The setting name the query. Kwargs: default (Any): The value to return if the setting doesn't exist or is None. Return: (Any): Setting value. """ # setting_path is pointing to the value of the setting, go one level up to get the other settings - e.g. itmes if setting_name: setting_path = setting_path.split("/")[:-1] setting_path.append(setting_name) setting_path = "/".join(setting_path) value = carb.settings.get_settings().get(setting_path) value = default if value is None else value return value @classmethod def get_checkbox_alignment(cls): if not cls.checkbox_alignment_set: settings = carb.settings.get_settings() cls.checkbox_alignment = settings.get("/ext/omni.kit.window.property/checkboxAlignment") cls.checkbox_alignment_set = True return cls.checkbox_alignment label_alignment = None label_alignment_set = False @classmethod def get_label_alignment(cls): if not cls.label_alignment_set: settings = carb.settings.get_settings() cls.label_alignment = settings.get("/ext/omni.kit.window.property/labelAlignment") cls.label_alignment_set = True return cls.label_alignment @classmethod def _restore_defaults(cls, path: str, button=None) -> None: omni.kit.commands.execute("RestoreDefaultRenderSetting", path=path) if button: button.visible = False @classmethod def _build_reset_button(cls, path) -> ui.Rectangle: with ui.VStack(width=0, height=0): ui.Spacer() with ui.ZStack(width=15, height=15): with ui.HStack(style={"margin_width": 0}): ui.Spacer() with ui.VStack(width=0): ui.Spacer() ui.Rectangle(width=5, height=5, name="reset_invalid") ui.Spacer() ui.Spacer() btn = ui.Rectangle(width=12, height=12, name="reset", tooltip="Click to reset value", identifier=f"{path}_reset") btn.visible = False btn.set_mouse_pressed_fn(lambda x, y, m, w, p=path, b=btn: cls._restore_defaults(path, b)) ui.Spacer() return btn @staticmethod def _create_multi_float_drag_with_labels(model, labels, comp_count, **kwargs) -> None: RECT_WIDTH = 13 SPACING = 4 with ui.ZStack(): with ui.HStack(): if labels: ui.Spacer(width=RECT_WIDTH) widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING} else: widget_kwargs = {"name": "multivalue", "h_spacing": 3} widget_kwargs.update(kwargs) ui.MultiFloatDragField(model, **widget_kwargs) with ui.HStack(): if labels: for i in range(comp_count): if i != 0: ui.Spacer(width=SPACING) label = labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": label[1]}) ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() @staticmethod def _create_multi_int_drag_with_labels(model, labels, comp_count, **kwargs) -> None: RECT_WIDTH = 13 SPACING = 4 with ui.ZStack(): with ui.HStack(): if labels: ui.Spacer(width=RECT_WIDTH) widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING} else: widget_kwargs = {"name": "multivalue", "h_spacing": 3} widget_kwargs.update(kwargs) ui.MultiIntDragField(model, **widget_kwargs) with ui.HStack(): if labels: for i in range(comp_count): if i != 0: ui.Spacer(width=SPACING) label = labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": label[1]}) ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() @classmethod def createColorWidget(cls, model, comp_count=3, additional_widget_kwargs=None) -> ui.HStack: with ui.HStack(spacing=HORIZONTAL_SPACING) as widget: widget_kwargs = {"min": 0.0, "max": 1.0} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) # TODO probably need to support "A" if comp_count is 4, but how many assumptions can we make? with ui.HStack(spacing=4): cls._create_multi_float_drag_with_labels( model=model, labels=[("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F)], comp_count=comp_count, **widget_kwargs, ) ui.ColorWidget(model, width=30, height=0) # cls._create_control_state(model) return widget @classmethod def createVecWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None): widget_kwargs = {"min": range_min, "max": range_max} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) cls._create_multi_float_drag_with_labels( model=model, labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)], comp_count=comp_count, **widget_kwargs, ) return model @classmethod def createDoubleArrayWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None): widget_kwargs = {"min": range_min, "max": range_max} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) cls._create_multi_float_drag_with_labels(model=model, labels=None, comp_count=comp_count, **widget_kwargs) return model @classmethod def createIntArrayWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None): widget_kwargs = {"min": range_min, "max": range_max} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) cls._create_multi_int_drag_with_labels(model=model, labels=None, comp_count=comp_count, **widget_kwargs) return model @staticmethod def _create_drag_or_slider(drag_widget, slider_widget, **kwargs): ''' A drag_widget lets you click and drag (you can drag as far left or right on the screen as you like) You can double-click to manually enter a value A slider_widget lets you click and sets the value to where you clicked. You don't drag outside the screen space occupied by the widget. No double click support. You press Ctrl-Click to manually enter a value This method will use a slider_widget when the range is <100 and a slider otherwise ''' if "min" in kwargs and "max" in kwargs: range_min = kwargs["min"] range_max = kwargs["max"] if range_max - range_min < 100: widget = slider_widget(name="value", **kwargs) if "hard_range" in kwargs and kwargs['hard_range']: model = kwargs["model"] model.set_range(range_min, range_max) return widget else: if "step" not in kwargs: kwargs["step"] = max(0.1, (range_max - range_min) / 1000.0) else: if "step" not in kwargs: kwargs["step"] = 0.1 # If range is too big or no range, don't use a slider widget = drag_widget(name="value", **kwargs) return widget @classmethod def _create_label(cls, attr_name, path, tooltip="", additional_label_kwargs=None): alignment = ui.Alignment.RIGHT if cls.get_label_alignment() == "right" else ui.Alignment.LEFT label_kwargs = { "name": "label", "word_wrap": True, "width": LABEL_WIDTH, "height": LABEL_HEIGHT, "alignment": alignment, } # Tooltip always contains setting name. If there's a user-defined one, add that too label_kwargs["tooltip"] = path if tooltip: label_kwargs["tooltip"] = f"{path} : {tooltip}" if additional_label_kwargs: label_kwargs.update(additional_label_kwargs) ui.Label(attr_name, **label_kwargs) ui.Spacer(width=5) @classmethod def createBoolWidget(cls, model, additional_widget_kwargs=None): widget = None with ui.HStack(): left_aligned = cls.get_checkbox_alignment() == "left" if not left_aligned: ui.Spacer(width=10) ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1)) ui.Spacer(width=5) with ui.VStack(style={"margin_width": 0}, width=10): ui.Spacer() widget_kwargs = {"width": 10, "height": 0, "name": "greenCheck", "model": model} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) widget = ui.CheckBox(**widget_kwargs) ui.Spacer() if left_aligned: ui.Spacer(width=10) ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1)) return widget @classmethod def createFloatWidget(cls, model, range_min, range_max, additional_widget_kwargs=None): widget_kwargs = {"model": model} # only set range if range is valid (min < max) if range_min < range_max: widget_kwargs["min"] = range_min widget_kwargs["max"] = range_max if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) widget_kwargs.update(style={"secondary_color": 0xFF444444}) return cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs) @classmethod def createIntWidget(cls, model, range_min, range_max, additional_widget_kwargs=None): widget_kwargs = {"model": model} # This passes the model into the widget # only set range if range is valid (min < max) if range_min < range_max: widget_kwargs["min"] = range_min widget_kwargs["max"] = range_max if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) widget_kwargs.update(style={"secondary_color": 0xFF444444}) return cls._create_drag_or_slider(ui.IntDrag, ui.IntSlider, **widget_kwargs) @classmethod def createAssetWidget(cls, model, additional_widget_kwargs=None): widget = AssetPicker(model) widget.build_ui(additional_widget_kwargs) return widget @classmethod def createRadiobuttonWidget( cls, model: RadioButtonSettingModel, setting_path: str = "", additional_widget_kwargs: dict = None) -> omni.ui.RadioCollection: """ Creating a RadioButtons Setting widget. This function creates a Radio Buttons that shows a list of names that are connected with setting by path specified - "{setting_path}/items". Args: model: A RadioButtonSettingModel instance. setting_path: Path to the setting to show and edit. Return: (omni.ui.RadioCollection): A omni.ui.RadioCollection instance. """ def _create_radio_button(_collection): extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) icon_dir = Path(extension_path).joinpath("data").joinpath("icons").absolute() icon_style = { "image_url": str(Path(icon_dir, Path("radio_off.svg"))), ":checked": {"image_url": str(Path(icon_dir, Path("radio_on.svg")))}, } radio_button = omni.ui.RadioButton( radio_collection=_collection, width=20, height=20, style=icon_style, **additional_widget_kwargs, ) omni.ui.Label(f"{item}\t", alignment=omni.ui.Alignment.LEFT) return radio_button additional_widget_kwargs = additional_widget_kwargs if additional_widget_kwargs else {} collection = omni.ui.RadioCollection(model=model) vertical = cls._get_setting(setting_path, "vertical", False) for item in model.items: stack = omni.ui.VStack() if vertical else omni.ui.HStack() with stack: _create_radio_button(collection) return collection @classmethod def createComboboxWidget( cls, setting_path: str, items: Union[list, dict, None] = None, setting_is_index: bool = True, additional_widget_kwargs: dict = None ) -> Tuple[SettingsComboItemModel, ui.ComboBox]: """ Creating a Combo Setting widget. This function creates a combo box that shows a provided list of names and it is connected with setting by path specified. Underlying setting values are used from values of `items` dict. Args: setting_path: Path to the setting to show and edit. items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values. setting_is_index: True - setting_path value is index into items list (default) False - setting_path value is string in items list """ name_to_value = None # Get items from toml settings if items is None: items = cls._get_setting(setting_path, "items", []) # if we have a list, we want to synthesize a dict of type label: index if isinstance(items, list): # TODO: WE should probably check the type of the target attribute before deciding what to do here name_to_value = collections.OrderedDict(zip(items, range(0, len(items)))) elif isinstance(items, dict): name_to_value = items else: carb.log_error(f"Unsupported type {type(items)} for items in create_setting_widget_combo") return None model = SettingsComboItemModel(setting_path, name_to_value, setting_is_index) widget = ui.ComboBox(model) # OM-91518: Fixed double slash in it's xpath as shown in inspector widget.identifier = setting_path.replace("/", "_") return widget, model class AssetPicker: def _on_file_pick(self, dialog, filename: str, dirname: str): """ when a file or folder is selected in the dialog """ path = "" if dirname: if self.is_folder: path = f"{dirname}" else: path = f"{dirname}/{filename}" elif filename: path = filename self.model.set_value(path) dialog.hide() @classmethod def get_icon_path(cls): 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") return icon_path def __init__(self, model): self.model = model self.item_filter_options = ["All Files (*)"] self.is_folder = False def on_show_dialog(self, model, item_filter_options): try: from omni.kit.window.filepicker import FilePickerDialog heading = "Select Folder..." if self.is_folder else "Select File.." dialog = FilePickerDialog( heading, apply_button_label="Select", click_apply_handler=lambda filename, dirname: self._on_file_pick(dialog, filename, dirname), item_filter_options=item_filter_options, ) dialog.show() except: carb.log_warn(f"Failed to import omni.kit.window.filepicker") pass def build_ui(self, additional_widget_kwargs=None): with ui.HStack(): def assign_value(model, path: omni.ui.WidgetMouseDropEvent): model.set_value(path.mime_data) def drop_accept(url: str): # TODO support filtering by file extension if "." not in url: # TODO dragging from stage view also result in a drop, which is a prim path not an asset path # For now just check if dot presents in the url (indicating file extension). return False return True with ui.ZStack(): widget_kwargs = {"name": "models", "model": self.model} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) value_widget = ui.StringField(**widget_kwargs) value_widget.identifier = "AssetPicker_path" # Drag and Drop behaviour value_widget.set_accept_drop_fn(drop_accept) assign_value_p = partial(assign_value, self.model) value_widget.set_drop_fn(assign_value_p) ui.Spacer(width=3) style = {"image_url": str(self.get_icon_path().joinpath("small_folder.png"))} heading = "Select Folder..." if self.is_folder else "Select File.." ui.Button( style=style, width=20, tooltip="Browse...", clicked_fn=lambda model=self.model: self.on_show_dialog(model, self.item_filter_options), identifier="AssetPicker_select" ) ui.Spacer(width=3) # Button to jump to the file in Content Window def locate_file(model): print("locate file") # omni.kit.window.content_browser is an optional dependency try: url = model.get_resolved_path() if len(url) == 0: print("Returning...") return from omni.kit.window.content_browser import get_content_window instance = get_content_window() if instance: instance.navigate_to(url) else: carb.log_warn(f"Failed to import omni.kit.window.content_browser") except Exception as e: carb.log_warn(f"Failed to locate file: {e}") style["image_url"] = str(self.get_icon_path().joinpath("find.png")) ui.Button( style=style, width=20, tooltip="Locate File", clicked_fn=lambda model=self.model: locate_file(model), identifier="AssetPicker_locate" )
20,438
Python
40.542683
143
0.571974
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/settings_model.py
from typing import Any, Dict, Union import carb import carb.dictionary import carb.settings import omni.kit.commands import omni.ui as ui def update_reset_button(settingModel): """ work out whether to show the reset button highlighted or not depending on whether the setting is set to it's default value """ if not settingModel._reset_button: return # This lookup of rtx-defaults involves some other extension having copied # the data from /rtx to /rtx-defaults.. default_path = settingModel._path.replace("/rtx/", "/rtx-defaults/") item = settingModel._settings.get_settings_dictionary(default_path) if item is not None: if settingModel._settings.get(settingModel._path) == settingModel._settings.get(default_path): settingModel._reset_button.visible = False else: settingModel._reset_button.visible = True else: # pragma: no cover carb.log_info(f"update_reset_button: \"{default_path}\" not found") class SettingModel(ui.AbstractValueModel): """ Model for simple scalar/POD carb.settings """ def __init__(self, setting_path: str, draggable: bool = False): """ Args: setting_path: setting_path carb setting to create a model for draggable: is it a numeric value you will drag in the UI? """ ui.AbstractValueModel.__init__(self) self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() self._path = setting_path self.draggable = draggable self.initialValue = None self._reset_button = None self._editing = False self._range_set = False self._min = None self._max = None self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_change) def set_range(self, min_val, max_val): ''' set the allowable range for the setting. This is more restrictive than the UI min/max setting which still lets you set out of range values using the keyboard (e.g click and type in slider) ''' self._range_set = True self._min = min_val self._max = max_val def _on_change(owner, value, event_type) -> None: if event_type == carb.settings.ChangeEventType.CHANGED: owner._on_dirty() if owner._editing == False: owner._update_reset_button() def begin_edit(self) -> None: self._editing = True ui.AbstractValueModel.begin_edit(self) self.initialValue = self._settings.get(self._path) if self.initialValue is None: # pragma: no cover carb.log_warn(f"a value for setting {self._path} has been requested but is not available") def end_edit(self) -> None: ui.AbstractValueModel.end_edit(self) value = self._settings.get(self._path) if value is None: # pragma: no cover carb.log_warn(f"a value for setting {self._path} has been requested but is not available") omni.kit.commands.execute( "ChangeSetting", path=self._path, value=value, prev=self.initialValue ) self._update_reset_button() self._editing = False def _get_value(self): value = self._settings.get(self._path) if value is None: # pragma: no cover carb.log_warn(f"a value for setting {self._path} has been requested but is not available") return value def get_value(self): return self._get_value() def get_value_as_string(self) -> str: return self._get_value() def get_value_as_float(self) -> float: return self._get_value() def get_value_as_bool(self) -> bool: return self._get_value() def get_value_as_int(self) -> int: return self._get_value() def set_value(self, value: Any): if self._range_set and (value < self._min or value > self._max): #print(f"not changing value to {value} as it's outside the range {self._min}-{self._max}") return if not self.draggable: omni.kit.commands.execute("ChangeSetting", path=self._path, value=value) update_reset_button(self) self._on_dirty() else: omni.kit.commands.execute("ChangeDraggableSetting", path=self._path, value=value) def _update_reset_button(self): update_reset_button(self) def set_reset_button(self, button: ui.Rectangle): self._reset_button = button update_reset_button(self) def _on_dirty(self): # Tell the widgets that the model value has changed self._value_changed() def destroy(self): # pragma: no cover self._reset_button = None self._update_setting = None class RadioButtonSettingModel(ui.SimpleStringModel): """Model for simple RadioButton widget. The setting value and options are strings.""" def __init__(self, setting_path: str): """ Args: setting_path: Carb setting path to create a model for. RadioButton items are specified in carb.settings "{setting_path}/items" """ super().__init__() self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() self._setting_path = setting_path self._items = None self._reset_button = None self._editing = False # This sets the index to the current value of the setting, we can't always assume 0th/first self._on_setting_change(self, carb.settings.ChangeEventType.CHANGED) self.add_value_changed_fn(self._value_changed) self._update_setting = omni.kit.app.SettingChangeSubscription(self.setting_path, self._on_setting_change) @property def setting_path(self): return self._setting_path @property def items(self) -> tuple: return self._items if self._items is not None else self._get_items() def set_reset_button(self, button: ui.Rectangle): self._reset_button = button update_reset_button(self) def _update_reset_button(self): update_reset_button(self) def _execute_kit_change_setting_command(self, value, previous_value=None): kwargs = {"value": value, "path": self.setting_path} if isinstance(previous_value, int): kwargs["prev"] = previous_value omni.kit.commands.execute("ChangeSetting", **kwargs) def _on_setting_change(self, _: carb.dictionary.Item, event_type): """ This gets called this if: + Something else changes the setting (e.g an undo command) + We also use as a debugging tool to make sure things were changed.. Args: _ (carb.dictionary.Item): Not used here. event_type: use to filter """ if event_type != carb.settings.ChangeEventType.CHANGED: return value = self._settings.get(self.setting_path) self.set_value(value, update_setting=False) self._update_reset_button() def _value_changed(self, model): self.set_value(self.get_value_as_string()) def get_value(self) -> str: """Return current selected item string/label.""" return self.get_value_as_string() def set_value(self, value: Union[int, str], update_setting: bool = True): """Set given value as current selected Args: value (int|str): Value to set. It can be either an int (index) or a string (label) Kwargs: update_setting (bool): Update corresponding carb.setting. Default True. """ if isinstance(value, int): value = self.items[value] super().set_value(value) if update_setting: self._execute_kit_change_setting_command(value) update_reset_button(self) def get_value_as_int(self) -> int: """Return current selected item idx.""" value = self.get_value() try: idx = self.items.index(value) except ValueError: idx = -1 return idx def _get_items(self) -> tuple: """Return radiobutton items from carb.settings.""" setting_path = self.setting_path.split("/")[:-1] setting_path.append("items") setting_path = "/".join(setting_path) self._itmes = tuple(self._settings.get(setting_path) or []) return self._itmes class AssetPathSettingsModel(SettingModel): def get_resolved_path(self): # @TODO: do I need to add in some kind of URI Resolution here? return self.get_value_as_string() class VectorFloatComponentModel(ui.SimpleFloatModel): def __init__(self, parent, vec_index, immediate_mode): super().__init__() self.parent = parent self.vec_index = vec_index self.immediate_mode = immediate_mode def get_value_as_float(self): # The SimpleFloatModel class is storing a simple float value which works with get/set, so lets use that if not self.immediate_mode: return super().get_value_as_float() val = self.parent._settings.get(self.parent._path) # NOTE: Not sure why, but sometimes val can be a 2 float rather than a 3 if val is not None and len(val) > self.vec_index: return val[self.vec_index] return 0.0 def set_value(self, val): super().set_value(val) # If this isn't here, any callbacks won't get called # As the change occurs, set the setting immediately so any client (e.g the viewport) see it instantly if self.immediate_mode: vec = self.parent._settings.get(self.parent._path) vec[self.vec_index] = val self.parent._settings.set(self.parent._path, vec) class VectorIntComponentModel(ui.SimpleIntModel): def __init__(self, parent, vec_index, immediate_mode): super().__init__() self.parent = parent self.vec_index = vec_index self.immediate_mode = immediate_mode def get_value_as_int(self): # The SimpleIntModel class is storing a simple int value which works with get/set, so lets use that if not self.immediate_mode: return super().get_value_as_int() val = self.parent._settings.get(self.parent._path) # NOTE: Not sure why, but sometimes val can be a 2 int rather than a 3 if len(val) > self.vec_index: return val[self.vec_index] return 0 def set_value(self, val): super().set_value(val) # If this isn't here, any callbacks won't get called # As the change occurs, set the setting immediately so any client (e.g the viewport) see it instantly if self.immediate_mode: vec = self.parent._settings.get(self.parent._path) vec[self.vec_index] = val self.parent._settings.set(self.parent._path, vec) class VectorSettingsModel(ui.AbstractItemModel): """ Model For Color, Vec3 and other multi-component settings Assumption is the items are draggable, so we only store a command when the dragging has completed. TODO: Needs testing with component_count = 2,4 """ def __init__(self, setting_path: str, component_count: int, item_class: ui.AbstractItemModel, immediate_mode: bool): """ Args: setting_path: setting_path carb setting to create a model for component_count: how many elements does the setting have? immediate_mode: do we update the underlying setting immediately, or wait for endEdit """ ui.AbstractItemModel.__init__(self) self._comp_count = component_count self._path = setting_path self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() self._dirty = False self._reset_button = None class VectorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model # Create one model per component self._items = [VectorItem(item_class(self, i, immediate_mode)) for i in range(self._comp_count)] for item in self._items: # Tell the parent model when the submodel changes the value item.model.add_value_changed_fn(lambda a, item=item: self._item_changed(item)) # These cause the component-wise R,G,B sliders to log a change command item.model.add_begin_edit_fn(lambda a, item=item: self.begin_edit(item)) item.model.add_end_edit_fn(lambda a, item=item: self.end_edit(item)) def _on_change(owner, item: carb.dictionary._dictionary.Item, event_type: carb.settings.ChangeEventType): """ when an undo, reset_to_default or other change to the setting happens outside this model update the component child models """ if event_type == carb.settings.ChangeEventType.CHANGED and not owner._dirty: owner._item_changed(None) owner._update_reset_button() def get_item_children(self, item: ui.AbstractItem = None): """ this is called by the widget when it needs the submodel items """ if item is None: return self._items return super().get_item_children(item) def get_item_value_model(self, sub_model_item: ui.AbstractItem = None, column_id: int = 0): """ this is called by the widget when it needs the submodel item models (to then get or set them) """ if sub_model_item is None: return self._items[column_id].model return sub_model_item.model def begin_edit(self, item: ui.AbstractItem): """ TODO: if we don't add even a dummy implementation we get crashes """ lambda: None def set_reset_button(self, button: ui.Rectangle): self._reset_button = button update_reset_button(self) def _update_reset_button(self): update_reset_button(self) def end_edit(self, item): pass def destroy(self): # pragma: no cover self._update_setting = None self._root_model = None self._on_change = None self._reset_button = None def set_value(self, values: Union[tuple, list]): """Set list of values to the model.""" for idx, child_item in enumerate(self.get_item_children()): child_item.model.set_value(values[idx]) class VectorFloatSettingsModel(VectorSettingsModel): def __init__(self, setting_path: str, component_count: int, immediate_mode: bool = True): super().__init__(setting_path, component_count, VectorFloatComponentModel, immediate_mode) # Register change event when the underlying setting changes.. but make sure start off with the correct # Setting also.. dict1 = carb.dictionary.acquire_dictionary_interface() arint_item = dict1.create_item(None, "", carb.dictionary.ItemType.DICTIONARY) value = self._settings.get(self._path) if value is None: carb.log_warn(f"a value for setting {self._path} has been requested but is not available") if value is not None: dict1.set_float_array(arint_item, value) self._on_change(arint_item, carb.settings.ChangeEventType.CHANGED) self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_change) def end_edit(self, item): old_dirty = self._dirty self._dirty = True # Use to stop _on_change running vector = [item.model.get_value_as_float() for item in self._items] if vector: omni.kit.commands.execute("ChangeSetting", path=self._path, value=vector) self._update_reset_button() self._dirty = old_dirty def get_value(self) -> tuple: """Return current float values tuple.""" values = [] for child_item in self.get_item_children(): values.append(child_item.model.get_value_as_float()) return tuple(values) class VectorIntSettingsModel(VectorSettingsModel): def __init__(self, setting_path: str, component_count: int, immediate_mode: bool = True): super().__init__(setting_path, component_count, VectorIntComponentModel, immediate_mode) # Register change event when the underlying setting changes.. but make sure start off with the correct # Setting also.. dict1 = carb.dictionary.acquire_dictionary_interface() arint_item = dict1.create_item(None, "", carb.dictionary.ItemType.DICTIONARY) value = self._settings.get(self._path) if value is None: carb.log_warn(f"a value for setting {self._path} has been requested but is not available") dict1.set_int_array(arint_item, value) self._on_change(arint_item, carb.settings.ChangeEventType.CHANGED) self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_change) def end_edit(self, item): old_dirty = self._dirty self._dirty = True # Use to stop _on_change running vector = [item.model.get_value_as_float() for item in self._items] if vector: omni.kit.commands.execute("ChangeSetting", path=self._path, value=vector) self._update_reset_button() self._dirty = old_dirty def get_value(self) -> tuple: """Return current int values tuple.""" values = [] for child_item in self.get_item_children(): values.append(child_item.model.get_value_as_int()) return tuple(values) class SettingsComboValueModel(ui.AbstractValueModel): """ Model to store a pair (label, value of arbitrary type) for use in a ComboBox """ def __init__(self, label: str, value: Any): """ Args: label: what appears in the UI widget value: the value corresponding to that label """ ui.AbstractValueModel.__init__(self) self.label = label self.value = value def __repr__(self): return f'"SettingsComboValueModel label:{self.label} value:{self.value}"' def get_value_as_string(self) -> str: """ this is called to get the label of the combo box item """ return self.label def get_setting_value(self) -> Union[str, int]: """ we call this to get the value of the combo box item """ return self.value class SettingsComboNameValueItem(ui.AbstractItem): def __init__(self, label: str, value: str): super().__init__() self.model = SettingsComboValueModel(label, value) def __repr__(self): return f'"SettingsComboNameValueItem {self.model}"' class SettingsComboItemModel(ui.AbstractItemModel): """ Model for a combo box - for each setting we have a dictionary of key, values """ def __init__(self, setting_path, key_value_pairs: Dict[str, Any], setting_is_index: bool = True): super().__init__() self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() self._setting_is_index = setting_is_index self._path = setting_path self._reset_button = None self._items = [] for x, y in key_value_pairs.items(): self._items.append(SettingsComboNameValueItem(x, y)) self._current_index = ui.SimpleIntModel() self._prev_index_val = self._current_index.as_int # This sets the index to the current value of the setting, we can't always assume 0th/first self._on_setting_change(self, carb.settings.ChangeEventType.CHANGED) self._current_index.add_value_changed_fn(self._current_index_changed) self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_setting_change) self._dirty = True def _update_reset_button(self): update_reset_button(self) def _on_setting_change(owner, item: carb.dictionary.Item, event_type): """ This gets called this if: + Something else changes the setting (e.g an undo command) + We also use as a debugging tool to make sure things were changed.. Args: owner: will be an instance of SettingsComboItemModel item: ? event_type: use to filter """ # TODO: should be able to extract the value from the item, but not sure how value = owner._settings.get(owner._path) if event_type == carb.settings.ChangeEventType.CHANGED: # We need to back track from the value to the index of the item that contains it index = -1 for i in range(0, len(owner._items)): if owner._setting_is_index and owner._items[i].model.value == value: index = i elif owner._items[i].model.label == value: index = i if index != -1 and owner._current_index.as_int != index: owner._dirty = False owner._current_index.set_value(index) owner._item_changed(None) owner._dirty = True owner._update_reset_button() def _current_index_changed(self, model): if self._dirty: self._item_changed(None) if self._setting_is_index: new_value = self._items[model.as_int].model.get_setting_value() old_value = self._items[self._prev_index_val].model.get_setting_value() else: new_value = self._items[model.as_int].model.get_value_as_string() old_value = self._items[self._prev_index_val].model.get_value_as_string() self._prev_index_val = model.as_int omni.kit.commands.execute("ChangeSetting", path=self._path, value=new_value, prev=old_value) self._update_reset_button() def set_items(self, key_value_pairs: Dict[str, Any]): self._items.clear() for x, y in key_value_pairs.items(): self._items.append(SettingsComboNameValueItem(x, y)) self._item_changed(None) self._dirty = True def set_reset_button(self, button: ui.Rectangle): self._reset_button = button update_reset_button(self) def get_item_children(self, item: ui.AbstractItem = None): """ this is called by the widget when it needs the submodel items """ if item is None: return self._items return super().get_item_children(item) def get_item_value_model(self, item: ui.AbstractItem = None, column_id: int = 0): if item is None: return self._current_index return item.model def get_value_as_int(self) -> int: """Get current selected item index Return: (int) Current selected item index """ return self._current_index.get_value_as_int() def get_value_as_string(self) -> str: """Get current selected item string/label Return: (str) Current selected item label string. """ return self._items[self.get_value_as_int()].model.get_value_as_string() def get_value(self) -> Union[int, str]: """Get current selected item label string or index value. Return: (int|str) Current selected item label string or index value depends on the self._setting_is_index attribute. """ return self.get_value_as_int if self._setting_is_index else self.get_value_as_string() def set_value(self, value: Union[int, str]): """Set current selected to given value Arg: value (int|str): The value to set. """ value = 0 if not isinstance(value, int): try: value = self._items.index(value) except IndexError: pass self._current_index.set_value(value) def destroy(self): # pragma: no cover self._update_setting = None self._reset_button = None
24,184
Python
36.8482
120
0.616606
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/deprecated/__init__.py
"""Settings Omniverse Kit API Module to work with **Settings** in the Kit. It is built on top of ``carb.settings`` generic setting system. Example code to create :class:`omni.kit.ui.Widget` to show and edit particular setting: >>> import omni.kit.settings >>> import omni.kit.ui >>> widget = omni.kit.settings.create_setting_widget("some/path/to/param", SettingType.FLOAT) """ from .ui import SettingType, create_setting_widget, create_setting_widget_combo from .model import UiModel, get_ui_model
502
Python
34.928569
108
0.750996
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/deprecated/model.py
import typing import carb import carb.settings import carb.dictionary import carb.events import omni.kit.ui import omni.kit.commands import omni.kit.app class ChangeGroup: def __init__(self, direct_set=False): self.path = None self.value = None self.info = None self.direct_set = direct_set def _set_path(self, path): if self.path is None: self.path = path elif self.path != path: carb.log_error(f"grouped change with different path: {self.path} != {path}") return False return True def set_array_size(self, path, size, info): if self._set_path(path): # add resize self.value = [None] * size self.info = info def set_value(self, path, value, index, info): if self._set_path(path): if isinstance(self.value, list): self.value[index] = value else: self.value = value self.info = info def apply(self, model): prev_value = model._settings.get(self.path) new_value = self.value if isinstance(new_value, str): pass elif hasattr(new_value, "__getitem__"): new_value = tuple(new_value) if isinstance(new_value, str) and isinstance(prev_value, int): try: new_value = int(new_value) except ValueError: pass if self.info.transient: if self.path not in model._prev_values: model._prev_values[self.path] = prev_value model._settings.set(self.path, new_value) else: undo_value = model._prev_values.pop(self.path, prev_value) if self.direct_set: model._settings.set(self.path, new_value) else: omni.kit.commands.execute("ChangeSetting", path=self.path, value=new_value, prev=undo_value) class UiModel(omni.kit.ui.Model): def __init__(self, direct_set=False): omni.kit.ui.Model.__init__(self) self._subs = {} self._prev_values = {} self._change_group = None self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() self._direct_set = direct_set self._change_group_refcount = 0 self._TYPE_MAPPER = {} self._TYPE_MAPPER[carb.dictionary.ItemType.BOOL] = omni.kit.ui.ModelNodeType.BOOL self._TYPE_MAPPER[carb.dictionary.ItemType.INT] = omni.kit.ui.ModelNodeType.NUMBER self._TYPE_MAPPER[carb.dictionary.ItemType.FLOAT] = omni.kit.ui.ModelNodeType.NUMBER self._TYPE_MAPPER[carb.dictionary.ItemType.STRING] = omni.kit.ui.ModelNodeType.STRING self._TYPE_MAPPER[carb.dictionary.ItemType.DICTIONARY] = omni.kit.ui.ModelNodeType.OBJECT self._TYPE_MAPPER[carb.dictionary.ItemType.COUNT] = omni.kit.ui.ModelNodeType.UNKNOWN def _get_sanitized_path(self, path): if path is not None and len(path) > 0 and path[0] == "/": return path[1:] return "" def _is_array(item): # Hacky way and get_keys() call is slow if len(item) > 0 and "0" in item.get_keys(): v = item["0"] return isinstance(v, int) or isinstance(v, float) or isinstance(v, bool) or isinstance(v, str) return False def get_type(self, path, meta): settings_dict = self._settings.get_settings_dictionary("") path = self._get_sanitized_path(path) item = self._dictionary.get_item(settings_dict, path) item_type = self._dictionary.get_item_type(item) if item_type == carb.dictionary.ItemType.DICTIONARY: if UiModel._is_array(item): return omni.kit.ui.ModelNodeType.ARRAY return self._TYPE_MAPPER[item_type] def get_array_size(self, path, meta): settings_dict = self._settings.get_settings_dictionary("") path = self._get_sanitized_path(path) item = self._dictionary.get_item(settings_dict, path) item_type = self._dictionary.get_item_type(item) if item_type == carb.dictionary.ItemType.DICTIONARY: if UiModel._is_array(item): return len(item) return 0 def get_value(self, path, meta, index, is_time_sampled, time): if not meta: value = self._settings.get(path) if isinstance(value, str): return value elif hasattr(value, "__getitem__"): return value[index] else: return value else: if meta == omni.kit.ui.MODEL_META_WIDGET_TYPE: return self._get_widget_type_for_setting(path, index) if meta == omni.kit.ui.MODEL_META_SERIALIZED_CONTENTS: settings_item = self._settings.get(path) return "%s" % (settings_item,) return None def begin_change_group(self): if self._change_group_refcount == 0: self._change_group = ChangeGroup(direct_set=self._direct_set) self._change_group_refcount += 1 def end_change_group(self): if self._change_group: self._change_group_refcount -= 1 if self._change_group_refcount != 0: return self._change_group.apply(self) self._change_group = None def set_array_size(self, path, meta, size, is_time_sampled, time, info): change = self._change_group if self._change_group else ChangeGroup(direct_set=self._direct_set) change.set_array_size(path, size, info) if not self._change_group: change.apply(self) def set_value(self, path, meta, value, index, is_time_sampled, time, info): change = self._change_group if self._change_group else ChangeGroup(direct_set=self._direct_set) change.set_value(path, value, index, info) if not self._change_group: change.apply(self) def on_subscribe_to_change(self, path, meta, stream): if path in self._subs: return def on_change(item, event_type, path=path): self.signal_change(path) self._subs[path] = omni.kit.app.SettingChangeSubscription(path, on_change) def on_unsubscribe_to_change(self, path, meta, stream): if path in self._subs: del self._subs[path] def get_key_count(self, path, meta): settings_dict = self._settings.get_settings_dictionary("") if len(path) > 0 and path[0] == "/": path = path[1:] parent_item = self._dictionary.get_item(settings_dict, path) return self._dictionary.get_item_child_count(parent_item) def get_key(self, path, meta, index): settings_dict = self._settings.get_settings_dictionary("") if len(path) > 0 and path[0] == "/": path = path[1:] parent_item = self._dictionary.get_item(settings_dict, path) key_item = self._dictionary.get_item_child_by_index(parent_item, index) return self._dictionary.get_item_name(key_item) def _get_widget_type_for_setting(self, path, index): settings_dict = self._settings.get_settings_dictionary("") path = self._get_sanitized_path(path) item = self._dictionary.get_item(settings_dict, path) if UiModel._is_array(item): size = len(item) value = item["0"] if size == 2 and isinstance(value, int): return "DragInt2" elif size == 2 and isinstance(value, float): return "DragDouble2" elif size == 3 and isinstance(value, float): return "DragDouble3" elif size == 4 and isinstance(value, float): return "DragDouble4" elif size == 16 and isinstance(value, float): return "Transform" return "" def get_ui_model() -> UiModel: """Returns :class:`UiModel` singleton""" if not hasattr(get_ui_model, "model"): get_ui_model.model = UiModel(direct_set=False) return get_ui_model.model
8,135
Python
35.981818
108
0.588199
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/deprecated/ui.py
import omni.kit.ui import carb import carb.dictionary import carb.settings import collections from typing import Union, Callable from . import model class SettingType: """ Supported setting types """ FLOAT = 0 INT = 1 COLOR3 = 2 BOOL = 3 STRING = 4 DOUBLE3 = 5 INT2 = 6 DOUBLE2 = 7 def create_setting_widget( setting_path: str, setting_type: SettingType, range_from=0, range_to=0, speed=1, **kwargs ) -> omni.kit.ui.Widget: """ Create a UI widget connected with a setting. If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`. Args: setting_path: Path to the setting to show and edit. setting_type: Type of the setting to expect. range_from: Limit setting value lower bound. range_to: Limit setting value upper bound. Returns: :class:`omni.kit.ui.Widget` connected with the setting on the path specified. """ # Create widget to be used for particular type if setting_type == SettingType.INT: widget = omni.kit.ui.DragInt("", min=range_from, max=range_to, drag_speed=speed, **kwargs) elif setting_type == SettingType.FLOAT: widget = omni.kit.ui.DragDouble("", min=range_from, max=range_to, drag_speed=speed, **kwargs) elif setting_type == SettingType.BOOL: widget = omni.kit.ui.CheckBox(**kwargs) elif setting_type == SettingType.STRING: widget = omni.kit.ui.TextBox("", **kwargs) elif setting_type == SettingType.COLOR3: widget = omni.kit.ui.ColorRgb("", **kwargs) elif setting_type == SettingType.DOUBLE3: widget = omni.kit.ui.DragDouble3("", min=range_from, max=range_to, drag_speed=speed, **kwargs) elif setting_type == SettingType.INT2: widget = omni.kit.ui.DragInt2("", min=range_from, max=range_to, drag_speed=speed, **kwargs) elif setting_type == SettingType.DOUBLE2: widget = omni.kit.ui.DragDouble2("", min=range_from, max=range_to, drag_speed=speed, **kwargs) else: return None if isinstance(widget, omni.kit.ui.ModelWidget): widget.set_model(model.get_ui_model(), setting_path) return widget def create_setting_widget_combo(setting_path: str, items: Union[list, dict]): """ Creating a Combo Setting widget. This function creates a combo box that shows a provided list of names and it is connected with setting by path specified. Underlying setting values are used from values of `items` dict. Args: setting_path: Path to the setting to show and edit. items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values. """ if isinstance(items, list): name_to_value = collections.OrderedDict(zip(items, items)) elif isinstance(items, dict): name_to_value = items else: carb.log_error(f"Unsupported type {type(items)} for items in create_setting_widget_combo") return None if isinstance(next(iter(name_to_value.values())), int): widget = omni.kit.ui.ComboBoxInt("", list(name_to_value.values()), list(name_to_value.keys())) else: widget = omni.kit.ui.ComboBox("", list(name_to_value.values()), list(name_to_value.keys())) widget.set_model(model.get_ui_model(), setting_path) return widget
3,601
Python
35.755102
122
0.663149
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/tests/test_model.py
import omni.kit.test import carb.settings from ..settings_model import VectorFloatSettingsModel, RadioButtonSettingModel class TestModel(omni.kit.test.AsyncTestCase): async def test_vector_model(self): setting_name = "/rtx/pathtracing/maxBlah" settings = carb.settings.get_settings() initial_vals = (0.6, 0.7, 0.8) settings.set(setting_name, initial_vals) vector_model = VectorFloatSettingsModel(setting_name, 3, True) # Lets simulate a bit of what the color widget would do when getting values sub_items = vector_model.get_item_children(None) for cnt, sub_item in enumerate(sub_items): sub_model = vector_model.get_item_value_model(sub_item) val = sub_model.get_value_as_float() self.assertTrue(val == initial_vals[cnt]) # Lets check if things work when we change the value new_vals = (0.5, 0.4, 0.3) settings.set(setting_name, new_vals) for cnt, sub_item in enumerate(sub_items): sub_model = vector_model.get_item_value_model(sub_item) val = sub_model.get_value_as_float() self.assertTrue(val == new_vals[cnt]) # Let's set the value through the item model new_vals = [0.1, 0.15, 0.2] for cnt, sub_item in enumerate(sub_items): sub_model = vector_model.get_item_value_model(sub_item) val = sub_model.set_value(new_vals[cnt]) settings_val = settings.get(setting_name) self.assertTrue(settings_val == new_vals) # Let's set the value directly through the Vector model new_vals = [0.2, 0.8, 0.9] vector_model.set_value(new_vals) settings_val = settings.get(setting_name) self.assertTrue(settings_val == new_vals) # TODO test begin_edit/end_edit # TODO test other sizes (2, 4 components # TODO test immediate mode on/off async def test_radio_button_setting_model(self): setting_value_path = "/ext/ui/settings/radiobutton/value" setting_items_path = "/ext/ui/settings/radiobutton/items" settings = carb.settings.get_settings() initial_val = "option1" items = ("option0", "option1", "option2", "option3") settings.set(setting_value_path, initial_val) settings.set(setting_items_path, items) radio_button_model = RadioButtonSettingModel(setting_value_path) # Lets check the initial_val and items self.assertEqual(radio_button_model.items, items) self.assertEqual(radio_button_model.get_value(), initial_val) self.assertEqual(radio_button_model.get_value_as_int(), 1) # Lets check if things work when we change the value # Set as int new_val = "option0" radio_button_model.set_value(0) self.assertEqual(radio_button_model.get_value(), new_val) self.assertEqual(settings.get(setting_value_path), new_val) self.assertEqual(radio_button_model.get_value_as_int(), 0) # Set as str new_val = "option2" radio_button_model.set_value(new_val) self.assertEqual(radio_button_model.get_value(), new_val) self.assertEqual(settings.get(setting_value_path), new_val) self.assertEqual(radio_button_model.get_value_as_int(), 2) # Let's the the value through settings new_val = "option3" settings.set(setting_value_path, new_val) self.assertEqual(radio_button_model.get_value(), new_val) self.assertEqual(radio_button_model.get_value_as_int(), 3)
3,583
Python
39.727272
83
0.641641
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/tests/test_settings.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import omni.kit.app import omni.kit.test import omni.ui as ui import omni.kit.ui_test as ui_test from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from ..settings_widget import create_setting_widget, create_setting_widget_combo, SettingType, SettingsWidgetBuilder, SettingsSearchableCombo, SettingWidgetType from ..settings_model import VectorFloatSettingsModel from ..style import get_ui_style_name, get_style PERSISTENT_SETTINGS_PREFIX = "/persistent" class TestSettings(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").joinpath("golden_img").absolute() # create settings carb.settings.get_settings().set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_bool", True) carb.settings.get_settings().set_default_float(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_float", 1.0) carb.settings.get_settings().set_default_int(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int", 27) carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_str", "test-test") carb.settings.get_settings().set_float_array(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_color3", [1, 2, 3]) carb.settings.get_settings().set_float_array(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double2", [1.5, 2.7]) carb.settings.get_settings().set_float_array( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double3", [2.7, 1.5, 9.2] ) carb.settings.get_settings().set_int_array(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int2", [10, 13]) carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo1", "AAAAAA") carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo2", "BBBBBB") carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo3", "CCCCCC") carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo4", "DDDDDD") carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo5", "") carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo6", "cheese") carb.settings.get_settings().set_default_string("/rtx/test_asset", "/home/") carb.settings.get_settings().set_default_string("/rtx-defaults/test_asset", "/home/") carb.settings.get_settings().set_default_string( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_radiobutton/value", "A" ) carb.settings.get_settings().set_string_array( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_radiobutton/items", ["A", "B", "C", "D"] ) # After running each test async def tearDown(self): await super().tearDown() omni.kit.window.preferences.hide_preferences_window() def _build_window(self, window): with window.frame: with ui.VStack(height=-0, style=get_style()): with ui.CollapsableFrame(title="create_setting_widget"): with ui.VStack(): with ui.HStack(height=24): omni.ui.Label("bool", word_wrap=True, width=ui.Percent(35)) create_setting_widget(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_bool", SettingType.BOOL) with ui.HStack(height=24): omni.ui.Label("float", word_wrap=True, width=ui.Percent(35)) create_setting_widget( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_float", SettingType.FLOAT ) with ui.HStack(height=24): omni.ui.Label("int", word_wrap=True, width=ui.Percent(35)) create_setting_widget(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int", SettingType.FLOAT) with ui.HStack(height=24): omni.ui.Label("string", word_wrap=True, width=ui.Percent(35)) create_setting_widget( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_str", SettingType.STRING ) with ui.HStack(height=24): omni.ui.Label("color3", word_wrap=True, width=ui.Percent(35)) create_setting_widget( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_color3", SettingType.COLOR3 ) with ui.HStack(height=24): omni.ui.Label("double2", word_wrap=True, width=ui.Percent(35)) create_setting_widget( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double2", SettingType.DOUBLE2 ) with ui.HStack(height=24): omni.ui.Label("double3", word_wrap=True, width=ui.Percent(35)) create_setting_widget( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double3", SettingType.DOUBLE3 ) with ui.HStack(height=24): omni.ui.Label("int2", word_wrap=True, width=ui.Percent(35)) create_setting_widget(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int2", SettingType.INT2) with ui.HStack(height=24): omni.ui.Label("radiobutton", word_wrap=True, width=ui.Percent(35)) create_setting_widget( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_radiobutton/value", SettingWidgetType.RADIOBUTTON ) ui.Spacer(height=20) with ui.CollapsableFrame(title="create_setting_widget_combo"): with ui.VStack(): with ui.HStack(height=24): omni.ui.Label("combo1", word_wrap=True, width=ui.Percent(35)) create_setting_widget_combo( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo1", ["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"], ) with ui.HStack(height=24): omni.ui.Label("combo2", word_wrap=True, width=ui.Percent(35)) create_setting_widget_combo( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo2", ["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"], ) with ui.HStack(height=24): omni.ui.Label("combo3", word_wrap=True, width=ui.Percent(35)) create_setting_widget_combo( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo3", ["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"], ) with ui.HStack(height=24): omni.ui.Label("combo4", word_wrap=True, width=ui.Percent(35)) create_setting_widget_combo( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo4", ["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"], ) with ui.HStack(height=24): omni.ui.Label("combo5", word_wrap=True, width=ui.Percent(35)) create_setting_widget_combo( PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo5", ["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"], ) ui.Spacer(height=20) with ui.CollapsableFrame(title="create_setting_widget_asset"): with ui.VStack(): with ui.HStack(height=24): path = "/rtx/test_asset" omni.ui.Label("asset", word_wrap=True, width=ui.Percent(35)) widget, model = create_setting_widget(path, "ASSET") ui.Spacer(width=4) button = SettingsWidgetBuilder._build_reset_button(path) model.set_reset_button(button) ui.Spacer(height=20) with ui.CollapsableFrame(title="create_searchable_widget_combo"): with ui.VStack(): with ui.HStack(height=24): path = PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo6" SettingsWidgetBuilder._create_label("Searchable", path, "Search Me...") widget = SettingsSearchableCombo(path, {"Whiskey": "whiskey", "Wine": "Wine", "plain": "Plain", "cheese": "Cheese", "juice": "Juice"}, "cheese") # Test(s) async def test_widgets_golden(self): window = await self.create_test_window(width=300, height=600) self._build_window(window) await ui_test.human_delay(50) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_widgets.png") async def test_widget_ui(self): window = ui.Window("Test Window", width=600, height=600) self._build_window(window) await ui_test.human_delay(10) widget = ui_test.find("Test Window//Frame/**/StringField[*].identifier=='AssetPicker_path'") widget.model.set_value("/cheese/") await ui_test.human_delay(10) await ui_test.find("Test Window//Frame/**/Rectangle[*].identifier=='/rtx/test_asset_reset'").click() await ui_test.human_delay(10) await ui_test.find("Test Window//Frame/**/Button[*].identifier=='AssetPicker_locate'").click() await ui_test.human_delay(10) await widget.input("my hovercraft is full of eels") await ui_test.human_delay(10) await ui_test.find("Test Window//Frame/**/Rectangle[*].identifier=='/rtx/test_asset_reset'").click() await ui_test.human_delay(10) # await ui_test.human_delay(1000) async def test_show_pages(self): omni.kit.window.preferences.show_preferences_window() pages = omni.kit.window.preferences.get_page_list() for page in pages: omni.kit.window.preferences.select_page(page) await ui_test.human_delay(50) async def test_widget_types(self): path = PERSISTENT_SETTINGS_PREFIX + "/test/test/test_widget_types" # This is for catching a case that deprecated SettingType is given widget, model = create_setting_widget(path, 5) # COLOR3 self.assertTrue(isinstance(model, VectorFloatSettingsModel)) # Test unsupported types widget, model = create_setting_widget(path, None) self.assertEqual((widget, model), (None, None))
11,993
Python
55.575471
172
0.560994
omniverse-code/kit/exts/omni.kit.widget.settings/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.1] - 2022-06-23 ### Changed - Added identifier to create_setting_widget_combo for easier testing ## [1.0.0] - 2021-03-25 ### Created - Created as updated omni.kit.settings
276
Markdown
22.083331
80
0.695652
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/__init__.py
from .pipapi import *
22
Python
10.499995
21
0.727273
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/pipapi.py
"""Pip Omniverse Kit API Module to enable usage of ``pip install`` in Omniverse Kit environment. It wraps ``pip install`` calls and reroutes package installation into user specified environment folder. Package folder is selected from config string at path: `/app/omni.kit.pipapi/archiveDirs` and added into :mod:`sys.path`. """ __all__ = ["ExtensionManagerPip", "install", "call_pip", "remove_archive_directory", "add_archive_directory"] import carb import carb.profiler import carb.settings import carb.tokens import omni.ext import omni.kit.app import importlib import logging import typing import os import json import sys from contextlib import contextmanager from pathlib import Path import functools logger = logging.getLogger(__name__) DEFAULT_ENV_PATH = "../../target-deps/pip3-envs/default" CACHE_FILE_NAME = ".install_cache.json" USE_INTERNAL_PIP = False ALLOW_ONLINE_INDEX_KEY = "/exts/omni.kit.pipapi/allowOnlineIndex" _user_env_path = "" # pip additional dirs/links (pip install --find-links) _archive_dirs = set() _install_check_ignore_version = True # print() instead of carb.log_info when this env var is set: _debug_log = bool(os.getenv("OMNI_KIT_PIPAPI_DEBUG", default=False)) _attempted_to_upgrade_pip = False _settings_iface = None _started = False # Temporary helper-decorator for profiling def profile(f=None, mask=1, zone_name=None, add_args=True): def profile_internal(f): @functools.wraps(f) def wrapper(*args, **kwds): if zone_name is None: active_zone_name = f.__name__ else: active_zone_name = zone_name if add_args: active_zone_name += str(args) + str(kwds) carb.profiler.begin(mask, active_zone_name) try: r = f(*args, **kwds) finally: carb.profiler.end(mask) return r return wrapper if f is None: return profile_internal else: return profile_internal(f) def _get_setting(path, default=None): # It can be called at import time during doc generation, enable that `_started` check: if not _started: return default global _settings_iface if not _settings_iface: _settings_iface = carb.settings.get_settings() setting = _settings_iface.get(path) return setting if setting is not None else default def _log_info(s): s = f"[omni.kit.pipapi] {s}" if _debug_log: print(s) else: carb.log_info(s) def _log_error(s): logger.error(s) @functools.lru_cache() def _initialize(): env_path = _get_setting("/exts/omni.kit.pipapi/envPath") env_path = carb.tokens.get_tokens_interface().resolve(env_path) path = Path(env_path).resolve() if not path.exists(): path.mkdir(parents=True) global _user_env_path _user_env_path = str(path) import sys global _install_check_ignore_version _install_check_ignore_version = _get_setting("/exts/omni.kit.pipapi/installCheckIgnoreVersion", default=True) global _attempted_to_upgrade_pip _attempted_to_upgrade_pip = not _get_setting("/exts/omni.kit.pipapi/tryUpgradePipOnFirstUse", default=False) global _archive_dirs for archive_dir in _get_setting("/exts/omni.kit.pipapi/archiveDirs", default=[]): add_archive_directory(archive_dir) sys.path.append(_user_env_path) _log_info(f"Python UserEnvPath: {_user_env_path}") _load_cache() @contextmanager def _change_envvar(name: str, value: str): """Change environment variable for the execution block and then revert it back. This function is a context manager. Example: .. code-block:: python with _change_envvar("PYTHONPATH", "C:/hello"): print(os.environ.get("PYTHONPATH")) Args: name (str): Env var to change. value: new value """ old_value = os.environ.get(name, None) os.environ[name] = value try: yield finally: if old_value is None: del os.environ[name] else: os.environ[name] = old_value def call_pip(args, surpress_output=False): """Call pip with given arguments. Args: args (list): list of arguments to pass to pip surpress_output (bool): if True, surpress pip output Returns: int: return code of pip call""" if USE_INTERNAL_PIP: try: from pip import main as pipmain except: from pip._internal import main as pipmain return pipmain(args) else: import subprocess with _change_envvar("PYTHONPATH", _user_env_path): python_exe = "python.exe" if sys.platform == "win32" else "bin/python3" cmd = [sys.prefix + "/" + python_exe, "-m", "pip"] + args print("calling pip install: {}".format(" ".join(cmd))) # Capture output and print it only if pip install failed: p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) output, _ = p.communicate() output = output.decode(errors="replace").replace("\r\n", "\n").replace("\r", "\n") message = f"pip install returned {p.returncode}, output:\n{output}" if p.returncode != 0 and not surpress_output: print(message) else: carb.log_info(message) return p.returncode def add_archive_directory(path: str, root: str = None): """ Add pip additional dirs/links (for pip install --find-links). """ global _archive_dirs path = carb.tokens.get_tokens_interface().resolve(path) if not os.path.isabs(path) and root is not None: path = os.path.join(root, path) path = os.path.normcase(path) _log_info(f"Add archive dir: '{path}'") _archive_dirs.add(path) def remove_archive_directory(path: str): """ Remove pip additional dirs/links. """ global _archive_dirs _archive_dirs.remove(path) def _try_import(module: str, log_error: bool = False): try: importlib.import_module(module) except ImportError as e: if log_error: logger.error(f"Failed to import python module {module}. Error: {e}") return False return True @profile def install( package: str, module: str = None, ignore_import_check: bool = False, ignore_cache: bool = False, version: str = None, use_online_index: bool = True, surpress_output: bool = False, extra_args: typing.List[str] = None, ) -> bool: """ Install pacakage using pip into user specified env path. Install calls for particular package name persistently cache to avoid overhead for future calls when package is already installed. Cache is stored in the `.install_cache.json` file in the user specified env path folder. Args: package(str): Package name to install. It is basically a command to pip install, it can include version and other flags. module(str): Module name to import, by default module assumed to be equal to package. ignore_import_check(bool, optional): If ``True`` ignore attempt to import module and call to ``pip`` anyway - can be slow. ignore_cache(bool, optional): If ``True`` ignore caching and call to ``pip`` anyway - can be slow. version (str, optional): Package version. use_online_index(bool, optional): If ``True`` and package can't be found in any of archive directories try to use default pip index. surpress_output(bool, optional): If ``True`` pip process output to stdout and stderr will be surpressed, as well as warning when install failed. extra_args(List[str], optional): a list of extra arguments to pass to the Pip process Returns: ``True`` if installation was successfull. """ _initialize() # Support both install("foo==1.2.3") and install("foo", version="1.2.3") syntax if "==" not in package and version: package = f"{package}=={version}" # By default module == package if module is None: module = package.split("==")[0] # Trying to import beforehand saves a lot of time, because pip run takes long time even if package is already installed. if not ignore_import_check and _try_import(module): return True # We have our own cache of install() calls saved into separate json file, that is the fastest early out. if not ignore_cache and _is_in_cache(package): return True # Use now pkg_resources module to check if it was already installed. It checks that it was installed by other means, # like just zipping packages and adding it to sys.path somewhere. That allows to check for package name instead of # module (e.g. 'Pillow' instead of 'PIL'). We need to call explicitly on it to initialize and gather packages every time. # Import it here instead of on the file root because it has long import time. import pkg_resources pkg_resources._initialize_master_working_set() installed = {pkg.key for pkg in pkg_resources.working_set} package_name = package.lower() if _install_check_ignore_version: package_name = package_name.split("==")[0] if package_name in installed: return True # We are about to try installing, lets upgrade pip first (it will be done only once). Flag protects from recursion. global _attempted_to_upgrade_pip if not _attempted_to_upgrade_pip: _attempted_to_upgrade_pip = True install("--upgrade --no-index pip", ignore_import_check=True, use_online_index=False) installed = False common_args = ["--isolated", "install", "--target=" + _user_env_path] if extra_args: common_args.extend(extra_args) common_args.extend(package.split()) for archive_dir in _archive_dirs: _log_info(f"Attempting to install '{package}' from local acrhive: '{archive_dir}'") rc = call_pip( common_args + ["--no-index", f"--find-links={archive_dir}"], surpress_output=(surpress_output or use_online_index), ) if rc == 0: importlib.invalidate_caches() installed = True break if not installed and use_online_index: allow_online = _get_setting(ALLOW_ONLINE_INDEX_KEY, default=True) if allow_online: _log_info(f"Attempting to install '{package}' from online index") rc = call_pip(common_args, surpress_output=surpress_output) if rc == 0: importlib.invalidate_caches() installed = True else: _log_error( f"Attempting to install '{package}' from online index, while '{ALLOW_ONLINE_INDEX_KEY}' is set to false. That prevents from accidentally going to online index. Enable it if it is intentional." ) if installed and not ignore_import_check: installed = _try_import(module, log_error=True) if installed: _log_info(f"'{package}' was installed successfully.") _add_to_cache(package) else: if not surpress_output: logger.warning(f"'{package}' failed to install.") return installed _cached_install_calls_file = None _cached_install_calls = {} def _load_cache(): global _cached_install_calls global _cached_install_calls_file _cached_install_calls_file = Path(_user_env_path, CACHE_FILE_NAME) try: with _cached_install_calls_file.open("r") as f: _cached_install_calls = json.load(f) except (IOError, ValueError): _cached_install_calls = {} def _add_to_cache(package): _cached_install_calls[package] = True with _cached_install_calls_file.open("w") as f: json.dump(_cached_install_calls, f) def _is_in_cache(package) -> bool: return package in _cached_install_calls class ExtensionManagerPip(omni.ext.IExt): def on_startup(self, ext_id): # Hook in extension manager in "before extension enable" events if extension specifies "python/pipapi" config key. manager = omni.kit.app.get_app().get_extension_manager() self._hook = manager.get_hooks().create_extension_state_change_hook( ExtensionManagerPip.on_before_ext_enabled, omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_ENABLE, ext_dict_path="python/pipapi", hook_name="python.pipapi", ) global _started _started = True @staticmethod @profile(zone_name="pipapi hook", add_args=False) def on_before_ext_enabled(ext_id: str, *_): ExtensionManagerPip._process_ext_pipapi_config(ext_id) @staticmethod def _process_ext_pipapi_config(ext_id: str): # Get extension config manager = omni.kit.app.get_app().get_extension_manager() d = manager.get_extension_dict(ext_id) pip_dict = d.get("python", {}).get("pipapi", {}) # Add archive path. Relative path will be resolved relative to extension folder path. for path in pip_dict.get("archiveDirs", []): add_archive_directory(path, d["path"]) # Allows module names to be different to package names modules = pip_dict.get("modules", []) # Allows extra PIP repositores to be added extra_args = [] for line in pip_dict.get("repositories", []): extra_args.extend(["--extra-index-url", line]) # Allow extra args extra_args += pip_dict.get("extra_args", []) # Allow to ignore import check ignore_import_check = pip_dict.get("ignore_import_check", False) # Install packages (requirements) use_online_index = pip_dict.get("use_online_index", False) requirements = pip_dict.get("requirements", []) if requirements: # If use_online_index is not set, just ignore those entries. Otherwise they hide slowdowns on pip access for local only # search, which is not really used currently. if not use_online_index: logger.warning(f"extension {ext_id} has a [python.pipapi] entry, but use_online_index=true is not set. It doesn't do anything and can be removed.") return for idx, line in enumerate(requirements): module = modules[idx] if len(modules) > idx else None install(line, module, extra_args=extra_args, use_online_index=use_online_index, ignore_import_check=ignore_import_check)
14,494
Python
34.26764
208
0.641576
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/tests/__init__.py
from .test_pipapi import *
27
Python
12.999994
26
0.740741
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/tests/test_pipapi.py
import omni.kit.test import omni.kit.pipapi class TestPipApi(omni.kit.test.AsyncTestCase): async def test_pipapi_install(self): # Install simple package and import it. omni.kit.pipapi.install( "toml", version="0.10.1", ignore_import_check=True, ignore_cache=True ) # SWIPAT filed under: http://nvbugs/3060676 import toml self.assertIsNotNone(toml) async def test_pipapi_install_non_existing(self): res = omni.kit.pipapi.install("weird_package_name_2312515") self.assertFalse(res)
562
Python
28.631577
81
0.669039
omniverse-code/kit/exts/omni.ui/omni/ui/abstract_shade.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["AbstractShade"] from . import _ui as ui from collections import defaultdict from typing import Any from typing import Dict from typing import Optional import abc import weakref DEFAULT_SHADE = "default" class AbstractShade(metaclass=abc.ABCMeta): """ The implementation of shades for custom style parameter type. The user has to reimplement methods _store and _find to set/get the value in the specific store. """ class _ShadeName(str): """An str-like object with a custom method to edit shade""" def _keep_as_weak(self, shade: "AbstractShade"): # Shade here is omni.ui.color or omni.ui.url. Weak pointer prevents # circular references. self.__weak_shade = weakref.ref(shade) def add_shade(self, **kwargs): """Explicitly add additional color to the shade""" shade = self.__weak_shade() if not shade: return # Edit the shade shade.shade(name=self, **kwargs) def __init__(self): # Avoid calling AbstractShade.__setattr__ that sets the color in the Store super().__setattr__("_current_shade", DEFAULT_SHADE) super().__setattr__("_shades", defaultdict(dict)) # The list of dependencides. Example `cl.shade(0x0, light="background")` # makes dependency dict like this: # `{"background": ("shade:0x0;light=background")}` # We need it to update the shade once `background` is changed. # TODO: Clear the dict when the shade is updated. Example: after # `cl.bg = "red"; cl.bg = "green"` we will have two dependencies. super().__setattr__("_dependencies", defaultdict(set)) def __getattr__(self, name: str): # We need it for the syntax `style={"color": cl.bg_color}` result = AbstractShade._ShadeName(name) result._keep_as_weak(self) return result def __setattr__(self, name: str, value): if name in self.__dict__: # We are here because this class has the method variable. Set it. super().__setattr__(name, value) return if isinstance(value, str) and value in self._shades: # It's a shade. Redirect it to the coresponding method. self.shade(name=name, **self._shades[value]) else: # This class doesn't have this method variable. We need to set the # value in the Store. self.__set_value(name, {DEFAULT_SHADE: value}) def shade(self, default: Any = None, **kwargs) -> str: """Save the given shade, pick the color and apply it to ui.ColorStore.""" mangled_name = self.__mangle_name(default, kwargs, kwargs.pop("name", None)) shade = self._shades[mangled_name] shade.update(kwargs) if default is not None: shade[DEFAULT_SHADE] = default self.__set_value(mangled_name, shade) return mangled_name def set_shade(self, name: Optional[str] = None): """Set the default shade.""" if not name: name = DEFAULT_SHADE if name == self._current_shade: return self._current_shade = name for value_name, shade in self._shades.items(): self.__set_value(value_name, shade) def __mangle_name(self, default: Any, values: Dict[str, Any], name: Optional[str] = None) -> str: """Convert set of values to the shade name""" if name: return name mangled_name = "shade:" if isinstance(default, float) or isinstance(default, int): mangled_name += str(default) else: mangled_name += default for name in sorted(values.keys()): value = values[name] if mangled_name: mangled_name += ";" if isinstance(value, int): value = str(value) mangled_name += f"{name}={value}" return mangled_name def __set_value(self, name: str, shade: Dict[str, float]): """Pick the color from the given shade and set it to ui.ColorStore""" # Save dependencies for dependentName, dependentFloat in shade.items(): if isinstance(dependentFloat, str): self._dependencies[dependentFloat].add(name) value = shade.get(self._current_shade, shade.get(DEFAULT_SHADE)) if isinstance(value, str): # It's named color. We need to resolve it from ColorStore. found = self._find(value) if found is not None: value = found self._store(name, value) # Recursively replace all the values that refer to the current name if name in self._dependencies: for dependent in self._dependencies[name]: shade = self._shades.get(dependent, None) if shade: value = shade.get(self._current_shade, shade.get(DEFAULT_SHADE)) if value == name: self.__set_value(dependent, shade) @abc.abstractmethod def _find(self, name): pass @abc.abstractmethod def _store(self, name, value): pass
5,673
Python
34.024691
101
0.599859
omniverse-code/kit/exts/omni.ui/omni/ui/scene.py
# WAR `import omni.ui.scene` failure when `omni.ui.scene` was not enabled. # It happends during doc building, when running from python.bat, during stubgen, intellinse - anywhere that is not kit runtime from omni.ui_scene.scene import *
236
Python
58.249985
126
0.771186
omniverse-code/kit/exts/omni.ui/omni/ui/_ui.pyi
from __future__ import annotations import omni.ui._ui import typing import carb._carb import numpy import omni.appwindow._appwindow import omni.gpu_foundation_factory._gpu_foundation_factory _Shape = typing.Tuple[int, ...] __all__ = [ "AbstractField", "AbstractItem", "AbstractItemDelegate", "AbstractItemModel", "AbstractMultiField", "AbstractSlider", "AbstractValueModel", "Alignment", "ArrowHelper", "ArrowType", "Axis", "BezierCurve", "Button", "ByteImageProvider", "CanvasFrame", "CheckBox", "Circle", "CircleSizePolicy", "CollapsableFrame", "ColorStore", "ColorWidget", "ComboBox", "Container", "CornerFlag", "Direction", "DockPolicy", "DockPosition", "DockPreference", "DockSpace", "DynamicTextureProvider", "Ellipse", "FillPolicy", "FloatDrag", "FloatField", "FloatSlider", "FloatStore", "FocusPolicy", "FontStyle", "Fraction", "Frame", "FreeBezierCurve", "FreeCircle", "FreeEllipse", "FreeLine", "FreeRectangle", "FreeTriangle", "Grid", "HGrid", "HStack", "Image", "ImageProvider", "ImageWithProvider", "Inspector", "IntDrag", "IntField", "IntSlider", "InvisibleButton", "ItemModelHelper", "IwpFillPolicy", "Label", "Length", "Line", "MainWindow", "Menu", "MenuBar", "MenuDelegate", "MenuHelper", "MenuItem", "MenuItemCollection", "MultiFloatDragField", "MultiFloatField", "MultiIntDragField", "MultiIntField", "MultiStringField", "OffsetLine", "Percent", "Pixel", "Placer", "Plot", "ProgressBar", "RadioButton", "RadioCollection", "RasterImageProvider", "RasterPolicy", "Rectangle", "ScrollBarPolicy", "ScrollingFrame", "Separator", "ShadowFlag", "Shape", "SimpleBoolModel", "SimpleFloatModel", "SimpleIntModel", "SimpleStringModel", "SliderDrawMode", "Spacer", "Stack", "StringField", "StringStore", "Style", "ToolBar", "ToolBarAxis", "ToolButton", "TreeView", "Triangle", "Type", "UIntDrag", "UIntSlider", "UnitType", "VGrid", "VStack", "ValueModelHelper", "VectorImageProvider", "WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR", "WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR", "WINDOW_FLAGS_MENU_BAR", "WINDOW_FLAGS_MODAL", "WINDOW_FLAGS_NONE", "WINDOW_FLAGS_NO_BACKGROUND", "WINDOW_FLAGS_NO_CLOSE", "WINDOW_FLAGS_NO_COLLAPSE", "WINDOW_FLAGS_NO_DOCKING", "WINDOW_FLAGS_NO_FOCUS_ON_APPEARING", "WINDOW_FLAGS_NO_MOUSE_INPUTS", "WINDOW_FLAGS_NO_MOVE", "WINDOW_FLAGS_NO_RESIZE", "WINDOW_FLAGS_NO_SAVED_SETTINGS", "WINDOW_FLAGS_NO_SCROLLBAR", "WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE", "WINDOW_FLAGS_NO_TITLE_BAR", "WINDOW_FLAGS_POPUP", "WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR", "Widget", "WidgetMouseDropEvent", "Window", "WindowHandle", "Workspace", "ZStack", "dock_window_in_window", "get_custom_glyph_code", "get_main_window_height", "get_main_window_width" ] class AbstractField(Widget, ValueModelHelper): """ The abstract widget that is base for any field, which is a one-line text editor. A field allows the user to enter and edit a single line of plain text. It's implemented using the model-view pattern and uses AbstractValueModel as the central component of the system. """ def focus_keyboard(self, focus: bool = True) -> None: """ Puts cursor to this field or removes focus if focus """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class AbstractItem(): """ The object that is associated with the data entity of the AbstractItemModel. """ def __init__(self) -> None: ... pass class AbstractItemDelegate(): """ AbstractItemDelegate is used to generate widgets that display and edit data items from a model. """ def __init__(self) -> None: """ Constructs AbstractItemDelegate. `kwargs : dict` See below ### Keyword Arguments: """ def build_branch(self, model: AbstractItemModel, item: AbstractItem = None, column_id: int = 0, level: int = 0, expanded: bool = False) -> None: """ This pure abstract method must be reimplemented to generate custom collapse/expand button. """ def build_header(self, column_id: int = 0) -> None: """ This pure abstract method must be reimplemented to generate custom widgets for the header table. """ def build_widget(self, model: AbstractItemModel, item: AbstractItem = None, index: int = 0, level: int = 0, expanded: bool = False) -> None: """ This pure abstract method must be reimplemented to generate custom widgets for specific item in the model. """ pass class AbstractItemModel(): """ The central component of the item widget. It is the application's dynamic data structure, independent of the user interface, and it directly manages the nested data. It follows closely model-view pattern. It's abstract, and it defines the standard interface to be able to interoperate with the components of the model-view architecture. It is not supposed to be instantiated directly. Instead, the user should subclass it to create a new model. The item model doesn't return the data itself. Instead, it returns the value model that can contain any data type and supports callbacks. Thus the client of the model can track the changes in both the item model and any value it holds. From any item, the item model can get both the value model and the nested items. Therefore, the model is flexible to represent anything from color to complicated tree-table construction. """ def __init__(self) -> None: """ Constructs AbstractItemModel. `kwargs : dict` See below ### Keyword Arguments: """ def _item_changed(self, arg0: AbstractItem) -> None: ... def add_begin_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> int: """ Adds the function that will be called every time the user starts the editing. The id of the callback that is used to remove the callback. """ def add_end_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> int: """ Adds the function that will be called every time the user finishes the editing. The id of the callback that is used to remove the callback. """ def add_item_changed_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> int: """ Adds the function that will be called every time the value changes. The id of the callback that is used to remove the callback. """ def append_child_item(self, parentItem: AbstractItem, model: AbstractValueModel) -> AbstractItem: """ Creates a new item from the value model and appends it to the list of the children of the given item. """ def begin_edit(self, item: AbstractItem) -> None: """ Called when the user starts the editing. If it's a field, this method is called when the user activates the field and places the cursor inside. """ def can_item_have_children(self, parentItem: AbstractItem = None) -> bool: """ Returns true if the item can have children. In this way the delegate usually draws +/- icon. ### Arguments: `id :` The item to request children from. If it's null, the children of root will be returned. """ @typing.overload def drop(self, item_tagget: AbstractItem, item_source: AbstractItem, drop_location: int = -1) -> None: """ Called when the user droped one item to another. Small explanation why the same default value is declared in multiple places. We use the default value to be compatible with the previous API and especially with Stage 2.0. Thr signature in the old Python API is: def drop(self, target_item, source) drop(self, target_item, source) PyAbstractItemModel::drop AbstractItemModel.drop pybind11::class_<AbstractItemModel>.def("drop") AbstractItemModel Called when the user droped a string to the item. """ @typing.overload def drop(self, item_tagget: AbstractItem, source: str, drop_location: int = -1) -> None: ... @typing.overload def drop_accepted(self, item_tagget: AbstractItem, item_source: AbstractItem, drop_location: int = -1) -> bool: """ Called to determine if the model can perform drag and drop to the given item. If this method returns false, the widget shouldn't highlight the visual element that represents this item. Called to determine if the model can perform drag and drop of the given string to the given item. If this method returns false, the widget shouldn't highlight the visual element that represents this item. """ @typing.overload def drop_accepted(self, item_tagget: AbstractItem, source: str, drop_location: int = -1) -> bool: ... def end_edit(self, item: AbstractItem) -> None: """ Called when the user finishes the editing. If it's a field, this method is called when the user presses Enter or selects another field for editing. It's useful for undo/redo. """ def get_drag_mime_data(self, item: AbstractItem = None) -> str: """ Returns Multipurpose Internet Mail Extensions (MIME) for drag and drop. """ def get_item_children(self, parentItem: AbstractItem = None) -> typing.List[AbstractItem]: """ Returns the vector of items that are nested to the given parent item. ### Arguments: `id :` The item to request children from. If it's null, the children of root will be returned. """ def get_item_value_model(self, item: AbstractItem = None, column_id: int = 0) -> AbstractValueModel: """ Get the value model associated with this item. ### Arguments: `item :` The item to request the value model from. If it's null, the root value model will be returned. `index :` The column number to get the value model. """ def get_item_value_model_count(self, item: AbstractItem = None) -> int: """ Returns the number of columns this model item contains. """ def remove_begin_edit_fn(self, arg0: int) -> None: """ Remove the callback by its id. ### Arguments: `id :` The id that addBeginEditFn returns. """ def remove_end_edit_fn(self, arg0: int) -> None: """ Remove the callback by its id. ### Arguments: `id :` The id that addEndEditFn returns. """ def remove_item(self, item: AbstractItem) -> None: """ Removes the item from the model. There is no parent here because we assume that the reimplemented model deals with its data and can figure out how to remove this item. """ def remove_item_changed_fn(self, arg0: int) -> None: """ Remove the callback by its id. ### Arguments: `id :` The id that addValueChangedFn returns. """ def subscribe_begin_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> carb._carb.Subscription: """ Adds the function that will be called every time the user starts the editing. The id of the callback that is used to remove the callback. """ def subscribe_end_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> carb._carb.Subscription: """ Adds the function that will be called every time the user finishes the editing. The id of the callback that is used to remove the callback. """ def subscribe_item_changed_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> carb._carb.Subscription: """ Adds the function that will be called every time the value changes. The id of the callback that is used to remove the callback. """ pass class AbstractMultiField(Widget, ItemModelHelper): """ AbstractMultiField is the abstract class that has everything to create a custom widget per model item. The class that wants to create multiple widgets per item needs to reimplement the method _createField. """ @property def column_count(self) -> int: """ The max number of fields in a line. :type: int """ @column_count.setter def column_count(self, arg1: int) -> None: """ The max number of fields in a line. """ @property def h_spacing(self) -> float: """ Sets a non-stretchable horizontal space in pixels between child fields. :type: float """ @h_spacing.setter def h_spacing(self, arg1: float) -> None: """ Sets a non-stretchable horizontal space in pixels between child fields. """ @property def v_spacing(self) -> float: """ Sets a non-stretchable vertical space in pixels between child fields. :type: float """ @v_spacing.setter def v_spacing(self, arg1: float) -> None: """ Sets a non-stretchable vertical space in pixels between child fields. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class AbstractSlider(Widget, ValueModelHelper): """ The abstract widget that is base for drags and sliders. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class AbstractValueModel(): """ """ def __init__(self) -> None: """ Constructs AbstractValueModel. `kwargs : dict` See below ### Keyword Arguments: """ def _value_changed(self) -> None: """ Called when any data of the model is changed. It will notify the subscribed widgets. """ def add_begin_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> int: """ Adds the function that will be called every time the user starts the editing. The id of the callback that is used to remove the callback. """ def add_end_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> int: """ Adds the function that will be called every time the user finishes the editing. The id of the callback that is used to remove the callback. """ def add_value_changed_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> int: """ Adds the function that will be called every time the value changes. The id of the callback that is used to remove the callback. """ def begin_edit(self) -> None: """ Called when the user starts the editing. If it's a field, this method is called when the user activates the field and places the cursor inside. This method should be reimplemented. """ def end_edit(self) -> None: """ Called when the user finishes the editing. If it's a field, this method is called when the user presses Enter or selects another field for editing. It's useful for undo/redo. This method should be reimplemented. """ def get_value_as_bool(self) -> bool: """ Return the bool representation of the value. """ def get_value_as_float(self) -> float: """ Return the float representation of the value. """ def get_value_as_int(self) -> int: """ Return the int representation of the value. """ def get_value_as_string(self) -> str: """ Return the string representation of the value. """ def remove_begin_edit_fn(self, arg0: int) -> None: """ Remove the callback by its id. ### Arguments: `id :` The id that addBeginEditFn returns. """ def remove_end_edit_fn(self, arg0: int) -> None: """ Remove the callback by its id. ### Arguments: `id :` The id that addEndEditFn returns. """ def remove_value_changed_fn(self, arg0: int) -> None: """ Remove the callback by its id. ### Arguments: `id :` The id that addValueChangedFn returns. """ @typing.overload def set_value(self, value: bool) -> None: """ Set the value. Set the value. Set the value. Set the value. """ @typing.overload def set_value(self, value: int) -> None: ... @typing.overload def set_value(self, value: float) -> None: ... @typing.overload def set_value(self, value: str) -> None: ... def subscribe_begin_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription: """ Adds the function that will be called every time the user starts the editing. The id of the callback that is used to remove the callback. """ def subscribe_end_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription: """ Adds the function that will be called every time the user finishes the editing. The id of the callback that is used to remove the callback. """ def subscribe_item_changed_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription: ... def subscribe_value_changed_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription: """ Adds the function that will be called every time the value changes. The id of the callback that is used to remove the callback. """ @property def as_bool(self) -> bool: """ Return the bool representation of the value. :type: bool """ @as_bool.setter def as_bool(self, arg1: bool) -> None: """ Return the bool representation of the value. """ @property def as_float(self) -> float: """ Return the float representation of the value. :type: float """ @as_float.setter def as_float(self, arg1: float) -> None: """ Return the float representation of the value. """ @property def as_int(self) -> int: """ Return the int representation of the value. :type: int """ @as_int.setter def as_int(self, arg1: int) -> None: """ Return the int representation of the value. """ @property def as_string(self) -> str: """ Return the string representation of the value. :type: str """ @as_string.setter def as_string(self, arg1: str) -> None: """ Return the string representation of the value. """ pass class Alignment(): """ Members: UNDEFINED LEFT_TOP LEFT_CENTER LEFT_BOTTOM CENTER_TOP CENTER CENTER_BOTTOM RIGHT_TOP RIGHT_CENTER RIGHT_BOTTOM LEFT RIGHT H_CENTER TOP BOTTOM V_CENTER """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ BOTTOM: omni.ui._ui.Alignment # value = <Alignment.BOTTOM: 32> CENTER: omni.ui._ui.Alignment # value = <Alignment.CENTER: 72> CENTER_BOTTOM: omni.ui._ui.Alignment # value = <Alignment.CENTER_BOTTOM: 40> CENTER_TOP: omni.ui._ui.Alignment # value = <Alignment.CENTER_TOP: 24> H_CENTER: omni.ui._ui.Alignment # value = <Alignment.H_CENTER: 8> LEFT: omni.ui._ui.Alignment # value = <Alignment.LEFT: 2> LEFT_BOTTOM: omni.ui._ui.Alignment # value = <Alignment.LEFT_BOTTOM: 34> LEFT_CENTER: omni.ui._ui.Alignment # value = <Alignment.LEFT_CENTER: 66> LEFT_TOP: omni.ui._ui.Alignment # value = <Alignment.LEFT_TOP: 18> RIGHT: omni.ui._ui.Alignment # value = <Alignment.RIGHT: 4> RIGHT_BOTTOM: omni.ui._ui.Alignment # value = <Alignment.RIGHT_BOTTOM: 36> RIGHT_CENTER: omni.ui._ui.Alignment # value = <Alignment.RIGHT_CENTER: 68> RIGHT_TOP: omni.ui._ui.Alignment # value = <Alignment.RIGHT_TOP: 20> TOP: omni.ui._ui.Alignment # value = <Alignment.TOP: 16> UNDEFINED: omni.ui._ui.Alignment # value = <Alignment.UNDEFINED: 0> V_CENTER: omni.ui._ui.Alignment # value = <Alignment.V_CENTER: 64> __members__: dict # value = {'UNDEFINED': <Alignment.UNDEFINED: 0>, 'LEFT_TOP': <Alignment.LEFT_TOP: 18>, 'LEFT_CENTER': <Alignment.LEFT_CENTER: 66>, 'LEFT_BOTTOM': <Alignment.LEFT_BOTTOM: 34>, 'CENTER_TOP': <Alignment.CENTER_TOP: 24>, 'CENTER': <Alignment.CENTER: 72>, 'CENTER_BOTTOM': <Alignment.CENTER_BOTTOM: 40>, 'RIGHT_TOP': <Alignment.RIGHT_TOP: 20>, 'RIGHT_CENTER': <Alignment.RIGHT_CENTER: 68>, 'RIGHT_BOTTOM': <Alignment.RIGHT_BOTTOM: 36>, 'LEFT': <Alignment.LEFT: 2>, 'RIGHT': <Alignment.RIGHT: 4>, 'H_CENTER': <Alignment.H_CENTER: 8>, 'TOP': <Alignment.TOP: 16>, 'BOTTOM': <Alignment.BOTTOM: 32>, 'V_CENTER': <Alignment.V_CENTER: 64>} pass class ArrowHelper(): """ The ArrowHelper widget provides a colored rectangle to display. """ @property def begin_arrow_height(self) -> float: """ This property holds the height of the begin arrow. :type: float """ @begin_arrow_height.setter def begin_arrow_height(self, arg1: float) -> None: """ This property holds the height of the begin arrow. """ @property def begin_arrow_type(self) -> ArrowType: """ This property holds the type of the begin arrow can only be eNone or eRrrow. By default, the arrow type is eNone. :type: ArrowType """ @begin_arrow_type.setter def begin_arrow_type(self, arg1: ArrowType) -> None: """ This property holds the type of the begin arrow can only be eNone or eRrrow. By default, the arrow type is eNone. """ @property def begin_arrow_width(self) -> float: """ This property holds the width of the begin arrow. :type: float """ @begin_arrow_width.setter def begin_arrow_width(self, arg1: float) -> None: """ This property holds the width of the begin arrow. """ @property def end_arrow_height(self) -> float: """ This property holds the height of the end arrow. :type: float """ @end_arrow_height.setter def end_arrow_height(self, arg1: float) -> None: """ This property holds the height of the end arrow. """ @property def end_arrow_type(self) -> ArrowType: """ This property holds the type of the end arrow can only be eNone or eRrrow. By default, the arrow type is eNone. :type: ArrowType """ @end_arrow_type.setter def end_arrow_type(self, arg1: ArrowType) -> None: """ This property holds the type of the end arrow can only be eNone or eRrrow. By default, the arrow type is eNone. """ @property def end_arrow_width(self) -> float: """ This property holds the width of the end arrow. :type: float """ @end_arrow_width.setter def end_arrow_width(self, arg1: float) -> None: """ This property holds the width of the end arrow. """ pass class ArrowType(): """ Members: NONE ARROW """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ ARROW: omni.ui._ui.ArrowType # value = <ArrowType.ARROW: 1> NONE: omni.ui._ui.ArrowType # value = <ArrowType.NONE: 0> __members__: dict # value = {'NONE': <ArrowType.NONE: 0>, 'ARROW': <ArrowType.ARROW: 1>} pass class Axis(): """ Members: None X Y XY """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ None: omni.ui._ui.Axis # value = <Axis.None: 0> X: omni.ui._ui.Axis # value = <Axis.X: 1> XY: omni.ui._ui.Axis # value = <Axis.XY: 3> Y: omni.ui._ui.Axis # value = <Axis.Y: 2> __members__: dict # value = {'None': <Axis.None: 0>, 'X': <Axis.X: 1>, 'Y': <Axis.Y: 2>, 'XY': <Axis.XY: 3>} pass class BezierCurve(Shape, Widget, ArrowHelper): """ Smooth curve that can be scaled infinitely. """ def __init__(self, **kwargs) -> None: ... def call_mouse_hovered_fn(self, arg0: bool) -> None: """ Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered) """ def has_mouse_hovered_fn(self) -> bool: """ Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered) """ def set_mouse_hovered_fn(self, fn: typing.Callable[[bool], None]) -> None: """ Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered) """ @property def end_tangent_height(self) -> Length: """ This property holds the Y coordinate of the end of the curve relative to the width bound of the curve. :type: Length """ @end_tangent_height.setter def end_tangent_height(self, arg1: Length) -> None: """ This property holds the Y coordinate of the end of the curve relative to the width bound of the curve. """ @property def end_tangent_width(self) -> Length: """ This property holds the X coordinate of the end of the curve relative to the width bound of the curve. :type: Length """ @end_tangent_width.setter def end_tangent_width(self, arg1: Length) -> None: """ This property holds the X coordinate of the end of the curve relative to the width bound of the curve. """ @property def start_tangent_height(self) -> Length: """ This property holds the Y coordinate of the start of the curve relative to the width bound of the curve. :type: Length """ @start_tangent_height.setter def start_tangent_height(self, arg1: Length) -> None: """ This property holds the Y coordinate of the start of the curve relative to the width bound of the curve. """ @property def start_tangent_width(self) -> Length: """ This property holds the X coordinate of the start of the curve relative to the width bound of the curve. :type: Length """ @start_tangent_width.setter def start_tangent_width(self, arg1: Length) -> None: """ This property holds the X coordinate of the start of the curve relative to the width bound of the curve. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Button(InvisibleButton, Widget): """ The Button widget provides a command button. The command button, is perhaps the most commonly used widget in any graphical user interface. Click a button to execute a command. It is rectangular and typically displays a text label describing its action. """ def __init__(self, text: str = '', **kwargs) -> None: """ Construct a button with a text on it. ### Arguments: `text :` The text for the button to use. `kwargs : dict` See below ### Keyword Arguments: `text : str` This property holds the button's text. `image_url : str` This property holds the button's optional image URL. `image_width : float` This property holds the width of the image widget. Do not use this function to find the width of the image. `image_height : float` This property holds the height of the image widget. Do not use this function to find the height of the image. `spacing : float` Sets a non-stretchable space in points between image and text. `clicked_fn : Callable[[], None]` Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button). `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def image_height(self) -> Length: """ This property holds the height of the image widget. Do not use this function to find the height of the image. :type: Length """ @image_height.setter def image_height(self, arg1: Length) -> None: """ This property holds the height of the image widget. Do not use this function to find the height of the image. """ @property def image_url(self) -> str: """ This property holds the button's optional image URL. :type: str """ @image_url.setter def image_url(self, arg1: str) -> None: """ This property holds the button's optional image URL. """ @property def image_width(self) -> Length: """ This property holds the width of the image widget. Do not use this function to find the width of the image. :type: Length """ @image_width.setter def image_width(self, arg1: Length) -> None: """ This property holds the width of the image widget. Do not use this function to find the width of the image. """ @property def spacing(self) -> float: """ Sets a non-stretchable space in points between image and text. :type: float """ @spacing.setter def spacing(self, arg1: float) -> None: """ Sets a non-stretchable space in points between image and text. """ @property def text(self) -> str: """ This property holds the button's text. :type: str """ @text.setter def text(self, arg1: str) -> None: """ This property holds the button's text. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ByteImageProvider(ImageProvider): """ doc """ @typing.overload def __init__(self) -> None: """ doc doc """ @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: ... @staticmethod def set_bytes_data(*args, **kwargs) -> typing.Any: """ Sets Python sequence as byte data. The image provider will recognize flattened color values, or sequence within sequence and convert it into an image. """ def set_bytes_data_from_gpu(self, gpu_bytes: int, sizes: typing.List[int], format: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat = TextureFormat.RGBA8_UNORM, stride: int = -1) -> None: """ Sets byte data from a copy of gpu memory at gpuBytes. """ def set_data(self, arg0: typing.List[int], arg1: typing.List[int]) -> None: """ [DEPRECATED FUNCTION] """ def set_data_array(self, arg0: numpy.ndarray[numpy.uint8], arg1: typing.List[int]) -> None: ... def set_raw_bytes_data(self, raw_bytes: capsule, sizes: typing.List[int], format: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat = TextureFormat.RGBA8_UNORM, stride: int = -1) -> None: """ Sets byte data that the image provider will turn raw pointer array into an image. """ pass class CanvasFrame(Frame, Container, Widget): """ CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has the layout that can be infinitely moved in any direction. """ def __init__(self, **kwargs) -> None: """ Constructs CanvasFrame. `kwargs : dict` See below ### Keyword Arguments: `pan_x : ` The horizontal offset of the child item. `pan_y : ` The vertical offset of the child item. `zoom : ` The zoom minimum of the child item. `zoom_min : ` The zoom maximum of the child item. `zoom_max : ` The zoom level of the child item. `compatibility : ` This boolean property controls the behavior of CanvasFrame. When set to true, the widget will function in the old way. When set to false, the widget will use a newer and faster implementation. This variable is included as a transition period to ensure that the update does not break any existing functionality. Please be aware that the old behavior may be deprecated in the future, so it is recommended to set this variable to false once you have thoroughly tested the new implementation. `pan_x_changed_fn : ` The horizontal offset of the child item. `pan_y_changed_fn : ` The vertical offset of the child item. `zoom_changed_fn : ` The zoom level of the child item. `draggable : ` Provides a convenient way to make the content draggable and zoomable. `horizontal_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction. `vertical_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction. `separate_window : ` A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. `raster_policy : ` Determine how the content of the frame should be rasterized. `build_fn : ` Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def screen_to_canvas(self, x: float, y: float) -> typing.Tuple[float, float]: """ Transforms screen-space coordinates to canvas-space """ def screen_to_canvas_x(self, x: float) -> float: """ Transforms screen-space X to canvas-space X. """ def screen_to_canvas_y(self, y: float) -> float: """ Transforms screen-space Y to canvas-space Y. """ def set_pan_key_shortcut(self, mouse_button: int, key_flag: int) -> None: """ Specify the mouse button and key to pan the canvas. """ def set_pan_x_changed_fn(self, fn: typing.Callable[[float], None]) -> None: """ The horizontal offset of the child item. """ def set_pan_y_changed_fn(self, fn: typing.Callable[[float], None]) -> None: """ The vertical offset of the child item. """ def set_zoom_changed_fn(self, fn: typing.Callable[[float], None]) -> None: """ The zoom level of the child item. """ def set_zoom_key_shortcut(self, mouse_button: int, key_flag: int) -> None: """ Specify the mouse button and key to zoom the canvas. """ @property def compatibility(self) -> bool: """ This boolean property controls the behavior of CanvasFrame. When set to true, the widget will function in the old way. When set to false, the widget will use a newer and faster implementation. This variable is included as a transition period to ensure that the update does not break any existing functionality. Please be aware that the old behavior may be deprecated in the future, so it is recommended to set this variable to false once you have thoroughly tested the new implementation. :type: bool """ @compatibility.setter def compatibility(self, arg1: bool) -> None: """ This boolean property controls the behavior of CanvasFrame. When set to true, the widget will function in the old way. When set to false, the widget will use a newer and faster implementation. This variable is included as a transition period to ensure that the update does not break any existing functionality. Please be aware that the old behavior may be deprecated in the future, so it is recommended to set this variable to false once you have thoroughly tested the new implementation. """ @property def draggable(self) -> bool: """ Provides a convenient way to make the content draggable and zoomable. :type: bool """ @draggable.setter def draggable(self, arg1: bool) -> None: """ Provides a convenient way to make the content draggable and zoomable. """ @property def pan_x(self) -> float: """ The horizontal offset of the child item. :type: float """ @pan_x.setter def pan_x(self, arg1: float) -> None: """ The horizontal offset of the child item. """ @property def pan_y(self) -> float: """ The vertical offset of the child item. :type: float """ @pan_y.setter def pan_y(self, arg1: float) -> None: """ The vertical offset of the child item. """ @property def smooth_zoom(self) -> bool: """ When true, zoom is smooth like in Bifrost even if the user is using mouse wheen that doesn't provide smooth scrolling. :type: bool """ @smooth_zoom.setter def smooth_zoom(self, arg1: bool) -> None: """ When true, zoom is smooth like in Bifrost even if the user is using mouse wheen that doesn't provide smooth scrolling. """ @property def zoom(self) -> float: """ The zoom level of the child item. :type: float """ @zoom.setter def zoom(self, arg1: float) -> None: """ The zoom level of the child item. """ @property def zoom_max(self) -> float: """ The zoom maximum of the child item. :type: float """ @zoom_max.setter def zoom_max(self, arg1: float) -> None: """ The zoom maximum of the child item. """ @property def zoom_min(self) -> float: """ The zoom minimum of the child item. :type: float """ @zoom_min.setter def zoom_min(self, arg1: float) -> None: """ The zoom minimum of the child item. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class CheckBox(Widget, ValueModelHelper): """ A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are typically used to represent features in an application that can be enabled or disabled without affecting others. The checkbox is implemented using the model-view pattern. The model is the central component of this system. It is the application's dynamic data structure independent of the widget. It directly manages the data, logic, and rules of the checkbox. If the model is not specified, the simple one is created automatically when the object is constructed. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ CheckBox with specified model. If model is not specified, it's using the default one. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Circle(Shape, Widget): """ The Circle widget provides a colored circle to display. """ def __init__(self, **kwargs) -> None: """ Constructs Circle. `kwargs : dict` See below ### Keyword Arguments: `alignment :` This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered. `radius :` This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0. `arc :` This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered. `size_policy :` Define what happens when the source image has a different size than the item. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def alignment(self) -> Alignment: """ This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered. :type: Alignment """ @alignment.setter def alignment(self, arg1: Alignment) -> None: """ This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered. """ @property def arc(self) -> Alignment: """ This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered. :type: Alignment """ @arc.setter def arc(self, arg1: Alignment) -> None: """ This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered. """ @property def radius(self) -> float: """ This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0. :type: float """ @radius.setter def radius(self, arg1: float) -> None: """ This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0. """ @property def size_policy(self) -> CircleSizePolicy: """ Define what happens when the source image has a different size than the item. :type: CircleSizePolicy """ @size_policy.setter def size_policy(self, arg1: CircleSizePolicy) -> None: """ Define what happens when the source image has a different size than the item. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class CircleSizePolicy(): """ Define what happens when the source image has a different size than the item. Members: STRETCH FIXED """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ FIXED: omni.ui._ui.CircleSizePolicy # value = <CircleSizePolicy.FIXED: 1> STRETCH: omni.ui._ui.CircleSizePolicy # value = <CircleSizePolicy.STRETCH: 0> __members__: dict # value = {'STRETCH': <CircleSizePolicy.STRETCH: 0>, 'FIXED': <CircleSizePolicy.FIXED: 1>} pass class CollapsableFrame(Frame, Container, Widget): """ CollapsableFrame is a frame widget that can hide or show its content. It has two states expanded and collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a frame with the content. It's handy to group properties, and temporarily hide them to get more space for something else. """ def __init__(self, title: str = '', **kwargs) -> None: """ Constructs CollapsableFrame. ### Arguments: `text :` The text for the caption of the frame. `kwargs : dict` See below ### Keyword Arguments: `collapsed : ` The state of the CollapsableFrame. `title : ` The header text. `alignment : ` This property holds the alignment of the label in the default header. By default, the contents of the label are left-aligned and vertically-centered. `build_header_fn : ` Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly. `collapsed_changed_fn : ` The state of the CollapsableFrame. `horizontal_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction. `vertical_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction. `separate_window : ` A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. `raster_policy : ` Determine how the content of the frame should be rasterized. `build_fn : ` Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def call_build_header_fn(self, arg0: bool, arg1: str) -> None: """ Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly. """ def has_build_header_fn(self) -> bool: """ Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly. """ def set_build_header_fn(self, fn: typing.Callable[[bool, str], None]) -> None: """ Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly. """ def set_collapsed_changed_fn(self, fn: typing.Callable[[bool], None]) -> None: """ The state of the CollapsableFrame. """ @property def alignment(self) -> Alignment: """ This property holds the alignment of the label in the default header. By default, the contents of the label are left-aligned and vertically-centered. :type: Alignment """ @alignment.setter def alignment(self, arg1: Alignment) -> None: """ This property holds the alignment of the label in the default header. By default, the contents of the label are left-aligned and vertically-centered. """ @property def collapsed(self) -> bool: """ The state of the CollapsableFrame. :type: bool """ @collapsed.setter def collapsed(self, arg1: bool) -> None: """ The state of the CollapsableFrame. """ @property def title(self) -> str: """ The header text. :type: str """ @title.setter def title(self, arg1: str) -> None: """ The header text. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ColorStore(): """ A singleton that stores all the UI Style color properties of omni.ui. """ @staticmethod def find(name: str) -> int: """ Return the index of the color with specific name. """ @staticmethod def store(name: str, color: int) -> None: """ Save the color by name. """ pass class ColorWidget(Widget, ItemModelHelper): """ The ColorWidget widget is a button that displays the color from the item model and can open a picker window to change the color. """ @typing.overload def __init__(self, **kwargs) -> None: """ Construct ColorWidget. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, **kwargs) -> None: ... @typing.overload def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float, **kwargs) -> None: ... FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ComboBox(Widget, ItemModelHelper): """ The ComboBox widget is a combined button and a drop-down list. A combo box is a selection widget that displays the current item and can pop up a list of selectable items. The ComboBox is implemented using the model-view pattern. The model is the central component of this system. The root of the item model should contain the index of currently selected items, and the children of the root include all the items of the combo box. """ def __init__(self, *args, **kwargs) -> None: """ Construct ComboBox. ### Arguments: `model :` The model that determines if the button is checked. `kwargs : dict` See below ### Keyword Arguments: `arrow_only : bool` Determines if it's necessary to hide the text of the ComboBox. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Container(Widget): """ Base class for all UI containers. Container can hold one or many other :class:`omni.ui.Widget` s """ def __enter__(self) -> None: ... def __exit__(self, arg0: object, arg1: object, arg2: object) -> None: ... def add_child(self, arg0: Widget) -> None: """ Adds widget to this container in a manner specific to the container. If it's allowed to have one sub-widget only, it will be overwriten. """ def clear(self) -> None: """ Removes the container items from the container. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class CornerFlag(): """ Members: NONE TOP_LEFT TOP_RIGHT BOTTOM_LEFT BOTTOM_RIGHT TOP BOTTOM LEFT RIGHT ALL """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ ALL: omni.ui._ui.CornerFlag # value = <CornerFlag.ALL: 15> BOTTOM: omni.ui._ui.CornerFlag # value = <CornerFlag.BOTTOM: 12> BOTTOM_LEFT: omni.ui._ui.CornerFlag # value = <CornerFlag.BOTTOM_LEFT: 4> BOTTOM_RIGHT: omni.ui._ui.CornerFlag # value = <CornerFlag.BOTTOM_RIGHT: 8> LEFT: omni.ui._ui.CornerFlag # value = <CornerFlag.LEFT: 5> NONE: omni.ui._ui.CornerFlag # value = <CornerFlag.NONE: 0> RIGHT: omni.ui._ui.CornerFlag # value = <CornerFlag.RIGHT: 10> TOP: omni.ui._ui.CornerFlag # value = <CornerFlag.TOP: 3> TOP_LEFT: omni.ui._ui.CornerFlag # value = <CornerFlag.TOP_LEFT: 1> TOP_RIGHT: omni.ui._ui.CornerFlag # value = <CornerFlag.TOP_RIGHT: 2> __members__: dict # value = {'NONE': <CornerFlag.NONE: 0>, 'TOP_LEFT': <CornerFlag.TOP_LEFT: 1>, 'TOP_RIGHT': <CornerFlag.TOP_RIGHT: 2>, 'BOTTOM_LEFT': <CornerFlag.BOTTOM_LEFT: 4>, 'BOTTOM_RIGHT': <CornerFlag.BOTTOM_RIGHT: 8>, 'TOP': <CornerFlag.TOP: 3>, 'BOTTOM': <CornerFlag.BOTTOM: 12>, 'LEFT': <CornerFlag.LEFT: 5>, 'RIGHT': <CornerFlag.RIGHT: 10>, 'ALL': <CornerFlag.ALL: 15>} pass class Direction(): """ Members: LEFT_TO_RIGHT RIGHT_TO_LEFT TOP_TO_BOTTOM BOTTOM_TO_TOP BACK_TO_FRONT FRONT_TO_BACK """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ BACK_TO_FRONT: omni.ui._ui.Direction # value = <Direction.BACK_TO_FRONT: 4> BOTTOM_TO_TOP: omni.ui._ui.Direction # value = <Direction.BOTTOM_TO_TOP: 3> FRONT_TO_BACK: omni.ui._ui.Direction # value = <Direction.FRONT_TO_BACK: 5> LEFT_TO_RIGHT: omni.ui._ui.Direction # value = <Direction.LEFT_TO_RIGHT: 0> RIGHT_TO_LEFT: omni.ui._ui.Direction # value = <Direction.RIGHT_TO_LEFT: 1> TOP_TO_BOTTOM: omni.ui._ui.Direction # value = <Direction.TOP_TO_BOTTOM: 2> __members__: dict # value = {'LEFT_TO_RIGHT': <Direction.LEFT_TO_RIGHT: 0>, 'RIGHT_TO_LEFT': <Direction.RIGHT_TO_LEFT: 1>, 'TOP_TO_BOTTOM': <Direction.TOP_TO_BOTTOM: 2>, 'BOTTOM_TO_TOP': <Direction.BOTTOM_TO_TOP: 3>, 'BACK_TO_FRONT': <Direction.BACK_TO_FRONT: 4>, 'FRONT_TO_BACK': <Direction.FRONT_TO_BACK: 5>} pass class DockPolicy(): """ Members: DO_NOTHING CURRENT_WINDOW_IS_ACTIVE TARGET_WINDOW_IS_ACTIVE """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ CURRENT_WINDOW_IS_ACTIVE: omni.ui._ui.DockPolicy # value = <DockPolicy.CURRENT_WINDOW_IS_ACTIVE: 1> DO_NOTHING: omni.ui._ui.DockPolicy # value = <DockPolicy.DO_NOTHING: 0> TARGET_WINDOW_IS_ACTIVE: omni.ui._ui.DockPolicy # value = <DockPolicy.TARGET_WINDOW_IS_ACTIVE: 2> __members__: dict # value = {'DO_NOTHING': <DockPolicy.DO_NOTHING: 0>, 'CURRENT_WINDOW_IS_ACTIVE': <DockPolicy.CURRENT_WINDOW_IS_ACTIVE: 1>, 'TARGET_WINDOW_IS_ACTIVE': <DockPolicy.TARGET_WINDOW_IS_ACTIVE: 2>} pass class DockPosition(): """ Members: RIGHT LEFT TOP BOTTOM SAME """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ BOTTOM: omni.ui._ui.DockPosition # value = <DockPosition.BOTTOM: 3> LEFT: omni.ui._ui.DockPosition # value = <DockPosition.LEFT: 0> RIGHT: omni.ui._ui.DockPosition # value = <DockPosition.RIGHT: 1> SAME: omni.ui._ui.DockPosition # value = <DockPosition.SAME: 4> TOP: omni.ui._ui.DockPosition # value = <DockPosition.TOP: 2> __members__: dict # value = {'RIGHT': <DockPosition.RIGHT: 1>, 'LEFT': <DockPosition.LEFT: 0>, 'TOP': <DockPosition.TOP: 2>, 'BOTTOM': <DockPosition.BOTTOM: 3>, 'SAME': <DockPosition.SAME: 4>} pass class DockPreference(): """ Members: DISABLED MAIN RIGHT LEFT RIGHT_TOP RIGHT_BOTTOM LEFT_BOTTOM """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ DISABLED: omni.ui._ui.DockPreference # value = <DockPreference.DISABLED: 0> LEFT: omni.ui._ui.DockPreference # value = <DockPreference.LEFT: 3> LEFT_BOTTOM: omni.ui._ui.DockPreference # value = <DockPreference.LEFT_BOTTOM: 6> MAIN: omni.ui._ui.DockPreference # value = <DockPreference.MAIN: 1> RIGHT: omni.ui._ui.DockPreference # value = <DockPreference.RIGHT: 2> RIGHT_BOTTOM: omni.ui._ui.DockPreference # value = <DockPreference.RIGHT_BOTTOM: 5> RIGHT_TOP: omni.ui._ui.DockPreference # value = <DockPreference.RIGHT_TOP: 4> __members__: dict # value = {'DISABLED': <DockPreference.DISABLED: 0>, 'MAIN': <DockPreference.MAIN: 1>, 'RIGHT': <DockPreference.RIGHT: 2>, 'LEFT': <DockPreference.LEFT: 3>, 'RIGHT_TOP': <DockPreference.RIGHT_TOP: 4>, 'RIGHT_BOTTOM': <DockPreference.RIGHT_BOTTOM: 5>, 'LEFT_BOTTOM': <DockPreference.LEFT_BOTTOM: 6>} pass class DockSpace(): """ The DockSpace class represents Dock Space for the OS Window. """ def __init__(self, arg0: object, **kwargs) -> None: """ Construct the main window, add it to the underlying windowing system, and makes it appear. `kwargs : dict` See below ### Keyword Arguments: """ @property def dock_frame(self) -> Frame: """ This represents Styling opportunity for the Window background. :type: Frame """ pass class DynamicTextureProvider(ByteImageProvider, ImageProvider): """ doc """ def __init__(self, arg0: str) -> None: """ doc """ pass class Ellipse(Shape, Widget): """ Constructs Ellipse. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def __init__(self, **kwargs) -> None: ... FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FillPolicy(): """ Members: STRETCH PRESERVE_ASPECT_FIT PRESERVE_ASPECT_CROP """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ PRESERVE_ASPECT_CROP: omni.ui._ui.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_CROP: 2> PRESERVE_ASPECT_FIT: omni.ui._ui.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_FIT: 1> STRETCH: omni.ui._ui.FillPolicy # value = <FillPolicy.STRETCH: 0> __members__: dict # value = {'STRETCH': <FillPolicy.STRETCH: 0>, 'PRESERVE_ASPECT_FIT': <FillPolicy.PRESERVE_ASPECT_FIT: 1>, 'PRESERVE_ASPECT_CROP': <FillPolicy.PRESERVE_ASPECT_CROP: 2>} pass class FloatDrag(FloatSlider, AbstractSlider, Widget, ValueModelHelper): """ The drag widget that looks like a field but it's possible to change the value with dragging. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Construct FloatDrag. `kwargs : dict` See below ### Keyword Arguments: `min : float` This property holds the slider's minimum value. `max : float` This property holds the slider's maximum value. `step : float` This property controls the steping speed on the drag. `format : str` This property overrides automatic formatting if needed. `precision : uint32_t` This property holds the slider value's float precision. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FloatField(AbstractField, Widget, ValueModelHelper): """ The FloatField widget is a one-line text editor with a string model. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Construct FloatField. `kwargs : dict` See below ### Keyword Arguments: `precision : uint32_t` This property holds the field value's float precision. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def precision(self) -> int: """ This property holds the field value's float precision. :type: int """ @precision.setter def precision(self, arg1: int) -> None: """ This property holds the field value's float precision. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FloatSlider(AbstractSlider, Widget, ValueModelHelper): """ The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along a horizontal groove and translates the handle's position into a float value within the legal range. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Construct FloatSlider. `kwargs : dict` See below ### Keyword Arguments: `min : float` This property holds the slider's minimum value. `max : float` This property holds the slider's maximum value. `step : float` This property controls the steping speed on the drag. `format : str` This property overrides automatic formatting if needed. `precision : uint32_t` This property holds the slider value's float precision. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def format(self) -> str: """ This property overrides automatic formatting if needed. :type: str """ @format.setter def format(self, arg1: str) -> None: """ This property overrides automatic formatting if needed. """ @property def max(self) -> float: """ This property holds the slider's maximum value. :type: float """ @max.setter def max(self, arg1: float) -> None: """ This property holds the slider's maximum value. """ @property def min(self) -> float: """ This property holds the slider's minimum value. :type: float """ @min.setter def min(self, arg1: float) -> None: """ This property holds the slider's minimum value. """ @property def precision(self) -> int: """ This property holds the slider value's float precision. :type: int """ @precision.setter def precision(self, arg1: int) -> None: """ This property holds the slider value's float precision. """ @property def step(self) -> float: """ This property controls the steping speed on the drag. :type: float """ @step.setter def step(self, arg1: float) -> None: """ This property controls the steping speed on the drag. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FloatStore(): """ A singleton that stores all the UI Style float properties of omni.ui. """ @staticmethod def find(name: str) -> float: """ Return the index of the color with specific name. """ @staticmethod def store(name: str, value: float) -> None: """ Save the color by name. """ pass class FocusPolicy(): """ Members: DEFAULT FOCUS_ON_LEFT_MOUSE_DOWN FOCUS_ON_ANY_MOUSE_DOWN FOCUS_ON_HOVER """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ DEFAULT: omni.ui._ui.FocusPolicy # value = <FocusPolicy.DEFAULT: 0> FOCUS_ON_ANY_MOUSE_DOWN: omni.ui._ui.FocusPolicy # value = <FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN: 1> FOCUS_ON_HOVER: omni.ui._ui.FocusPolicy # value = <FocusPolicy.FOCUS_ON_HOVER: 2> FOCUS_ON_LEFT_MOUSE_DOWN: omni.ui._ui.FocusPolicy # value = <FocusPolicy.DEFAULT: 0> __members__: dict # value = {'DEFAULT': <FocusPolicy.DEFAULT: 0>, 'FOCUS_ON_LEFT_MOUSE_DOWN': <FocusPolicy.DEFAULT: 0>, 'FOCUS_ON_ANY_MOUSE_DOWN': <FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN: 1>, 'FOCUS_ON_HOVER': <FocusPolicy.FOCUS_ON_HOVER: 2>} pass class FontStyle(): """ Supported font styles. Members: NONE NORMAL LARGE SMALL EXTRA_LARGE XXL XXXL EXTRA_SMALL XXS XXXS ULTRA """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ EXTRA_LARGE: omni.ui._ui.FontStyle # value = <FontStyle.EXTRA_LARGE: 4> EXTRA_SMALL: omni.ui._ui.FontStyle # value = <FontStyle.EXTRA_SMALL: 7> LARGE: omni.ui._ui.FontStyle # value = <FontStyle.LARGE: 2> NONE: omni.ui._ui.FontStyle # value = <FontStyle.NONE: 0> NORMAL: omni.ui._ui.FontStyle # value = <FontStyle.NORMAL: 1> SMALL: omni.ui._ui.FontStyle # value = <FontStyle.SMALL: 3> ULTRA: omni.ui._ui.FontStyle # value = <FontStyle.ULTRA: 10> XXL: omni.ui._ui.FontStyle # value = <FontStyle.XXL: 5> XXS: omni.ui._ui.FontStyle # value = <FontStyle.XXS: 8> XXXL: omni.ui._ui.FontStyle # value = <FontStyle.XXL: 5> XXXS: omni.ui._ui.FontStyle # value = <FontStyle.XXXS: 9> __members__: dict # value = {'NONE': <FontStyle.NONE: 0>, 'NORMAL': <FontStyle.NORMAL: 1>, 'LARGE': <FontStyle.LARGE: 2>, 'SMALL': <FontStyle.SMALL: 3>, 'EXTRA_LARGE': <FontStyle.EXTRA_LARGE: 4>, 'XXL': <FontStyle.XXL: 5>, 'XXXL': <FontStyle.XXL: 5>, 'EXTRA_SMALL': <FontStyle.EXTRA_SMALL: 7>, 'XXS': <FontStyle.XXS: 8>, 'XXXS': <FontStyle.XXXS: 9>, 'ULTRA': <FontStyle.ULTRA: 10>} pass class Fraction(Length): """ Fraction length is made to take the space of the parent widget, divides it up into a row of boxes, and makes each child widget fill one box. """ def __init__(self, value: float) -> None: """ Construct Fraction. `kwargs : dict` See below ### Keyword Arguments: """ pass class Frame(Container, Widget): """ The Frame is a widget that can hold one child widget. Frame is used to crop the contents of a child widget or to draw small widget in a big view. The child widget must be specified with addChild(). """ def __init__(self, **kwargs) -> None: """ Constructs Frame. `kwargs : dict` See below ### Keyword Arguments: `horizontal_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction. `vertical_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction. `separate_window : ` A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. `raster_policy : ` Determine how the content of the frame should be rasterized. `build_fn : ` Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def call_build_fn(self) -> None: """ Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load. """ def has_build_fn(self) -> bool: """ Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load. """ def invalidate_raster(self) -> None: """ This method regenerates the raster image of the widget, even if the widget's content has not changed. This can be used with both the eOnDemand and eAuto raster policies, and is used to update the content displayed in the widget. Note that this operation may be resource-intensive, and should be used sparingly. """ def rebuild(self) -> None: """ After this method is called, the next drawing cycle build_fn will be called again to rebuild everything. """ def set_build_fn(self, fn: typing.Callable[[], None]) -> None: """ Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load. """ @property def frozen(self) -> bool: """ A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. :type: bool """ @frozen.setter def frozen(self, arg1: bool) -> None: """ A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. """ @property def horizontal_clipping(self) -> bool: """ When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction. :type: bool """ @horizontal_clipping.setter def horizontal_clipping(self, arg1: bool) -> None: """ When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction. """ @property def raster_policy(self) -> RasterPolicy: """ Determine how the content of the frame should be rasterized. :type: RasterPolicy """ @raster_policy.setter def raster_policy(self, arg1: RasterPolicy) -> None: """ Determine how the content of the frame should be rasterized. """ @property def separate_window(self) -> bool: """ A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. :type: bool """ @separate_window.setter def separate_window(self, arg1: bool) -> None: """ A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. """ @property def vertical_clipping(self) -> bool: """ When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction. :type: bool """ @vertical_clipping.setter def vertical_clipping(self, arg1: bool) -> None: """ When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FreeBezierCurve(BezierCurve, Shape, Widget, ArrowHelper): """ Smooth curve that can be scaled infinitely. The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another. """ def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: """ Initialize the the shape with bounds limited to the positions of the given widgets. ### Arguments: `start :` The bound corder is in the center of this given widget. `end :` The bound corder is in the center of this given widget. `kwargs : dict` See below ### Keyword Arguments: start_tangent_width: This property holds the X coordinate of the start of the curve relative to the width bound of the curve. start_tangent_height: This property holds the Y coordinate of the start of the curve relative to the width bound of the curve. end_tangent_width: This property holds the X coordinate of the end of the curve relative to the width bound of the curve. end_tangent_height: This property holds the Y coordinate of the end of the curve relative to the width bound of the curve. set_mouse_hovered_fn: Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered) `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FreeCircle(Circle, Shape, Widget): """ The Circle widget provides a colored circle to display. The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another. """ def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: """ Initialize the the shape with bounds limited to the positions of the given widgets. ### Arguments: `start :` The bound corder is in the center of this given widget. `end :` The bound corder is in the center of this given widget. `kwargs : dict` See below ### Keyword Arguments: `alignment :` This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered. `radius :` This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0. `arc :` This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered. `size_policy :` Define what happens when the source image has a different size than the item. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FreeEllipse(Ellipse, Shape, Widget): """ The Ellipse widget provides a colored ellipse to display. The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another. """ def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: """ Initialize the the shape with bounds limited to the positions of the given widgets. ### Arguments: `start :` The bound corder is in the center of this given widget. `end :` The bound corder is in the center of this given widget. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FreeLine(Line, Shape, Widget, ArrowHelper): """ The Line widget provides a colored line to display. The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another. """ def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: """ Initialize the the shape with bounds limited to the positions of the given widgets. ### Arguments: `start :` The bound corder is in the center of this given widget. `end :` The bound corder is in the center of this given widget. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FreeRectangle(Rectangle, Shape, Widget): """ The Rectangle widget provides a colored rectangle to display. The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another. """ def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: """ Initialize the the shape with bounds limited to the positions of the given widgets. ### Arguments: `start :` The bound corder is in the center of this given widget. `end :` The bound corder is in the center of this given widget. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class FreeTriangle(Triangle, Shape, Widget): """ The Triangle widget provides a colored triangle to display. The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another. """ def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: """ Initialize the the shape with bounds limited to the positions of the given widgets. ### Arguments: `start :` The bound corder is in the center of this given widget. `end :` The bound corder is in the center of this given widget. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class HGrid(Grid, Stack, Container, Widget): """ Shortcut for Grid{eLeftToRight}. The grid grows from left to right with the widgets placed. """ def __init__(self, **kwargs) -> None: """ Construct a grid that grow from left to right with the widgets placed. `kwargs : dict` See below ### Keyword Arguments: `column_width : ` The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget. `row_height : ` The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget. `column_count : ` The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size. `row_count : ` The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size. `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Grid(Stack, Container, Widget): """ Grid is a container that arranges its child views in a grid. The grid vertical/horizontal direction is the direction the grid size growing with creating more children. """ def __init__(self, arg0: Direction, **kwargs) -> None: """ Constructor. ### Arguments: `direction :` Determines the direction the widget grows when adding more children. `kwargs : dict` See below ### Keyword Arguments: `column_width : ` The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget. `row_height : ` The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget. `column_count : ` The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size. `row_count : ` The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size. `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def column_count(self) -> int: """ The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size. :type: int """ @column_count.setter def column_count(self, arg1: int) -> None: """ The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size. """ @property def column_width(self) -> float: """ The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget. :type: float """ @column_width.setter def column_width(self, arg1: float) -> None: """ The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget. """ @property def row_count(self) -> int: """ The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size. :type: int """ @row_count.setter def row_count(self, arg1: int) -> None: """ The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size. """ @property def row_height(self) -> float: """ The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget. :type: float """ @row_height.setter def row_height(self, arg1: float) -> None: """ The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class HStack(Stack, Container, Widget): """ Shortcut for Stack{eLeftToRight}. The widgets are placed in a row, with suitable sizes. """ def __init__(self, **kwargs) -> None: """ Construct a stack with the widgets placed in a row from left to right. `kwargs : dict` See below ### Keyword Arguments: `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Image(Widget): """ The Image widget displays an image. The source of the image is specified as a URL using the source property. By default, specifying the width and height of the item causes the image to be scaled to that size. This behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled instead. The property alignment controls where to align the scaled image. """ @typing.overload def __init__(self, arg0: str, **kwargs) -> None: """ Construct image with given url. If the url is empty, it gets the image URL from styling. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered. `fill_policy : ` Define what happens when the source image has a different size than the item. `pixel_aligned : ` Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) `progress_changed_fn : ` The progress of the image loading. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. Construct image with given url. If the url is empty, it gets the image URL from styling. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered. `fill_policy : ` Define what happens when the source image has a different size than the item. `pixel_aligned : ` Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) `progress_changed_fn : ` The progress of the image loading. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, **kwargs) -> None: ... def set_progress_changed_fn(self, fn: typing.Callable[[float], None]) -> None: """ The progress of the image loading. """ @property def alignment(self) -> Alignment: """ This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered. :type: Alignment """ @alignment.setter def alignment(self, arg1: Alignment) -> None: """ This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered. """ @property def fill_policy(self) -> FillPolicy: """ Define what happens when the source image has a different size than the item. :type: FillPolicy """ @fill_policy.setter def fill_policy(self, arg1: FillPolicy) -> None: """ Define what happens when the source image has a different size than the item. """ @property def pixel_aligned(self) -> bool: """ Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) :type: bool """ @pixel_aligned.setter def pixel_aligned(self, arg1: bool) -> None: """ Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) """ @property def source_url(self) -> str: """ This property holds the image URL. It can be an omni: file: :type: str """ @source_url.setter def source_url(self, arg1: str) -> None: """ This property holds the image URL. It can be an omni: file: """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ImageProvider(): """ ImageProvider class, the goal of this class is to provide ImGui reference for the image to be rendered. """ def __init__(self, **kwargs) -> None: """ doc """ def destroy(self) -> None: ... def get_managed_resource(self) -> omni.gpu_foundation_factory._gpu_foundation_factory.RpResource: ... @typing.overload def set_image_data(self, arg0: capsule, arg1: int, arg2: int, arg3: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> None: ... @typing.overload def set_image_data(self, rp_resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, presentation_key: int = 0) -> None: ... @property def height(self) -> int: """ Gets image height. :type: int """ @property def is_reference_valid(self) -> bool: """ Returns true if ImGui reference is valid, false otherwise. :type: bool """ @property def width(self) -> int: """ Gets image width. :type: int """ pass class ImageWithProvider(Widget): """ The Image widget displays an image. The source of the image is specified as a URL using the source property. By default, specifying the width and height of the item causes the image to be scaled to that size. This behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled instead. The property alignment controls where to align the scaled image. """ @typing.overload def __init__(self, arg0: ImageProvider, **kwargs) -> None: """ Construct image with given ImageProvider. If the ImageProvider is nullptr, it gets the image URL from styling. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered. `fill_policy : ` Define what happens when the source image has a different size than the item. `pixel_aligned : ` Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: str, **kwargs) -> None: ... @typing.overload def __init__(self, **kwargs) -> None: ... def prepare_draw(self, width: float, height: float) -> None: """ Force call `ImageProvider::prepareDraw` to ensure the next draw call the image is loaded. It can be used to load the image for a hidden widget or to set the rasterization resolution. """ @property def alignment(self) -> Alignment: """ This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered. :type: Alignment """ @alignment.setter def alignment(self, arg1: Alignment) -> None: """ This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered. """ @property def fill_policy(self) -> IwpFillPolicy: """ Define what happens when the source image has a different size than the item. :type: IwpFillPolicy """ @fill_policy.setter def fill_policy(self, arg1: IwpFillPolicy) -> None: """ Define what happens when the source image has a different size than the item. """ @property def pixel_aligned(self) -> bool: """ Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) :type: bool """ @pixel_aligned.setter def pixel_aligned(self, arg1: bool) -> None: """ Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Inspector(): """ Inspector is the helper to check the internal state of the widget. It's not recommended to use it for the routine UI. """ @staticmethod def begin_computed_height_metric() -> None: """ Start counting how many times Widget::setComputedHeight is called """ @staticmethod def begin_computed_width_metric() -> None: """ Start counting how many times Widget::setComputedWidth is called """ @staticmethod def end_computed_height_metric() -> int: """ Start counting how many times Widget::setComputedHeight is called and return the number """ @staticmethod def end_computed_width_metric() -> int: """ Start counting how many times Widget::setComputedWidth is called and return the number """ @staticmethod def get_children(widget: Widget) -> typing.List[Widget]: """ Get the children of the given Widget. """ @staticmethod def get_resolved_style(*args, **kwargs) -> typing.Any: """ Get the resolved style of the given Widget. """ @staticmethod def get_stored_font_atlases() -> typing.List[typing.Tuple[str, int]]: """ Provides the information about font atlases """ pass class IntDrag(IntSlider, AbstractSlider, Widget, ValueModelHelper): """ The drag widget that looks like a field but it's possible to change the value with dragging. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Constructs IntDrag. ### Arguments: `model :` The widget's model. If the model is not assigned, the default model is created. `kwargs : dict` See below ### Keyword Arguments: `step : ` This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer. `min : ` This property holds the slider's minimum value. `max : ` This property holds the slider's maximum value. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def step(self) -> float: """ This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer. :type: float """ @step.setter def step(self, arg1: float) -> None: """ This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class IntField(AbstractField, Widget, ValueModelHelper): """ The IntField widget is a one-line text editor with a string model. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Construct IntField. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class IntSlider(AbstractSlider, Widget, ValueModelHelper): """ The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along a horizontal groove and translates the handle's position into an integer value within the legal range. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Constructs IntSlider. ### Arguments: `model :` The widget's model. If the model is not assigned, the default model is created. `kwargs : dict` See below ### Keyword Arguments: `min : ` This property holds the slider's minimum value. `max : ` This property holds the slider's maximum value. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def max(self) -> int: """ This property holds the slider's maximum value. :type: int """ @max.setter def max(self, arg1: int) -> None: """ This property holds the slider's maximum value. """ @property def min(self) -> int: """ This property holds the slider's minimum value. :type: int """ @min.setter def min(self, arg1: int) -> None: """ This property holds the slider's minimum value. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class InvisibleButton(Widget): """ The InvisibleButton widget provides a transparent command button. """ def __init__(self, **kwargs) -> None: """ Constructor. `kwargs : dict` See below ### Keyword Arguments: `clicked_fn : Callable[[], None]` Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button). `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def call_clicked_fn(self) -> None: """ Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button). """ def has_clicked_fn(self) -> bool: """ Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button). """ def set_clicked_fn(self, fn: typing.Callable[[], None]) -> None: """ Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button). """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ItemModelHelper(): """ The ItemModelHelper class provides the basic functionality for item widget classes. """ @property def model(self) -> AbstractItemModel: """ Returns the current model. :type: AbstractItemModel """ @model.setter def model(self, arg1: AbstractItemModel) -> None: """ Returns the current model. """ pass class IwpFillPolicy(): """ Members: IWP_STRETCH IWP_PRESERVE_ASPECT_FIT IWP_PRESERVE_ASPECT_CROP """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ IWP_PRESERVE_ASPECT_CROP: omni.ui._ui.IwpFillPolicy # value = <IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP: 2> IWP_PRESERVE_ASPECT_FIT: omni.ui._ui.IwpFillPolicy # value = <IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT: 1> IWP_STRETCH: omni.ui._ui.IwpFillPolicy # value = <IwpFillPolicy.IWP_STRETCH: 0> __members__: dict # value = {'IWP_STRETCH': <IwpFillPolicy.IWP_STRETCH: 0>, 'IWP_PRESERVE_ASPECT_FIT': <IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT: 1>, 'IWP_PRESERVE_ASPECT_CROP': <IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP: 2>} pass class Label(Widget): """ The Label widget provides a text to display. Label is used for displaying text. No additional to Widget user interaction functionality is provided. """ def __init__(self, arg0: str, **kwargs) -> None: """ Create a label with the given text. ### Arguments: `text :` The text for the label. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered. `word_wrap : ` This property holds the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled. `elided_text : ` When the text of a big length has to be displayed in a small area, it can be useful to give the user a visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property is true, Label elides the middle of the last visible line and replaces it with "...". `elided_text_str : ` Customized elidedText string when elidedText is True, default is .... `hide_text_after_hash : ` Hide anything after a '##' string or not `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def alignment(self) -> Alignment: """ This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered. :type: Alignment """ @alignment.setter def alignment(self, arg1: Alignment) -> None: """ This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered. """ @property def elided_text(self) -> bool: """ When the text of a big length has to be displayed in a small area, it can be useful to give the user a visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property is true, Label elides the middle of the last visible line and replaces it with "...". :type: bool """ @elided_text.setter def elided_text(self, arg1: bool) -> None: """ When the text of a big length has to be displayed in a small area, it can be useful to give the user a visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property is true, Label elides the middle of the last visible line and replaces it with "...". """ @property def elided_text_str(self) -> str: """ Customized elidedText string when elidedText is True, default is .... :type: str """ @elided_text_str.setter def elided_text_str(self, arg1: str) -> None: """ Customized elidedText string when elidedText is True, default is .... """ @property def exact_content_height(self) -> float: """ Return the exact height of the content of this label. Computed content height is a size hint and may be bigger than the text in the label. :type: float """ @property def exact_content_width(self) -> float: """ Return the exact width of the content of this label. Computed content width is a size hint and may be bigger than the text in the label. :type: float """ @property def hide_text_after_hash(self) -> bool: """ Hide anything after a '##' string or not :type: bool """ @hide_text_after_hash.setter def hide_text_after_hash(self, arg1: bool) -> None: """ Hide anything after a '##' string or not """ @property def text(self) -> str: """ This property holds the label's text. :type: str """ @text.setter def text(self, arg1: str) -> None: """ This property holds the label's text. """ @property def word_wrap(self) -> bool: """ This property holds the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled. :type: bool """ @word_wrap.setter def word_wrap(self, arg1: bool) -> None: """ This property holds the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Length(): """ OMNI.UI has several different units for expressing a length. Many widget properties take "Length" values, such as width, height, minWidth, minHeight, etc. Pixel is the absolute length unit. Percent and Fraction are relative length units, and they specify a length relative to the parent length. Relative length units are scaled with the parent. """ def __add__(self, value: float) -> float: ... def __float__(self) -> float: ... def __iadd__(self, value: float) -> float: ... def __imul__(self, value: float) -> Length: ... @staticmethod @typing.overload def __init__(*args, **kwargs) -> typing.Any: """ Construct Length. `kwargs : dict` See below ### Keyword Arguments: """ @typing.overload def __init__(self, arg0: float) -> None: ... @typing.overload def __init__(self, arg0: int) -> None: ... def __isub__(self, value: float) -> float: ... def __itruediv__(self, value: float) -> Length: ... def __mul__(self, value: float) -> Length: ... def __radd__(self, value: float) -> float: ... def __repr__(self) -> str: ... def __rmul__(self, value: float) -> Length: ... def __rsub__(self, value: float) -> float: ... def __rtruediv__(self, value: float) -> Length: ... def __str__(self) -> str: ... def __sub__(self, value: float) -> float: ... def __truediv__(self, value: float) -> Length: ... @property def unit(self) -> omni::ui::UnitType: """ (:obj:`.UnitType.`) Unit. :type: omni::ui::UnitType """ @unit.setter def unit(self, arg0: omni::ui::UnitType) -> None: """ (:obj:`.UnitType.`) Unit. """ @property def value(self) -> float: """ (float) Value :type: float """ @value.setter def value(self, arg0: float) -> None: """ (float) Value """ pass class Line(Shape, Widget, ArrowHelper): """ The Line widget provides a colored line to display. """ def __init__(self, **kwargs) -> None: """ Constructs Line. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def alignment(self) -> Alignment: """ This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter. :type: Alignment """ @alignment.setter def alignment(self, arg1: Alignment) -> None: """ This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MainWindow(): """ The MainWindow class represents Main Window for the Application, draw optional MainMenuBar and StatusBar. """ def __init__(self, show_foreground: bool = False, **kwargs) -> None: """ Construct the main window, add it to the underlying windowing system, and makes it appear. `kwargs : dict` See below ### Keyword Arguments: """ @property def cpp_status_bar_enabled(self) -> bool: """ Workaround to reserve space for C++ status bar. :type: bool """ @cpp_status_bar_enabled.setter def cpp_status_bar_enabled(self, arg1: bool) -> None: """ Workaround to reserve space for C++ status bar. """ @property def main_frame(self) -> Frame: """ This represents Styling opportunity for the Window background. :type: Frame """ @property def main_menu_bar(self) -> MenuBar: """ The main MenuBar for the application. :type: MenuBar """ @property def show_foreground(self) -> bool: """ When show_foreground is True, MainWindow prevents other windows from showing. :type: bool """ @show_foreground.setter def show_foreground(self, arg1: bool) -> None: """ When show_foreground is True, MainWindow prevents other windows from showing. """ @property def status_bar_frame(self) -> Frame: """ The StatusBar Frame is empty by default and is meant to be filled by other part of the system. :type: Frame """ pass class MenuBar(Menu, Stack, Container, Widget, MenuHelper): """ The MenuBar class provides a MenuBar at the top of the Window, could also be the MainMenuBar of the MainWindow. it can only contain Menu, at the moment there is no way to remove item appart from clearing it all together """ def __init__(self, **kwargs) -> None: """ Construct MenuBar. `kwargs : dict` See below ### Keyword Arguments: `tearable : bool` The ability to tear the window off. `shown_changed_fn : ` If the pulldown menu is shown on the screen. `teared_changed_fn : ` If the window is teared off. `on_build_fn : ` Called to re-create new children. `text : str` This property holds the menu's text. `hotkey_text : str` This property holds the menu's hotkey text. `checkable : bool` This property holds whether this menu item is checkable. A checkable item is one which has an on/off state. `hide_on_click : bool` Hide or keep the window when the user clicked this item. `delegate : MenuDelegate` The delegate that generates a widget per menu item. `triggered_fn : void` Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MenuItemCollection(Menu, Stack, Container, Widget, MenuHelper): """ The MenuItemCollection is the menu that unchecks children when one of them is checked. """ def __init__(self, text: str = '', **kwargs) -> None: """ Construct MenuItemCollection. `kwargs : dict` See below ### Keyword Arguments: `tearable : bool` The ability to tear the window off. `shown_changed_fn : ` If the pulldown menu is shown on the screen. `teared_changed_fn : ` If the window is teared off. `on_build_fn : ` Called to re-create new children. `text : str` This property holds the menu's text. `hotkey_text : str` This property holds the menu's hotkey text. `checkable : bool` This property holds whether this menu item is checkable. A checkable item is one which has an on/off state. `hide_on_click : bool` Hide or keep the window when the user clicked this item. `delegate : MenuDelegate` The delegate that generates a widget per menu item. `triggered_fn : void` Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Menu(Stack, Container, Widget, MenuHelper): """ The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus. It can be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the menu bar when the user clicks on the respective item. Context menus are usually invoked by some special keyboard key or by right-clicking. """ def __init__(self, text: str = '', **kwargs) -> None: """ Construct Menu. ### Arguments: `text :` The text for the menu. `kwargs : dict` See below ### Keyword Arguments: `tearable : bool` The ability to tear the window off. `shown_changed_fn : ` If the pulldown menu is shown on the screen. `teared_changed_fn : ` If the window is teared off. `on_build_fn : ` Called to re-create new children. `text : str` This property holds the menu's text. `hotkey_text : str` This property holds the menu's hotkey text. `checkable : bool` This property holds whether this menu item is checkable. A checkable item is one which has an on/off state. `hide_on_click : bool` Hide or keep the window when the user clicked this item. `delegate : MenuDelegate` The delegate that generates a widget per menu item. `triggered_fn : void` Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def call_on_build_fn(self) -> None: """ Called to re-create new children. """ @staticmethod def get_current() -> Menu: """ Return the menu that is currently shown. """ def has_on_build_fn(self) -> bool: """ Called to re-create new children. """ def hide(self) -> None: """ Close the menu window. It only works for pop-up context menu and for teared off menu. """ def invalidate(self) -> None: """ Make Menu dirty so onBuild will be executed to replace the children. """ def set_on_build_fn(self, fn: typing.Callable[[], None]) -> None: """ Called to re-create new children. """ def set_shown_changed_fn(self, fn: typing.Callable[[bool], None]) -> None: """ If the pulldown menu is shown on the screen. """ def set_teared_changed_fn(self, fn: typing.Callable[[bool], None]) -> None: """ If the window is teared off. """ def show(self) -> None: """ Create a popup window and show the menu in it. It's usually used for context menus that are typically invoked by some special keyboard key or by right-clicking. """ def show_at(self, arg0: float, arg1: float) -> None: """ Create a popup window and show the menu in it. This enable to popup the menu at specific position. X and Y are in points to make it easier to the Python users. """ @property def shown(self) -> bool: """ If the pulldown menu is shown on the screen. :type: bool """ @property def tearable(self) -> bool: """ The ability to tear the window off. :type: bool """ @tearable.setter def tearable(self, arg1: bool) -> None: """ The ability to tear the window off. """ @property def teared(self) -> bool: """ If the window is teared off. :type: bool """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MenuDelegate(): """ MenuDelegate is used to generate widgets that represent the menu item. """ def __init__(self, **kwargs) -> None: """ Constructor. `kwargs : dict` See below ### Keyword Arguments: `on_build_item : ` Called to create a new item. `on_build_title : ` Called to create a new title. `on_build_status : ` Called to create a new widget on the bottom of the window. `propagate : ` Determine if Menu children should use this delegate when they don't have the own one. """ @staticmethod def build_item(*args, **kwargs) -> typing.Any: """ This method must be reimplemented to generate custom item. """ @staticmethod def build_status(*args, **kwargs) -> typing.Any: """ This method must be reimplemented to generate custom widgets on the bottom of the window. """ @staticmethod def build_title(*args, **kwargs) -> typing.Any: """ This method must be reimplemented to generate custom title. """ @staticmethod def call_on_build_item_fn(*args, **kwargs) -> typing.Any: """ Called to create a new item. """ @staticmethod def call_on_build_status_fn(*args, **kwargs) -> typing.Any: """ Called to create a new widget on the bottom of the window. """ @staticmethod def call_on_build_title_fn(*args, **kwargs) -> typing.Any: """ Called to create a new title. """ def has_on_build_item_fn(self) -> bool: """ Called to create a new item. """ def has_on_build_status_fn(self) -> bool: """ Called to create a new widget on the bottom of the window. """ def has_on_build_title_fn(self) -> bool: """ Called to create a new title. """ @staticmethod def set_default_delegate(delegate: MenuDelegate) -> None: """ Set the default delegate to use it when the item doesn't have a delegate. """ @staticmethod def set_on_build_item_fn(*args, **kwargs) -> typing.Any: """ Called to create a new item. """ @staticmethod def set_on_build_status_fn(*args, **kwargs) -> typing.Any: """ Called to create a new widget on the bottom of the window. """ @staticmethod def set_on_build_title_fn(*args, **kwargs) -> typing.Any: """ Called to create a new title. """ @property def propagate(self) -> bool: """ :type: bool """ @propagate.setter def propagate(self, arg1: bool) -> None: pass pass class MenuItem(Widget, MenuHelper): """ A MenuItem represents the items the Menu consists of. MenuItem can be inserted only once in the menu. """ def __init__(self, arg0: str, **kwargs) -> None: """ Construct MenuItem. `kwargs : dict` See below ### Keyword Arguments: `text : str` This property holds the menu's text. `hotkey_text : str` This property holds the menu's hotkey text. `checkable : bool` This property holds whether this menu item is checkable. A checkable item is one which has an on/off state. `hide_on_click : bool` Hide or keep the window when the user clicked this item. `delegate : MenuDelegate` The delegate that generates a widget per menu item. `triggered_fn : void` Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MenuHelper(): """ The helper class for the menu that draws the menu line. """ def call_triggered_fn(self) -> None: """ Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. """ def has_triggered_fn(self) -> bool: """ Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. """ def set_triggered_fn(self, fn: typing.Callable[[], None]) -> None: """ Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. """ @property def checkable(self) -> bool: """ This property holds whether this menu item is checkable. A checkable item is one which has an on/off state. :type: bool """ @checkable.setter def checkable(self, arg1: bool) -> None: """ This property holds whether this menu item is checkable. A checkable item is one which has an on/off state. """ @property def delegate(self) -> MenuDelegate: """ :type: MenuDelegate """ @delegate.setter def delegate(self, arg1: MenuDelegate) -> None: pass @property def hide_on_click(self) -> bool: """ Hide or keep the window when the user clicked this item. :type: bool """ @hide_on_click.setter def hide_on_click(self, arg1: bool) -> None: """ Hide or keep the window when the user clicked this item. """ @property def hotkey_text(self) -> str: """ This property holds the menu's hotkey text. :type: str """ @hotkey_text.setter def hotkey_text(self, arg1: str) -> None: """ This property holds the menu's hotkey text. """ @property def menu_compatibility(self) -> bool: """ :type: bool """ @menu_compatibility.setter def menu_compatibility(self, arg1: bool) -> None: pass @property def text(self) -> str: """ This property holds the menu's text. :type: str """ @text.setter def text(self, arg1: str) -> None: """ This property holds the menu's text. """ pass class MultiFloatDragField(AbstractMultiField, Widget, ItemModelHelper): """ MultiFloatDragField is the widget that has a sub widget (FloatDrag) per model item. It's handy to use it for multi-component data, like for example, float3 or color. """ @typing.overload def __init__(self, **kwargs) -> None: """ Constructs MultiFloatDragField. ### Arguments: `model :` The widget's model. If the model is not assigned, the default model is created. `kwargs : dict` See below ### Keyword Arguments: `min : ` This property holds the drag's minimum value. `max : ` This property holds the drag's maximum value. `step : ` This property controls the steping speed on the drag. `column_count : ` The max number of fields in a line. `h_spacing : ` Sets a non-stretchable horizontal space in pixels between child fields. `v_spacing : ` Sets a non-stretchable vertical space in pixels between child fields. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ... @typing.overload def __init__(self, *args, **kwargs) -> None: ... @property def max(self) -> float: """ This property holds the drag's maximum value. :type: float """ @max.setter def max(self, arg1: float) -> None: """ This property holds the drag's maximum value. """ @property def min(self) -> float: """ This property holds the drag's minimum value. :type: float """ @min.setter def min(self, arg1: float) -> None: """ This property holds the drag's minimum value. """ @property def step(self) -> float: """ This property controls the steping speed on the drag. :type: float """ @step.setter def step(self, arg1: float) -> None: """ This property controls the steping speed on the drag. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MultiFloatField(AbstractMultiField, Widget, ItemModelHelper): """ MultiFloatField is the widget that has a sub widget (FloatField) per model item. It's handy to use it for multi-component data, like for example, float3 or color. """ @typing.overload def __init__(self, **kwargs) -> None: """ Constructor. `kwargs : dict` See below ### Keyword Arguments: `column_count : ` The max number of fields in a line. `h_spacing : ` Sets a non-stretchable horizontal space in pixels between child fields. `v_spacing : ` Sets a non-stretchable vertical space in pixels between child fields. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ... @typing.overload def __init__(self, *args, **kwargs) -> None: ... FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MultiIntDragField(AbstractMultiField, Widget, ItemModelHelper): """ MultiIntDragField is the widget that has a sub widget (IntDrag) per model item. It's handy to use it for multi-component data, like for example, int3. """ @typing.overload def __init__(self, **kwargs) -> None: """ Constructs MultiIntDragField. ### Arguments: `model :` The widget's model. If the model is not assigned, the default model is created. `kwargs : dict` See below ### Keyword Arguments: `min : ` This property holds the drag's minimum value. `max : ` This property holds the drag's maximum value. `step : ` This property controls the steping speed on the drag. `column_count : ` The max number of fields in a line. `h_spacing : ` Sets a non-stretchable horizontal space in pixels between child fields. `v_spacing : ` Sets a non-stretchable vertical space in pixels between child fields. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ... @typing.overload def __init__(self, *args, **kwargs) -> None: ... @property def max(self) -> int: """ This property holds the drag's maximum value. :type: int """ @max.setter def max(self, arg1: int) -> None: """ This property holds the drag's maximum value. """ @property def min(self) -> int: """ This property holds the drag's minimum value. :type: int """ @min.setter def min(self, arg1: int) -> None: """ This property holds the drag's minimum value. """ @property def step(self) -> float: """ This property controls the steping speed on the drag. :type: float """ @step.setter def step(self, arg1: float) -> None: """ This property controls the steping speed on the drag. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MultiIntField(AbstractMultiField, Widget, ItemModelHelper): """ MultiIntField is the widget that has a sub widget (IntField) per model item. It's handy to use it for multi-component data, like for example, int3. """ @typing.overload def __init__(self, **kwargs) -> None: """ Constructor. `kwargs : dict` See below ### Keyword Arguments: `column_count : ` The max number of fields in a line. `h_spacing : ` Sets a non-stretchable horizontal space in pixels between child fields. `v_spacing : ` Sets a non-stretchable vertical space in pixels between child fields. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ... @typing.overload def __init__(self, *args, **kwargs) -> None: ... FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class MultiStringField(AbstractMultiField, Widget, ItemModelHelper): """ MultiStringField is the widget that has a sub widget (StringField) per model item. It's handy to use it for string arrays. """ @typing.overload def __init__(self, **kwargs) -> None: """ Constructor. `kwargs : dict` See below ### Keyword Arguments: `column_count : ` The max number of fields in a line. `h_spacing : ` Sets a non-stretchable horizontal space in pixels between child fields. `v_spacing : ` Sets a non-stretchable vertical space in pixels between child fields. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ... @typing.overload def __init__(self, *args, **kwargs) -> None: ... FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class OffsetLine(FreeLine, Line, Shape, Widget, ArrowHelper): """ The free widget is the widget that is independent of the layout. It draws the line stuck to the bounds of other widgets. """ def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: ... @property def bound_offset(self) -> float: """ The offset from the bounds of the widgets this line is stuck to. :type: float """ @bound_offset.setter def bound_offset(self, arg1: float) -> None: """ The offset from the bounds of the widgets this line is stuck to. """ @property def offset(self) -> float: """ The offset to the direction of the line normal. :type: float """ @offset.setter def offset(self, arg1: float) -> None: """ The offset to the direction of the line normal. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Percent(Length): """ Percent is the length in percents from the parent widget. """ def __init__(self, value: float) -> None: """ Construct Percent. `kwargs : dict` See below ### Keyword Arguments: """ pass class Pixel(Length): """ Pixel length is exact length in pixels. """ def __init__(self, value: float) -> None: """ Construct Pixel. `kwargs : dict` See below ### Keyword Arguments: """ pass class Placer(Container, Widget): """ The Placer class place a single widget to a particular position based on the offet. """ def __init__(self, **kwargs) -> None: """ Construct Placer. `kwargs : dict` See below ### Keyword Arguments: `offset_x : toLength` offsetX defines the offset placement for the child widget relative to the Placer `offset_y : toLength` offsetY defines the offset placement for the child widget relative to the Placer `draggable : bool` Provides a convenient way to make an item draggable. `drag_axis : Axis` Sets if dragging can be horizontally or vertically. `stable_size : bool` The placer size depends on the position of the child when false. `raster_policy : ` Determine how the content of the frame should be rasterized. `offset_x_changed_fn : Callable[[ui.Length], None]` offsetX defines the offset placement for the child widget relative to the Placer `offset_y_changed_fn : Callable[[ui.Length], None]` offsetY defines the offset placement for the child widget relative to the Placer `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def invalidate_raster(self) -> None: """ This method regenerates the raster image of the widget, even if the widget's content has not changed. This can be used with both the eOnDemand and eAuto raster policies, and is used to update the content displayed in the widget. Note that this operation may be resource-intensive, and should be used sparingly. """ def set_offset_x_changed_fn(self, arg0: typing.Callable[[Length], None]) -> None: """ offsetX defines the offset placement for the child widget relative to the Placer """ def set_offset_y_changed_fn(self, arg0: typing.Callable[[Length], None]) -> None: """ offsetY defines the offset placement for the child widget relative to the Placer """ @property def drag_axis(self) -> Axis: """ Sets if dragging can be horizontally or vertically. :type: Axis """ @drag_axis.setter def drag_axis(self, arg1: Axis) -> None: """ Sets if dragging can be horizontally or vertically. """ @property def draggable(self) -> bool: """ Provides a convenient way to make an item draggable. :type: bool """ @draggable.setter def draggable(self, arg1: bool) -> None: """ Provides a convenient way to make an item draggable. """ @property def frames_to_start_drag(self) -> int: """ The placer size depends on the position of the child when false. :type: int """ @frames_to_start_drag.setter def frames_to_start_drag(self, arg1: int) -> None: """ The placer size depends on the position of the child when false. """ @property def offset_x(self) -> Length: """ offsetX defines the offset placement for the child widget relative to the Placer :type: Length """ @offset_x.setter def offset_x(self, arg1: handle) -> None: """ offsetX defines the offset placement for the child widget relative to the Placer """ @property def offset_y(self) -> Length: """ offsetY defines the offset placement for the child widget relative to the Placer :type: Length """ @offset_y.setter def offset_y(self, arg1: handle) -> None: """ offsetY defines the offset placement for the child widget relative to the Placer """ @property def raster_policy(self) -> RasterPolicy: """ Determine how the content of the frame should be rasterized. :type: RasterPolicy """ @raster_policy.setter def raster_policy(self, arg1: RasterPolicy) -> None: """ Determine how the content of the frame should be rasterized. """ @property def stable_size(self) -> bool: """ The placer size depends on the position of the child when false. :type: bool """ @stable_size.setter def stable_size(self, arg1: bool) -> None: """ The placer size depends on the position of the child when false. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Plot(Widget): """ The Plot widget provides a line/histogram to display. """ def __init__(self, type: Type = Type.LINE, scale_min: float = 3.4028234663852886e+38, scale_max: float = 3.4028234663852886e+38, *args, **kwargs) -> None: """ Construct Plot. ### Arguments: `type :` The type of the image, can be line or histogram. `scaleMin :` The minimal scale value. `scaleMax :` The maximum scale value. `valueList :` The list of values to draw the image. `kwargs : dict` See below ### Keyword Arguments: `value_offset : int` This property holds the value offset. By default, the value is 0. `value_stride : int` This property holds the stride to get value list. By default, the value is 1. `title : str` This property holds the title of the image. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def set_data(self, *args) -> None: """ Sets the image data value. """ def set_data_provider_fn(self, arg0: typing.Callable[[int], float], arg1: int) -> None: """ Sets the function that will be called when when data required. """ def set_xy_data(self, arg0: typing.List[typing.Tuple[float, float]]) -> None: ... @property def scale_max(self) -> float: """ This property holds the max scale values. By default, the value is FLT_MAX. :type: float """ @scale_max.setter def scale_max(self, arg1: float) -> None: """ This property holds the max scale values. By default, the value is FLT_MAX. """ @property def scale_min(self) -> float: """ This property holds the min scale values. By default, the value is FLT_MAX. :type: float """ @scale_min.setter def scale_min(self, arg1: float) -> None: """ This property holds the min scale values. By default, the value is FLT_MAX. """ @property def title(self) -> str: """ This property holds the title of the image. :type: str """ @title.setter def title(self, arg1: str) -> None: """ This property holds the title of the image. """ @property def type(self) -> Type: """ This property holds the type of the image, can only be line or histogram. By default, the type is line. :type: Type """ @type.setter def type(self, arg1: Type) -> None: """ This property holds the type of the image, can only be line or histogram. By default, the type is line. """ @property def value_offset(self) -> int: """ This property holds the value offset. By default, the value is 0. :type: int """ @value_offset.setter def value_offset(self, arg1: int) -> None: """ This property holds the value offset. By default, the value is 0. """ @property def value_stride(self) -> int: """ This property holds the stride to get value list. By default, the value is 1. :type: int """ @value_stride.setter def value_stride(self, arg1: int) -> None: """ This property holds the stride to get value list. By default, the value is 1. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ProgressBar(Widget, ValueModelHelper): """ A progressbar is a classic widget for showing the progress of an operation. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Construct ProgressBar. ### Arguments: `model :` The model that determines if the button is checked. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class RadioButton(Button, InvisibleButton, Widget): """ RadioButton is the widget that allows the user to choose only one of a predefined set of mutually exclusive options. RadioButtons are arranged in collections of two or more with the class RadioCollection, which is the central component of the system and controls the behavior of all the RadioButtons in the collection. """ def __init__(self, **kwargs) -> None: """ Constructs RadioButton. `kwargs : dict` See below ### Keyword Arguments: `radio_collection : ` This property holds the button's text. `text : str` This property holds the button's text. `image_url : str` This property holds the button's optional image URL. `image_width : float` This property holds the width of the image widget. Do not use this function to find the width of the image. `image_height : float` This property holds the height of the image widget. Do not use this function to find the height of the image. `spacing : float` Sets a non-stretchable space in points between image and text. `clicked_fn : Callable[[], None]` Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button). `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def radio_collection(self) -> RadioCollection: """ This property holds the button's text. :type: RadioCollection """ @radio_collection.setter def radio_collection(self, arg1: RadioCollection) -> None: """ This property holds the button's text. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class RadioCollection(ValueModelHelper): """ Radio Collection is a class that groups RadioButtons and coordinates their state. It makes sure that the choice is mutually exclusive, it means when the user selects a radio button, any previously selected radio button in the same collection becomes deselected. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Constructs RadioCollection. `kwargs : dict` See below ### Keyword Arguments: """ pass class RasterImageProvider(ImageProvider): """ doc """ def __init__(self, source_url: str = None, **kwargs) -> None: """ doc """ @property def max_mip_levels(self) -> int: """ Maximum number of mip map levels allowed :type: int """ @max_mip_levels.setter def max_mip_levels(self, arg1: int) -> None: """ Maximum number of mip map levels allowed """ @property def source_url(self) -> str: """ Sets byte data that the image provider will turn into an image. :type: str """ @source_url.setter def source_url(self, arg1: str) -> None: """ Sets byte data that the image provider will turn into an image. """ pass class RasterPolicy(): """ Used to set the rasterization behaviour. Members: NEVER : Do not rasterize the widget at any time. ON_DEMAND : Rasterize the widget as soon as possible and always use the rasterized version. This means that the widget will only be updated when the user called invalidateRaster. AUTO : Automatically determine whether to rasterize the widget based on performance considerations. If necessary, the widget will be rasterized and updated when its content changes. """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ AUTO: omni.ui._ui.RasterPolicy # value = <RasterPolicy.AUTO: 2> NEVER: omni.ui._ui.RasterPolicy # value = <RasterPolicy.NEVER: 0> ON_DEMAND: omni.ui._ui.RasterPolicy # value = <RasterPolicy.ON_DEMAND: 1> __members__: dict # value = {'NEVER': <RasterPolicy.NEVER: 0>, 'ON_DEMAND': <RasterPolicy.ON_DEMAND: 1>, 'AUTO': <RasterPolicy.AUTO: 2>} pass class Rectangle(Shape, Widget): """ The Rectangle widget provides a colored rectangle to display. """ def __init__(self, **kwargs) -> None: """ Constructs Rectangle. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ScrollBarPolicy(): """ Members: SCROLLBAR_AS_NEEDED SCROLLBAR_ALWAYS_OFF SCROLLBAR_ALWAYS_ON """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ SCROLLBAR_ALWAYS_OFF: omni.ui._ui.ScrollBarPolicy # value = <ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF: 1> SCROLLBAR_ALWAYS_ON: omni.ui._ui.ScrollBarPolicy # value = <ScrollBarPolicy.SCROLLBAR_ALWAYS_ON: 2> SCROLLBAR_AS_NEEDED: omni.ui._ui.ScrollBarPolicy # value = <ScrollBarPolicy.SCROLLBAR_AS_NEEDED: 0> __members__: dict # value = {'SCROLLBAR_AS_NEEDED': <ScrollBarPolicy.SCROLLBAR_AS_NEEDED: 0>, 'SCROLLBAR_ALWAYS_OFF': <ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF: 1>, 'SCROLLBAR_ALWAYS_ON': <ScrollBarPolicy.SCROLLBAR_ALWAYS_ON: 2>} pass class ScrollingFrame(Frame, Container, Widget): """ The ScrollingFrame class provides the ability to scroll onto another widget. ScrollingFrame is used to display the contents of a child widget within a frame. If the widget exceeds the size of the frame, the frame can provide scroll bars so that the entire area of the child widget can be viewed. The child widget must be specified with addChild(). """ def __init__(self, **kwargs) -> None: """ Construct ScrollingFrame. `kwargs : dict` See below ### Keyword Arguments: `scroll_x : float` The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly. `scroll_x_max : float` The max position of the horizontal scroll bar. `scroll_x_changed_fn : Callable[[float], None]` The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly. `scroll_y : float` The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly. `scroll_y_max : float` The max position of the vertical scroll bar. `scroll_y_changed_fn : Callable[[float], None]` The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly. `horizontal_scrollbar_policy : ui.ScrollBarPolicy` This property holds the policy for the horizontal scroll bar. `vertical_scrollbar_policy : ui.ScrollBarPolicy` This property holds the policy for the vertical scroll bar. `horizontal_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction. `vertical_clipping : ` When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction. `separate_window : ` A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows. `raster_policy : ` Determine how the content of the frame should be rasterized. `build_fn : ` Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ def set_scroll_x_changed_fn(self, arg0: typing.Callable[[float], None]) -> None: """ The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly. """ def set_scroll_y_changed_fn(self, arg0: typing.Callable[[float], None]) -> None: """ The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly. """ @property def horizontal_scrollbar_policy(self) -> ScrollBarPolicy: """ This property holds the policy for the horizontal scroll bar. :type: ScrollBarPolicy """ @horizontal_scrollbar_policy.setter def horizontal_scrollbar_policy(self, arg1: ScrollBarPolicy) -> None: """ This property holds the policy for the horizontal scroll bar. """ @property def scroll_x(self) -> float: """ The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly. :type: float """ @scroll_x.setter def scroll_x(self, arg1: float) -> None: """ The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly. """ @property def scroll_x_max(self) -> float: """ The max position of the horizontal scroll bar. :type: float """ @property def scroll_y(self) -> float: """ The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly. :type: float """ @scroll_y.setter def scroll_y(self, arg1: float) -> None: """ The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly. """ @property def scroll_y_max(self) -> float: """ The max position of the vertical scroll bar. :type: float """ @property def vertical_scrollbar_policy(self) -> ScrollBarPolicy: """ This property holds the policy for the vertical scroll bar. :type: ScrollBarPolicy """ @vertical_scrollbar_policy.setter def vertical_scrollbar_policy(self, arg1: ScrollBarPolicy) -> None: """ This property holds the policy for the vertical scroll bar. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Separator(Widget, MenuHelper): """ The Separator class provides blank space. Normally, it's used to create separator line in the UI elements """ def __init__(self, text: str = '', **kwargs) -> None: """ Construct Separator. `kwargs : dict` See below ### Keyword Arguments: `text : str` This property holds the menu's text. `hotkey_text : str` This property holds the menu's hotkey text. `checkable : bool` This property holds whether this menu item is checkable. A checkable item is one which has an on/off state. `hide_on_click : bool` Hide or keep the window when the user clicked this item. `delegate : MenuDelegate` The delegate that generates a widget per menu item. `triggered_fn : void` Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ShadowFlag(): """ Members: NONE CUT_OUT_SHAPE_BACKGROUND """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ CUT_OUT_SHAPE_BACKGROUND: omni.ui._ui.ShadowFlag # value = <ShadowFlag.CUT_OUT_SHAPE_BACKGROUND: 1> NONE: omni.ui._ui.ShadowFlag # value = <ShadowFlag.NONE: 0> __members__: dict # value = {'NONE': <ShadowFlag.NONE: 0>, 'CUT_OUT_SHAPE_BACKGROUND': <ShadowFlag.CUT_OUT_SHAPE_BACKGROUND: 1>} pass class Shape(Widget): """ The Shape widget provides a base class for all the Shape Widget. Currently implemented are Rectangle, Circle, Triangle, Line, Ellipse and BezierCurve. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class SimpleBoolModel(AbstractValueModel): """ A very simple bool model. """ def __init__(self, default_value: bool = False, **kwargs) -> None: ... def get_max(self) -> bool: ... def get_min(self) -> bool: ... def set_max(self, arg0: bool) -> None: ... def set_min(self, arg0: bool) -> None: ... @property def max(self) -> bool: """ This property holds the model's maximum value. :type: bool """ @max.setter def max(self, arg1: bool) -> None: """ This property holds the model's maximum value. """ @property def min(self) -> bool: """ This property holds the model's minimum value. :type: bool """ @min.setter def min(self, arg1: bool) -> None: """ This property holds the model's minimum value. """ pass class SimpleFloatModel(AbstractValueModel): """ A very simple double model. """ def __init__(self, default_value: float = 0.0, **kwargs) -> None: ... def get_max(self) -> float: ... def get_min(self) -> float: ... def set_max(self, arg0: float) -> None: ... def set_min(self, arg0: float) -> None: ... @property def max(self) -> float: """ This property holds the model's minimum value. :type: float """ @max.setter def max(self, arg1: float) -> None: """ This property holds the model's minimum value. """ @property def min(self) -> float: """ This property holds the model's minimum value. :type: float """ @min.setter def min(self, arg1: float) -> None: """ This property holds the model's minimum value. """ pass class SimpleIntModel(AbstractValueModel): """ A very simple Int model. """ def __init__(self, default_value: int = 0, **kwargs) -> None: ... def get_max(self) -> int: ... def get_min(self) -> int: ... def set_max(self, arg0: int) -> None: ... def set_min(self, arg0: int) -> None: ... @property def max(self) -> int: """ This property holds the model's minimum value. :type: int """ @max.setter def max(self, arg1: int) -> None: """ This property holds the model's minimum value. """ @property def min(self) -> int: """ This property holds the model's minimum value. :type: int """ @min.setter def min(self, arg1: int) -> None: """ This property holds the model's minimum value. """ pass class SimpleStringModel(AbstractValueModel): """ A very simple value model that holds a single string. """ def __init__(self, defaultValue: str = '') -> None: ... pass class SliderDrawMode(): """ Members: FILLED HANDLE DRAG """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ DRAG: omni.ui._ui.SliderDrawMode # value = <SliderDrawMode.DRAG: 2> FILLED: omni.ui._ui.SliderDrawMode # value = <SliderDrawMode.FILLED: 0> HANDLE: omni.ui._ui.SliderDrawMode # value = <SliderDrawMode.HANDLE: 1> __members__: dict # value = {'FILLED': <SliderDrawMode.FILLED: 0>, 'HANDLE': <SliderDrawMode.HANDLE: 1>, 'DRAG': <SliderDrawMode.DRAG: 2>} pass class Spacer(Widget): """ The Spacer class provides blank space. Normally, it's used to place other widgets correctly in a layout. """ def __init__(self, **kwargs) -> None: """ Construct Spacer. `kwargs : dict` See below ### Keyword Arguments: `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Stack(Container, Widget): """ The Stack class lines up child widgets horizontally, vertically or sorted in a Z-order. """ def __init__(self, arg0: Direction, **kwargs) -> None: """ Constructor. ### Arguments: `direction :` Determines the orientation of the Stack. `kwargs : dict` See below ### Keyword Arguments: `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def content_clipping(self) -> bool: """ Determines if the child widgets should be clipped by the rectangle of this Stack. :type: bool """ @content_clipping.setter def content_clipping(self, arg1: bool) -> None: """ Determines if the child widgets should be clipped by the rectangle of this Stack. """ @property def direction(self) -> Direction: """ This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. :type: Direction """ @direction.setter def direction(self, arg1: Direction) -> None: """ This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. """ @property def send_mouse_events_to_back(self) -> bool: """ When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. :type: bool """ @send_mouse_events_to_back.setter def send_mouse_events_to_back(self, arg1: bool) -> None: """ When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. """ @property def spacing(self) -> float: """ Sets a non-stretchable space in pixels between child items of this layout. :type: float """ @spacing.setter def spacing(self, arg1: float) -> None: """ Sets a non-stretchable space in pixels between child items of this layout. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class StringField(AbstractField, Widget, ValueModelHelper): """ The StringField widget is a one-line text editor with a string model. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Constructs StringField. ### Arguments: `model :` The widget's model. If the model is not assigned, the default model is created. `kwargs : dict` See below ### Keyword Arguments: `password_mode : ` This property holds the password mode. If the field is in the password mode when the entered text is obscured. `read_only : ` This property holds if the field is read-only. `multiline : ` Multiline allows to press enter and create a new line. `allow_tab_input : ` This property holds if the field allows Tab input. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def allow_tab_input(self) -> bool: """ This property holds if the field allows Tab input. :type: bool """ @allow_tab_input.setter def allow_tab_input(self, arg1: bool) -> None: """ This property holds if the field allows Tab input. """ @property def multiline(self) -> bool: """ Multiline allows to press enter and create a new line. :type: bool """ @multiline.setter def multiline(self, arg1: bool) -> None: """ Multiline allows to press enter and create a new line. """ @property def password_mode(self) -> bool: """ This property holds the password mode. If the field is in the password mode when the entered text is obscured. :type: bool """ @password_mode.setter def password_mode(self, arg1: bool) -> None: """ This property holds the password mode. If the field is in the password mode when the entered text is obscured. """ @property def read_only(self) -> bool: """ This property holds if the field is read-only. :type: bool """ @read_only.setter def read_only(self, arg1: bool) -> None: """ This property holds if the field is read-only. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class StringStore(): """ A singleton that stores all the UI Style string properties of omni.ui. """ @staticmethod def find(name: str) -> str: """ Return the index of the color with specific name. """ @staticmethod def store(name: str, string: str) -> None: """ Save the color by name. """ pass class Style(): """ A singleton that controls the global style of the session. """ @staticmethod def get_instance() -> Style: """ Get the instance of this singleton object. """ @property def default(self) -> object: """ Set the default root style. It's the style that is preselected when no alternative is specified. :type: object """ @default.setter def default(self, arg1: handle) -> None: """ Set the default root style. It's the style that is preselected when no alternative is specified. """ pass class ToolBar(Window, WindowHandle): """ The ToolBar class represents a window in the underlying windowing system that as some fixed size property. """ def __init__(self, title: str, **kwargs) -> None: """ Construct ToolBar. `kwargs : dict` See below ### Keyword Arguments: `axis : ui.Axis` @breif axis for the toolbar `axis_changed_fn : Callable[[ui.Axis], None]` @breif axis for the toolbar `flags : ` This property set the Flags for the Window. `visible : ` This property holds whether the window is visible. `title : ` This property holds the window's title. `padding_x : ` This property set the padding to the frame on the X axis. `padding_y : ` This property set the padding to the frame on the Y axis. `width : ` This property holds the window Width. `height : ` This property holds the window Height. `position_x : ` This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. `position_y : ` This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. `auto_resize : ` setup the window to resize automatically based on its content `noTabBar : ` setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically `raster_policy : ` Determine how the content of the window should be rastered. `width_changed_fn : ` This property holds the window Width. `height_changed_fn : ` This property holds the window Height. `visibility_changed_fn : ` This property holds whether the window is visible. """ def set_axis_changed_fn(self, arg0: typing.Callable[[ToolBarAxis], None]) -> None: ... @property def axis(self) -> ToolBarAxis: """ :type: ToolBarAxis """ @axis.setter def axis(self, arg1: ToolBarAxis) -> None: pass pass class ToolBarAxis(): """ Members: X Y """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ X: omni.ui._ui.ToolBarAxis # value = <ToolBarAxis.X: 0> Y: omni.ui._ui.ToolBarAxis # value = <ToolBarAxis.Y: 1> __members__: dict # value = {'X': <ToolBarAxis.X: 0>, 'Y': <ToolBarAxis.Y: 1>} pass class ToolButton(Button, InvisibleButton, Widget, ValueModelHelper): """ ToolButton is functionally similar to Button, but provides a model that determines if the button is checked. This button toggles between checked (on) and unchecked (off) when the user clicks it. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Construct a checkable button with the model. If the bodel is not provided, then the default model is created. ### Arguments: `model :` The model that determines if the button is checked. `kwargs : dict` See below ### Keyword Arguments: `text : str` This property holds the button's text. `image_url : str` This property holds the button's optional image URL. `image_width : float` This property holds the width of the image widget. Do not use this function to find the width of the image. `image_height : float` This property holds the height of the image widget. Do not use this function to find the height of the image. `spacing : float` Sets a non-stretchable space in points between image and text. `clicked_fn : Callable[[], None]` Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button). `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class TreeView(Widget, ItemModelHelper): """ TreeView is a widget that presents a hierarchical view of information. Each item can have a number of subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if any exist, and collapsed to hide subitems. TreeView can be used in file manager applications, where it allows the user to navigate the file system directories. They are also used to present hierarchical data, such as the scene object hierarchy. TreeView uses a model/view pattern to manage the relationship between data and the way it is presented. The separation of functionality gives developers greater flexibility to customize the presentation of items and provides a standard interface to allow a wide range of data sources to be used with other widgets. TreeView is responsible for the presentation of model data to the user and processing user input. To allow some flexibility in the way the data is presented, the creation of the sub-widgets is performed by the delegate. It provides the ability to customize any sub-item of TreeView. """ @typing.overload def __init__(self, **kwargs) -> None: """ Create TreeView with default model. Create TreeView with the given model. ### Arguments: `model :` The given model. `kwargs : dict` See below ### Keyword Arguments: `delegate : ` The Item delegate that generates a widget per item. `header_visible : ` This property holds if the header is shown or not. `selection : ` Set current selection. `expand_on_branch_click : ` This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user wants to control how the items expanded or collapsed. `keep_alive : ` When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for the temporary filtering if it's necessary to display thousands of nodes. `keep_expanded : ` Expand all the nodes and keep them expanded regardless their state. `drop_between_items : ` When true, the tree nodes can be dropped between items. `column_widths : ` Widths of the columns. If not set, the width is Fraction(1). `min_column_widths : ` Minimum widths of the columns. If not set, the width is Pixel(0). `columns_resizable : ` When true, the columns can be resized with the mouse. `selection_changed_fn : ` Set the callback that is called when the selection is changed. `root_expanded : ` The expanded state of the root item. Changing this flag doesn't make the children repopulated. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @typing.overload def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ... def call_hover_changed_fn(self, arg0: AbstractItem, arg1: bool) -> None: """ Set the callback that is called when the item hover status is changed. """ def call_selection_changed_fn(self, arg0: typing.List[AbstractItem]) -> None: """ Set the callback that is called when the selection is changed. """ def clear_selection(self) -> None: """ Deselects all selected items. """ def dirty_widgets(self) -> None: """ When called, it will make the delegate to regenerate all visible widgets the next frame. """ def extend_selection(self, item: AbstractItem) -> None: """ Extends the current selection selecting all the items between currently selected nodes and the given item. It's when user does shift+click. """ def has_hover_changed_fn(self) -> bool: """ Set the callback that is called when the item hover status is changed. """ def has_selection_changed_fn(self) -> bool: """ Set the callback that is called when the selection is changed. """ def is_expanded(self, item: AbstractItem) -> bool: """ Returns true if the given item is expanded. """ def set_expanded(self, item: AbstractItem, expanded: bool, recursive: bool) -> None: """ Sets the given item expanded or collapsed. ### Arguments: `item :` The item to expand or collapse. `expanded :` True if it's necessary to expand, false to collapse. `recursive :` True if it's necessary to expand children. """ def set_hover_changed_fn(self, fn: typing.Callable[[AbstractItem, bool], None]) -> None: """ Set the callback that is called when the item hover status is changed. """ def set_selection_changed_fn(self, fn: typing.Callable[[typing.List[AbstractItem]], None]) -> None: """ Set the callback that is called when the selection is changed. """ def toggle_selection(self, item: AbstractItem) -> None: """ Switches the selection state of the given item. """ @property def column_widths(self) -> typing.List[Length]: """ Widths of the columns. If not set, the width is Fraction(1). :type: typing.List[Length] """ @column_widths.setter def column_widths(self, arg1: typing.List[Length]) -> None: """ Widths of the columns. If not set, the width is Fraction(1). """ @property def columns_resizable(self) -> bool: """ When true, the columns can be resized with the mouse. :type: bool """ @columns_resizable.setter def columns_resizable(self, arg1: bool) -> None: """ When true, the columns can be resized with the mouse. """ @property def drop_between_items(self) -> bool: """ When true, the tree nodes can be dropped between items. :type: bool """ @drop_between_items.setter def drop_between_items(self, arg1: bool) -> None: """ When true, the tree nodes can be dropped between items. """ @property def expand_on_branch_click(self) -> bool: """ This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user wants to control how the items expanded or collapsed. :type: bool """ @expand_on_branch_click.setter def expand_on_branch_click(self, arg1: bool) -> None: """ This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user wants to control how the items expanded or collapsed. """ @property def header_visible(self) -> bool: """ This property holds if the header is shown or not. :type: bool """ @header_visible.setter def header_visible(self, arg1: bool) -> None: """ This property holds if the header is shown or not. """ @property def keep_alive(self) -> bool: """ When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for the temporary filtering if it's necessary to display thousands of nodes. :type: bool """ @keep_alive.setter def keep_alive(self, arg1: bool) -> None: """ When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for the temporary filtering if it's necessary to display thousands of nodes. """ @property def keep_expanded(self) -> bool: """ Expand all the nodes and keep them expanded regardless their state. :type: bool """ @keep_expanded.setter def keep_expanded(self, arg1: bool) -> None: """ Expand all the nodes and keep them expanded regardless their state. """ @property def min_column_widths(self) -> typing.List[Length]: """ Minimum widths of the columns. If not set, the width is Pixel(0). :type: typing.List[Length] """ @min_column_widths.setter def min_column_widths(self, arg1: typing.List[Length]) -> None: """ Minimum widths of the columns. If not set, the width is Pixel(0). """ @property def root_expanded(self) -> bool: """ The expanded state of the root item. Changing this flag doesn't make the children repopulated. :type: bool """ @root_expanded.setter def root_expanded(self, arg1: bool) -> None: """ The expanded state of the root item. Changing this flag doesn't make the children repopulated. """ @property def root_visible(self) -> bool: """ This property holds if the root is shown. It can be used to make a single level tree appear like a simple list. :type: bool """ @root_visible.setter def root_visible(self, arg1: bool) -> None: """ This property holds if the root is shown. It can be used to make a single level tree appear like a simple list. """ @property def selection(self) -> typing.List[AbstractItem]: """ Set current selection. :type: typing.List[AbstractItem] """ @selection.setter def selection(self, arg1: typing.List[AbstractItem]) -> None: """ Set current selection. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Triangle(Shape, Widget): """ The Triangle widget provides a colored triangle to display. """ def __init__(self, **kwargs) -> None: """ Constructs Triangle. `kwargs : dict` See below ### Keyword Arguments: `alignment : ` This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def alignment(self) -> Alignment: """ This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered. :type: Alignment """ @alignment.setter def alignment(self, arg1: Alignment) -> None: """ This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class Type(): """ Members: LINE HISTOGRAM LINE2D """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ HISTOGRAM: omni.ui._ui.Type # value = <Type.HISTOGRAM: 1> LINE: omni.ui._ui.Type # value = <Type.LINE: 0> LINE2D: omni.ui._ui.Type # value = <Type.LINE2D: 2> __members__: dict # value = {'LINE': <Type.LINE: 0>, 'HISTOGRAM': <Type.HISTOGRAM: 1>, 'LINE2D': <Type.LINE2D: 2>} pass class UIntDrag(UIntSlider, AbstractSlider, Widget, ValueModelHelper): """ """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Constructs UIntDrag. ### Arguments: `model :` The widget's model. If the model is not assigned, the default model is created. `kwargs : dict` See below ### Keyword Arguments: `step : ` This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer. `min : ` This property holds the slider's minimum value. `max : ` This property holds the slider's maximum value. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def step(self) -> float: """ This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer. :type: float """ @step.setter def step(self, arg1: float) -> None: """ This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class UIntSlider(AbstractSlider, Widget, ValueModelHelper): """ The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along a horizontal groove and translates the handle's position into an integer value within the legal range. The difference with IntSlider is that UIntSlider has unsigned min/max. """ def __init__(self, model: AbstractValueModel = None, **kwargs) -> None: """ Constructs UIntSlider. ### Arguments: `model :` The widget's model. If the model is not assigned, the default model is created. `kwargs : dict` See below ### Keyword Arguments: `min : ` This property holds the slider's minimum value. `max : ` This property holds the slider's maximum value. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ @property def max(self) -> int: """ This property holds the slider's maximum value. :type: int """ @max.setter def max(self, arg1: int) -> None: """ This property holds the slider's maximum value. """ @property def min(self) -> int: """ This property holds the slider's minimum value. :type: int """ @min.setter def min(self, arg1: int) -> None: """ This property holds the slider's minimum value. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class UnitType(): """ Unit types. Widths, heights or other UI length can be specified in pixels or relative to window (or child window) size. Members: PIXEL PERCENT FRACTION """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ FRACTION: omni.ui._ui.UnitType # value = <UnitType.FRACTION: 2> PERCENT: omni.ui._ui.UnitType # value = <UnitType.PERCENT: 1> PIXEL: omni.ui._ui.UnitType # value = <UnitType.PIXEL: 0> __members__: dict # value = {'PIXEL': <UnitType.PIXEL: 0>, 'PERCENT': <UnitType.PERCENT: 1>, 'FRACTION': <UnitType.FRACTION: 2>} pass class VGrid(Grid, Stack, Container, Widget): """ Shortcut for Grid{eTopToBottom}. The grid grows from top to bottom with the widgets placed. """ def __init__(self, **kwargs) -> None: """ Construct a grid that grows from top to bottom with the widgets placed. `kwargs : dict` See below ### Keyword Arguments: `column_width : ` The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget. `row_height : ` The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget. `column_count : ` The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size. `row_count : ` The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size. `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class VStack(Stack, Container, Widget): """ Shortcut for Stack{eTopToBottom}. The widgets are placed in a column, with suitable sizes. """ def __init__(self, **kwargs) -> None: """ Construct a stack with the widgets placed in a column from top to bottom. `kwargs : dict` See below ### Keyword Arguments: `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class ValueModelHelper(): """ The ValueModelHelper class provides the basic functionality for value widget classes. ValueModelHelper class is the base class for every standard widget that uses a AbstractValueModel. ValueModelHelper is an abstract class and itself cannot be instantiated. It provides a standard interface for interoperating with models. """ @property def model(self) -> AbstractValueModel: """ :type: AbstractValueModel """ @model.setter def model(self, arg1: AbstractValueModel) -> None: pass pass class VectorImageProvider(ImageProvider): """ doc """ def __init__(self, source_url: str = None, **kwargs) -> None: """ doc """ @property def max_mip_levels(self) -> int: """ Maximum number of mip map levels allowed :type: int """ @max_mip_levels.setter def max_mip_levels(self, arg1: int) -> None: """ Maximum number of mip map levels allowed """ @property def source_url(self) -> str: """ Sets the vector image URL. Asset loading doesn't happen immediately, but rather is started the next time widget is visible, in prepareDraw call. :type: str """ @source_url.setter def source_url(self, arg1: str) -> None: """ Sets the vector image URL. Asset loading doesn't happen immediately, but rather is started the next time widget is visible, in prepareDraw call. """ pass class Widget(): """ The Widget class is the base class of all user interface objects. The widget is the atom of the user interface: it receives mouse, keyboard and other events, and paints a representation of itself on the screen. Every widget is rectangular. A widget is clipped by its parent and by the widgets in front of it. """ def __init__(self, **kwargs) -> None: ... def call_accept_drop_fn(self, arg0: str) -> bool: """ Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. """ def call_computed_content_size_changed_fn(self) -> None: """ Called when the size of the widget is changed. """ def call_drag_fn(self) -> str: """ Specify that this Widget is draggable, and set the callback that is attached to the drag operation. """ def call_drop_fn(self, arg0: WidgetMouseDropEvent) -> None: """ Specify that this Widget accepts drops and set the callback to the drop operation. """ def call_key_pressed_fn(self, arg0: int, arg1: int, arg2: bool) -> None: """ Sets the function that will be called when the user presses the keyboard key when the mouse clicks the widget. """ def call_mouse_double_clicked_fn(self, arg0: float, arg1: float, arg2: int, arg3: int) -> None: """ Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) """ def call_mouse_hovered_fn(self, arg0: bool) -> None: """ Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) """ def call_mouse_moved_fn(self, arg0: float, arg1: float, arg2: int, arg3: bool) -> None: """ Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) """ def call_mouse_pressed_fn(self, arg0: float, arg1: float, arg2: int, arg3: int) -> None: """ Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. """ def call_mouse_released_fn(self, arg0: float, arg1: float, arg2: int, arg3: int) -> None: """ Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) """ def call_mouse_wheel_fn(self, arg0: float, arg1: float, arg2: int) -> None: """ Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) """ def call_tooltip_fn(self) -> None: """ Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. """ def destroy(self) -> None: """ Removes all the callbacks and circular references. """ def has_accept_drop_fn(self) -> bool: """ Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. """ def has_computed_content_size_changed_fn(self) -> bool: """ Called when the size of the widget is changed. """ def has_drag_fn(self) -> bool: """ Specify that this Widget is draggable, and set the callback that is attached to the drag operation. """ def has_drop_fn(self) -> bool: """ Specify that this Widget accepts drops and set the callback to the drop operation. """ def has_key_pressed_fn(self) -> bool: """ Sets the function that will be called when the user presses the keyboard key when the mouse clicks the widget. """ def has_mouse_double_clicked_fn(self) -> bool: """ Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) """ def has_mouse_hovered_fn(self) -> bool: """ Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) """ def has_mouse_moved_fn(self) -> bool: """ Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) """ def has_mouse_pressed_fn(self) -> bool: """ Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. """ def has_mouse_released_fn(self) -> bool: """ Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) """ def has_mouse_wheel_fn(self) -> bool: """ Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) """ def has_tooltip_fn(self) -> bool: """ Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. """ def scroll_here(self, center_ratio_x: float = 0.0, center_ratio_y: float = 0.0) -> None: """ Adjust scrolling amount in two axes to make current item visible. ### Arguments: `centerRatioX :` 0.0: left, 0.5: center, 1.0: right `centerRatioY :` 0.0: top, 0.5: center, 1.0: bottom """ def scroll_here_x(self, center_ratio: float = 0.0) -> None: """ Adjust scrolling amount to make current item visible. ### Arguments: `centerRatio :` 0.0: left, 0.5: center, 1.0: right """ def scroll_here_y(self, center_ratio: float = 0.0) -> None: """ Adjust scrolling amount to make current item visible. ### Arguments: `centerRatio :` 0.0: top, 0.5: center, 1.0: bottom """ def set_accept_drop_fn(self, fn: typing.Callable[[str], bool]) -> None: """ Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. """ def set_checked_changed_fn(self, fn: typing.Callable[[bool], None]) -> None: """ This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. """ def set_computed_content_size_changed_fn(self, fn: typing.Callable[[], None]) -> None: """ Called when the size of the widget is changed. """ def set_drag_fn(self, fn: typing.Callable[[], str]) -> None: """ Specify that this Widget is draggable, and set the callback that is attached to the drag operation. """ def set_drop_fn(self, fn: typing.Callable[[WidgetMouseDropEvent], None]) -> None: """ Specify that this Widget accepts drops and set the callback to the drop operation. """ def set_key_pressed_fn(self, fn: typing.Callable[[int, int, bool], None]) -> None: """ Sets the function that will be called when the user presses the keyboard key when the mouse clicks the widget. """ def set_mouse_double_clicked_fn(self, fn: typing.Callable[[float, float, int, int], None]) -> None: """ Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) """ def set_mouse_hovered_fn(self, fn: typing.Callable[[bool], None]) -> None: """ Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) """ def set_mouse_moved_fn(self, fn: typing.Callable[[float, float, int, bool], None]) -> None: """ Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) """ def set_mouse_pressed_fn(self, fn: typing.Callable[[float, float, int, int], None]) -> None: """ Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. """ def set_mouse_released_fn(self, fn: typing.Callable[[float, float, int, int], None]) -> None: """ Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) """ def set_mouse_wheel_fn(self, fn: typing.Callable[[float, float, int], None]) -> None: """ Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) """ def set_style(self, arg0: handle) -> None: """ Set the current style. The style contains a description of customizations to the widget's style. """ def set_tooltip(self, tooltip_label: str) -> None: """ Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style """ def set_tooltip_fn(self, fn: typing.Callable[[], None]) -> None: """ Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. """ @property def checked(self) -> bool: """ This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. :type: bool """ @checked.setter def checked(self, arg1: bool) -> None: """ This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. """ @property def computed_content_height(self) -> float: """ Returns the final computed height of the content of the widget. It's in puplic section. For the explanation why please see the draw() method. :type: float """ @property def computed_content_width(self) -> float: """ Returns the final computed width of the content of the widget. It's in puplic section. For the explanation why please see the draw() method. :type: float """ @property def computed_height(self) -> float: """ Returns the final computed height of the widget. It includes margins. It's in puplic section. For the explanation why please see the draw() method. :type: float """ @property def computed_width(self) -> float: """ Returns the final computed width of the widget. It includes margins. It's in puplic section. For the explanation why please see the draw() method. :type: float """ @property def dragging(self) -> bool: """ This property holds if the widget is being dragged. :type: bool """ @dragging.setter def dragging(self, arg1: bool) -> None: """ This property holds if the widget is being dragged. """ @property def enabled(self) -> bool: """ This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. :type: bool """ @enabled.setter def enabled(self, arg1: bool) -> None: """ This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. """ @property def height(self) -> Length: """ This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. :type: Length """ @height.setter def height(self, arg1: Length) -> None: """ This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. """ @property def identifier(self) -> str: """ An optional identifier of the widget we can use to refer to it in queries. :type: str """ @identifier.setter def identifier(self, arg1: str) -> None: """ An optional identifier of the widget we can use to refer to it in queries. """ @property def name(self) -> str: """ The name of the widget that user can set. :type: str """ @name.setter def name(self, arg1: str) -> None: """ The name of the widget that user can set. """ @property def opaque_for_mouse_events(self) -> bool: """ If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either :type: bool """ @opaque_for_mouse_events.setter def opaque_for_mouse_events(self, arg1: bool) -> None: """ If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either """ @property def screen_position_x(self) -> float: """ Returns the X Screen coordinate the widget was last draw. This is in Screen Pixel size. It's a float because we need negative numbers and precise position considering DPI scale factor. :type: float """ @property def screen_position_y(self) -> float: """ Returns the Y Screen coordinate the widget was last draw. This is in Screen Pixel size. It's a float because we need negative numbers and precise position considering DPI scale factor. :type: float """ @property def scroll_only_window_hovered(self) -> bool: """ When it's false, the scroll callback is called even if other window is hovered. :type: bool """ @scroll_only_window_hovered.setter def scroll_only_window_hovered(self, arg1: bool) -> None: """ When it's false, the scroll callback is called even if other window is hovered. """ @property def selected(self) -> bool: """ This property holds a flag that specifies the widget has to use eSelected state of the style. :type: bool """ @selected.setter def selected(self, arg1: bool) -> None: """ This property holds a flag that specifies the widget has to use eSelected state of the style. """ @property def skip_draw_when_clipped(self) -> bool: """ The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. :type: bool """ @skip_draw_when_clipped.setter def skip_draw_when_clipped(self, arg1: bool) -> None: """ The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. """ @property def style(self) -> object: """ The local style. When the user calls setStyle() :type: object """ @style.setter def style(self, arg1: handle) -> None: """ The local style. When the user calls setStyle() """ @property def style_type_name_override(self) -> str: """ By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. :type: str """ @style_type_name_override.setter def style_type_name_override(self, arg1: str) -> None: """ By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. """ @property def tooltip(self) -> str: """ Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style :type: str """ @tooltip.setter def tooltip(self, arg1: str) -> None: """ Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style """ @property def tooltip_offset_x(self) -> float: """ Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. :type: float """ @tooltip_offset_x.setter def tooltip_offset_x(self, arg1: float) -> None: """ Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. """ @property def tooltip_offset_y(self) -> float: """ Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. :type: float """ @tooltip_offset_y.setter def tooltip_offset_y(self, arg1: float) -> None: """ Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. """ @property def visible(self) -> bool: """ This property holds whether the widget is visible. :type: bool """ @visible.setter def visible(self, arg1: bool) -> None: """ This property holds whether the widget is visible. """ @property def visible_max(self) -> float: """ If the current zoom factor and DPI is bigger than this value, the widget is not visible. :type: float """ @visible_max.setter def visible_max(self, arg1: float) -> None: """ If the current zoom factor and DPI is bigger than this value, the widget is not visible. """ @property def visible_min(self) -> float: """ If the current zoom factor and DPI is less than this value, the widget is not visible. :type: float """ @visible_min.setter def visible_min(self, arg1: float) -> None: """ If the current zoom factor and DPI is less than this value, the widget is not visible. """ @property def width(self) -> Length: """ This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. :type: Length """ @width.setter def width(self, arg1: Length) -> None: """ This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass class WidgetMouseDropEvent(): """ Holds the data which is sent when a drag and drop action is completed. """ def __repr__(self) -> str: ... def __str__(self) -> str: ... @property def mime_data(self) -> str: """ The data that was dropped on the widget. :type: str """ @property def x(self) -> float: """ Position where the drop was made. :type: float """ @property def y(self) -> float: """ Position where the drop was made. :type: float """ pass class Window(WindowHandle): """ The Window class represents a window in the underlying windowing system. This window is a child window of main Kit window. And it can be docked. Rasterization omni.ui generates vertices every frame to render UI elements. One of the features of the framework is the ability to bake a DrawList per window and reuse it if the content has not changed, which can significantly improve performance. However, in some cases, such as the Viewport window and Console window, it may not be possible to detect whether the window content has changed, leading to a frozen window. To address this problem, you can control the rasterization behavior by adjusting RasterPolicy. The RasterPolicy is an enumeration class that defines the rasterization behavior of a window. It has three possible values: NEVER: Do not rasterize the widget at any time. ON_DEMAND: Rasterize the widget as soon as possible and always use the rasterized version. The widget will only be updated when the user calls invalidateRaster. AUTO: Automatically determine whether to rasterize the widget based on performance considerations. If necessary, the widget will be rasterized and updated when its content changes. To resolve the frozen window issue, you can manually set the RasterPolicy of the problematic window to Never. This will force the window to rasterize its content and use the rasterized version until the user explicitly calls invalidateRaster to request an update. window = ui.Window("Test window", raster_policy=ui.RasterPolicy.NEVER) """ def __init__(self, title: str, dockPreference: DockPreference = DockPreference.DISABLED, **kwargs) -> None: """ Construct the window, add it to the underlying windowing system, and makes it appear. ### Arguments: `title :` The window title. It's also used as an internal window ID. `dockPrefence :` In the old Kit determines where the window should be docked. In Kit Next it's unused. `kwargs : dict` See below ### Keyword Arguments: `flags : ` This property set the Flags for the Window. `visible : ` This property holds whether the window is visible. `title : ` This property holds the window's title. `padding_x : ` This property set the padding to the frame on the X axis. `padding_y : ` This property set the padding to the frame on the Y axis. `width : ` This property holds the window Width. `height : ` This property holds the window Height. `position_x : ` This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. `position_y : ` This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. `auto_resize : ` setup the window to resize automatically based on its content `noTabBar : ` setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically `raster_policy : ` Determine how the content of the window should be rastered. `width_changed_fn : ` This property holds the window Width. `height_changed_fn : ` This property holds the window Height. `visibility_changed_fn : ` This property holds whether the window is visible. """ def call_key_pressed_fn(self, arg0: int, arg1: int, arg2: bool) -> None: """ Sets the function that will be called when the user presses the keyboard key on the focused window. """ def deferred_dock_in(self, target_window: str, active_window: DockPolicy = DockPolicy.DO_NOTHING) -> None: """ Deferred docking. We need it when we want to dock windows before they were actually created. It's helpful when extension initialization, before any window is created. ### Arguments: `targetWindowTitle :` Dock to window with this title when it appears. `activeWindow :` Make target or this window active when docked. """ def destroy(self) -> None: """ Removes all the callbacks and circular references. """ def dock_in_window(self, title: str, dockPosition: DockPosition, ratio: float = 0.5) -> bool: """ place the window in a specific docking position based on a target window name. We will find the target window dock node and insert this window in it, either by spliting on ratio or on top if the window is not found false is return, otherwise true """ @staticmethod def get_window_callback(*args, **kwargs) -> typing.Any: """ Returns window set draw callback pointer for the given UI window. """ def has_key_pressed_fn(self) -> bool: """ Sets the function that will be called when the user presses the keyboard key on the focused window. """ def move_to_app_window(self, arg0: omni.appwindow._appwindow.IAppWindow) -> None: """ Moves the window to the specific OS window. """ def move_to_main_os_window(self) -> None: """ Bring back the Window callback to the Main Window and destroy the Current OS Window. """ def move_to_new_os_window(self) -> None: """ Move the Window Callback to a new OS Window. """ def notify_app_window_change(self, arg0: omni.appwindow._appwindow.IAppWindow) -> None: """ Notifies the window that window set has changed. """ def setPosition(self, x: float, y: float) -> None: """ This property set/get the position of the window in both axis calling the property. """ def set_docked_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None: """ Has true if this window is docked. False otherwise. It's a read-only property. """ def set_focused_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None: """ Read only property that is true when the window is focused. """ def set_height_changed_fn(self, arg0: typing.Callable[[float], None]) -> None: """ This property holds the window Height. """ def set_key_pressed_fn(self, fn: typing.Callable[[int, int, bool], None]) -> None: """ Sets the function that will be called when the user presses the keyboard key on the focused window. """ def set_position_x_changed_fn(self, arg0: typing.Callable[[float], None]) -> None: """ This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. """ def set_position_y_changed_fn(self, arg0: typing.Callable[[float], None]) -> None: """ This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. """ def set_selected_in_dock_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None: """ Has true if this window is currently selected in the dock. False otherwise. It's a read-only property. """ def set_top_modal(self) -> None: """ Brings this window to the top level of modal windows. """ def set_visibility_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None: """ This property holds whether the window is visible. """ def set_width_changed_fn(self, arg0: typing.Callable[[float], None]) -> None: """ This property holds the window Width. """ @property def app_window(self) -> omni.appwindow._appwindow.IAppWindow: """ :type: omni.appwindow._appwindow.IAppWindow """ @property def auto_resize(self) -> bool: """ setup the window to resize automatically based on its content :type: bool """ @auto_resize.setter def auto_resize(self, arg1: bool) -> None: """ setup the window to resize automatically based on its content """ @property def detachable(self) -> bool: """ If the window is able to be separated from the main application window. :type: bool """ @detachable.setter def detachable(self, arg1: bool) -> None: """ If the window is able to be separated from the main application window. """ @property def docked(self) -> bool: """ Has true if this window is docked. False otherwise. It's a read-only property. :type: bool """ @property def exclusive_keyboard(self) -> bool: """ When true, only the current window will receive keyboard events when it's focused. It's useful to override the global key bindings. :type: bool """ @exclusive_keyboard.setter def exclusive_keyboard(self, arg1: bool) -> None: """ When true, only the current window will receive keyboard events when it's focused. It's useful to override the global key bindings. """ @property def flags(self) -> int: """ This property set the Flags for the Window. :type: int """ @flags.setter def flags(self, arg1: int) -> None: """ This property set the Flags for the Window. """ @property def focus_policy(self) -> FocusPolicy: """ How the Window gains focus. :type: FocusPolicy """ @focus_policy.setter def focus_policy(self, arg1: FocusPolicy) -> None: """ How the Window gains focus. """ @property def focused(self) -> bool: """ Read only property that is true when the window is focused. :type: bool """ @property def frame(self) -> Frame: """ The main layout of this window. :type: Frame """ @property def height(self) -> float: """ This property holds the window Height. :type: float """ @height.setter def height(self, arg1: float) -> None: """ This property holds the window Height. """ @property def menu_bar(self) -> MenuBar: """ :type: MenuBar """ @property def noTabBar(self) -> bool: """ setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically :type: bool """ @noTabBar.setter def noTabBar(self, arg1: bool) -> None: """ setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically """ @property def padding_x(self) -> float: """ This property set the padding to the frame on the X axis. :type: float """ @padding_x.setter def padding_x(self, arg1: float) -> None: """ This property set the padding to the frame on the X axis. """ @property def padding_y(self) -> float: """ This property set the padding to the frame on the Y axis. :type: float """ @padding_y.setter def padding_y(self, arg1: float) -> None: """ This property set the padding to the frame on the Y axis. """ @property def position_x(self) -> float: """ This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. :type: float """ @position_x.setter def position_x(self, arg1: float) -> None: """ This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. """ @property def position_y(self) -> float: """ This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. :type: float """ @position_y.setter def position_y(self, arg1: float) -> None: """ This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position. """ @property def raster_policy(self) -> RasterPolicy: """ Determine how the content of the window should be rastered. :type: RasterPolicy """ @raster_policy.setter def raster_policy(self, arg1: RasterPolicy) -> None: """ Determine how the content of the window should be rastered. """ @property def selected_in_dock(self) -> bool: """ Has true if this window is currently selected in the dock. False otherwise. It's a read-only property. :type: bool """ @property def title(self) -> str: """ This property holds the window's title. :type: str """ @title.setter def title(self, arg1: str) -> None: """ This property holds the window's title. """ @property def visible(self) -> bool: """ This property holds whether the window is visible. :type: bool """ @visible.setter def visible(self, arg1: bool) -> None: """ This property holds whether the window is visible. """ @property def width(self) -> float: """ This property holds the window Width. :type: float """ @width.setter def width(self, arg1: float) -> None: """ This property holds the window Width. """ pass class WindowHandle(): """ WindowHandle is a handle object to control any of the windows in Kit. It can be created any time, and if it's destroyed, the source window doesn't disappear. """ def __repr__(self) -> str: ... def dock_in(self, window: WindowHandle, dock_position: DockPosition, ratio: float = 0.5) -> None: """ Dock the window to the existing window. It can split the window to two parts or it can convert the window to a docking tab. """ def focus(self) -> None: """ Brings the window to the top. If it's a docked window, it makes the window currently visible in the dock. """ def is_selected_in_dock(self) -> bool: """ Return true is the window is the current window in the docking area. """ def notify_app_window_change(self, arg0: omni.appwindow._appwindow.IAppWindow) -> None: """ Notifies the UI window that the AppWindow it attached to has changed. """ def undock(self) -> None: """ Undock the window and make it floating. """ @property def dock_id(self) -> int: """ Returns ID of the dock node this window is docked to. :type: int """ @property def dock_order(self) -> int: """ The position of the window in the dock. :type: int """ @dock_order.setter def dock_order(self, arg1: int) -> None: """ The position of the window in the dock. """ @property def dock_tab_bar_enabled(self) -> bool: """ Checks if the current docking space is disabled. The disabled docking tab bar can't be shown by the user. :type: bool """ @dock_tab_bar_enabled.setter def dock_tab_bar_enabled(self, arg1: bool) -> None: """ Checks if the current docking space is disabled. The disabled docking tab bar can't be shown by the user. """ @property def dock_tab_bar_visible(self) -> bool: """ Checks if the current docking space has the tab bar. :type: bool """ @dock_tab_bar_visible.setter def dock_tab_bar_visible(self, arg1: bool) -> None: """ Checks if the current docking space has the tab bar. """ @property def docked(self) -> bool: """ True if this window is docked. False otherwise. :type: bool """ @property def height(self) -> float: """ The height of the window in points. :type: float """ @height.setter def height(self, arg1: float) -> None: """ The height of the window in points. """ @property def position_x(self) -> float: """ The position of the window in points. :type: float """ @position_x.setter def position_x(self, arg1: float) -> None: """ The position of the window in points. """ @property def position_y(self) -> float: """ The position of the window in points. :type: float """ @position_y.setter def position_y(self, arg1: float) -> None: """ The position of the window in points. """ @property def title(self) -> str: """ The title of the window. :type: str """ @property def visible(self) -> bool: """ Returns whether the window is visible. :type: bool """ @visible.setter def visible(self, arg1: bool) -> None: """ Returns whether the window is visible. """ @property def width(self) -> float: """ The width of the window in points. :type: float """ @width.setter def width(self, arg1: float) -> None: """ The width of the window in points. """ pass class Workspace(): """ Workspace object provides access to the windows in Kit. """ @staticmethod def clear() -> None: """ Undock all. """ @staticmethod def get_dock_children_id(dock_id: int) -> object: """ Get two dock children of the given dock ID. true if the given dock ID has children ### Arguments: `dockId :` the given dock ID `first :` output. the first child dock ID `second :` output. the second child dock ID """ @staticmethod def get_dock_id_height(dock_id: int) -> float: """ Returns the height of the docking node. It's different from the window height because it considers dock tab bar. ### Arguments: `dockId :` the given dock ID """ @staticmethod def get_dock_id_width(dock_id: int) -> float: """ Returns the width of the docking node. ### Arguments: `dockId :` the given dock ID """ @staticmethod def get_dock_position(dock_id: int) -> DockPosition: """ Returns the position of the given dock ID. Left/Right/Top/Bottom. """ @staticmethod def get_docked_neighbours(member: WindowHandle) -> typing.List[WindowHandle]: """ Get all the windows that docked with the given widow. """ @staticmethod def get_docked_windows(dock_id: int) -> typing.List[WindowHandle]: """ Get all the windows of the given dock ID. """ @staticmethod def get_dpi_scale() -> float: """ Returns current DPI Scale. """ @staticmethod def get_main_window_height() -> float: """ Get the height in points of the current main window. """ @staticmethod def get_main_window_width() -> float: """ Get the width in points of the current main window. """ @staticmethod def get_parent_dock_id(dock_id: int) -> int: """ Return the parent Dock Node ID. ### Arguments: `dockId :` the child Dock Node ID to get parent """ @staticmethod def get_selected_window_index(dock_id: int) -> int: """ Get currently selected window inedx from the given dock id. """ @staticmethod def get_window(title: str) -> WindowHandle: """ Find Window by name. """ @staticmethod def get_window_from_callback(*args, **kwargs) -> typing.Any: """ Find Window by window callback. """ @staticmethod def get_windows() -> typing.List[WindowHandle]: """ Returns the list of windows ordered from back to front. If the window is a Omni::UI window, it can be upcasted. """ @staticmethod def remove_window_visibility_changed_callback(fn: int) -> None: """ Remove the callback that is triggered when window's visibility changed. """ @staticmethod def set_dock_id_height(dock_id: int, height: float) -> None: """ Set the height of the dock node. It also sets the height of parent nodes if necessary and modifies the height of siblings. ### Arguments: `dockId :` the given dock ID `height :` the given height """ @staticmethod def set_dock_id_width(dock_id: int, width: float) -> None: """ Set the width of the dock node. It also sets the width of parent nodes if necessary and modifies the width of siblings. ### Arguments: `dockId :` the given dock ID `width :` the given width """ @staticmethod def set_show_window_fn(title: str, fn: typing.Callable[[bool], None]) -> None: """ Add the callback to create a window with the given title. When the callback's argument is true, it's necessary to create the window. Otherwise remove. """ @staticmethod def set_window_created_callback(fn: typing.Callable[[WindowHandle], None]) -> None: """ Addd the callback that is triggered when a new window is created. """ @staticmethod def set_window_visibility_changed_callback(fn: typing.Callable[[str, bool], None]) -> int: """ Add the callback that is triggered when window's visibility changed. """ @staticmethod def show_window(title: str, show: bool = True) -> bool: """ Makes the window visible or create the window with the callback provided with set_show_window_fn. true if the window is already created, otherwise it's necessary to wait one frame ### Arguments: `title :` the given window title `show :` true to show, false to hide """ pass class ZStack(Stack, Container, Widget): """ Shortcut for Stack{eBackToFront}. The widgets are placed sorted in a Z-order in top right corner with suitable sizes. """ def __init__(self, **kwargs) -> None: """ Construct a stack with the widgets placed in a Z-order with sorting from background to foreground. `kwargs : dict` See below ### Keyword Arguments: `direction : ` This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front. `content_clipping : ` Determines if the child widgets should be clipped by the rectangle of this Stack. `spacing : ` Sets a non-stretchable space in pixels between child items of this layout. `send_mouse_events_to_back : ` When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child. `width : ui.Length` This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen. `height : ui.Length` This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen. `name : str` The name of the widget that user can set. `style_type_name_override : str` By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style. `identifier : str` An optional identifier of the widget we can use to refer to it in queries. `visible : bool` This property holds whether the widget is visible. `visibleMin : float` If the current zoom factor and DPI is less than this value, the widget is not visible. `visibleMax : float` If the current zoom factor and DPI is bigger than this value, the widget is not visible. `tooltip : str` Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style `tooltip_fn : Callable` Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly. `tooltip_offset_x : float` Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `tooltip_offset_y : float` Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown. `enabled : bool` This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled. `selected : bool` This property holds a flag that specifies the widget has to use eSelected state of the style. `checked : bool` This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked. `dragging : bool` This property holds if the widget is being dragged. `opaque_for_mouse_events : bool` If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either `skip_draw_when_clipped : bool` The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list. `mouse_moved_fn : Callable` Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier) `mouse_pressed_fn : Callable` Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key. `mouse_released_fn : Callable` Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_double_clicked_fn : Callable` Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) `mouse_wheel_fn : Callable` Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier) `mouse_hovered_fn : Callable` Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered) `drag_fn : Callable` Specify that this Widget is draggable, and set the callback that is attached to the drag operation. `accept_drop_fn : Callable` Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted. `drop_fn : Callable` Specify that this Widget accepts drops and set the callback to the drop operation. `computed_content_size_changed_fn : Callable` Called when the size of the widget is changed. """ FLAG_WANT_CAPTURE_KEYBOARD = 1073741824 pass def dock_window_in_window(arg0: str, arg1: str, arg2: DockPosition, arg3: float) -> bool: """ place a named window in a specific docking position based on a target window name. We will find the target window dock node and insert this named window in it, either by spliting on ratio or on top if the windows is not found false is return, otherwise true """ def get_custom_glyph_code(file_path: str, font_style: FontStyle = FontStyle.NORMAL) -> str: """ Get glyph code. Args: file_path (str): Path to svg file font_style(:class:`.FontStyle`): font style to use. """ def get_main_window_height() -> float: """ Get the height in points of the current main window. """ def get_main_window_width() -> float: """ Get the width in points of the current main window. """ WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR = 32768 WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR = 16384 WINDOW_FLAGS_MENU_BAR = 1024 WINDOW_FLAGS_MODAL = 134217728 WINDOW_FLAGS_NONE = 0 WINDOW_FLAGS_NO_BACKGROUND = 128 WINDOW_FLAGS_NO_CLOSE = 2147483648 WINDOW_FLAGS_NO_COLLAPSE = 32 WINDOW_FLAGS_NO_DOCKING = 2097152 WINDOW_FLAGS_NO_FOCUS_ON_APPEARING = 4096 WINDOW_FLAGS_NO_MOUSE_INPUTS = 512 WINDOW_FLAGS_NO_MOVE = 4 WINDOW_FLAGS_NO_RESIZE = 2 WINDOW_FLAGS_NO_SAVED_SETTINGS = 256 WINDOW_FLAGS_NO_SCROLLBAR = 8 WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE = 16 WINDOW_FLAGS_NO_TITLE_BAR = 1 WINDOW_FLAGS_POPUP = 67108864 WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR = 2048
598,452
unknown
49.780908
755
0.649192
omniverse-code/kit/exts/omni.ui/omni/ui/__init__.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## """ Omni::UI -------- Omni::UI is Omniverse's UI toolkit for creating beautiful and flexible graphical user interfaces in the Kit extensions. Omni::UI provides the basic types necessary to create rich extensions with a fluid and dynamic user interface in Omniverse Kit. It gives a layout system and includes widgets for creating visual components, receiving user input, and creating data models. It allows user interface components to be built around their behavior and enables a declarative flavor of describing the layout of the application. Omni::UI gives a very flexible styling system that allows deep customizing the final look of the application. Typical Example --------------- Typical example to create a window with two buttons: .. code-block:: import omni.ui as ui _window_example = ui.Window("Example Window", width=300, height=300) with _window_example.frame: with ui.VStack(): ui.Button("click me") def move_me(window): window.setPosition(200, 200) def size_me(window): window.width = 300 window.height = 300 ui.Button("Move to (200,200)", clicked_fn=lambda w=self._window_example: move_me(w)) ui.Button("Set size (300,300)", clicked_fn=lambda w=self._window_example: size_me(w)) Detailed Documentation ---------------------- Omni::UI is shipped with the developer documentation that is written with Omni::UI. For detailed documentation, please see `omni.example.ui` extension. It has detailed descriptions of all the classes, best practices, and real-world usage examples. Layout ------ * Arrangement of elements * :class:`omni.ui.CollapsableFrame` * :class:`omni.ui.Frame` * :class:`omni.ui.HStack` * :class:`omni.ui.Placer` * :class:`omni.ui.ScrollingFrame` * :class:`omni.ui.Spacer` * :class:`omni.ui.VStack` * :class:`omni.ui.ZStack` * Lengths * :class:`omni.ui.Fraction` * :class:`omni.ui.Percent` * :class:`omni.ui.Pixel` Widgets ------- * Base Widgets * :class:`omni.ui.Button` * :class:`omni.ui.Image` * :class:`omni.ui.Label` * Shapes * :class:`omni.ui.Circle` * :class:`omni.ui.Line` * :class:`omni.ui.Rectangle` * :class:`omni.ui.Triangle` * Menu * :class:`omni.ui.Menu` * :class:`omni.ui.MenuItem` * Model-View Widgets * :class:`omni.ui.AbstractItemModel` * :class:`omni.ui.AbstractValueModel` * :class:`omni.ui.CheckBox` * :class:`omni.ui.ColorWidget` * :class:`omni.ui.ComboBox` * :class:`omni.ui.RadioButton` * :class:`omni.ui.RadioCollection` * :class:`omni.ui.TreeView` * Model-View Fields * :class:`omni.ui.FloatField` * :class:`omni.ui.IntField` * :class:`omni.ui.MultiField` * :class:`omni.ui.StringField` * Model-View Drags and Sliders * :class:`omni.ui.FloatDrag` * :class:`omni.ui.FloatSlider` * :class:`omni.ui.IntDrag` * :class:`omni.ui.IntSlider` * Model-View ProgressBar * :class:`omni.ui.ProgressBar` * Windows * :class:`omni.ui.ToolBar` * :class:`omni.ui.Window` * :class:`omni.ui.Workspace` * Web * :class:`omni.ui.WebViewWidget` """ import omni.gpu_foundation_factory # carb::graphics::Format used as default argument in BindByteImageProvider.cpp from ._ui import * from .color_utils import color from .constant_utils import constant from .style_utils import style from .url_utils import url from .workspace_utils import dump_workspace from .workspace_utils import restore_workspace from .workspace_utils import compare_workspace from typing import Optional # Importing TextureFormat here explicitly to maintain backwards compatibility from omni.gpu_foundation_factory import TextureFormat def add_to_namespace(module=None, module_locals=locals()): class AutoRemove: def __init__(self): self.__key = module.__name__.split(".")[-1] module_locals[self.__key] = module def __del__(self): module_locals.pop(self.__key, None) if not module: return return AutoRemove() # Add the static methods to Workspace setattr(Workspace, "dump_workspace", dump_workspace) setattr(Workspace, "restore_workspace", restore_workspace) setattr(Workspace, "compare_workspace", compare_workspace) del dump_workspace del restore_workspace del compare_workspace def set_shade(shade_name: Optional[str] = None): color.set_shade(shade_name) constant.set_shade(shade_name) url.set_shade(shade_name) def set_menu_delegate(delegate: MenuDelegate): """ Set the default delegate to use it when the item doesn't have a delegate. """ MenuDelegate.set_default_delegate(delegate)
5,164
Python
28.514286
118
0.687452
omniverse-code/kit/exts/omni.ui/omni/ui/workspace_utils.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. # """The utilities to capture and restore layout""" from . import _ui as ui from typing import Any, Tuple from typing import Dict from typing import List from typing import Optional import asyncio import carb import carb.settings import functools import math import omni.appwindow import omni.kit.app import omni.kit.renderer.bind import traceback ROOT_WINDOW_NAME = "DockSpace" SAME = "SAME" LEFT = "LEFT" RIGHT = "RIGHT" TOP = "TOP" BOTTOM = "BOTTOM" EXCLUDE_WINDOWS = [ ROOT_WINDOW_NAME, "Debug##Default", "Status Bar", "Select File to Save Layout", "Select File to Load Layout", ] # Used to prevent _restore_workspace_async from execution simultaneously restore_workspace_task_global = None # Define the settings path for enabling and setting the number of frames for # draw freeze in UI SETTING_DRAWFREEZE_ENABLED = "/exts/omni.ui/workpace/draw_freeze/enabled" SETTING_DRAWFREEZE_FRAMES = "/exts/omni.ui/workpace/draw_freeze/frames" class CompareDelegate(): def __init__(self): pass def failed_get_window(self, error_list: list, target: dict): if target["visible"]: error_list.append(f"failed to get window \"{target['title']}\"") def failed_window_key(self, error_list: list, key: str, target: dict, target_window: ui.Window): error_list.append(f"{key} not found in {target_window.__class__.__name__} for window \"{target}\"") def failed_window_value(self, error_list: list, key: str, value, target: dict, target_window: ui.Window): error_list.append(f"failure for window \"{target['title']}\". Key \"{key}\" expected {target[key]} but has {value}") def compare_value(self, key:str, value, target): if type(value) == float: return math.isclose(value, target[key], abs_tol=1.5) return bool(value == target[key]) def compare_dock_in_value_position_x(self, key:str, value, target): # position_x isn't set for docked windows, so skip compare return True def compare_dock_in_value_position_y(self, key:str, value, target): # position_y isn't set for docked windows, so skip compare return True def compare_dock_in_value_width(self, key:str, value, target): # width isn't set for docked windows, so skip compare return True def compare_dock_in_value_height(self, key:str, value, target): # height isn't set for docked windows, so skip compare return True def compare_dock_in_value_dock_id(self, key:str, value, target): # compare dock_id for docked windows - dock_id isn't guarenteed to be same value, so just verify they are docked return bool(value != int(0) and target[key] != int(0)) def compare_window_value_dock_id(self, key:str, value, target): # compare dock_id for floating windows - dock_id should be 0 return bool(value == int(0) and target[key] == int(0)) 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 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 _dump_window(window: ui.WindowHandle, window_list: List[str]): """Convert WindowHandle to the window description as a dict.""" window_title = window.title window_list.append(window_title) selected_in_dock = window.is_selected_in_dock() result = { "title": window_title, "width": window.width, "height": window.height, "position_x": window.position_x, "position_y": window.position_y, "dock_id": window.dock_id, "visible": window.visible if type(window) != ui.WindowHandle else False, "selected_in_dock": selected_in_dock, } if selected_in_dock: result["dock_tab_bar_visible"] = window.dock_tab_bar_visible result["dock_tab_bar_enabled"] = window.dock_tab_bar_enabled return result def _dump_dock_node(dock_id: int, window_list: List[str]): """Convert dock id to the node description as a dict.""" result: Dict[str, Any] = {"dock_id": dock_id} children_docks = ui.Workspace.get_dock_children_id(dock_id) position = ui.Workspace.get_dock_position(dock_id) if position != ui.DockPosition.SAME: result["position"] = position.name if children_docks: # Children are docking nodes. Add them recursively. result["children"] = [ _dump_dock_node(children_docks[0], window_list), _dump_dock_node(children_docks[1], window_list), ] else: # All the children are windows docked_windows = ui.Workspace.get_docked_windows(dock_id) children_windows = [_dump_window(window, window_list) for window in docked_windows] # The size of the unselected window is the size the window was visible. # We need to get the size of the selected window and set it to all the # siblings. selected = [window["selected_in_dock"] for window in children_windows] try: selected_id = selected.index(True) except ValueError: selected_id = None if selected_id is not None: width = children_windows[selected_id]["width"] height = children_windows[selected_id]["height"] # Found width/height of selected window. Set it to all children. for child in children_windows: child["width"] = width child["height"] = height result["children"] = children_windows return result def _dock_in(target: dict, source: dict, position: str, ratio: float): """ Docks windows together. The difference with ui.WindowHandle.dock_in is that, it takes window descriptions as dicts. Args: target: the dictionary with the description of the window it's necessary to dock to source. source: the dictionary with the description of the window to dock in. position: "SAME", "LEFT", "RIGHT", "TOP", "BOTTOM". ratio: when docking side by side, specifies where there will be the border. """ # Convert string to DockPosition # TODO: DockPosition is pybind11 enum and it probably has this conversion if position == SAME: dock_position = ui.DockPosition.SAME elif position == LEFT: dock_position = ui.DockPosition.LEFT elif position == RIGHT: dock_position = ui.DockPosition.RIGHT elif position == TOP: dock_position = ui.DockPosition.TOP elif position == BOTTOM: dock_position = ui.DockPosition.BOTTOM else: raise ValueError(f"{position} is not member of ui.DockPosition") target_window = ui.Workspace.get_window(target["title"]) source_window = ui.Workspace.get_window(source["title"]) carb.log_verbose(f"Docking window '{target_window}'.dock_in('{source_window}', {dock_position}, {ratio})") try: target_window.dock_in(source_window, dock_position, ratio) except AttributeError: carb.log_warn( f"Can't restore {target['title']}. A window with this title could not be found. Make sure that auto-load has been enabled for this extension." ) # Stop deferred docking if isinstance(target_window, ui.Window): target_window.deferred_dock_in("") def _compare_dock_in(target: dict, error_list: list, compare_delegate: CompareDelegate): target_window = ui.Workspace.get_window(target["title"]) if not target_window: return compare_delegate.failed_get_window(error_list, target) # windows of type ui.WindowHandle are placeholders and values are not necessarily valid if type(target_window) == ui.WindowHandle: return if not target["visible"] and not target_window.visible: return elif target["visible"] != target_window.visible: return compare_delegate.failed_window_value(error_list, "visible", target_window.visible, target, target_window) selected_in_dock = target["selected_in_dock"] for key in target: if not hasattr(target_window, key): compare_delegate.failed_window_key(error_list, key, target, target_window) continue value = getattr(target_window, key) compare_fn = getattr(compare_delegate, f"compare_dock_in_value_{key}", compare_delegate.compare_value) if not compare_fn(key, value, target): compare_delegate.failed_window_value(error_list, key, value, target, target_window) def _dock_order(target: dict, order: int): """Set the position of the window in the dock.""" window = ui.Workspace.get_window(target["title"]) try: window.dock_order = order if target.get("selected_in_dock", None): window.focus() except AttributeError: carb.log_warn( f"Can't set dock order for {target['title']}. A window with this title could not be found. Make sure that auto-load has been enabled for this extension." ) def _restore_tab_bar(target: dict): """Restore dock_tab_bar_visible and dock_tab_bar_enabled""" window = ui.Workspace.get_window(target["title"]) dock_tab_bar_visible = target.get("dock_tab_bar_visible", None) if dock_tab_bar_visible is not None: if window: window.dock_tab_bar_visible = dock_tab_bar_visible else: carb.log_warn( f"Can't set tab bar visibility for {target['title']}. A window " "with this title could not be found. Make sure that auto-load " "has been enabled for this extension." ) return dock_tab_bar_enabled = target.get("dock_tab_bar_enabled", None) if dock_tab_bar_enabled is not None: if window: window.dock_tab_bar_enabled = dock_tab_bar_enabled else: carb.log_warn( f"Can't enable tab bar for {target['title']}. A window with " "this title could not be found. Make sure that auto-load has " "been enabled for this extension." ) def _is_dock_node(node: dict): """Return True if the dict is a dock node description""" return isinstance(node, dict) and "children" in node def _is_window(window: dict): """Return True if the dict is a window description""" return isinstance(window, dict) and "title" in window def _is_all_windows(windows: list): """Return true if all the items of the given list are window descriptions""" for w in windows: if not _is_window(w): return False return True def _is_all_docks(children: list): """Return true if all the provided children are docking nodes""" return len(children) == 2 and _is_dock_node(children[0]) and _is_dock_node(children[1]) def _has_children(workspace_description: dict): """Return true if the item has valin nonempty children""" if not _is_dock_node(workspace_description): # Windows don't have children return False for c in workspace_description["children"]: if _is_window(c) or _has_children(c): return True return False def _get_children(workspace_description: dict): """Return nonempty children""" children = workspace_description["children"] children = [c for c in children if _is_window(c) or _has_children(c)] if len(children) == 1 and _is_dock_node(children[0]): return _get_children(children[0]) return children def _target(workspace_description: dict): """Recursively find the first available window in the dock node""" children = _get_children(workspace_description) first = children[0] if _is_window(first): return first return _target(first) def _restore_workspace( workspace_description: dict, root: dict, dock_order: List[Tuple[Any, int]], windows_to_set_dock_visibility: List[Dict], ): """ Dock all the windows according to the workspace description. Args: workspace_description: the given workspace description. root: the root node to dock everything into. dock_order: output list of windows to adjust docking order. windows_to_set_dock_visibility: list of windows that have the info about dock_tab_bar """ children = _get_children(workspace_description) if _is_all_docks(children): # Children are dock nodes first = _target(children[0]) second = _target(children[1]) if children[1]["position"] == RIGHT: first_width = _get_width(children[0]) second_width = _get_width(children[1]) ratio = second_width / (first_width + second_width) else: first_height = _get_height(children[0]) second_height = _get_height(children[1]) ratio = second_height / (first_height + second_height) # Dock the second window to the root _dock_in(second, root, children[1]["position"], ratio) # Recursively dock children _restore_workspace(children[0], first, dock_order, windows_to_set_dock_visibility) _restore_workspace(children[1], second, dock_order, windows_to_set_dock_visibility) elif _is_all_windows(children): # Children are windows. Dock everything to the first window in the list first = None children_count = len(children) for i, w in enumerate(children): # Save docking order if children_count > 1: dock_order.append((w, i)) if w.get("selected_in_dock", None): windows_to_set_dock_visibility.append(w) if not first: first = w else: _dock_in(w, first, "SAME", 0.5) def _compare_workspace(workspace_description: dict, root: dict, error_list: list, compare_delegate: CompareDelegate): children = _get_children(workspace_description) if _is_all_docks(children): # Children are dock nodes first = _target(children[0]) second = _target(children[1]) if children[1]["position"] == RIGHT: first_width = _get_width(children[0]) second_width = _get_width(children[1]) ratio = second_width / (first_width + second_width) else: first_height = _get_height(children[0]) second_height = _get_height(children[1]) ratio = second_height / (first_height + second_height) # Verify the second window to the root _compare_dock_in(second, error_list, compare_delegate) # Recursively verify children _compare_workspace(children[0], first, error_list, compare_delegate) _compare_workspace(children[1], second, error_list, compare_delegate) elif _is_all_windows(children): # Children are windows. Verify everything to the first window in the list first = None children_count = len(children) for i, w in enumerate(children): if not first: first = w else: _compare_dock_in(w, error_list, compare_delegate) def _get_visible_windows(workspace_description: dict, visible: bool): result = [] if _is_dock_node(workspace_description): for w in _get_children(workspace_description): result += _get_visible_windows(w, visible) elif _is_window(workspace_description): visible_flag = workspace_description.get("visible", None) if visible: if visible_flag is None or visible_flag: result.append(workspace_description["title"]) else: # visible == False # Separate branch because we don't want to add the window with no # "visible" flag if not visible_flag: result.append(workspace_description["title"]) return result async def _restore_window(window_description: dict): """Set the position and the size of the window""" # Skip invisible windows visible = window_description.get("visible", None) if visible is False: return # Skip the window that doesn't exist window = ui.Workspace.get_window(window_description["title"]) if not window: return # window could docked, need to undock otherwise position/size may not take effect # but window.docked is always False and window.dock_id is always 0, so cannot test window.undock() await omni.kit.app.get_app().next_update_async() window.position_x = window_description["position_x"] window.position_y = window_description["position_y"] window.width = window_description["width"] window.height = window_description["height"] def _compare_window(window_description: dict, error_list: list, compare_delegate: CompareDelegate): target_window = ui.Workspace.get_window(window_description["title"]) if not target_window: return compare_delegate.failed_get_window(error_list, window_description) # windows of type ui.WindowHandle are placeholders and values are not necessarily valid if type(target_window) == ui.WindowHandle: return if not window_description["visible"] and not target_window.visible: return elif window_description["visible"] != target_window.visible: return compare_delegate.failed_window_value(error_list, "visible", target_window.visible, window_description, target_window) for key in window_description: if not hasattr(target_window, key): compare_delegate.failed_window_key(error_list, key, window_description, target_window) continue value = getattr(target_window, key) compare_fn = getattr(compare_delegate, f"compare_window_value_{key}", compare_delegate.compare_value) if not compare_fn(key, value, window_description): compare_delegate.failed_window_value(error_list, key, value, window_description, target_window) def _get_width(node: dict): """Compute width of the given dock. It recursively checks the child windows.""" children = _get_children(node) if _is_all_docks(children): if children[1]["position"] == BOTTOM or children[1]["position"] == TOP: return _get_width(children[0]) elif children[1]["position"] == RIGHT or children[1]["position"] == LEFT: return _get_width(children[0]) + _get_width(children[1]) elif _is_all_windows(children): return children[0]["width"] def _get_height(node: dict): """Compute height of the given dock. It recursively checks the child windows.""" children = _get_children(node) if _is_all_docks(children): if children[1]["position"] == BOTTOM or children[1]["position"] == TOP: return _get_height(children[0]) + _get_height(children[1]) elif children[1]["position"] == RIGHT or children[1]["position"] == LEFT: return _get_height(children[0]) elif _is_all_windows(children): return children[0]["height"] @handle_exception async def _restore_workspace_async( workspace_dump: List[Any], visible_titles: List[str], keep_windows_open: bool, wait_for: Optional[asyncio.Task] = None, ): """Dock the windows according to the workspace description""" if wait_for is not None: # Wait for another _restore_workspace_async task await wait_for # Fetching and reading the settings settings = carb.settings.get_settings() draw_freeze_enabled = settings.get(SETTING_DRAWFREEZE_ENABLED) # Freeze the window drawing if draw freeze is enabled # This is done to ensure a smooth layout change, without visible updates, if # draw freeze is enabled if draw_freeze_enabled: # Get IRenderer renderer = omni.kit.renderer.bind.get_renderer_interface() # Get default IAppWindow app_window_factory = omni.appwindow.acquire_app_window_factory_interface() app_window = app_window_factory.get_app_window() # Draw freeze the window renderer.draw_freeze_app_window(app_window, True) ui.Workspace.clear() visible_titles_set = set(visible_titles) workspace_visible_windows = set() workspace_hidden_windows = set() already_visible = True for workspace_description in workspace_dump: visible_windows = _get_visible_windows(workspace_description, True) hidden_windows = _get_visible_windows(workspace_description, False) workspace_visible_windows = workspace_visible_windows.union(visible_windows) workspace_hidden_windows = workspace_hidden_windows.union(hidden_windows) for window_title in visible_windows: already_visible = ui.Workspace.show_window(window_title) and already_visible # The rest of the windows should be closed hide_windows = [] if keep_windows_open: # Close the windows with flag "visible=False". Don't close the windows # that don't have this flag. hide_windows = visible_titles_set.intersection(workspace_hidden_windows) for window_title in hide_windows: ui.Workspace.show_window(window_title, False) else: # Close all the widows that don't have flag "visible=True" hide_windows = visible_titles_set - workspace_visible_windows for window_title in hide_windows: ui.Workspace.show_window(window_title, False) if not already_visible: # One of the windows is just created. ImGui needs to initialize it # to dock it. Wait one frame. await omni.kit.app.get_app().next_update_async() else: # Otherwise: RuntimeWarning: coroutine '_restore_workspace_async' was never awaited await asyncio.sleep(0) dock_order: List[Tuple[Any, int]] = [] windows_to_set_dock_visibility: List[Dict] = [] for i, workspace_description in enumerate(workspace_dump): if i == 0: # The first window in the dump is the root window root_window_dump = workspace_dump[0] if not _has_children(root_window_dump): continue first_root = _target(root_window_dump) _dock_in(first_root, {"title": ROOT_WINDOW_NAME}, "SAME", 0.5) _restore_workspace(root_window_dump, first_root, dock_order, windows_to_set_dock_visibility) elif _is_window(workspace_description): # Floating window await _restore_window(workspace_description) # TODO: Floating window that is docked to another floating window if dock_order or windows_to_set_dock_visibility: # Wait one frame to dock everything await omni.kit.app.get_app().next_update_async() if dock_order: # Restore docking order for window, position in dock_order: _dock_order(window, position) if windows_to_set_dock_visibility: # Restore dock_tab_bar_visible and dock_tab_bar_enabled for window in windows_to_set_dock_visibility: _restore_tab_bar(window) wait_frames = 1 # If draw freeze is enable we fetch the number of frames we have to wait if draw_freeze_enabled: wait_frames = settings.get(SETTING_DRAWFREEZE_FRAMES) or 0 # Let ImGui finish all the layout, by waiting for the specified frames number. for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() # After workspace processing and the specified number of frames passed, we # unfreeze the drawing if draw_freeze_enabled: renderer.draw_freeze_app_window(app_window, False) def dump_workspace(): """ Capture current workspace and return the dict with the description of the docking state and window size. """ dumped_windows: List[str] = [] workspace_dump: List[Any] = [] # Dump the root window dock_space = ui.Workspace.get_window(ROOT_WINDOW_NAME) if dock_space: workspace_dump.append(_dump_dock_node(dock_space.dock_id, dumped_windows)) # Dump the rest for window in ui.Workspace.get_windows(): title = window.title if title not in EXCLUDE_WINDOWS and title not in dumped_windows: workspace_dump.append(_dump_window(window, dumped_windows)) return workspace_dump def restore_workspace(workspace_dump: List[Any], keep_windows_open=False): """ Dock the windows according to the workspace description. ### Arguments `workspace_dump : List[Any]` The dictionary with the description of the layout. It's the dict received from `dump_workspace`. `keep_windows_open : bool` Determines if it's necessary to hide the already opened windows that are not present in `workspace_dump`. """ global restore_workspace_task_global # Visible titles # `WindowHandle.visible` is different when it's called from `ensure_future` # because it's called outside of ImGui::Begin/ImGui::End. As result, the # `Console` window is not in the list of visible windows and it's not # closed. That's why it's called here and passed to # `_restore_workspace_async`. workspace_windows = ui.Workspace.get_windows() visible_titles = [w.title for w in workspace_windows if w.visible and w.title not in EXCLUDE_WINDOWS] restore_workspace_task_global = asyncio.ensure_future( _restore_workspace_async(workspace_dump, visible_titles, keep_windows_open, restore_workspace_task_global) ) def compare_workspace(workspace_dump: List[Any], compare_delegate: CompareDelegate=CompareDelegate()): """ Compare current docked windows according to the workspace description. ### Arguments `workspace_dump : List[Any]` The dictionary with the description of the layout. It's the dict received from `dump_workspace`. """ workspace_windows = ui.Workspace.get_windows() visible_titles = [w.title for w in workspace_windows if w.visible and w.title not in EXCLUDE_WINDOWS] visible_titles_set = set(visible_titles) workspace_visible_windows = set() workspace_hidden_windows = set() already_visible = True for workspace_description in workspace_dump: visible_windows = _get_visible_windows(workspace_description, True) workspace_visible_windows = workspace_visible_windows.union(visible_windows) error_list = [] for i, workspace_description in enumerate(workspace_dump): if i == 0: # The first window in the dump is the root window root_window_dump = workspace_dump[0] if not _has_children(root_window_dump): continue first_root = _target(root_window_dump) _compare_dock_in(first_root, error_list, compare_delegate=compare_delegate) _compare_workspace(root_window_dump, first_root, error_list, compare_delegate=compare_delegate) elif _is_window(workspace_description): # Floating window _compare_window(workspace_description, error_list, compare_delegate=compare_delegate) return error_list
27,741
Python
37.854342
165
0.654987
omniverse-code/kit/exts/omni.ui/omni/ui/url_utils.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from . import _ui as ui from .singleton import Singleton from .abstract_shade import AbstractShade @Singleton class StringShade(AbstractShade): """ The shade functionality for float style parameters. Usage: ui.Rectangle(style={"border_width": fl.shade(1, light=0)}) # Make no border cl.set_shade("light") # Make border width 1 cl.set_shade("default") """ def _find(self, name: str) -> float: return ui.StringStore.find(name) def _store(self, name: str, value: str): return ui.StringStore.store(name, value) url = StringShade()
1,044
Python
27.243243
76
0.706897
omniverse-code/kit/exts/omni.ui/omni/ui/color_utils.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from . import _ui as ui from .abstract_shade import AbstractShade from .singleton import Singleton from typing import Optional from typing import Union import struct @Singleton class ColorShade(AbstractShade): """ Usage: import omni.ui.color as cl ui.Button(style={"color": cl.kit_bg}) ui.CheckBox(style={"color": cl.kit_bg}) ui.Slider(style={"color": "kit_bg"}) # Make everything light: cl.kit_bg = (1,1,1) # Make everything dark: cl.kit_bg = (0,0,0) Usage: ui.Button( style={ "color": cl.shade( (0.1, 0.1, 0.1), light=(1,1,1), green=(0,0,1))}) ui.CheckBox( style={ "color": cl.shade( (0.2, 0.2, 0.2), light=(1,1,1), name="my_bg")}) ui.Slider( style={"color": cl.my_bg}) # Make everything light: cl.set_shade("light") # Make everything dark: cl.set_shade("default") """ def _find(self, name: str) -> int: return ui.ColorStore.find(name) def _store(self, name: str, value: int): return ui.ColorStore.store(name, value) def __call__( self, r: Union[str, int, float], g: Optional[Union[float, int]] = None, b: Optional[Union[float, int]] = None, a: Optional[Union[float, int]] = None, ) -> int: """ Convert color representation to uint32_t color. ### Supported ways to set color: - `cl("#CCCCCC")` - `cl("#CCCCCCFF")` - `cl(128, 128, 128)` - `cl(0.5, 0.5, 0.5)` - `cl(128, 128, 128, 255)` - `cl(0.5, 0.5, 0.5, 1.0)` - `cl(128)` - `cl(0.5)` """ # Check if rgb are numeric allnumeric = True hasfloat = False for i in [r, g, b]: if isinstance(i, int): pass elif isinstance(i, float): hasfloat = True else: allnumeric = False break if allnumeric: if hasfloat: # FLOAT RGBA if isinstance(a, float) or isinstance(a, int): alpha = min(255, max(0, int(a * 255))) else: alpha = 255 rgba = ( min(255, max(0, int(r * 255))), min(255, max(0, int(g * 255))), min(255, max(0, int(b * 255))), alpha, ) else: # INT RGBA if isinstance(a, int): alpha = min(255, max(0, a)) else: alpha = 255 rgba = (min(255, max(0, r)), min(255, max(0, g)), min(255, max(0, b)), alpha) elif isinstance(r, str) and g is None and b is None and a is None: # HTML Color value = r.lstrip("#") # Add FF alpha if there is no alpha value += "F" * max(0, 8 - len(value)) rgba = struct.unpack("BBBB", bytes.fromhex(value)) elif isinstance(r, int) and g is None and b is None: # Single INT rr = min(255, max(0, r)) rgba = (rr, rr, rr, 255) elif isinstance(r, float) and g is None and b is None: # Single FLOAT rr = min(255, max(0, int(r * 255))) rgba = (rr, rr, rr, 255) else: # TODO: More representations, like HSV raise ValueError return (rgba[3] << 24) + (rgba[2] << 16) + (rgba[1] << 8) + (rgba[0] << 0) color = ColorShade()
4,208
Python
29.280575
93
0.477899
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_overflow.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest from pathlib import Path import asyncio import sys import omni.kit.app import omni.ui as ui CURRENT_PATH = Path(__file__).parent DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data") class TestOverflow(OmniUiTest): # Testing ui.IntField for overflow exception async def test_int_overflow(self): from omni.kit import ui_test window = ui.Window("IntField", width=450, height=800) with window.frame: with ui.VStack(): ui.Spacer(height=10) ui.IntField(model=ui.SimpleIntModel()) ui.Spacer(height=10) widget = ui_test.find("IntField//Frame/**/IntField[*]") await widget.input("99999999999999999999999999999999999999999999") await ui_test.human_delay(500) # Testing ui.FloatField for overflow exception async def test_float_overflow(self): from omni.kit import ui_test window = ui.Window("FloatField", width=450, height=800) with window.frame: with ui.VStack(): ui.Spacer(height=10) ui.FloatField(model=ui.SimpleFloatModel()) ui.Spacer(height=10) widget = ui_test.find("FloatField//Frame/**/FloatField[*]") await widget.input("1.6704779438076223e-52") await ui_test.human_delay(500)
1,817
Python
34.647058
77
0.67749
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_no_gpu.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestNoGPU"] import omni.kit.test import omni.ui as ui class TestNoGPU(omni.kit.test.AsyncTestCase): def test_workspace(self): """Test using ui.Workspace will not crash if no GPUs are present.""" windows = ui.Workspace.get_windows() # Pass on release or odder debug builds self.assertTrue((windows == []) or (f"{windows}" == "[Debug##Default]")) # Test this call doesn't crash ui.Workspace.clear() def test_window(self): """Test using ui.Window will not crash if no GPUs are present.""" window = ui.Window("Name", width=512, height=512) # Test is not that window holds anything of value, just that app has not crashed
1,156
Python
37.566665
88
0.697232
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_tooltip.py
## Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest import omni.kit.app import omni.ui as ui import asyncio class TestTooltip(OmniUiTest): """Testing tooltip""" async def test_general(self): """Testing general properties of ui.Label""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: # Simple text label = ui.Label("Hello world", tooltip="This is a tooltip") ref = ui_test.WidgetRef(label, "") await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref.center) await asyncio.sleep(1.0) await self.finalize_test() async def test_property(self): """Testing general properties of ui.Label""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: # Simple text label = ui.Label("Hello world") label.tooltip = "This is a tooltip" self.assertEqual(label.tooltip, "This is a tooltip") ref = ui_test.WidgetRef(label, "") await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref.center) await asyncio.sleep(1.0) await self.finalize_test() async def test_delay(self): """Testing general properties of ui.Label""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: # Simple text label = ui.Label("Hello world", tooltip="This is a tooltip") ref = ui_test.WidgetRef(label, "") await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref.center) await asyncio.sleep(0.2) await self.finalize_test() await ui_test.emulate_mouse_move(ui_test.Vec2(ref.center.x, ref.center.y + 50)) # get rid of tooltip await asyncio.sleep(0.2) async def test_tooltip_in_separate_window(self): """Testing tooltip on a separate window""" import omni.kit.ui_test as ui_test win = await self.create_test_window(block_devices=False) with win.frame: with ui.VStack(): ui.Spacer() # create a new frame which is on a separate window with ui.Frame(separate_window=True): style = {"BezierCurve": {"color": omni.ui.color.red, "border_width": 2}} curve = ui.BezierCurve(style=style, tooltip="This is a tooltip") ref = ui_test.WidgetRef(curve, "") await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref.center) await asyncio.sleep(1.0) await self.finalize_test()
3,308
Python
33.113402
109
0.632709
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_separator.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest import omni.kit.app import omni.ui as ui from functools import partial class TestSeparator(OmniUiTest): """Testing ui.Menu""" async def test_general(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: ui.Spacer() shown = [False, False] def on_shown(index, s): shown[index] = s self.menu_h = ui.Menu("Test Hidden Context Menu", shown_changed_fn=partial(on_shown, 0)) self.menu_v = ui.Menu("Test Visible Context Menu", shown_changed_fn=partial(on_shown, 1)) with self.menu_h: ui.Separator() ui.MenuItem("Hidden 1") ui.Separator("Hidden 1") ui.MenuItem("Hidden 2") ui.Separator("Hidden 2") ui.MenuItem("Hidden 3") ui.Separator() with self.menu_v: ui.Separator() ui.MenuItem("Test 1") ui.Separator("Separator 1") ui.MenuItem("Test 2") ui.Separator("Separator 2") ui.MenuItem("Test 3") ui.Separator() # No menu is shown self.assertIsNone(ui.Menu.get_current()) self.menu_h.show_at(0, 0) self.menu_v.show_at(0, 0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Check the callback is called self.assertFalse(shown[0]) self.assertTrue(shown[1]) # Check the property self.assertFalse(self.menu_h.shown) self.assertTrue(self.menu_v.shown) # Check the current menu self.assertEqual(ui.Menu.get_current(), self.menu_v) await self.finalize_test() async def test_general_modern(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: ui.Spacer() self.menu_v = ui.Menu("Test Visible Context Menu Modern", menu_compatibility=0) with self.menu_v: ui.Separator() ui.MenuItem("Test 1") ui.Separator("Separator 1") ui.MenuItem("Test 2") ui.Separator("Separator 2") ui.MenuItem("Test 3") ui.Separator() self.menu_v.show_at(0, 0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test() self.menu_v.destroy() self.menu_v = None
3,041
Python
29.118812
97
0.60046
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_menu.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import asyncio from .test_base import OmniUiTest import omni.kit.app import omni.ui as ui from functools import partial class TestMenu(OmniUiTest): """Testing ui.Menu""" async def test_general(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: ui.Spacer() shown = [False, False] def on_shown(index, s): shown[index] = s self.menu_h = ui.Menu("Test Hidden Context Menu", shown_changed_fn=partial(on_shown, 0)) self.menu_v = ui.Menu("Test Visible Context Menu", shown_changed_fn=partial(on_shown, 1)) with self.menu_h: ui.MenuItem("Hidden 1") ui.MenuItem("Hidden 2") ui.MenuItem("Hidden 3") with self.menu_v: ui.MenuItem("Test 1") ui.MenuItem("Test 2") ui.MenuItem("Test 3") # No menu is shown self.assertIsNone(ui.Menu.get_current()) self.menu_h.show_at(0, 0) self.menu_v.show_at(0, 0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Check the callback is called self.assertFalse(shown[0]) self.assertTrue(shown[1]) # Check the property self.assertFalse(self.menu_h.shown) self.assertTrue(self.menu_v.shown) # Check the current menu self.assertEqual(ui.Menu.get_current(), self.menu_v) await self.finalize_test() # Remove menus for later tests self.menu_h.destroy() self.menu_v.destroy() async def test_modern(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: ui.Spacer() shown = [False, False] def on_shown(index, s): shown[index] = s self.menu_h = ui.Menu( "Test Hidden Context Menu Modern", shown_changed_fn=partial(on_shown, 0), menu_compatibility=0 ) self.menu_v = ui.Menu( "Test Visible Context Menu Modern", shown_changed_fn=partial(on_shown, 1), menu_compatibility=0 ) with self.menu_h: ui.MenuItem("Hidden 1") ui.MenuItem("Hidden 2") ui.MenuItem("Hidden 3") with self.menu_v: ui.MenuItem("Test 1") ui.MenuItem("Test 2") ui.MenuItem("Test 3") self.menu_h.show_at(0, 0) self.menu_v.show_at(0, 0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Check the callback is called self.assertFalse(shown[0]) self.assertTrue(shown[1]) # Check the property self.assertFalse(self.menu_h.shown) self.assertTrue(self.menu_v.shown) # Check the current menu self.assertEqual(ui.Menu.get_current(), self.menu_v) await self.finalize_test() # Remove menus for later tests self.menu_h.destroy() self.menu_v.destroy() self.menu_h = None self.menu_v = None async def test_modern_visibility(self): import omni.kit.ui_test as ui_test triggered = [] def on_triggered(): triggered.append(True) window = await self.create_test_window(block_devices=False) with window.frame: ui.Spacer() menu = ui.Menu("Test Visibility Context Menu Modern", menu_compatibility=0) with menu: ui.MenuItem("Hidden 1") ui.MenuItem("Hidden 2") ui.MenuItem("Hidden 3") invis = ui.MenuItem("Invisible", triggered_fn=on_triggered) invis.visible = False ui.MenuItem("Another Invisible", visible=False) menu.show_at(0, 0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() invis.visible = True await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() ref_invis = ui_test.WidgetRef(invis, "") await ui_test.emulate_mouse_move_and_click(ref_invis.center) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Check the callback is called self.assertTrue(triggered) await self.finalize_test_no_image() async def test_modern_horizontal(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): with ui.Menu("File"): ui.MenuItem("Hidden 1") ui.MenuItem("Hidden 2") ui.MenuItem("Hidden 3") with ui.Menu("Edit"): ui.MenuItem("Test 1") ui.MenuItem("Test 2") ui.MenuItem("Test 3") await self.finalize_test() async def test_modern_horizontal_right(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): with ui.Menu("File"): ui.MenuItem("Hidden 1") ui.MenuItem("Hidden 2") ui.MenuItem("Hidden 3") ui.Spacer() with ui.Menu("Edit"): ui.MenuItem("Test 1") ui.MenuItem("Test 2") ui.MenuItem("Test 3") await self.finalize_test() async def test_modern_delegate(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: ui.Spacer() class Delegate(ui.MenuDelegate): def build_item(self, item): if item.text[0] == "#": ui.Rectangle(height=20, style={"background_color": ui.color(item.text)}) def build_title(self, item): ui.Label(item.text) def build_status(self, item): ui.Label("Status is also here") self.menu = ui.Menu("Test Modern Delegate", menu_compatibility=0, delegate=Delegate()) with self.menu: ui.MenuItem("#ff6600") ui.MenuItem("#00ff66") ui.MenuItem("#0066ff") ui.MenuItem("#66ff00") ui.MenuItem("#6600ff") ui.MenuItem("#ff0066") self.menu.show_at(0, 0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test() # Remove menu for later tests self.menu.destroy() self.menu = None async def test_modern_checked(self): """Testing general properties of ui.Menu""" window = await self.create_test_window() with window.frame: ui.Spacer() called = [False, False] checked = [False, False] self.menu_v = ui.Menu("Test Visible Context Menu Modern", menu_compatibility=0) def checked_changed(i, c): called[i] = True checked[i] = c with self.menu_v: item1 = ui.MenuItem("Test 1", checked=False, checkable=True) item1.set_checked_changed_fn(partial(checked_changed, 0)) item2 = ui.MenuItem("Test 2", checked=False, checkable=True, checked_changed_fn=partial(checked_changed, 1)) ui.MenuItem("Test 3", checked=True, checkable=True) ui.MenuItem("Test 4", checked=False, checkable=True) ui.MenuItem("Test 5") item1.checked = True item2.checked = True self.menu_v.show_at(0, 0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Check the callback is called self.assertTrue(called[0]) self.assertTrue(checked[0]) self.assertTrue(called[1]) self.assertTrue(checked[1]) await self.finalize_test() self.menu_v.destroy() self.menu_v = None async def test_radio(self): """Testing radio collections""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: ui.Spacer() called = [False, False] checked = [False, False] self.menu = ui.Menu("Test Visible Context Menu Modern", menu_compatibility=0) def checked_changed(i, c): called[i] = True checked[i] = c with self.menu: collection = ui.MenuItemCollection("Collection") with collection: m1 = ui.MenuItem("Test 1", checked=False, checkable=True) m2 = ui.MenuItem("Test 2", checked=False, checkable=True) m3 = ui.MenuItem("Test 3", checked=False, checkable=True) m4 = ui.MenuItem("Test 4", checked=False, checkable=True) m2.checked = True m3.checked = True self.menu.show_at(0, 0) ref = ui_test.WidgetRef(collection, "") await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref.center) await omni.kit.app.get_app().next_update_async() # Check the checked states self.assertFalse(m1.checked) self.assertFalse(m2.checked) self.assertTrue(m3.checked) self.assertFalse(m4.checked) await self.finalize_test() self.menu.destroy() self.menu = None async def test_modern_click(self): """Click the menu bar""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: ui.MenuItem("File 1") ui.MenuItem("File 2") ui.MenuItem("File 3") with ui.Menu("Edit"): ui.MenuItem("Edit 1") ui.MenuItem("Edit 2") ui.MenuItem("Edit 3") ref = ui_test.WidgetRef(file, "") # Click the File item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(ref.center) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_modern_click_click(self): """Click the menu bar, wait, click again""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: ui.MenuItem("File 1") ui.MenuItem("File 2") ui.MenuItem("File 3") with ui.Menu("Edit"): ui.MenuItem("Edit 1") ui.MenuItem("Edit 2") ui.MenuItem("Edit 3") ref = ui_test.WidgetRef(file, "") # Click the File item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(ref.center) await asyncio.sleep(0.5) # Click the File item one more time await ui_test.emulate_mouse_move_and_click(ref.center) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_modern_click_move(self): """Click the menu bar, move to another item""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: ui.MenuItem("File 1") ui.MenuItem("File 2") ui.MenuItem("File 3") edit = ui.Menu("Edit") with edit: ui.MenuItem("Edit 1") ui.MenuItem("Edit 2") ui.MenuItem("Edit 3") refFile = ui_test.WidgetRef(file, "") refEdit = ui_test.WidgetRef(edit, "") # Click the File item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(refFile.center) await asyncio.sleep(0.5) # Hover the Edit item await ui_test.emulate_mouse_move(refEdit.center) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_modern_click_submenu(self): """Click the menu bar, wait, click again""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: ui.MenuItem("File 1") sub = ui.Menu("Sub") with sub: ui.MenuItem("File 2") mid = ui.MenuItem("Middle") ui.MenuItem("File 4") ui.MenuItem("File 5") with ui.Menu("Edit"): ui.MenuItem("Edit 1") ui.MenuItem("Edit 2") ui.MenuItem("Edit 3") refFile = ui_test.WidgetRef(file, "") refSub = ui_test.WidgetRef(sub, "") refMid = ui_test.WidgetRef(mid, "") # Click the File item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(refFile.center) # Hover the Sub item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(refSub.center) # Hover the Middle item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(refMid.center) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_modern_tearoff(self): """Click the menu bar, wait, click again""" import omni.kit.ui_test as ui_test shown_times = [0, 0] def on_shown(shown, shown_times=shown_times): """Called when the file menu is opened""" if shown: # It will show if it's opened or closed shown_times[0] += 1 else: shown_times[0] -= 1 # Could times it's called shown_times[1] += 1 await self.create_test_area(block_devices=False) ui_main_window = ui.MainWindow() ui_main_window.main_menu_bar.visible = False window = ui.Window( "test_modern_tearoff", flags=ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE, ) window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}}) await omni.kit.app.get_app().next_update_async() main_dockspace = ui.Workspace.get_window("DockSpace") window.dock_in(main_dockspace, ui.DockPosition.SAME) window.dock_tab_bar_visible = False with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File", shown_changed_fn=on_shown) with file: ui.MenuItem("File 1") ui.MenuItem("File 2") ui.MenuItem("File 5") with ui.Menu("Edit"): ui.MenuItem("Edit 1") ui.MenuItem("Edit 2") ui.MenuItem("Edit 3") refFile = ui_test.WidgetRef(file, "") # Click the File item for _ in range(2): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(refFile.center) # Move the menu window to the middle of the screen await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_drag_and_drop( ui_test.Vec2(refFile.center.x, refFile.center.y + 15), ui_test.Vec2(128, 128) ) await omni.kit.app.get_app().next_update_async() # Menu should be torn off self.assertTrue(file.teared) # But the pull-down portion of the menu is not shown self.assertFalse(file.shown) # Click the File item for _ in range(2): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(refFile.center) await omni.kit.app.get_app().next_update_async() # It should be 1 to indicate that the menu is opened self.assertEqual(shown_times[0], 1) # It was called three times: # - To open menu # - To tear off, the menu is closed # - Opened again to make a screenshot self.assertEqual(shown_times[1], 3) # Menu should be torn off self.assertTrue(file.teared) # But the pull-down portion of the menu is not shown self.assertTrue(file.shown) await self.finalize_test() async def test_modern_tearoff_submenu(self): """Click the menu bar, wait, click again""" import omni.kit.ui_test as ui_test await self.create_test_area(block_devices=False) ui_main_window = ui.MainWindow() ui_main_window.main_menu_bar.visible = False window = ui.Window( "test_modern_tearoff", flags=ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE, ) window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}}) await omni.kit.app.get_app().next_update_async() main_dockspace = ui.Workspace.get_window("DockSpace") window.dock_in(main_dockspace, ui.DockPosition.SAME) window.dock_tab_bar_visible = False with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: ui.MenuItem("File 1") sub = ui.Menu("Sub") with sub: ui.MenuItem("File 2") ui.MenuItem("File 3") ui.MenuItem("File 4") ui.MenuItem("File 5") with ui.Menu("Edit"): ui.MenuItem("Edit 1") ui.MenuItem("Edit 2") ui.MenuItem("Edit 3") refFile = ui_test.WidgetRef(file, "") refSub = ui_test.WidgetRef(sub, "") # Click the File item for _ in range(2): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(refFile.center) # Hover the Sub item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(refSub.center) # Move the menu window to the middle of the screen for _ in range(2): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_drag_and_drop( ui_test.Vec2(refSub.position.x + refSub.size.x + 10, refSub.center.y - 10), ui_test.Vec2(128, 128) ) # Click the File item for _ in range(2): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(refFile.center) # Hover the Sub item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(refSub.center) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_modern_button(self): """Click the menu bar""" import omni.kit.ui_test as ui_test clicked = [] class Delegate(ui.MenuDelegate): def build_item(self, item): with ui.HStack(width=200): ui.Label(item.text) with ui.VStack(content_clipping=1, width=0): ui.Button("Button", clicked_fn=lambda: clicked.append(True)) delegate = Delegate() window = await self.create_test_window(block_devices=False) with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: child = ui.MenuItem("File 1", delegate=delegate) ui.MenuItem("File 2", delegate=delegate) ui.MenuItem("File 3", delegate=delegate) with ui.Menu("Edit"): ui.MenuItem("Edit 1", delegate=delegate) ui.MenuItem("Edit 2", delegate=delegate) ui.MenuItem("Edit 3", delegate=delegate) ref_file = ui_test.WidgetRef(file, "") ref_child = ui_test.WidgetRef(child, "") # Click the File item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(ref_file.center) await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(ref_child.position.x + ref_child.size.x - 10, ref_child.center.y) ) await omni.kit.app.get_app().next_update_async() self.assertEqual(len(clicked), 1) await self.finalize_test() async def test_modern_enabled(self): """Click the menu bar""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: ui.MenuItem("File 1") ui.MenuItem("File 2", enabled=False) f3 = ui.MenuItem("File 3") f4 = ui.MenuItem("File 4", enabled=False) with ui.Menu("Edit"): ui.MenuItem("Edit 1") ui.MenuItem("Edit 2") ui.MenuItem("Edit 3") ref = ui_test.WidgetRef(file, "") # Click the File item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(ref.center) await omni.kit.app.get_app().next_update_async() # Changed enabled runtime while the menu is open f3.enabled = False f4.enabled = True await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_modern_submenu_disabled(self): """Test sub-menu items when parent si disabled""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT): file = ui.Menu("File") with file: file_1 = ui.Menu("File 1", enabled=True) with file_1: ui.MenuItem("File 1a") ui.MenuItem("File 1b") file_2 = ui.Menu("File 2", enabled=False) with file_2: ui.MenuItem("File 2a") ui.MenuItem("File 2b") ref = ui_test.WidgetRef(file, "") ref_1 = ui_test.WidgetRef(file_1, "") ref_2 = ui_test.WidgetRef(file_2, "") # Click the File item await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click(ref.center) await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref_1.center) for _ in range(3): await omni.kit.app.get_app().next_update_async() await self.capture_and_compare(golden_img_name="omni.ui_scene.tests.TestMenu.test_modern_submenu_disabled_on.png") await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref_2.center) for _ in range(3): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_name="omni.ui_scene.tests.TestMenu.test_modern_submenu_disabled_off.png") async def test_window(self): """Check we can create a window from menu""" import omni.kit.ui_test as ui_test menu = ui.Menu("menu", name="this") dialogs = [] def _build_message_popup(): dialogs.append(ui.Window("Message", width=100, height=50)) def _show_context_menu(x, y, button, modifier): if button != 1: return menu.clear() with menu: ui.MenuItem("Create Pop-up", triggered_fn=_build_message_popup) menu.show() window = await self.create_test_window(block_devices=False) with window.frame: button = ui.Button("context menu", width=0, height=0, mouse_pressed_fn=_show_context_menu) await omni.kit.app.get_app().next_update_async() ref = ui_test.WidgetRef(button, "") await ui_test.emulate_mouse_move_and_click(ref.center, right_click=True) await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(ref.position.x + ref.size.x, ref.position.y + ref.size.y) ) await omni.kit.app.get_app().next_update_async() await self.finalize_test()
26,901
Python
32.924338
122
0.562358
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_namespace.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest import omni.ui as ui def one(): return 1 class TestNamespace(OmniUiTest): """Testing ui.Workspace""" async def test_namespace(self): """Testing window selection callback""" subscription = ui.add_to_namespace(one) self.assertIn("one", dir(ui)) self.assertEqual(ui.one(), 1) del subscription subscription = None self.assertNotIn("one", dir(ui)) # Testing module=None ui.add_to_namespace()
974
Python
28.545454
77
0.702259
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_rectangle.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest import omni.ui as ui class TestRectangle(OmniUiTest): """Testing ui.Rectangle""" async def test_general(self): """Testing general properties of ui.Rectangle""" window = await self.create_test_window() with window.frame: with ui.VStack(): with ui.HStack(): ui.Rectangle() ui.Rectangle(style={"background_color": 0xFFFF0000}) ui.Rectangle(style={"Rectangle": {"background_color": 0x66FF0000}}) with ui.HStack(): ui.Rectangle( style={"background_color": 0x0, "border_color": 0xFF00FFFF, "border_width": 1, "margin": 5} ) ui.Rectangle( style={ "background_color": 0x0, "border_color": 0xFFFFFF00, "border_width": 2, "border_radius": 20, "margin_width": 5, } ) ui.Rectangle( style={ "background_color": 0xFF00FFFF, "border_color": 0xFFFFFF00, "border_width": 2, "border_radius": 5, "margin_height": 5, } ) with ui.HStack(): ui.Rectangle( style={ "background_color": 0xFF00FFFF, "border_color": 0xFFFFFF00, "border_width": 1, "border_radius": 10, "corner_flag": ui.CornerFlag.LEFT, } ) ui.Rectangle( style={ "background_color": 0xFFFF00FF, "border_color": 0xFF00FF00, "border_width": 1, "border_radius": 10, "corner_flag": ui.CornerFlag.RIGHT, } ) ui.Rectangle( style={ "background_color": 0xFFFFFF00, "border_color": 0xFFFF0000, "border_width": 1, "border_radius": 10, "corner_flag": ui.CornerFlag.TOP, } ) ui.Rectangle( style={ "background_color": 0xFF666666, "border_color": 0xFF0000FF, "border_width": 1, "border_radius": 10, "corner_flag": ui.CornerFlag.BOTTOM, } ) await self.finalize_test()
3,585
Python
39.75
115
0.406974
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_canvasframe.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import unittest from .test_base import OmniUiTest from functools import partial import omni.kit.app import omni.ui as ui WINDOW_STYLE = {"Window": {"background_color": 0xFF303030, "border_color": 0x0, "border_width": 0, "border_radius": 0}} TEXT = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut " "labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco " "laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ) class TestCanvasFrame(OmniUiTest): """Testing ui.CanvasFrame""" async def test_general(self): """Testing general properties of ui.CanvasFrame""" window = await self.create_test_window() with window.frame: with ui.CanvasFrame(): with ui.VStack(height=0): # Simple text ui.Label("Hello world") # Word wrap ui.Label(TEXT, word_wrap=True) # Gray button ui.Button( "Button", style={ "Button": {"background_color": 0xFF666666, "margin": 0, "padding": 4, "border_radius": 0} }, ) await self.finalize_test() @unittest.skip("Disabling temporarily to avoid failure due to bold 'l' on linux font") async def test_zoom(self): """Testing zoom of ui.CanvasFrame""" window = await self.create_test_window() with window.frame: with ui.CanvasFrame(zoom=0.5): with ui.VStack(height=0): # Simple text ui.Label("Hello world") # Word wrap ui.Label(TEXT, word_wrap=True) # Gray button ui.Button( "Button", style={ "Button": {"background_color": 0xFF666666, "margin": 0, "padding": 8, "border_radius": 0} }, ) await self.finalize_test() async def test_pan(self): """Testing zoom of ui.CanvasFrame""" window = await self.create_test_window() with window.frame: with ui.CanvasFrame(pan_x=64, pan_y=128): with ui.VStack(height=0): # Simple text ui.Label("Hello world") # Word wrap ui.Label(TEXT, word_wrap=True) # Gray button ui.Button( "Button", style={ "Button": {"background_color": 0xFF666666, "margin": 0, "padding": 4, "border_radius": 0} }, ) await self.finalize_test() async def test_space(self): """Testing transforming screen space to canvas space of ui.CanvasFrame""" window = await self.create_test_window() with window.frame: frame = ui.CanvasFrame(pan_x=512, pan_y=1024) with frame: placer = ui.Placer() with placer: # Gray button ui.Button( "Button", width=0, height=0, style={ "Button": {"background_color": 0xFF666666, "margin": 0, "padding": 4, "border_radius": 0} }, ) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() placer.offset_x = frame.screen_to_canvas_x(frame.screen_position_x + 128) placer.offset_y = frame.screen_to_canvas_y(frame.screen_position_y + 128) await self.finalize_test() async def test_navigation_pan(self): """Test how CanvasFrame interacts with mouse""" import omni.kit.ui_test as ui_test pan = [0, 0] def pan_changed(axis, value): pan[axis] = value window = await self.create_test_window(block_devices=False) with window.frame: canvas = ui.CanvasFrame(smooth_zoom=False) canvas.set_pan_key_shortcut(0, 0) canvas.set_pan_x_changed_fn(partial(pan_changed, 0)) canvas.set_pan_y_changed_fn(partial(pan_changed, 1)) with canvas: with ui.VStack(height=0): # Simple text ui.Label("Hello world") # Word wrap ui.Label(TEXT, word_wrap=True) # Button ui.Button("Button") ref = ui_test.WidgetRef(window.frame, "") for i in range(2): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref.center) await ui_test.emulate_mouse_drag_and_drop(ref.center, ref.center * 0.8, human_delay_speed=1) for i in range(2): await omni.kit.app.get_app().next_update_async() await self.finalize_test() self.assertEqual(pan[0], -26) self.assertEqual(pan[1], -26) async def test_navigation_zoom(self): """Test how CanvasFrame interacts with mouse zoom""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: canvas = ui.CanvasFrame(smooth_zoom=False) canvas.set_zoom_key_shortcut(1, 0) self.assertEqual(canvas.zoom, 1.0) ref = ui_test.WidgetRef(window.frame, "") for i in range(2): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_move(ref.center) await ui_test.emulate_mouse_drag_and_drop(ref.center, ref.center * 0.5, right_click=True, human_delay_speed=1) for i in range(2): await omni.kit.app.get_app().next_update_async() # check the zoom is changed with the key_index press and right click self.assertAlmostEqual(canvas.zoom, 0.8950250148773193, 1) await self.finalize_test_no_image() async def test_zoom_with_limits(self): """Testing zoom is limited by the zoom_min and zoom_max""" window = await self.create_test_window() with window.frame: frame = ui.CanvasFrame(zoom=2.5, zoom_max=2.0, zoom_min=0.5) with frame: with ui.HStack(): ui.Spacer() with ui.VStack(): ui.Spacer() ui.Rectangle(width=50, height=50, style={"background_color": 0xFF000066}) ui.Spacer() ui.Spacer() await omni.kit.app.get_app().next_update_async() await self.finalize_test() # check the zoom is limited by zoom_max = 2.0 self.assertEqual(frame.screen_position_x, 2.0) self.assertEqual(frame.screen_position_y, 2.0) async def test_compatibility(self): """Testing zoom of ui.CanvasFrame""" window = await self.create_test_window() with window.frame: with ui.CanvasFrame(zoom=0.5, pan_x=64, pan_y=64, compatibility=False): with ui.VStack(height=0): # Simple text ui.Label("NVIDIA") # Word wrap ui.Label(TEXT, word_wrap=True) # Gray button ui.Button( "Button", style={ "Button": {"background_color": 0xFF666666, "margin": 0, "padding": 8, "border_radius": 0} }, ) await self.finalize_test() async def test_compatibility_text(self): """Testing zoom of ui.CanvasFrame""" window = await self.create_test_window() with window.frame: with ui.CanvasFrame(zoom=4.0, compatibility=False): with ui.VStack(height=0): # Simple text ui.Label("NVIDIA") # Word wrap ui.Label(TEXT, word_wrap=True) # Gray button ui.Button( "Button", style={ "Button": {"background_color": 0xFF666666, "margin": 0, "padding": 8, "border_radius": 0} }, ) # Make sure we only have one font cached for _ in range(2): await omni.kit.app.get_app().next_update_async() self.assertEqual(len(ui.Inspector.get_stored_font_atlases()), 1) await self.finalize_test() async def test_compatibility_clipping(self): window = await self.create_test_window() with window.frame: with ui.CanvasFrame(compatibility=0): with ui.Placer(draggable=1, width=50, height=50, offset_x=5, offset_y=50): ui.Circle( width=50, height=50, style={"background_color": ui.color.white}, arc=ui.Alignment.RIGHT_BOTTOM, ) await self.finalize_test() async def test_compatibility_clipping_2(self): # Create a backgroud window window = await self.create_test_window() # Create a new UI window window1 = ui.Window("clip 2", width=100, height=100, position_x=10, position_y=10) # Begin drawing contents inside window1 with window1.frame: # Create a canvas frame with compatibility mode off canvas_frame = ui.CanvasFrame(compatibility=0, name="my") with canvas_frame: with ui.Frame(): with ui.ZStack(content_clipping=1): # Add a blue rectangle inside the ZStack ui.Rectangle(width=50, height=50, style={"background_color": ui.color.blue}) with ui.Placer(draggable=True, width=10, height=10): ui.Rectangle(style={"background_color": 0xff123456}) # Wait for the next update cycle of the application await omni.kit.app.get_app().next_update_async() # Pan the canvas frame to the specified coordinates canvas_frame.pan_x = 100 canvas_frame.pan_y = 80 # Finalize and clean up the test await self.finalize_test() async def test_compatibility_pan(self): """test pan is working when compatibility=0""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: canvas = ui.CanvasFrame(compatibility=0) canvas.set_pan_key_shortcut(0, 0) with canvas: with ui.VStack(height=0): # Simple text ui.Label("Hello world") # Word wrap ui.Label(TEXT, word_wrap=True) # Button ui.Button("Button") ref = ui_test.WidgetRef(window.frame, "") await ui_test.wait_n_updates(2) await ui_test.emulate_mouse_move(ref.center) await ui_test.emulate_mouse_drag_and_drop(ref.center, ref.center * 0.8, human_delay_speed=1) await ui_test.wait_n_updates(2) await self.finalize_test() async def test_pan_no_leak(self): """test pan from one canvasFrame is not leaking to another canvasFrame """ import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False, height=600) with window.frame: with ui.VStack(): with ui.Frame(height=300): canvas1 = ui.CanvasFrame(style={"background_color": omni.ui.color.red}) canvas1.set_pan_key_shortcut(1, 0) with canvas1: ui.Label("HELLO WORLD") with ui.Frame(height=300): canvas2 = ui.CanvasFrame(style={"background_color": omni.ui.color.blue}) canvas2.set_pan_key_shortcut(1, 0) with canvas2: ui.Label("NVIDIA") ref1 = ui_test.WidgetRef(canvas1, "") ref2 = ui_test.WidgetRef(canvas2, "") await ui_test.wait_n_updates(2) # pan from the first canvas to second canvas, we should only see first canvas panned, but not the second one await ui_test.emulate_mouse_move(ref1.center) await ui_test.emulate_mouse_drag_and_drop(ref1.center, ref2.center, right_click=True, human_delay_speed=1) await ui_test.wait_n_updates(2) await self.finalize_test() async def test_zoom_no_leak(self): """test zoom from one canvasFrame is not leaking to another canvasFrame """ import omni.kit.ui_test as ui_test from omni.kit.ui_test.vec2 import Vec2 window = await self.create_test_window(block_devices=False, height=600) with window.frame: with ui.VStack(): with ui.Frame(height=300): canvas1 = ui.CanvasFrame(compatibility=0, style={"background_color": omni.ui.color.red}) canvas1.set_zoom_key_shortcut(1, 0) with canvas1: ui.Label("HELLO WORLD") with ui.Frame(height=300): canvas2 = ui.CanvasFrame(compatibility=0, style={"background_color": omni.ui.color.blue}) canvas2.set_zoom_key_shortcut(1, 0) with canvas2: ui.Label("NVIDIA") ref1 = ui_test.WidgetRef(canvas1, "") ref2 = ui_test.WidgetRef(canvas2, "") await ui_test.wait_n_updates(2) # zoom from the second canvas to first canvas, we should only see second canvas zoomed, but not the first one await ui_test.emulate_mouse_move(ref2.center) await ui_test.emulate_mouse_drag_and_drop(ref2.center, ref1.center * 0.5, right_click=True, human_delay_speed=1) self.assertEqual(canvas1.zoom, 1.0) self.assertNotEqual(canvas2.zoom, 1.0) await self.finalize_test_no_image()
15,120
Python
37.184343
120
0.543783
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_field.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.ui as ui import omni.kit.app from .test_base import OmniUiTest STYLE = { "Field": { "background_color": 0xFF000000, "color": 0xFFFFFFFF, "border_color": 0xFFFFFFFF, "background_selected_color": 0xFFFF6600, "border_width": 1, "border_radius": 0, } } class TestField(OmniUiTest): """Testing fields""" async def test_general(self): """Testing general properties of ui.StringField""" window = await self.create_test_window() with window.frame: with ui.VStack(height=0, style=STYLE, spacing=2): # Simple field ui.StringField() ui.StringField().model.set_value("Hello World") await self.finalize_test() async def test_focus(self): """Testing the ability to focus in ui.StringField""" window = await self.create_test_window() with window.frame: with ui.VStack(height=0, style=STYLE, spacing=2): # Simple field ui.StringField() field = ui.StringField() field.model.set_value("Hello World") field.focus_keyboard() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_defocus(self): """Testing the ability to defocus in ui.StringField""" window = await self.create_test_window() with window.frame: with ui.VStack(height=0, style=STYLE, spacing=2): # Simple field ui.StringField() field = ui.StringField() field.model.set_value("Hello World") field.focus_keyboard() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() field.focus_keyboard(False) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_change_when_editing(self): """Testing the ability to defocus in ui.StringField""" window = await self.create_test_window() with window.frame: with ui.VStack(height=0, style=STYLE, spacing=2): # Simple field ui.StringField() field = ui.StringField() field.model.set_value("Hello World") field.focus_keyboard() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() field.model.set_value("Data Change") await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_multifield_resize(self): """Testing general properties of ui.StringField""" window = await self.create_test_window(256, 64) with window.frame: stack = ui.VStack(height=0, width=100, style=STYLE, spacing=2) with stack: # Simple field ui.MultiFloatField(1.0, 1.0, 1.0) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() stack.width = ui.Fraction(1) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test()
3,823
Python
30.089431
77
0.609207
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_slider.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest import omni.ui as ui import omni.kit.app from omni.ui import color as cl class TestSlider(OmniUiTest): """Testing ui.Frame""" async def test_general(self): """Testing general properties of ui.Slider""" window = await self.create_test_window() with window.frame: with ui.VStack(height=0, spacing=2): ui.FloatSlider(style={"draw_mode": ui.SliderDrawMode.HANDLE}).model.set_value(0.5) ui.IntSlider(style={"draw_mode": ui.SliderDrawMode.HANDLE}).model.set_value(15) ui.FloatSlider( style={ "draw_mode": ui.SliderDrawMode.FILLED, "background_color": 0xFF333333, "secondary_color": 0xFF666666, } ).model.set_value(0.25) ui.IntSlider( style={ "draw_mode": ui.SliderDrawMode.FILLED, "background_color": 0xFF333333, "secondary_color": 0xFF666666, } ).model.set_value(10) ui.FloatSlider( style={ "draw_mode": ui.SliderDrawMode.FILLED, "background_color": 0xFF333333, "secondary_color": 0xFF666666, "secondary_color": 0xFF666666, "border_color": 0xFFFFFFFF, "border_width": 1, "border_radius": 20, } ).model.set_value(0.4375) # 0.015625 will be rounded differently on linux and windows # See https://stackoverflow.com/questions/4649554 for details # To fix it, add something small ui.FloatSlider( style={ "draw_mode": ui.SliderDrawMode.FILLED, "background_color": 0xFF333333, "secondary_color": 0xFF666666, "secondary_color": 0xFF666666, "border_color": 0xFFFFFFFF, "border_width": 1, "border_radius": 20, } ).model.set_value(0.015625 + 1e-10) ui.FloatDrag().model.set_value(0.375) ui.IntDrag().model.set_value(25) await self.finalize_test() async def test_padding(self): """Testing slider's padding""" style = { "background_color": cl.grey, "draw_mode": ui.SliderDrawMode.FILLED, "border_width": 1, "border_color": cl.black, "border_radius": 0, "font_size": 16, "padding": 0, } window = await self.create_test_window() with window.frame: with ui.VStack(height=0): for i in range(8): style["padding"] = i * 2 with ui.HStack(height=0): ui.FloatSlider(style=style, height=0) ui.FloatField(style=style, height=0) await self.finalize_test() async def test_float_slider_precision(self): window = await self.create_test_window() with window.frame: with ui.VStack(height=0): ui.FloatSlider(precision=7, height=0).model.set_value(0.00041233) ui.FloatDrag(precision=8, height=0).model.set_value(0.00041233) ui.FloatField(precision=5, height=0).model.set_value(0.00041233) await self.finalize_test()
4,158
Python
38.990384
98
0.521164
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_shapes.py
## Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestShapes"] import omni.kit.test from .test_base import OmniUiTest import omni.ui as ui from omni.ui import color as cl class TestShapes(OmniUiTest): """Testing ui.Shape""" async def test_offsetline(self): """Testing general properties of ui.OffsetLine""" window = await self.create_test_window() with window.frame: with ui.ZStack( style={ "Rectangle": {"background_color": cl(0, 0, 0, 0), "border_color": cl.white, "border_width": 1}, "OffsetLine": {"color": cl.white, "border_width": 1}, } ): with ui.VStack(): with ui.HStack(height=32): rect1 = ui.Rectangle(width=32) ui.Spacer() ui.Spacer() with ui.HStack(height=32): ui.Spacer() rect2 = ui.Rectangle(width=32) ui.OffsetLine( rect1, rect2, alignment=ui.Alignment.UNDEFINED, begin_arrow_type=ui.ArrowType.ARROW, offset=7, bound_offset=20, ) ui.OffsetLine( rect2, rect1, alignment=ui.Alignment.UNDEFINED, begin_arrow_type=ui.ArrowType.ARROW, offset=7, bound_offset=20, ) await self.finalize_test() async def test_freebezier(self): """Testing general properties of ui.OffsetLine""" window = await self.create_test_window() with window.frame: with ui.ZStack( style={ "Rectangle": {"background_color": cl(0, 0, 0, 0), "border_color": cl.white, "border_width": 1}, "FreeBezierCurve": {"color": cl.white, "border_width": 1}, } ): with ui.VStack(): with ui.HStack(height=32): rect1 = ui.Rectangle(width=32) ui.Spacer() ui.Spacer() with ui.HStack(height=32): ui.Spacer() rect2 = ui.Rectangle(width=32) # Default tangents ui.FreeBezierCurve(rect1, rect2, style={"color": cl.chartreuse}) # 0 tangents ui.FreeBezierCurve( rect1, rect2, start_tangent_width=0, start_tangent_height=0, end_tangent_width=0, end_tangent_height=0, style={"color": cl.darkslategrey}, ) # Fraction tangents ui.FreeBezierCurve( rect1, rect2, start_tangent_width=0, start_tangent_height=ui.Fraction(2), end_tangent_width=0, end_tangent_height=ui.Fraction(-2), style={"color": cl.dodgerblue}, ) # Percent tangents ui.FreeBezierCurve( rect1, rect2, start_tangent_width=0, start_tangent_height=ui.Percent(100), end_tangent_width=0, end_tangent_height=ui.Percent(-100), style={"color": cl.peru}, ) # Super big tangents ui.FreeBezierCurve( rect1, rect2, start_tangent_width=0, start_tangent_height=1e8, end_tangent_width=0, end_tangent_height=-1e8, style={"color": cl.indianred}, ) await self.finalize_test() async def test_freeshape_hover(self): """Testing freeshape mouse hover""" import omni.kit.ui_test as ui_test is_hovered = False def mouse_hover(hovered): nonlocal is_hovered is_hovered = hovered window = await self.create_test_window(block_devices=False) with window.frame: with ui.ZStack(): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Circle(width=10, height=10) with ui.Placer(draggable=True, offset_x=150, offset_y=150): control2 = ui.Circle(width=10, height=10) # The rectangle that fits to the control points shape = ui.FreeRectangle( control1, control2, mouse_hovered_fn=mouse_hover, ) try: await ui_test.human_delay() self.assertFalse(is_hovered) shape_ref = ui_test.WidgetRef(shape, "") await ui_test.emulate_mouse_move(shape_ref.center) await ui_test.human_delay() self.assertTrue(is_hovered) finally: await self.finalize_test_no_image()
5,815
Python
34.463414
115
0.478074
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_frame.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from functools import partial from .test_base import OmniUiTest import omni.ui as ui import omni.kit.app class TestFrame(OmniUiTest): """Testing ui.Frame""" async def test_general(self): """Testing general properties of ui.Frame""" window = await self.create_test_window() with window.frame: with ui.VStack(): with ui.Frame(width=0, height=0): ui.Label("Label in Frame") with ui.Frame(width=0, height=0): ui.Label("First label, should not be displayed") ui.Label("Second label, should be displayed") with ui.Frame(height=0): ui.Label("Long Label in Frame. " * 10, word_wrap=True) with ui.Frame(horizontal_clipping=True, width=ui.Percent(50), height=0): ui.Label("This should be clipped horizontally. " * 10) with ui.Frame(vertical_clipping=True, height=20): ui.Label("This should be clipped vertically. " * 10, word_wrap=True) await self.finalize_test() async def test_deferred(self): """Testing deferred population of ui.Frame""" window = await self.create_test_window() def two_labels(): ui.Label("First label, should not be displayed") ui.Label("Second label, should be displayed") with window.frame: with ui.VStack(): ui.Frame(height=0, build_fn=lambda: ui.Label("Label in Frame")) ui.Frame(height=0, build_fn=two_labels) ui.Frame(height=0, build_fn=lambda: ui.Label("Long text " * 15, word_wrap=True)) ui.Frame( horizontal_clipping=True, width=ui.Percent(50), height=0, build_fn=lambda: ui.Label("horizontal clipping " * 15), ) frame = ui.Frame(height=0) with frame: ui.Label("A deferred function will override this widget") frame.set_build_fn(lambda: ui.Label("This widget should be displayed")) # Wait two frames to let Frame create deferred children. The first # frame the window is Appearing. await omni.kit.app.get_app().next_update_async() # The second frame build_fn is called await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_deferred_first_frame(self): """Testing the first frame of deferred population of ui.Frame""" window = await self.create_test_window() # The first frame the window is initializing its size. await omni.kit.app.get_app().next_update_async() with window.frame: with ui.VStack(): ui.Frame(height=0, build_fn=lambda: ui.Label("Label in the first frame")) await self.finalize_test() async def test_deferred_rebuild(self): """Testing deferred rebuild of ui.Frame""" window = await self.create_test_window() self._rebuild_counter = 0 def label_counter(self): self._rebuild_counter += 1 ui.Label(f"Rebuild was called {self._rebuild_counter} times") window.frame.set_build_fn(lambda s=self: label_counter(s)) # Wait two frames to let Frame create deferred children. The first # frame the window is Appearing. await omni.kit.app.get_app().next_update_async() # The second frame build_fn is called await omni.kit.app.get_app().next_update_async() # Rebuild everything so build_fn should be called window.frame.rebuild() await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_scroll(self): import omni.kit.ui_test as ui_test first = [] second = [] def scroll(flag, x, y, mod): flag.append(x) window = await self.create_test_window(block_devices=False) # Empty window window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10) with window1.frame: with ui.ZStack(): spacer = ui.Spacer( mouse_wheel_fn=partial(scroll, first), scroll_only_window_hovered=1, mouse_pressed_fn=None ) with ui.ZStack(content_clipping=1): ui.Spacer() await omni.kit.app.get_app().next_update_async() ref = ui_test.WidgetRef(spacer, "") await ui_test.emulate_mouse_move(ref.center) await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 0)) await omni.kit.app.get_app().next_update_async() self.assertTrue(len(first) == 0) await self.finalize_test_no_image() async def test_scroll_only_window_hovered(self): import omni.kit.ui_test as ui_test first = [] second = [] def scroll(flag, x, y, mod): flag.append(x) window = await self.create_test_window(block_devices=False) # Empty window window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10) with window1.frame: with ui.ZStack(): spacer = ui.Spacer( mouse_wheel_fn=partial(scroll, first), scroll_only_window_hovered=0, mouse_pressed_fn=None ) with ui.ZStack(content_clipping=1): ui.Spacer() await omni.kit.app.get_app().next_update_async() ref = ui_test.WidgetRef(spacer, "") await ui_test.emulate_mouse_move(ref.center) await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 0)) await omni.kit.app.get_app().next_update_async() self.assertTrue(len(first) == 1) await self.finalize_test_no_image()
6,360
Python
35.348571
110
0.592453
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_abuse.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import omni.kit.app from .test_base import OmniUiTest # *************** WARNING *************** # # NONE OF THE API USAGE OR PATTERNS IN THIS FILE SHOULD BE CONSIDERED GOOD # THESE ARE TESTS ONLY THAT THAT APPLICATION WILL NOT CRASH WHEN APIS MISUSED # class SimpleIntModel(ui.SimpleIntModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def set_value(self, *args, **kwargs): super().set_value(*args, **kwargs) super()._value_changed() class SimpleItem(ui.AbstractItem): def __init__(self, value: str, *args, **kwargs): super().__init__(*args, **kwargs) self.name_model = ui.SimpleStringModel(value) class SimpleItemModel(ui.AbstractItemModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__items = [] def destroy(self): self.__items = [] def get_item_children(self, item: SimpleItem): if item is None: return self.__items return [] def add_item(self, item: SimpleItem): self.__items.append(item) super()._item_changed(None) def get_item_value_model_count(self, item: SimpleItem): return 1 def get_item_value_model(self, item: SimpleItem, column_id: int): return item.name_model if item else None class TestAbuse(OmniUiTest): """Testing omni.ui callbacks do not crash""" async def __cleanup_window(self, window: omni.ui.Window): window.visible = False window.destroy() await self.finalize_test_no_image() return None async def test_empty_models_1(self): """Test that setting an empty model on ui objects does not crash""" window = await self.create_test_window(block_devices=False) app = omni.kit.app.get_app() with window.frame: with ui.VStack(): items = [ ui.CheckBox(), ui.ComboBox(), ui.FloatField(), ui.FloatSlider(), ui.IntField(), ui.IntSlider(), ui.ProgressBar(), ui.StringField(), ui.ToolButton(), ] for _ in range(5): await app.next_update_async() for item in items: item.model = None for _ in range(5): await app.next_update_async() window = await self.__cleanup_window(window) async def test_empty_models_2(self): """Test that setting an empty model on ui objects does not crash""" window = await self.create_test_window() app = omni.kit.app.get_app() model = ui.SimpleBoolModel() with window.frame: with ui.VStack(): items = [ ui.ToolButton(model=model), ui.CheckBox(model=model), ui.ComboBox(model=model), ui.FloatField(model=model), ui.FloatSlider(model=model), ui.IntField(model=model), ui.IntSlider(model=model), ui.ProgressBar(model=model), ui.StringField(model=model), ] model.set_value(True) for _ in range(5): await app.next_update_async() def check_changed(*args): # This slice is important to keep another crash from occuring by keeping at least on subscriber alive for i in range(1, len(items)): items[i].model = None items[0].set_checked_changed_fn(check_changed) model.set_value(False) for _ in range(5): await app.next_update_async() window = await self.__cleanup_window(window) async def test_workspace_window_visibility_changed(self): """Test that subscribe and unsubscribe to window visiblity will not crash""" await self.create_test_area() sub_1, sub_2 = None, None def window_visibility_callback_2(*args, **kwargs): nonlocal sub_1, sub_2 ui.Workspace.remove_window_visibility_changed_callback(sub_1) ui.Workspace.remove_window_visibility_changed_callback(sub_2) def window_visibility_callback_1(*args, **kwargs): nonlocal sub_2 if sub_2 is None: sub_2 = ui.Workspace.set_window_visibility_changed_callback(window_visibility_callback_2) sub_1 = ui.Workspace.set_window_visibility_changed_callback(window_visibility_callback_1) self.assertIsNotNone(sub_1) window_1 = ui.Window("window_1", width=100, height=100) self.assertIsNotNone(window_1) self.assertIsNotNone(sub_2) window_1.visible = False # Test against unsubscibing multiple times for _ in range(10): ui.Workspace.remove_window_visibility_changed_callback(sub_1) ui.Workspace.remove_window_visibility_changed_callback(sub_2) for idx in range(64): ui.Workspace.remove_window_visibility_changed_callback(idx) window_1 = await self.__cleanup_window(window_1) async def test_value_model_changed_subscriptions(self): """Test that subscribe and unsubscribe to ui.AbstractValueModel will not crash""" def null_callback(*args, **kwargs): pass model_a = SimpleIntModel() model_a.remove_value_changed_fn(64) sub_id = model_a.add_value_changed_fn(null_callback) for _ in range(4): model_a.remove_value_changed_fn(sub_id) model_a.remove_begin_edit_fn(64) sub_id = model_a.add_begin_edit_fn(null_callback) for _ in range(4): model_a.remove_begin_edit_fn(sub_id) model_a.remove_end_edit_fn(64) sub_id = model_a.add_end_edit_fn(null_callback) for _ in range(4): model_a.remove_end_edit_fn(sub_id) async def test_item_model_changed_subscriptions(self): """Test that subscribe and unsubscribe to ui.AbstractItemModel will not crash""" def null_callback(*args, **kwargs): pass model_a = SimpleItemModel() model_a.remove_item_changed_fn(64) sub_id = model_a.add_item_changed_fn(null_callback) for _ in range(4): model_a.remove_item_changed_fn(sub_id) model_a.remove_begin_edit_fn(64) sub_id = model_a.add_begin_edit_fn(null_callback) for _ in range(4): model_a.remove_begin_edit_fn(sub_id) model_a.remove_end_edit_fn(64) sub_id = model_a.add_end_edit_fn(null_callback) for _ in range(4): model_a.remove_end_edit_fn(sub_id)
7,198
Python
32.640187
113
0.591831
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_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. ## import omni.kit.test from .test_base import OmniUiTest from omni.ui import color as cl from omni.ui import style as st from omni.ui import url from pathlib import Path import omni.kit.app import omni.ui as ui CURRENT_PATH = Path(__file__).parent DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data") STYLE = { "MyRect": {"background_color": 0xFFEDB51A}, "MyRect::test": {"background_color": 0xFFD6D50D}, "MyRect:disabled": {"background_color": 0xFFB6F70F}, "Rectangle": {"background_color": 0xFFF73F0F}, "Rectangle::test": {"background_color": 0xFFD66C0D}, "Rectangle:disabled": {"background_color": 0xFFD99C38}, "Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}, } STYLE_SHADE = { "MyRect": {"background_color": cl.shade(0xFFEDB51A, light=cl("#DB6737"))}, "MyRect::test": {"background_color": cl.shade(0xFFD6D50D, light=cl("#F24E30"))}, "MyRect:disabled": {"background_color": cl.shade(0xFFB6F70F, light=cl("#E8302E"))}, "Rectangle": {"background_color": cl.shade(0xFFF73F0F, light=cl("#E8A838"))}, "Rectangle::test": {"background_color": cl.shade(0xFFD66C0D, light=cl("#F2983A"))}, "Rectangle:disabled": {"background_color": cl.shade(0xFFD99C38, light=cl("#DB7940"))}, "Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}, } class TestStyle(OmniUiTest): """Testing ui.Rectangle""" async def test_default(self): """Testing using of st.default""" buffer = st.default window = await self.create_test_window() with window.frame: with ui.HStack(): ui.Rectangle() ui.Rectangle(name="test") ui.Rectangle(enabled=False) ui.Rectangle(style_type_name_override="MyRect") ui.Rectangle(style_type_name_override="MyRect", name="test") ui.Rectangle(style_type_name_override="MyRect", enabled=False) st.default = STYLE await self.finalize_test() st.default = buffer async def test_window(self): """Testing using of window style""" window = await self.create_test_window() with window.frame: with ui.HStack(): ui.Rectangle() ui.Rectangle(name="test") ui.Rectangle(enabled=False) ui.Rectangle(style_type_name_override="MyRect") ui.Rectangle(style_type_name_override="MyRect", name="test") ui.Rectangle(style_type_name_override="MyRect", enabled=False) window.frame.style = STYLE await self.finalize_test() async def test_stack(self): """Testing using of stack style""" window = await self.create_test_window() with window.frame: with ui.HStack(style=STYLE): ui.Rectangle() ui.Rectangle(name="test") ui.Rectangle(enabled=False) ui.Rectangle(style_type_name_override="MyRect") ui.Rectangle(style_type_name_override="MyRect", name="test") ui.Rectangle(style_type_name_override="MyRect", enabled=False) await self.finalize_test() async def test_leaf(self): """Testing using of leaf children style""" window = await self.create_test_window() with window.frame: with ui.HStack(): ui.Rectangle(style=STYLE) ui.Rectangle(name="test", style=STYLE) ui.Rectangle(enabled=False, style=STYLE) ui.Rectangle(style_type_name_override="MyRect", style=STYLE) ui.Rectangle(style_type_name_override="MyRect", name="test", style=STYLE) ui.Rectangle(style_type_name_override="MyRect", enabled=False, style=STYLE) await self.finalize_test() async def test_shade(self): """Testing default shade""" window = await self.create_test_window() ui.set_shade() with window.frame: with ui.HStack(): ui.Rectangle() ui.Rectangle(name="test") ui.Rectangle(enabled=False) ui.Rectangle(style_type_name_override="MyRect") ui.Rectangle(style_type_name_override="MyRect", name="test") ui.Rectangle(style_type_name_override="MyRect", enabled=False) window.frame.style = STYLE_SHADE await self.finalize_test() async def test_named_shade(self): """Testing named shade""" window = await self.create_test_window() ui.set_shade() with window.frame: with ui.HStack(): ui.Rectangle() ui.Rectangle(name="test") ui.Rectangle(enabled=False) ui.Rectangle(style_type_name_override="MyRect") ui.Rectangle(style_type_name_override="MyRect", name="test") ui.Rectangle(style_type_name_override="MyRect", enabled=False) window.frame.style = STYLE_SHADE ui.set_shade("light") await self.finalize_test() # Return it back to default ui.set_shade() async def test_named_colors(self): """Testing named shade""" window = await self.create_test_window() ui.set_shade() cl.test = cl("#74B9AF") cl.common = cl("#F24E30") with window.frame: with ui.HStack(): ui.Rectangle(style={"background_color": "DarkSlateGrey"}) ui.Rectangle(style={"background_color": "DarkCyan"}) ui.Rectangle(style={"background_color": "test"}) ui.Rectangle(style={"background_color": cl.shade(cl.test, light=cl.common, name="shade_name")}) ui.Rectangle(style={"background_color": cl.shade_name}) window.frame.style = STYLE_SHADE ui.set_shade("light") # Checking read-only colors cl.DarkCyan = cl("#000000") # Checking changing of colors by name cl.common = cl("#9FDBCB") await self.finalize_test() # Return it back to default ui.set_shade() async def test_named_shade_append(self): """Testing named shade""" window = await self.create_test_window() ui.set_shade() cl.test_named_shade = cl.shade(cl("#000000"), red=cl("#FF0000"), blue=cl("#0000FF")) # Append blue to the existing shade. Two shades should be the same. cl.test_named_shade_append = cl.shade(cl("#000000"), red=cl("#FF0000")) cl.test_named_shade_append.add_shade(blue=cl("#0000FF")) with window.frame: with ui.HStack(): ui.Rectangle(style={"background_color": cl.test_named_shade}) ui.Rectangle(style={"background_color": cl.test_named_shade_append}) ui.set_shade("blue") await self.finalize_test() # Return it back to default ui.set_shade() async def test_named_urls(self): """Testing named shade""" loaded = [0] def track_progress(progress): if progress == 1.0: loaded[0] += 1 window = await self.create_test_window() ui.set_shade() # Wrong colors url.test_red = f"{DATA_PATH}/tests/blue.png" url.test_green = f"{DATA_PATH}/tests/red.png" url.test_blue = f"{DATA_PATH}/tests/green.png" with window.frame: with ui.VStack(): with ui.HStack(): ui.Image(style={"image_url": url.test_red}, progress_changed_fn=track_progress) ui.Image(style={"image_url": "test_green"}, progress_changed_fn=track_progress) ui.Image(style={"image_url": url.test_blue}, progress_changed_fn=track_progress) with ui.HStack(): ui.Image( style={"image_url": url.shade(f"{DATA_PATH}/tests/red.png")}, progress_changed_fn=track_progress ) ui.Image( style={ "image_url": url.shade( f"{DATA_PATH}/tests/blue.png", test_url=f"{DATA_PATH}/tests/green.png" ) }, progress_changed_fn=track_progress, ) ui.Image( style={ "image_url": url.shade( f"{DATA_PATH}/tests/blue.png", test_url_light=f"{DATA_PATH}/tests/green.png" ) }, progress_changed_fn=track_progress, ) # Correct colors url.test_red = f"{DATA_PATH}/tests/red.png" url.test_green = f"{DATA_PATH}/tests/green.png" url.test_blue = f"{DATA_PATH}/tests/blue.png" # Change shade ui.set_shade("test_url") while loaded[0] < 6: await omni.kit.app.get_app().next_update_async() await self.finalize_test() # Return it back to default ui.set_shade()
9,617
Python
36.866142
120
0.569616
omniverse-code/kit/exts/omni.ui/omni/ui/tests/__init__.py
## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .test_canvasframe import TestCanvasFrame from .test_collapsableframe import TestCollapsableFrame from .test_combobox import TestComboBox from .test_configuration import ConfigurationTest from .test_field import TestField from .test_frame import TestFrame from .test_grid import TestGrid from .test_image import TestImage from .test_label import TestLabel from .test_layout import TestLayout from .test_menu import TestMenu from .test_namespace import TestNamespace from .test_placer import TestPlacer from .test_present import TestPresent from .test_raster import TestRaster from .test_rectangle import TestRectangle from .test_scrollingframe import TestScrollingFrame from .test_separator import TestSeparator from .test_shapes import TestShapes from .test_shadows import TestShadows from .test_slider import TestSlider from .test_style import TestStyle from .test_tooltip import TestTooltip from .test_treeview import TestTreeView from .test_window import TestWindow from .test_workspace import TestWorkspace from .test_overflow import TestOverflow from .test_abuse import TestAbuse from .test_compare_utils import TestCompareUtils from .test_no_gpu import TestNoGPU
1,616
Python
39.424999
77
0.830446
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_scrollingframe.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest import omni.ui as ui import omni.kit.app STYLE = { "ScrollingFrame": {"background_color": 0xFF000000, "secondary_color": 0xFFFFFFFF, "scrollbar_size": 10}, "Label": {"color", 0xFFFFFFFF}, } class TestScrollingFrame(OmniUiTest): """Testing ui.ScrollingFrame""" async def test_general(self): """Testing general properties of ui.ScrollingFrame""" window = await self.create_test_window() with window.frame: with ui.ScrollingFrame( style=STYLE, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.VStack(): for i in range(50): ui.Label(f"Label in ScrollingFrame {i}") await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_scroll(self): """Testing precize scroll position""" window = await self.create_test_window() with window.frame: with ui.ScrollingFrame( style=STYLE, scroll_y=256, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.VStack(): for i in range(50): ui.Label(f"Label in ScrollingFrame {i}") await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_size(self): """Testing size of child""" window = await self.create_test_window() with window.frame: with ui.VStack(style=STYLE): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): ui.Rectangle(style={"background_color": "black", "border_color": "red", "border_width": 1}) with ui.HStack(): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): ui.Rectangle(style={"background_color": "black", "border_color": "red", "border_width": 1}) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): ui.Rectangle(style={"background_color": "black", "border_color": "red", "border_width": 1}) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_scroll_end(self): """Testing max scroll x/y of ui.ScrollingFrame""" window = await self.create_test_window() with window.frame: scrolling_frame = ui.ScrollingFrame( style=STYLE, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with scrolling_frame: with ui.VStack(): for i in range(50): ui.Label(f"Label in ScrollingFrame {i}") await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() scrolling_frame.scroll_y = scrolling_frame.scroll_y_max await omni.kit.app.get_app().next_update_async() await self.finalize_test()
4,365
Python
37.982143
115
0.596564
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_treeview.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.kit.test from .test_base import OmniUiTest from carb.input import MouseEventType import omni.kit.app import omni.ui as ui STYLE = { "TreeView:selected": {"background_color": 0x66FFFFFF}, "TreeView.Item": {"color": 0xFFCCCCCC}, "TreeView.Item:selected": {"color": 0xFFCCCCCC}, "TreeView.Header": {"background_color": 0xFF000000}, } class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) class ListModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ListModel(*string_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() self._children = [ListItem(t) for t in args] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model class ListModelDND(ListModel): def __init__(self, *args): super().__init__(*args) self.dropped = [] def get_drag_mime_data(self, item): """Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere""" # As we don't do Drag and Drop to the operating system, we return the string. return item.name_model.as_string def drop_accepted(self, target_item, source, drop_location=-1): return True def drop(self, target_item, source, drop_location=-1): self.dropped.append(source.name_model.as_string) class TreeItem(ListItem): """Single item of the model""" def __init__(self, text): super().__init__(text) self.children = None def get_children(self): if self.children is None: self.children = [TreeItem(f"{i}") for i in range(3)] return self.children class InfinityModel(ui.AbstractItemModel): def __init__(self, crash_test=False): super().__init__() self._children = [TreeItem("Root")] self._crash_test = crash_test self._dummy_model = ui.SimpleStringModel("NONE") def get_item_children(self, item): if item is None: return self._children if not hasattr(item, "get_children"): return [] children = item.get_children() if self._crash_test: # Destroy children to see if treeview will crash item.children = [] return children def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): if hasattr(item, "name_model"): return item.name_model return self._dummy_model class InfinityModelTwoColumns(InfinityModel): def get_item_value_model_count(self, item): return 2 class ListDelegate(ui.AbstractItemDelegate): """A very simple delegate""" def __init__(self): super().__init__() def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" pass def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" value_model = model.get_item_value_model(item, column_id) label = value_model.as_string ui.Label(label, name=label) def build_header(self, column_id): """Create a widget for the header""" label = f"Header {column_id}" ui.Label(label, alignment=ui.Alignment.CENTER, name=label) class TreeDelegate(ListDelegate): def build_branch(self, model, item, column_id, level, expanded): label = f"{'- ' if expanded else '+ '}" ui.Label(label, width=(level + 1) * 10, alignment=ui.Alignment.RIGHT_CENTER, name=label) class TestTreeView(OmniUiTest): """Testing ui.TreeView""" async def test_general(self): """Testing default view of ui.TreeView""" window = await self.create_test_window() self._list_model = ListModel("Simplest", "List", "Of", "Strings") with window.frame: tree_view = ui.TreeView(self._list_model, root_visible=False, header_visible=False, style=STYLE) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() # Simulate Shift+Click on the second item when the selection is empty. tree_view.extend_selection(self._list_model.get_item_children(None)[1]) await self.finalize_test() async def test_scrolling_header(self): """Testing how the ui.TreeView behaves when scrolling""" window = await self.create_test_window() self._list_model = ListModel(*[f"Item {i}" for i in range(500)]) self._list_delegate = ListDelegate() with window.frame: scrolling = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with scrolling: tree_view = ui.TreeView( self._list_model, delegate=self._list_delegate, root_visible=False, header_visible=True, style=STYLE ) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() scrolling.scroll_y = 1024 # Wait one frame for ScrollingFrame await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_tree(self): """Testing how the ui.TreeView show trees""" window = await self.create_test_window() self._tree_model = InfinityModel(crash_test=False) self._tree_delegate = TreeDelegate() with window.frame: tree_view = ui.TreeView( self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=False, style=STYLE ) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() # Expand root = self._tree_model.get_item_children(None)[0] first_level = self._tree_model.get_item_children(root)[0] tree_view.set_expanded(root, True, False) await omni.kit.app.get_app().next_update_async() tree_view.set_expanded(first_level, True, False) await self.finalize_test() async def test_inspector(self): """Testing how the ui.TreeView show trees""" window = await self.create_test_window() self._tree_model = InfinityModelTwoColumns() self._tree_delegate = TreeDelegate() with window.frame: tree_view = ui.TreeView( self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=True, style=STYLE ) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() # Expand root = self._tree_model.get_item_children(None)[0] first_level = self._tree_model.get_item_children(root)[0] tree_view.set_expanded(root, True, False) tree_view.set_expanded(first_level, True, False) children = ui.Inspector.get_children(tree_view) # Check all the children one by one self.assertEqual(len(children), 30) for child in children: self.assertIsInstance(child, ui.Label) self.assertEqual(child.name, child.text) self.assertEqual(children[0].text, "Header 0") self.assertEqual(children[1].text, "Header 1") self.assertEqual(children[2].text, "+ ") self.assertEqual(children[3].text, "Root") self.assertEqual(children[4].text, "+ ") self.assertEqual(children[5].text, "Root") self.assertEqual(children[6].text, "- ") self.assertEqual(children[7].text, "0") self.assertEqual(children[8].text, "- ") self.assertEqual(children[9].text, "0") self.assertEqual(children[10].text, "+ ") self.assertEqual(children[11].text, "0") self.assertEqual(children[12].text, "+ ") self.assertEqual(children[13].text, "0") self.assertEqual(children[14].text, "+ ") self.assertEqual(children[15].text, "1") self.assertEqual(children[16].text, "+ ") self.assertEqual(children[17].text, "1") self.assertEqual(children[18].text, "+ ") self.assertEqual(children[19].text, "2") self.assertEqual(children[20].text, "+ ") self.assertEqual(children[21].text, "2") self.assertEqual(children[22].text, "+ ") self.assertEqual(children[23].text, "1") self.assertEqual(children[24].text, "+ ") self.assertEqual(children[25].text, "1") self.assertEqual(children[26].text, "+ ") self.assertEqual(children[27].text, "2") self.assertEqual(children[28].text, "+ ") self.assertEqual(children[29].text, "2") await self.finalize_test() async def test_query(self): """ Testing if ui.TreeView crashing when querying right after initialization. """ window = await self.create_test_window() self._tree_model = InfinityModel() self._tree_delegate = TreeDelegate() with window.frame: tree_view = ui.TreeView( self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=True, style=STYLE ) # Don't wait one frame and don't let TreeView initialize the cache. # Trigger dirty tree_view.style = {"Label": {"font_size": 14}} # Query children and make sure it doesn't crash. children = ui.Inspector.get_children(tree_view) self.assertEqual(len(children), 3) self.assertEqual(children[0].text, "Header 0") self.assertEqual(children[1].text, "+ ") self.assertEqual(children[2].text, "Root") await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_lost_items(self): """Testing how the ui.TreeView behaves when the items are destroyed""" window = await self.create_test_window() self._tree_model = InfinityModel(crash_test=True) self._tree_delegate = TreeDelegate() with window.frame: tree_view = ui.TreeView( self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=False, style=STYLE ) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() # Expand tree_view.set_expanded(self._tree_model.get_item_children(None)[0], True, False) await omni.kit.app.get_app().next_update_async() await self.finalize_test() async def test_dnd(self): """Testing drag and drop multiple items in ui.TreeView""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) item_names = [f"Item {i}" for i in range(10)] _list_model = ListModelDND(*item_names) with window.frame: tree_view = ui.TreeView(_list_model, root_visible=False, header_visible=False, style=STYLE) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() item0 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 0'") item1 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 1'") # Select items [1..9] tree_view.extend_selection(_list_model.get_item_children(None)[1]) tree_view.extend_selection(_list_model.get_item_children(None)[len(item_names) - 1]) await ui_test.emulate_mouse_move(item1.center) await ui_test.emulate_mouse_drag_and_drop(item1.center, item0.center) await omni.kit.app.get_app().next_update_async() await self.finalize_test() # Check we received the drop events for all the selection for dropped, reference in zip(_list_model.dropped, item_names[1:]): self.assertEqual(dropped, reference) async def test_dnd_delegate_callbacks(self): moved = [0] pressed = [0] released = [0] class TestDelegate(ui.AbstractItemDelegate): def build_widget(self, model, item, column_id, level, expanded): if item is None: return if column_id == 0: with ui.HStack( mouse_pressed_fn=lambda x, y, b, m: self._on_item_mouse_pressed(item), mouse_released_fn=lambda x, y, b, m: self._on_item_mouse_released(item), mouse_moved_fn=lambda x, y, m, t: self._on_item_mouse_moved(x, y), ): ui.Label(item.name_model.as_string) def _on_item_mouse_moved(self, x, y): moved[0] += 1 def _on_item_mouse_pressed(self, item): pressed[0] += 1 def _on_item_mouse_released(self, item): released[0] += 1 import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) _model = ListModel("Test 1", "Test 2", "Test 3", "Test 4", "Test 5") _delegate = TestDelegate() with window.frame: ui.TreeView(_model, delegate=_delegate, root_visible=False) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() item1 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Test 1'") item5 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Test 5'") await ui_test.emulate_mouse_move(item1.center) await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN) await ui_test.human_delay(5) # Check pressed is called self.assertEqual(pressed[0], 1) self.assertEqual(moved[0], 0) await ui_test.input.emulate_mouse_slow_move(item1.center, item5.center) await ui_test.human_delay(5) # We have not released the mouse yet self.assertEqual(released[0], 0) self.assertTrue(moved[0] > 0) await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP) await ui_test.human_delay(5) # Checked release is called self.assertEqual(released[0], 1) await self.finalize_test_no_image() async def test_item_hovered_callback(self): """Testing hover items in ui.TreeView""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) item_names = [f"Item {i}" for i in range(10)] _list_model = ListModelDND(*item_names) with window.frame: tree_view = ui.TreeView(_list_model, root_visible=False, header_visible=False, style=STYLE) # Wait one frame to let TreeView initialize the cache. await omni.kit.app.get_app().next_update_async() item0 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 0'") item1 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 1'") # initialize mouse outside of list, so it doesn't accidentally hover on the wrong thing at the start await ui_test.emulate_mouse_move(ui_test.Vec2(0,0)) hover_status = {} def __item_hovered(item: ui.AbstractItem, hovered: bool): if item not in hover_status: hover_status[item] = { "enter": 0, "leave": 0 } if hovered: hover_status[item]["enter"] += 1 else: hover_status[item]["leave"] += 1 tree_view.set_hover_changed_fn(__item_hovered) # Hover items [0] await ui_test.emulate_mouse_move(item0.center) await omni.kit.app.get_app().next_update_async() # Hover items [1] await ui_test.emulate_mouse_move(item1.center) await omni.kit.app.get_app().next_update_async() # Check we received the hover callbacks self.assertEqual(len(hover_status), 2) items = _list_model.get_item_children(None) self.assertEqual(hover_status[items[0]]["enter"], 1) self.assertEqual(hover_status[items[0]]["leave"], 1) self.assertEqual(hover_status[items[1]]["enter"], 1) self.assertEqual(hover_status[items[1]]["leave"], 0) await self.finalize_test_no_image()
17,748
Python
34.640562
120
0.609984
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_combobox.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_base import OmniUiTest import omni.kit.app import omni.ui as ui from omni.ui import color as cl class TestComboBox(OmniUiTest): """Testing ui.ComboBox""" async def test_general(self): """Testing general look of ui.ComboBox""" window = await self.create_test_window() with window.frame: with ui.VStack(): # Simple combo box style = { "background_color": cl.black, "border_color": cl.white, "border_width": 1, "padding": 0, } for i in range(8): style["padding"] = i * 2 ui.ComboBox(0, f"{i}", "B", style=style, height=0) await self.finalize_test()
1,261
Python
32.210525
77
0.605868
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_compare_utils.py
import os from pathlib import Path import omni.kit.test from .compare_utils import GOLDEN_DIR, OUTPUTS_DIR, CompareMetric, compare from .test_base import OmniUiTest class TestCompareUtils(omni.kit.test.AsyncTestCase): async def setUp(self): self.test_name = "omni.ui.tests.test_compare_utils.TestCompareUtils" def cleanupTestFile(self, target: str): try: os.remove(target) except FileNotFoundError: pass async def test_compare_rgb(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_golden.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_modified.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertAlmostEqual(diff, 40.4879, places=3) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertAlmostEqual(diff, 0.031937, places=5) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 262144) async def test_compare_rgba(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_golden.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_modified.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertAlmostEqual(diff, 0.4000, places=3) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertAlmostEqual(diff, 0.001466, places=5) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 1961) async def test_compare_rgb_itself(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_golden.png") image2 = image1 image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertEqual(diff, 0) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertEqual(diff, 0) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 0) async def test_compare_grayscale(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_golden.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_modified.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertAlmostEqual(diff, 39.3010, places=3) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertAlmostEqual(diff, 0.030923, places=5) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 260827) async def test_compare_rgb_black_to_white(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_black.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_white.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertEqual(diff, 255.0) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertEqual(diff, 1.0) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 4096) async def test_compare_rgba_black_to_white(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_black.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_white.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertEqual(diff, 191.25) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertEqual(diff, 0.75) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 4096) async def test_compare_rgb_gray(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray_modified.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertEqual(diff, 48) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertAlmostEqual(diff, 0.094486, places=5) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 2048) async def test_compare_rgb_gray_pixel(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray_pixel.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray_pixel_modified.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertAlmostEqual(diff, 0.0468, places=3) # mean error squared diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertAlmostEqual(diff, 0.000092, places=5) # pixel count diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT) self.assertEqual(diff, 2) async def test_compare_threshold(self): image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_golden.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_modified.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") expected_diff = 39.30104446411133 # diff is below threshold (39.301 < 40) -> image_diffmap saved to disk diff = compare(image1, image2, image_diffmap, threshold=40) self.assertAlmostEqual(diff, expected_diff, places=3) self.assertTrue(os.path.exists(image_diffmap)) self.cleanupTestFile(image_diffmap) # diff is below threshold but threshold is above by 2 order of magnitude (39.301 < 4000/10) -> no image_diffmap diff = compare(image1, image2, image_diffmap, threshold=4000) self.assertAlmostEqual(diff, expected_diff, places=3) self.assertFalse(os.path.exists(image_diffmap)) # no file cleanup to do here # diff is above threshold (39.301 > 39) -> image_diffmap saved to disk diff = compare(image1, image2, image_diffmap, threshold=39) self.assertAlmostEqual(diff, expected_diff, places=3) self.assertTrue(os.path.exists(image_diffmap)) self.cleanupTestFile(image_diffmap) # diff is above threshold but threshold is below by 2 order of magnitude (39.301 > 3900/10) -> image_diffmap saved to disk diff = compare(image1, image2, image_diffmap, threshold=3900) self.assertAlmostEqual(diff, expected_diff, places=3) self.assertTrue(os.path.exists(image_diffmap)) self.cleanupTestFile(image_diffmap) async def test_default_threshold(self): """This test will give an example of an image comparison just above the default threshold""" image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_threshold.png") image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_threshold_modified.png") image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png") # mean error default threshold is 0.01 diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR) self.assertAlmostEqual(diff, OmniUiTest.MEAN_ERROR_THRESHOLD, places=2) # mean error squared default threshold is 1e-5 (0.00001) diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED) self.assertAlmostEqual(diff, OmniUiTest.MEAN_ERROR_SQUARED_THRESHOLD, places=5)
9,699
Python
55.069364
130
0.688731