file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/__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 .context_menu import ContextMenu
from .stage_extension import *
from .stage_icons import *
from .stage_widget import *
from .selection_watch import *
from .stage_model import *
from .stage_item import *
from .export_utils import ExportPrimUSD
from .commands import *
from .abstract_stage_column_delegate import *
from .stage_column_delegate_registry import *
| 797 | Python | 38.899998 | 76 | 0.797992 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_column_delegate_registry.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageColumnDelegateRegistry"]
from .abstract_stage_column_delegate import AbstractStageColumnDelegate
from .event import Event
from .event import EventSubscription
from .singleton import Singleton
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
import carb
@Singleton
class StageColumnDelegateRegistry:
"""
Singleton that keeps all the column delegated. It's used to put custom
columns to the content browser.
"""
class _ColumnDelegateSubscription:
"""
Event subscription.
Event has callback while this object exists.
"""
def __init__(self, name, delegate):
"""
Save name and type to the list.
"""
self._name = name
StageColumnDelegateRegistry()._delegates[self._name] = delegate
StageColumnDelegateRegistry()._on_delegates_changed()
def __del__(self):
"""Called by GC."""
del StageColumnDelegateRegistry()._delegates[self._name]
StageColumnDelegateRegistry()._on_delegates_changed()
def __init__(self):
self._delegates: Dict[str, Callable[[], AbstractStageColumnDelegate]] = {}
self._names: List[str] = []
self._on_delegates_changed = Event()
self.__delegate_changed_sub = self.subscribe_delegate_changed(self.__delegate_changed)
def register_column_delegate(self, name: str, delegate: Callable[[], AbstractStageColumnDelegate]):
"""
Add a new engine to the registry.
## Arguments
`name`: the name of the engine as it appears in the menu.
`delegate`: the type derived from AbstractColumnDelegate. Content
browser will create an object of this type to build
widgets for the custom column.
"""
if name in self._delegates:
carb.log_warn(f"Column delegate with name {name} is registered already.")
return
return self._ColumnDelegateSubscription(name, delegate)
def get_column_delegate_names(self) -> List[str]:
"""Returns all the column delegate names"""
return self._names
def get_column_delegate(self, name: str) -> Optional[Callable[[], AbstractStageColumnDelegate]]:
"""Returns the type of derived from AbstractColumnDelegate for the given name"""
return self._delegates.get(name, None)
def subscribe_delegate_changed(self, fn: Callable[[], None]) -> EventSubscription:
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return EventSubscription(self._on_delegates_changed, fn)
def __delegate_changed(self):
self._names = list(sorted(self._delegates.keys()))
| 3,251 | Python | 36.37931 | 103 | 0.665949 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/context_menu.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os, sys
import asyncio
import carb
import omni.usd
import omni.kit.ui
import omni.kit.usd.layers as layers
from omni import ui
from functools import partial
from pxr import Usd, Sdf, UsdShade, UsdGeom, UsdLux, Kind
class ContextMenu:
def __init__(self):
self.function_list = {}
def destroy(self):
self.function_list = {}
def on_mouse_event(self, event):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE):
return
# get context menu core functionality & check its enabled
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
carb.log_error("context_menu is disabled!")
return
# get stage
stage = event.payload.get("stage", None)
if stage is None:
carb.log_error("stage not avaliable")
return None
# get parameters passed by event
prim_path = event.payload["prim_path"]
# setup objects, this is passed to all functions
objects = {}
objects["use_hovered"] = True if prim_path else False
objects["stage_win"] = self._stage_win
objects["node_open"] = event.payload["node_open"]
objects["stage"] = stage
objects["function_list"] = self.function_list
prim_list = []
hovered_prim = event.payload["prim_path"]
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if len(paths) > 0:
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim:
prim_list.append(prim)
if prim == hovered_prim:
hovered_prim = None
elif prim_path is not None:
prim = stage.GetPrimAtPath(prim_path)
if prim:
prim_list.append(prim)
if prim_list:
objects["prim_list"] = prim_list
if hovered_prim:
objects["hovered_prim"] = stage.GetPrimAtPath(hovered_prim)
# setup menu
menu_dict = [
{"populate_fn": context_menu.show_selected_prims_names},
{"populate_fn": ContextMenu.show_create_menu},
{"name": ""},
{
"name": "Clear Default Prim",
"glyph": "menu_rename.svg",
"show_fn": [context_menu.is_prim_selected, ContextMenu.is_prim_sudo_root, ContextMenu.has_default_prim],
"onclick_fn": ContextMenu.clear_default_prim,
},
{
"name": "Set as Default Prim",
"glyph": "menu_rename.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
ContextMenu.is_prim_sudo_root,
ContextMenu.no_default_prim,
],
"onclick_fn": ContextMenu.set_default_prim,
},
{"name": ""},
{
"name": "Find in Content Browser",
"glyph": "menu_search.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
context_menu.can_show_find_in_browser,
],
"onclick_fn": context_menu.find_in_browser,
},
{"name": ""},
{
"name": "Group Selected",
"glyph": "group_selected.svg",
"show_fn": context_menu.is_prim_selected,
"onclick_fn": context_menu.group_selected_prims,
},
{
"name": "Ungroup Selected",
"glyph": "group_selected.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_prim_in_group,
],
"onclick_fn": context_menu.ungroup_selected_prims,
},
{
"name": "Duplicate",
"glyph": "menu_duplicate.svg",
"show_fn": [context_menu.is_prim_selected, context_menu.can_be_copied],
"onclick_fn": context_menu.duplicate_prim,
},
{
"name": "Rename",
"glyph": "menu_rename.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
context_menu.can_delete,
ContextMenu.has_rename_function
],
"onclick_fn": ContextMenu.rename_prim,
},
{
"name": "Delete",
"glyph": "menu_delete.svg",
"show_fn": [context_menu.is_prim_selected, context_menu.can_delete],
"onclick_fn": context_menu.delete_prim,
},
{
"name": "Save Selected",
"glyph": "menu_save.svg",
"show_fn": [context_menu.is_prim_selected],
"onclick_action": ("omni.kit.widget.stage", "save_prim"),
},
{"name": ""},
{
"name": "Refresh Reference",
"glyph": "sync.svg",
"name_fn": context_menu.refresh_reference_payload_name,
"show_fn": [context_menu.is_prim_selected, context_menu.has_payload_or_reference],
"onclick_fn": context_menu.refresh_payload_or_reference,
},
{
"name": "Convert Payloads to References",
"glyph": "menu_duplicate.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.has_payload,
context_menu.can_convert_references_or_payloads
],
"onclick_fn": context_menu.convert_payload_to_reference,
},
{
"name": "Convert References to Payloads",
"glyph": "menu_duplicate.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.has_reference,
context_menu.can_convert_references_or_payloads
],
"onclick_fn": context_menu.convert_reference_to_payload,
},
{
"name": "Select Bound Objects",
"glyph": "menu_search.svg",
"show_fn": [context_menu.is_prim_selected, context_menu.is_material],
"onclick_fn": context_menu.select_prims_using_material,
},
{
"name": "Bind Material To Selected Objects",
"glyph": "menu_material.svg",
"show_fn": [
context_menu.is_prim_selected,
ContextMenu.is_hovered_prim_material,
context_menu.is_material_bindable,
context_menu.is_one_prim_selected,
],
"onclick_fn": ContextMenu.bind_material_to_selected_prims,
},
{
"name":
{
'Expand':
[
{
"name": "Expand To:",
},
{
"name": "All",
"onclick_fn": ContextMenu.expand_all,
},
{
"name": "Component",
"onclick_fn": lambda o, k="component": ContextMenu.expand_to(o, k),
},
{
"name": "Group",
"onclick_fn": lambda o, k="group": ContextMenu.expand_to(o, k),
},
{
"name": "Assembly",
"onclick_fn": lambda o, k="assembly": ContextMenu.expand_to(o, k),
},
{
"name": "SubComponent",
"onclick_fn": lambda o, k="subcomponent": ContextMenu.expand_to(o, k),
},
]
},
"glyph": "menu_plus.svg",
"show_fn": [ContextMenu.show_open_tree],
},
{
"name":
{
'Collapse':
[
{
"name": "Collapse To:",
},
{
"name": "All",
"onclick_fn": ContextMenu.collapse_all,
},
{
"name": "Component",
"onclick_fn": lambda o, k="component": ContextMenu.collapse_to(o, k),
},
{
"name": "Group",
"onclick_fn": lambda o, k="group": ContextMenu.collapse_to(o, k),
},
{
"name": "Assembly",
"onclick_fn": lambda o, k="assembly": ContextMenu.collapse_to(o, k),
},
{
"name": "SubComponent",
"onclick_fn": lambda o, k="subcomponent": ContextMenu.collapse_to(o, k),
},
]
},
"glyph": "menu_minus.svg",
"show_fn": [ContextMenu.show_open_tree],
},
{"name": ""},
{
"name": "Assign Material",
"glyph": "menu_material.svg",
"show_fn_async": context_menu.can_assign_material_async,
"onclick_fn": ContextMenu.bind_material_to_prim_dialog,
},
{"name": "", "show_fn_async": context_menu.can_assign_material_async},
{
"name": "Copy URL Link",
"glyph": "menu_link.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
context_menu.can_show_find_in_browser,
context_menu.can_use_find_in_browser,
],
"onclick_fn": context_menu.copy_prim_url,
},
{
"name": "Copy Prim Path",
"glyph": "menu_link.svg",
"show_fn": context_menu.is_prim_selected,
"onclick_fn": context_menu.copy_prim_path,
},
]
if stage:
layers_interface = layers.get_layers(omni.usd.get_context())
auto_authoring = layers_interface.get_auto_authoring()
layers_state = layers_interface.get_layers_state()
edit_mode = layers_interface.get_edit_mode()
if edit_mode == layers.LayerEditMode.SPECS_LINKING:
per_layer_link_menu = []
for layer in stage.GetLayerStack():
if auto_authoring.is_auto_authoring_layer(layer.identifier):
continue
layer_name = layers_state.get_layer_name(layer.identifier)
per_layer_link_menu.append(
{
"name":
{
f"{layer_name}":
[
{
"name": "Link Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, True,
layer.identifier, False
),
},
{
"name": "Link Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, True,
layer.identifier, True
),
},
{
"name": "Unlink Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, False,
layer.identifier, False
),
},
{
"name": "Unlink Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, False,
layer.identifier, True
),
},
{
"name": "Select Linked Prims",
"show_fn": [
],
"onclick_fn": ContextMenu.select_linked_prims,
},
]
}
}
)
menu_dict.extend([{"name": ""}])
menu_dict.append(
{
"name":
{
"Layers": per_layer_link_menu
},
"glyph": "menu_link.svg",
}
)
menu_dict.extend([{"name": ""}])
menu_dict.append(
{
"name":
{
"Locks": [
{
"name": "Lock Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, True,
False
),
},
{
"name": "Lock Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, True,
True
),
},
{
"name": "Unlock Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, False,
False
),
},
{
"name": "Unlock Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, False,
True
),
},
{
"name": "Select Locked Prims",
"show_fn": [
],
"onclick_fn": ContextMenu.select_locked_prims,
},
]
},
"glyph": "menu_lock.svg",
}
)
menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "")
menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "omni.kit.widget.stage")
omni.kit.context_menu.reorder_menu_dict(menu_dict)
def _get_kinds():
builtin_kinds = ["model", "assembly", "group", "component", "subcomponent"]
display_builtin_kinds = builtin_kinds[1:]
plugin_kinds = list(set(Kind.Registry.GetAllKinds()) - set(builtin_kinds))
display_builtin_kinds.extend(plugin_kinds)
return display_builtin_kinds
def _set_kind(kind_string):
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
stage = omni.usd.get_context().get_stage()
for p in paths:
model = Usd.ModelAPI(stage.GetPrimAtPath(p))
model.SetKind(kind_string)
kind_list = _get_kinds()
sub_menu = []
menu = {}
menu["name"] = "None"
menu["onclick_fn"] = lambda i, kind_string="": _set_kind(kind_string)
sub_menu.append(menu)
for k in kind_list:
menu = {}
menu["name"] = str(k).capitalize()
menu["onclick_fn"] = lambda i, kind_string=str(k): _set_kind(kind_string)
sub_menu.append(menu)
menu_dict.append(
{
"name": {
"Set Kind": sub_menu
},
"glyph": "none.svg"
}
)
# show menu
context_menu.show_context_menu("stagewindow", objects, menu_dict)
# ---------------------------------------------- menu show functions ----------------------------------------------
def is_prim_sudo_root(objects):
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) != 1:
return False
prim = prim_list[0]
return prim.GetParent() == prim.GetStage().GetPseudoRoot()
def has_default_prim(objects):
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) != 1:
return False
stage = objects["stage"]
return stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim_list[0]
def no_default_prim(objects):
return not ContextMenu.has_default_prim(objects)
def is_hovered_prim_material(objects):
hovered_prim = objects.get("hovered_prim", None)
if not hovered_prim:
return False
return hovered_prim.IsA(UsdShade.Material)
def show_open_tree(objects): # pragma: no cover
"""Unused"""
if not "prim_list" in objects:
return False
prim = objects["prim_list"][0]
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
if prim.IsA(UsdGeom.Camera) or ((prim.HasAPI(UsdLux.LightAPI)) if hasattr(UsdLux, 'LightAPI') else prim.IsA(UsdLux.Light)):
if len(prim.GetChildren()) <= 1:
return False
else:
if len(prim.GetChildren()) == 0:
return False
if objects["node_open"]:
return False
else:
return True
def show_close_tree(objects): # pragma: no cover
"""Unused"""
if not "prim_list" in objects:
return False
prim = objects["prim_list"][0]
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
if prim.IsA(UsdGeom.Camera) or ((prim.HasAPI(UsdLux.LightAPI)) if hasattr(UsdLux, 'LightAPI') else prim.IsA(UsdLux.Light)):
if len(prim.GetChildren()) <= 1:
return False
else:
if len(prim.GetChildren()) == 0:
return False
if objects["node_open"]:
return True
else:
return False
# ---------------------------------------------- menu onClick functions ----------------------------------------------
def expand_all(objects):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
def recurse_expand(prim):
objects["stage_win"].context_menu_handler(
cmd="opentree", prim_path=prim.GetPath().pathString
)
for p in prim.GetChildren():
recurse_expand(p)
for p in prim_list:
if isinstance(p, Usd.Prim):
recurse_expand(p)
def expand_to(objects, kind):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
def recurse_expand(prim, kind):
expand = False
model = Usd.ModelAPI(prim)
if model.GetKind() != kind:
for p in prim.GetChildren():
expand = recurse_expand(p, kind) or expand
else:
# do not expand the target kind
return True
if expand:
objects["stage_win"].context_menu_handler(
cmd="opentree", prim_path=prim.GetPath().pathString
)
return expand
for p in prim_list:
if isinstance(p, Usd.Prim):
recurse_expand(p, kind)
def collapse_all(objects):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
for p in prim_list:
if isinstance(p, Usd.Prim):
objects["stage_win"].context_menu_handler(
cmd="closetree", prim_path=p.GetPath().pathString
)
def collapse_to(objects, kind):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
def recurse_collapse(prim, kind):
collapse = False
model = Usd.ModelAPI(prim)
if model.GetKind() != kind:
for p in prim.GetChildren():
collapse = recurse_collapse(p, kind) or collapse
else:
collapse = True
if collapse:
objects["stage_win"].context_menu_handler(
cmd="closetree", prim_path=prim.GetPath().pathString
)
for p in prim_list:
if isinstance(p, Usd.Prim):
recurse_collapse(p, kind)
def link_selected(link_or_unlink, layer_identifier, hierarchy, objects): # pragma: no cover
prim_list = objects.get("prim_list", None)
if not prim_list:
return
prim_paths = []
for prim in prim_list:
prim_paths.append(prim.GetPath())
if link_or_unlink:
command = "LinkSpecs"
else:
command = "UnlinkSpecs"
omni.kit.commands.execute(
command,
spec_paths=prim_paths,
layer_identifiers=layer_identifier,
hierarchy=hierarchy
)
def lock_selected(lock_or_unlock, hierarchy, objects):
prim_list = objects.get("prim_list", None)
if not prim_list:
return
prim_paths = []
for prim in prim_list:
prim_paths.append(prim.GetPath())
if lock_or_unlock:
command = "LockSpecs"
else:
command = "UnlockSpecs"
omni.kit.commands.execute(
command,
spec_paths=prim_paths,
hierarchy=hierarchy
)
def select_linked_prims(objects): # pragma: no cover
usd_context = omni.usd.get_context()
links = omni.kit.usd.layers.get_all_spec_links(usd_context)
prim_paths = [spec_path for spec_path in links.keys() if Sdf.Path(spec_path).IsPrimPath()]
if prim_paths:
old_prim_paths = usd_context.get_selection().get_selected_prim_paths()
omni.kit.commands.execute(
"SelectPrims", old_selected_paths=old_prim_paths,
new_selected_paths=prim_paths, expand_in_stage=True
)
def select_locked_prims(objects):
usd_context = omni.usd.get_context()
locked_specs = omni.kit.usd.layers.get_all_locked_specs(usd_context)
prim_paths = [spec_path for spec_path in locked_specs if Sdf.Path(spec_path).IsPrimPath()]
if prim_paths:
old_prim_paths = usd_context.get_selection().get_selected_prim_paths()
omni.kit.commands.execute(
"SelectPrims", old_selected_paths=old_prim_paths,
new_selected_paths=prim_paths, expand_in_stage=True
)
def clear_default_prim(objects):
objects["stage"].ClearDefaultPrim()
def set_default_prim(objects):
objects["stage"].SetDefaultPrim(objects["prim_list"][0])
def show_create_menu(objects):
prim_list = objects["prim_list"] if "prim_list" in objects else None
omni.kit.context_menu.get_instance().build_create_menu(
objects, prim_list, omni.kit.context_menu.get_menu_dict("CREATE", "omni.kit.widget.stage")
)
omni.kit.context_menu.get_instance().build_add_menu(
objects, prim_list, omni.kit.context_menu.get_menu_dict("ADD", "omni.kit.widget.stage")
)
def bind_material_to_prim_dialog(objects):
if not "prim_list" in objects:
return
omni.kit.material.library.bind_material_to_prims_dialog(objects["stage"], objects["prim_list"])
def bind_material_to_selected_prims(objects):
if not all(item in objects for item in ["hovered_prim", "prim_list"]):
return
material_prim = objects["hovered_prim"]
prim_paths = [i.GetPath() for i in objects["prim_list"]]
omni.kit.commands.execute(
"BindMaterial", prim_path=prim_paths, material_path=material_prim.GetPath().pathString, strength=None
)
def has_rename_function(objects):
return "rename_item" in objects["function_list"]
def rename_prim(objects):
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) != 1:
return False
prim = prim_list[0]
if "rename_item" in objects["function_list"]:
objects["function_list"]["rename_item"](prim.GetPath().pathString)
@staticmethod
def add_menu(menu_dict):
"""
Add the menu to the end of the context menu. Return the object that
should be alive all the time. Once the returned object is destroyed,
the added menu is destroyed as well.
"""
return omni.kit.context_menu.add_menu(menu_dict, "MENU", "omni.kit.widget.stage")
@staticmethod
def add_create_menu(menu_dict):
"""
Add the menu to the end of the stage context create menu. Return the object that
should be alive all the time. Once the returned object is destroyed,
the added menu is destroyed as well.
"""
return omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.widget.stage")
| 29,955 | Python | 37.306905 | 131 | 0.441362 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_actions.py | import carb
import omni.usd
import omni.kit.actions.core
import omni.kit.hotkeys.core
from omni.kit.hotkeys.core import KeyCombination, get_hotkey_registry
from .export_utils import ExportPrimUSD
def post_notification(message: str, info: bool = False, duration: int = 3):
try:
import omni.kit.notification_manager as nm
if info:
type = nm.NotificationStatus.INFO
else:
type = nm.NotificationStatus.WARNING
nm.post_notification(message, status=type, duration=duration)
except ModuleNotFoundError:
carb.log_warn(message)
def save_prim(objects):
if not objects:
prim_list = []
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
stage = omni.usd.get_context().get_stage()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim:
prim_list.append(prim)
objects = {"prim_list": prim_list}
elif isinstance(objects, tuple):
objects = objects[0]
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) == 0:
post_notification("Cannot save prims as no prims are selected")
elif len(prim_list) == 1:
ExportPrimUSD(select_msg=f"Save \"{prim_list[0].GetName()}\" As...").export(prim_list)
else:
ExportPrimUSD(select_msg=f"Save Prims As...").export(prim_list)
def register_actions(extension_id, owner):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Stage Actions"
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"save_prim",
lambda *o: save_prim(o),
display_name="Stage->Save Prim",
description="Save Prim",
tag=actions_tag,
)
def deregister_actions(extension_id, owner):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
hotkey_registry = get_hotkey_registry()
for key_reg in owner._registered_hotkeys:
hotkey_registry.deregister_hotkey(key_reg)
owner._registered_hotkeys = []
| 2,191 | Python | 31.235294 | 94 | 0.651301 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/utils.py | import carb
import traceback
import functools
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
| 475 | Python | 21.666666 | 60 | 0.6 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_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.
#
__all__ = ["StageWidget"]
from .column_menu import ColumnMenuDelegate
from .column_menu import ColumnMenuItem
from .column_menu import ColumnMenuModel
from .event import Event, EventSubscription
from .stage_column_delegate_registry import StageColumnDelegateRegistry
from .stage_delegate import StageDelegate
from .stage_icons import StageIcons
from .stage_model import StageModel
from .stage_settings import StageSettings
from .stage_style import Styles as StageStyles
from .stage_filter import StageFilterButton
from pxr import Sdf
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from pxr import UsdSkel
from typing import Callable
from typing import List
from typing import Tuple
import asyncio
import carb.settings
import omni.kit.app
import omni.ui as ui
import omni.kit.notification_manager as nm
import omni.kit.usd.layers as layers
import weakref
class StageWidget:
"""The Stage widget"""
def __init__(
self, stage: Usd.Stage,
columns_accepted: List[str] = None,
columns_enabled: List[str] = None,
lazy_payloads: bool = False,
**kwargs
):
"""
Constructor.
Args:
stage (Usd.Stage): The instance of USD stage to be managed by this widget.
columns_accepted (List[str]): The list of columns that are supported. By default, it's all registered
columns if this arg is not provided.
columns_enabled (List[str]): The list of columns that are enabled when the widget is shown by default.
lazy_payloads (bool): Whether it should load all payloads when stage items are shown or not.
False by default.
Kwargs:
children_reorder_supported (bool): Whether it should enable children reorder support or not. By default,
children reorder support is disabled, which means you cannot reorder children in the widget, and
renaming name of prim will put the prim at the end of the children list. REMINDER: Enabling this
option has performance penalty as it will trigger re-composition to the parent of the reordered/renamed
prims.
show_prim_display_name (bool): Whether it's to show displayName from prim's metadata or the name of the prim.
By default, it's False, which means it shows name of the prim.
auto_reload_prims (bool): Whether it will auto-reload prims if there are any new changes from disk. By
default, it's disabled.
Other:
All other arguments inside kwargs except the above 3 will be passed as params to the ui.Frame for the
stage widget.
"""
# create_stage_update_node` calls `_on_attach`, and the models will be created there.
self._model = None
self._tree_view = None
self._tree_view_flat = None
self._delegate = StageDelegate()
self._delegate.expand_fn = self.expand
self._delegate.collapse_fn = self.collapse
self._selection = None
self._stage_settings = StageSettings()
self._stage_settings.children_reorder_supported = kwargs.pop("children_reorder_supported", False)
self._stage_settings.show_prim_displayname = kwargs.pop("show_prim_display_name", False)
self._stage_settings.auto_reload_prims = kwargs.pop("auto_reload_prims", False)
# Initialize columns
self._columns_accepted = columns_accepted
self._columns_enabled = columns_enabled
self._lazy_payloads = lazy_payloads
self._column_widths = []
self._min_column_widths = []
self._column_model = ColumnMenuModel(self._columns_enabled, self._columns_accepted)
self._column_delegate = ColumnMenuDelegate()
self._column_changed_sub = self._column_model.subscribe_item_changed_fn(self._on_column_changed)
# We need it to be able to add callback to StageWidget
self._column_changed_event = Event()
self.open_stage(stage)
self._root_frame = ui.Frame(**kwargs)
self.build_layout()
# The filtering logic
self._begin_filter_subscription = self._search.subscribe_begin_edit_fn(
lambda _: StageWidget._set_widget_visible(self._search_label, False)
)
self._end_filter_subscription = self._search.subscribe_end_edit_fn(
lambda m: self._filter_by_text(m.as_string)
or StageWidget._set_widget_visible(self._search_label, not m.as_string)
)
# Update icons when they changed
self._icons_subscription = StageIcons().subscribe_icons_changed(self.update_icons)
self._expand_task = None
def build_layout(self):
"""Creates all the widgets in the window"""
style = StageStyles.STAGE_WIDGET
use_default_style = (
carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False
)
if not use_default_style:
self._root_frame.set_style(style)
with self._root_frame:
# Options menu
self._options_menu = ui.Menu("Options")
with self._options_menu:
ui.MenuItem("Options", enabled=False)
ui.Separator()
def _set_auto_reload_prims(value):
self.auto_reload_prims = value
stage_model = self.get_model()
all_stage_items = stage_model._get_all_stage_items_from_cache()
if not all_stage_items:
return
for stage_item in all_stage_items:
stage_item.update_flags()
stage_model._item_changed(stage_item)
property_window = omni.kit.window.property.get_window()
if property_window:
property_window.request_rebuild()
ui.MenuItem(
"Auto Reload Primitives",
checkable=True,
checked=self.auto_reload_prims,
checked_changed_fn=_set_auto_reload_prims
)
ui.MenuItem("Reload Outdated Primitives", triggered_fn=self._on_reload_all_prims)
ui.Separator()
self._options_menu_reset = ui.MenuItem("Reset", triggered_fn=self._on_reset)
ui.Separator()
ui.MenuItem(
"Flat List Search",
checkable=True,
checked=self._stage_settings.flat_search,
checked_changed_fn=self._on_flat_changed,
)
ui.MenuItem("Show Root", checkable=True, checked_changed_fn=self._on_show_root_changed)
def _set_display_name(value):
self.show_prim_display_name = value
ui.MenuItem(
"Show Display Names",
checkable=True,
checked=self.show_prim_display_name,
checked_changed_fn=_set_display_name
)
def _children_reorder_supported(value):
self.children_reorder_supported = value
ui.MenuItem(
"Enable Children Reorder",
checkable=True,
checked=self.children_reorder_supported,
checked_changed_fn=_children_reorder_supported
)
with ui.Menu("Columns"):
# Sub-menu with list view, so it's possible to reorder it.
with ui.Frame():
self._column_list = ui.TreeView(
self._column_model,
delegate=self._column_delegate,
root_visible=False,
drop_between_items=True,
width=150,
)
self._column_list.set_selection_changed_fn(self._on_column_selection_changed)
with ui.VStack(style=style):
ui.Spacer(height=4)
with ui.ZStack(height=0):
with ui.HStack(spacing=4):
# Search filed
self._search = ui.StringField(name="search").model
# Filter button
self._filter_button = StageFilterButton(self)
# Options button
ui.Button(name="options", width=20, height=20, clicked_fn=lambda: self._options_menu.show())
# The label on the top of the search field
self._search_label = ui.Label("Search", name="search")
ui.Spacer(height=7)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style_type_name_override="TreeView.ScrollingFrame",
mouse_pressed_fn=lambda x, y, b, _: self._delegate.on_mouse_pressed(
b, self._model and self._model.stage, None, False
),
):
with ui.ZStack():
# Sometimes we need to switch between regular tree and flat list. To do it fast we keep
# both widgets.
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
drop_between_items=True,
header_visible=True,
root_visible=False,
columns_resizable=True,
)
self._tree_view_flat = ui.TreeView(
self._model,
delegate=self._delegate,
header_visible=True,
root_visible=False,
columns_resizable=True,
visible=False,
)
self.set_columns_widths()
def update_filter_menu_state(self, filter_type_list: list):
"""
Enable filters.
Args:
filter_type_list (list): List of usd types to be enabled. If not all usd types are pre-defined, hide filter button and Reset in options button
"""
unknown_types = self._filter_button.enable_filters(filter_type_list)
if unknown_types:
self._options_menu_reset.visible = False
def set_selection_watch(self, selection):
self._selection = selection
if self._selection:
if self._tree_view.visible:
self._selection.set_tree_view(self._tree_view)
if self._tree_view_flat.visible:
self._selection.set_tree_view(self._tree_view_flat)
def get_model(self) -> StageModel:
if self._tree_view.visible:
return self._tree_view.model
elif self._tree_view_flat.visible:
return self._tree_view_flat.model
return None
def expand(self, path: Sdf.Path):
"""Set the given path expanded"""
if isinstance(path, str):
path = Sdf.Path(path)
if self._tree_view.visible:
widget = self._tree_view
elif self._tree_view_flat.visible:
widget = self._tree_view_flat
else:
return
# Get the selected item and its parents. Expand all the parents of the new selection.
full_chain = widget.model.find_full_chain(path.pathString)
if full_chain:
for item in full_chain:
widget.set_expanded(item, True, False)
def collapse(self, path: Sdf.Path):
"""Set the given path collapsed"""
if isinstance(path, str):
path = Sdf.Path(path)
if self._tree_view.visible:
widget = self._tree_view
elif self._tree_view_flat.visible:
widget = self._tree_view_flat
else:
return
widget.set_expanded(widget.model.find(path), False, True)
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
self._cancel_expand_task()
self._begin_filter_subscription = None
self._end_filter_subscription = None
self._icons_subscription = None
self._tree_view = None
self._tree_view_flat = None
self._search_label = None
if self._model:
self._model.destroy()
self._model = None
if self._delegate:
self._delegate.destroy()
self._delegate = None
self._stage_subscription = None
self._selection = None
self._options_menu = None
self._filter_button.destroy()
self._filter_button = None
self._root_frame = None
self._column_list = None
self._column_model.destroy()
self._column_model = None
self._column_delegate.destroy()
self._column_delegate = None
self._column_changed_sub = None
def _clear_filter_types(self):
self._filter_button.model.reset()
def _on_flat_changed(self, flat):
"""Toggle flat/not flat search"""
# Disable search. It makes the layout resetting to the original state
self._filter_by_text("")
self._clear_filter_types()
# Change flag and clear the model
self._stage_settings.flat_search = flat
self._search.set_value("")
self._search_label.visible = True
def _on_reset(self):
"""Toggle "Reset" menu"""
self._model.reset()
def _on_show_root_changed(self, show):
"""Called to trigger "Show Root" menu item"""
self._tree_view.root_visible = show
@property
def show_prim_display_name(self):
return self._stage_settings.show_prim_displayname
@show_prim_display_name.setter
def show_prim_display_name(self, show):
if self._stage_settings.show_prim_displayname != show:
self._stage_settings.show_prim_displayname = show
self._model.show_prim_displayname = show
@property
def children_reorder_supported(self):
return self._stage_settings.children_reorder_supported
@children_reorder_supported.setter
def children_reorder_supported(self, enabled):
self._stage_settings.children_reorder_supported = enabled
self._model.children_reorder_supported = enabled
@property
def auto_reload_prims(self):
return self._stage_settings.auto_reload_prims
def _on_reload_all_prims(self):
self._on_reload_prims(not_in_session=False)
def _on_reload_prims(self, not_in_session=True):
if not self._model:
return
stage = self._model.stage
if not stage:
return
usd_context = omni.usd.get_context_from_stage(stage)
if not usd_context:
return
layers_state_interface = layers.get_layers_state(usd_context)
if not_in_session:
# this will auto reload all layers that are not currently in a live session ( silently )
layers_state_interface.reload_outdated_non_sublayers()
else:
# this will reload all layers but will confirm with user if it is in a live session
all_outdated_layers = layers_state_interface.get_all_outdated_layer_identifiers(not_in_session)
try:
from omni.kit.widget.live_session_management.utils import reload_outdated_layers
reload_outdated_layers(all_outdated_layers, usd_context)
except ImportError:
# If live session management is not enabled. Skipps UI prompt to reload it directly.
layers.LayerUtils.reload_all_layers(all_outdated_layers)
@auto_reload_prims.setter
def auto_reload_prims(self, enabled):
if self._stage_settings.auto_reload_prims != enabled:
self._stage_settings.auto_reload_prims = enabled
if enabled:
self._on_reload_prims()
@staticmethod
def _set_widget_visible(widget: ui.Widget, visible):
"""Utility for using in lambdas"""
widget.visible = visible
def _get_geom_primvar(self, prim, primvar_name):
primvars_api = UsdGeom.PrimvarsAPI(prim)
return primvars_api.GetPrimvar(primvar_name)
def _filter_by_flattener_basemesh(self, enabled):
self._filter_by_lambda({"_is_prim_basemesh": lambda prim: self._get_geom_primvar(prim, "materialFlattening_isBaseMesh")}, enabled)
def _filter_by_flattener_decal(self, enabled):
self._filter_by_lambda({"_is_prim_decal": lambda prim: self._get_geom_primvar(prim, "materialFlattening_isDecal")}, enabled)
def _filter_by_visibility(self, enabled):
"""Filter Hidden On/Off"""
def _is_prim_hidden(prim):
imageable = UsdGeom.Imageable(prim)
return imageable.ComputeVisibility() == UsdGeom.Tokens.invisible
self._filter_by_lambda({"_is_prim_hidden": _is_prim_hidden}, enabled)
def _filter_by_type(self, usd_types, enabled):
"""
Set filtering by USD type.
Args:
usd_types: The type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
if not isinstance(usd_types, list):
usd_types = [usd_types]
for usd_type in usd_types:
# Create a lambda filter
fn = lambda p, t=usd_type: p.IsA(t)
name_to_fn_dict = {Tf.Type(usd_type).typeName: fn}
self._filter_by_lambda(name_to_fn_dict, enabled)
def _filter_by_api_type(self, api_types, enabled):
"""
Set filtering by USD api type.
Args:
api_types: The api type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
if not isinstance(api_types, list):
api_types = [api_types]
for api_type in api_types:
# Create a lambda filter
fn = lambda p, t=api_type: p.HasAPI(t)
name_to_fn_dict = {Tf.Type(api_type).typeName: fn}
self._filter_by_lambda(name_to_fn_dict, enabled)
def _filter_by_lambda(self, filters: dict, enabled):
"""
Set filtering by lambda.
Args:
filters: The dictionary of this form: {"type_name_string", lambda prim: True}. When lambda is True,
the prim will be shown.
enabled: True to add to filters, False to remove them from the filter list.
"""
if self._tree_view.visible:
tree_view = self._tree_view
else:
tree_view = self._tree_view_flat
if enabled:
tree_view.model.filter(add=filters)
# Filtering mode always expanded.
tree_view.keep_alive = True
tree_view.keep_expanded = True
self._delegate.set_highlighting(enable=True)
if self._selection:
self._selection.enable_filtering_checking(True)
else:
for lambda_name in filters:
keep_filtering = tree_view.model.filter(remove=lambda_name)
if not keep_filtering:
# Filtering is finished. Return it back to normal.
tree_view.keep_alive = False
tree_view.keep_expanded = False
self._delegate.set_highlighting(enable=False)
if self._selection:
self._selection.enable_filtering_checking(False)
def _filter_by_text(self, filter_text: str):
"""Set the search filter string to the models and widgets"""
tree_view = self._tree_view_flat if self._stage_settings.flat_search else self._tree_view
if self._selection:
self._selection.set_filtering(filter_text)
# It's only set when the visibility is changed. We need it to move the filtering data from the flat model to
# the tree model.
was_visible_before = None
is_visible_now = None
if filter_text and self._stage_settings.flat_search:
# Check if _tree_view_flat is just became visible
self._model.flat = True
if self._tree_view.visible:
was_visible_before = self._tree_view
is_visible_now = self._tree_view_flat
self._tree_view.visible = False
self._tree_view_flat.visible = True
else:
# Check if _tree_view is just became visible
self._model.flat = False
if self._tree_view_flat.visible:
was_visible_before = self._tree_view_flat
is_visible_now = self._tree_view
self._tree_view_flat.visible = False
self._tree_view.visible = True
tree_view.keep_alive = not not filter_text
tree_view.keep_expanded = not not filter_text
tree_view.model.filter_by_text(filter_text)
if was_visible_before and is_visible_now:
# Replace treeview in the selection model will allow to use only one selection watch for two treeviews
if self._selection:
self._selection.set_tree_view(is_visible_now)
self._delegate.set_highlighting(text=filter_text)
def _on_column_changed(self, column_model: ColumnMenuModel, item: ColumnMenuItem = None):
"""Called by Column Model when columns are changed or toggled"""
all_columns = column_model.get_columns()
column_delegate_names = [i[0] for i in all_columns if i[1]]
# Name column should always be shown
if "Name" not in column_delegate_names:
column_delegate_names.append("Name")
column_delegate_types = [
StageColumnDelegateRegistry().get_column_delegate(name) for name in column_delegate_names
]
# Create the column delegates
column_delegates = [delegate_type() for delegate_type in column_delegate_types if delegate_type]
column_delegates.sort(key=lambda item: item.order)
# Set the model
self._delegate.set_column_delegates(column_delegates)
if self._model:
self._model.set_item_value_model_count(len(column_delegates))
# Set the column widths
self._column_widths = [d.initial_width for d in column_delegates]
self._min_column_widths = [d.minimum_width for d in column_delegates]
self.set_columns_widths()
# Callback if someone subscribed to the StageWidget events
self._column_changed_event(all_columns)
def _on_column_selection_changed(self, selection):
self._column_list.selection = []
def set_columns_widths(self):
for w in [self._tree_view, self._tree_view_flat]:
if not w:
continue
w.column_widths = self._column_widths
w.min_column_widths = self._min_column_widths
w.dirty_widgets()
def subscribe_columns_changed(self, fn: Callable[[List[Tuple[str, bool]]], None]) -> EventSubscription:
return EventSubscription(self._column_changed_event, fn)
def _cancel_expand_task(self):
if self._expand_task and not self._expand_task.done():
self._expand_task.cancel()
self._expand_task = None
def open_stage(self, stage: Usd.Stage):
"""Called when opening a new stage"""
if self._model:
self._clear_filter_types()
self._model.destroy()
# Sometimes we need to switch between regular tree and flat list. To do it fast we keep both models.
self._model = StageModel(
stage, load_payloads=self._lazy_payloads,
children_reorder_supported=self._stage_settings.children_reorder_supported,
show_prim_displayname=self._stage_settings.show_prim_displayname
)
# Don't regenerate delegate as it's constructed already and treeview references to it.
self._delegate.model = self._model
self._on_column_changed(self._column_model)
# Widgets are not created if `_on_attach` is called from the constructor.
if self._tree_view:
self._tree_view.model = self._model
if self._tree_view_flat:
self._tree_view_flat.model = self._model
async def expand(tree_view, path_str: str):
await omni.kit.app.get_app().next_update_async()
# It's possible that weakly referenced tree view is not existed anymore.
if not tree_view:
return
chain_to_world = tree_view.model.find_full_chain(path_str)
if chain_to_world:
for item in chain_to_world:
tree_view.set_expanded(item, True, False)
self._expand_task = None
# Expand default or the only prim or World
if self._tree_view and stage:
default: Usd.Prim = stage.GetDefaultPrim()
if default:
# We have default prim
path_str = default.GetPath().pathString
else:
root: Usd.Prim = stage.GetPseudoRoot()
children: List[Usd.Prim] = root.GetChildren()
if children and len(children) == 1:
# Root has the only child
path_str = children[0].GetPath().pathString
else:
# OK, try to open /World
path_str = "/World"
self._cancel_expand_task()
self._expand_task = asyncio.ensure_future(expand(weakref.proxy(self._tree_view), path_str))
def update_icons(self):
"""Called to update icons in the TreeView"""
self._tree_view.dirty_widgets()
self._tree_view_flat.dirty_widgets()
def get_context_menu(self):
return self._delegate._context_menu
| 26,733 | Python | 38.430678 | 154 | 0.588299 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_item.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageItem"]
import carb
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.usd
from .models import PrimNameModel, TypeModel, VisibilityModel
from pxr import Sdf, UsdGeom, Usd
from typing import List
class StageItem(ui.AbstractItem):
"""
A single AbstractItemModel item that represents a single prim.
StageItem is a cached view of the prim.
"""
def __init__(
self,
path: Sdf.Path,
stage,
stage_model,
# Deprecated
flat=False,
root_identifier=None,
load_payloads=False,
check_missing_references=False,
):
super().__init__()
self.__stage_model = stage_model
# Internal access
self._path = path
# Prim handle
self.__prim = None
# Filtering
self.filtered = None
# True if it has any descendant that is filtered
self.child_filtered = None
# defaultPrim
self.__is_default = False
# True if it has missing references
self.__missing_references = None
# True if it has references authored
self.__has_references = False
# All references/payloads for this prim
self.__payrefs = set()
# If this prim includes references/payloads that are out of sync.
self.__is_outdated = False
# True if it has payloads authored
self.__has_payloads = False
# True if it's visible
self.__visible = True
# True if is in session
self.__in_session = False
# True if it's instanceable
self.__instanceable = False
# True if this item should be auto-loaded when its
# references or payloads are outdated.
self.__auto_reload = False
# True if it's children of instance.
self.__instance_proxy = False
self.__display_name = None
# Lazy load
self.__flags_updated = True
# Models for builtin columns. Those models
# will only be accessed internally.
self.__name_model = None
self.__type_model = None
self.__visibility_model = None
def destroy(self):
self.__stage = None
self.__stage_model = None
self.__payrefs.clear()
@property
def path(self):
"""Prim path."""
return self._path
@property
def stage_model(self):
"""StageModel this StageItem belongs to."""
return self.__stage_model
@property
def usd_context(self) -> omni.usd.UsdContext:
return self.__stage_model.usd_context if self.__stage_model else None
@property
def stage(self) -> Usd.Stage:
"""USD stage the prim belongs to."""
return self.__stage_model.stage if self.__stage_model else None
@property
def payrefs(self) -> List[str]:
"""All external references and payloads that influence this prim."""
self.__update_flags_internal()
return list(self.__payrefs)
@property
def is_default(self) -> bool:
"""Whether this prim is the default prim or not."""
self.__update_flags_internal()
return self.__is_default
@property
def is_outdated(self) -> bool:
"""Whether this prim includes references or payloads that has new changes to fetch or not."""
self.__update_flags_internal()
return self.__is_outdated
@property
def in_session(self) -> bool:
"""Whether this prim includes references or payloads that are in session or not."""
self.__update_flags_internal()
return self.__in_session
@property
def auto_reload(self):
"""Whether this prim is configured as auto-reload when its references or payloads are outdated."""
self.__update_flags_internal()
return self.__auto_reload
@property
def root_identifier(self) -> str:
"""Returns the root layer's identifier of the stage this prim belongs to."""
stage = self.stage
return stage.GetRootLayer().identifier if stage else None
@property
def instance_proxy(self) -> bool:
"""Whether the prim is an instance proxy or not."""
self.__update_flags_internal()
return self.__instance_proxy
@property
def instanceable(self) -> bool:
"""True when it has `instanceable` flag enabled"""
self.__update_flags_internal()
return self.__instanceable
@property
def visible(self) -> bool:
self.__update_flags_internal()
return self.__visible
@property
def payloads(self):
"""True when the prim has authored payloads"""
self.__update_flags_internal()
return self.__has_payloads
@property
def references(self) -> bool:
"""True when the prim has authored references"""
self.__update_flags_internal()
return self.__has_references
@property
def name(self) -> str:
"""The path name."""
return self._path.name
@property
def display_name(self) -> str:
"""The display name of prim inside the metadata."""
self.__update_flags_internal()
return self.__display_name or self.name
@property
def prim(self):
"""The prim handle."""
self.__update_flags_internal()
return self.__prim
@property
def active(self):
"""True if the prim is active."""
self.__update_flags_internal()
if not self.__prim:
return False
return self.__prim.IsActive()
@property
def type_name(self):
"""Type name of the prim."""
self.__update_flags_internal()
prim = self.__prim
if not prim:
return ""
return prim.GetTypeName()
@property
def has_missing_references(self):
"""
Whether the prim includes any missing references or payloads or not.
It checkes the references/payloads recursively.
"""
self.__update_flags_internal()
return self.__missing_references
@property
def children(self):
"""Returns children items. If children are not populated yet, they will be populated."""
return self.__stage_model.get_item_children(self)
def update_flags(self, prim=None):
"""Refreshes item states from USD."""
# Lazy load.
self.__flags_updated = True
def __update_prim(self):
stage = self.stage
self.__prim = stage.GetPrimAtPath(self._path) if stage else None
def __update_visibility(self):
prim = self.prim
if prim and prim.IsA(UsdGeom.Imageable):
visibility = UsdGeom.Imageable(prim).ComputeVisibility()
self.__visible = visibility != UsdGeom.Tokens.invisible
else:
self.__visible = False
def __get_payrefs(self):
if not self.__has_references and not self.__has_payloads:
return set()
result = set()
references = omni.usd.get_composed_references_from_prim(self.__prim)
payloads = omni.usd.get_composed_payloads_from_prim(self.__prim)
for reference, layer in payloads + references:
if not reference.assetPath:
continue
absolute_path = layer.ComputeAbsolutePath(reference.assetPath)
result.add(absolute_path)
return result
def __get_live_status(self):
if not self.__stage_model.usd_context:
return
if self.__payrefs:
live_syncing = layers.get_live_syncing(self.__stage_model.usd_context)
for absolute_path in self.__payrefs:
if live_syncing.is_prim_in_live_session(self.prim.GetPath(), absolute_path):
return True
return False
def __get_outdated_status(self):
if not self.__stage_model.usd_context:
return
if self.__payrefs:
layers_state_interface = layers.get_layers_state(self.__stage_model.usd_context)
for absolute_path in self.__payrefs:
if layers_state_interface.is_layer_outdated(absolute_path):
return True
return False
def __get_auto_reload_status(self):
if not self.__stage_model.usd_context:
return
if carb.settings.get_settings().get_as_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS):
if not self.is_outdated:
return True
if self.__payrefs:
layers_state_interface = layers.get_layers_state(self.__stage_model.usd_context)
for absolute_path in self.__payrefs:
if layers_state_interface.is_auto_reload_layer(absolute_path):
return True
return False
def __has_missing_payrefs(self):
prim = self.prim
# If prim is not loaded.
if prim and not prim.IsLoaded():
return False
for identifier in self.payrefs:
layer = Sdf.Find(identifier)
if not layer:
return True
return False
def __update_flags_internal(self):
# Param is for back compitability.
if not self.__flags_updated:
return
self.__flags_updated = False
self.__update_prim()
prim = self.prim
if not prim:
return
self.__is_default = prim == self.stage.GetDefaultPrim()
self.__display_name = omni.usd.editor.get_display_name(prim) or ""
# Refresh model to decide which name to display.
if self.__name_model:
self.__name_model.rebuild()
self.__update_visibility()
self.__has_references = prim.HasAuthoredReferences()
self.__has_payloads = prim.HasAuthoredPayloads()
self.__payrefs = self.__get_payrefs()
self.__instanceable = prim.IsInstanceable()
self.__instance_proxy = prim.IsInstanceProxy()
self.__missing_references = self.__has_missing_payrefs()
self.__is_outdated = self.__get_outdated_status()
self.__in_session = self.__get_live_status()
self.__auto_reload = self.__get_auto_reload_status()
def __repr__(self):
return f"<Omni::UI Stage Item '{self._path}'>"
def __str__(self):
return f"{self._path}"
# Internal properties
@property
def name_model(self):
self.__update_flags_internal()
if not self.__name_model:
self.__name_model = PrimNameModel(self)
return self.__name_model
@property
def type_model(self):
self.__update_flags_internal()
if not self.__type_model:
self.__type_model = TypeModel(self)
return self.__type_model
@property
def visibility_model(self):
self.__update_flags_internal()
if not self.__visibility_model:
self.__visibility_model = VisibilityModel(self)
return self.__visibility_model
@property
def is_flat(self):
return self.__stage_model.flat if self.__stage_model else False
@is_flat.setter
def is_flat(self, flat: bool):
# Rebuild it only when it's populated
if self.__name_model:
self.__name_model.rebuild()
@property
def load_payloads(self):
return self.stage_model.load_payloads if self.stage_model else None
# Deprecated functions
@property
def check_missing_references(self):
"""Deprecated: It will always check missing references now."""
return True
@check_missing_references.setter
def check_missing_references(self, value):
"""Deprecated."""
pass
def set_default_prim(self, is_default):
"""Deprecated."""
pass
| 12,211 | Python | 26.198218 | 106 | 0.598641 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/export_utils.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["export", "Export"]
import os
from pathlib import Path
from typing import List
from functools import partial
from pxr import Sdf, Gf, Usd, UsdGeom, UsdUI
from omni.kit.window.file_exporter import get_file_exporter
from omni.kit.helper.file_utils import FileEventModel, FILE_SAVED_EVENT
import carb
import carb.tokens
import omni.kit.app
import omni.client
import omni.usd
last_dir = None
# OM-48055: Add subscription to stage open to update default save directory
_default_save_dir = None
def __on_stage_open(event: carb.events.IEvent):
"""Update default save directory on stage open."""
if event.type == int(omni.usd.StageEventType.OPENED):
stage = omni.usd.get_context().get_stage()
global _default_save_dir
_default_save_dir = os.path.dirname(stage.GetRootLayer().realPath)
def _get_stage_open_sub():
stage_open_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(__on_stage_open,
name="Export Selected Prim Stage Open")
return stage_open_sub
def __set_xform_prim_transform(prim: UsdGeom.Xformable, transform: Gf.Matrix4d):
prim = UsdGeom.Xformable(prim)
_, _, scale, rot_mat, translation, _ = transform.Factor()
angles = rot_mat.ExtractRotation().Decompose(Gf.Vec3d.ZAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis())
rotation = Gf.Vec3f(angles[2], angles[1], angles[0])
for xform_op in prim.GetOrderedXformOps():
attr = xform_op.GetAttr()
prim.GetPrim().RemoveProperty(attr.GetName())
prim.ClearXformOpOrder()
UsdGeom.XformCommonAPI(prim).SetTranslate(translation)
UsdGeom.XformCommonAPI(prim).SetRotate(rotation)
UsdGeom.XformCommonAPI(prim).SetScale(Gf.Vec3f(scale[0], scale[1], scale[2]))
def export(path: str, prims: List[Usd.Prim]):
"""Export prim to external USD file"""
filename = Path(path).stem
# TODO: stage.Flatten() is extreamly slow
stage = omni.usd.get_context().get_stage()
source_layer = stage.Flatten()
target_layer = Sdf.Layer.CreateNew(path)
target_stage = Usd.Stage.Open(target_layer)
axis = UsdGeom.GetStageUpAxis(stage)
UsdGeom.SetStageUpAxis(target_stage, axis)
# All prims will be put under /Root
root_path = Sdf.Path.absoluteRootPath.AppendChild("Root")
UsdGeom.Xform.Define(target_stage, root_path)
keep_transforms = len(prims) > 1
center_point = Gf.Vec3d(0.0)
transforms = []
if keep_transforms:
bound_box = Gf.BBox3d()
bbox_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
for prim in prims:
xformable = UsdGeom.Xformable(prim)
if xformable:
local_bound_box = bbox_cache.ComputeWorldBound(prim)
transforms.append(xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default()))
bound_box = Gf.BBox3d.Combine(bound_box, local_bound_box)
else:
transforms.append(None)
center_point = bound_box.ComputeCentroid()
else:
transforms.append(Gf.Matrix4d(1.0))
for i in range(len(transforms)):
if transforms[i]:
transforms[i] = transforms[i].SetTranslateOnly(transforms[i].ExtractTranslation() - center_point)
# Set default prim name
target_layer.defaultPrim = root_path.name
for i in range(len(prims)):
source_path = prims[i].GetPath()
if len(prims) > 1 and transforms[i]:
target_xform_path = root_path.AppendChild(source_path.name)
target_xform_path = Sdf.Path(omni.usd.get_stage_next_free_path(target_stage, target_xform_path, False))
target_xform = UsdGeom.Xform.Define(target_stage, target_xform_path)
__set_xform_prim_transform(target_xform, transforms[i])
target_path = target_xform_path.AppendChild(source_path.name)
else:
target_path = root_path.AppendChild(source_path.name)
target_path = Sdf.Path(omni.usd.get_stage_next_free_path(target_stage, target_path, False))
all_external_references = set([])
def on_prim_spec_path(root_path, prim_spec_path):
if prim_spec_path.IsPropertyPath():
return
if prim_spec_path == Sdf.Path.absoluteRootPath:
return
prim_spec = source_layer.GetPrimAtPath(prim_spec_path)
if not prim_spec or not prim_spec.HasInfo(Sdf.PrimSpec.ReferencesKey):
return
op = prim_spec.GetInfo(Sdf.PrimSpec.ReferencesKey)
items = []
items = op.ApplyOperations(items)
for item in items:
if not item.primPath.HasPrefix(root_path):
all_external_references.add(item.primPath)
# Traverse the source prim tree to find all references that are outside of the source tree.
source_layer.Traverse(source_path, partial(on_prim_spec_path, source_path))
# Copy dependencies
for path in all_external_references:
Sdf.CreatePrimInLayer(target_layer, path)
Sdf.CopySpec(source_layer, path, target_layer, path)
Sdf.CreatePrimInLayer(target_layer, target_path)
Sdf.CopySpec(source_layer, source_path, target_layer, target_path)
prim = target_stage.GetPrimAtPath(target_path)
if transforms[i]:
__set_xform_prim_transform(prim, Gf.Matrix4d(1.0))
# Edit UI info of compound
spec = target_layer.GetPrimAtPath(target_path)
attributes = spec.attributes
if UsdUI.Tokens.uiDisplayGroup not in attributes:
attr = Sdf.AttributeSpec(spec, UsdUI.Tokens.uiDisplayGroup, Sdf.ValueTypeNames.Token)
attr.default = "Material Graphs"
if UsdUI.Tokens.uiDisplayName not in attributes:
attr = Sdf.AttributeSpec(spec, UsdUI.Tokens.uiDisplayName, Sdf.ValueTypeNames.Token)
attr.default = target_path.name
if "ui:order" not in attributes:
attr = Sdf.AttributeSpec(spec, "ui:order", Sdf.ValueTypeNames.Int)
attr.default = 1024
# Save
target_layer.Save()
# OM-61553: Add exported USD file to recent files
# since the layer save will not trigger stage save event, it can't be caught automatically
# by omni.kit.menu.file.scripts stage event sub, thus we have to manually put it in the
# carb settings to trigger the update
_add_to_recent_files(path)
def _add_to_recent_files(filename: str):
"""Utility to add the filename to recent file list."""
if not filename:
return
# OM-87021: The "recentFiles" setting is deprecated. However, the welcome extension still
# reads from it so we leave this code here for the time being.
import carb.settings
recent_files = carb.settings.get_settings().get("/persistent/app/file/recentFiles") or []
recent_files.insert(0, filename)
carb.settings.get_settings().set("/persistent/app/file/recentFiles", recent_files)
# Emit a file saved event to the event stream
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(FILE_SAVED_EVENT, payload=FileEventModel(url=filename).dict())
class ExportPrimUSDLegacy:
"""
It's still used in Material Graph
"""
EXPORT_USD_EXTS = ("usd", "usda", "usdc")
def __init__(self, select_msg="Save As", save_msg="Save", save_dir=None, postfix_name=None):
self._prim = None
self._dialog = None
self._select_msg = select_msg
self._save_msg = save_msg
self._save_dir = save_dir
self._postfix_name = postfix_name
self._last_dir = None
def destroy(self):
self._prim = None
if self._dialog:
self._dialog.destroy()
self._dialog = None
def export(self, prim):
self.destroy()
if isinstance(prim, list):
self._prim = prim
else:
self._prim = [prim]
write_dir = self._save_dir
if not write_dir:
write_dir = last_dir if last_dir else ""
try:
from omni.kit.window.filepicker import FilePickerDialog
usd_filter_descriptions = [f"{ext.upper()} (*.{ext})" for ext in self.EXPORT_USD_EXTS]
usd_filter_descriptions.append("All Files (*)")
self._dialog = FilePickerDialog(
self._select_msg,
apply_button_label=self._save_msg,
current_directory=write_dir,
click_apply_handler=self.__on_apply_save,
item_filter_options=usd_filter_descriptions,
item_filter_fn=self.__on_filter_item,
)
except:
carb.log_info(f"Failed to import omni.kit.window.filepicker")
def __on_filter_item(self, item: "FileBrowserItem") -> bool:
if not item or item.is_folder:
return True
if self._dialog.current_filter_option < len(self.EXPORT_USD_EXTS):
# Show only files with listed extensions
return item.path.endswith("." + self.EXPORT_USD_EXTS[self._dialog.current_filter_option])
else:
# Show All Files (*)
return True
def __on_apply_save(self, filename: str, dir: str):
"""Called when the user presses the Save button in the dialog"""
# Get the file extension from the filter
if not filename.lower().endswith(self.EXPORT_USD_EXTS):
if self._dialog.current_filter_option < len(self.EXPORT_USD_EXTS):
filename += "." + self.EXPORT_USD_EXTS[self._dialog.current_filter_option]
# Add postfix name
if self._postfix_name:
filename = filename.replace(".usd", f".{self._postfix_name}.usd")
# TODO: Nucleus
path = omni.client.combine_urls(dir + "/", filename)
self._dialog.hide()
export(f"{path}", self._prim)
self._prim = None
global last_dir
last_dir = dir
class ExportPrimUSD:
def __init__(self, select_msg="Save As", save_msg="Save", save_dir=None, postfix_name=None):
self._select_msg = select_msg
if save_msg != "Save" or save_dir or postfix_name:
self._legacy = ExportPrimUSDLegacy(select_msg, save_msg, save_dir, postfix_name)
else:
self._legacy = None
def destroy(self):
if self._legacy:
self._legacy.destroy()
def export(self, prims: List[Usd.Prim]):
if self._legacy:
return self._legacy.export(prims)
file_exporter = get_file_exporter()
if file_exporter:
# OM-48055: Use the current stage directory as default save directory if export selected happened for the
# first time after opened the current stage; Otherwise use the last saved directory that user specifed.
global _default_save_dir
filename = prims[0].GetName() if prims else ""
dirname = _default_save_dir if _default_save_dir else ""
filename_url = ""
if dirname:
filename_url = dirname.rstrip('/') + '/'
if filename:
filename_url += filename
file_exporter.show_window(
title=self._select_msg,
export_button_label="Save Selected",
export_handler=partial(self.__on_apply_save, prims),
# OM-61553: Add default filename for export using the selected prim name
filename_url=filename_url or None,
)
def __on_apply_save(
self, prims: List[Usd.Prim], filename: str, dirname: str, extension: str, selections: List[str] = []
):
"""Called when the user presses the Save button in the dialog"""
if prims:
path = omni.client.combine_urls(dirname, f"{filename}{extension}")
export(path, prims)
# update default save dir after successful export
global _default_save_dir
_default_save_dir = dirname
| 12,466 | Python | 37.597523 | 117 | 0.634285 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_drag_and_drop_handler.py | __all__ = ["StageDragAndDropHandler", "AssetType"]
import carb
import re
import omni.kit.commands
import omni.kit.notification_manager as nm
from .stage_item import StageItem
from .stage_settings import StageSettings
from .utils import handle_exception
from pxr import Sdf, Tf, UsdGeom
from pathlib import Path
from omni.kit.async_engine import run_coroutine
KEEP_TRANSFORM_FOR_REPARENTING = "/persistent/app/stage/movePrimInPlace"
STAGE_DRAGDROP_IMPORT = "/persistent/app/stage/dragDropImport"
class AssetType:
"""A singleton that determines the type of asset using regex"""
def __init__(self):
self._re_mdl = re.compile(r"^.*\.mdl(\?.*)?(@.*)?$", re.IGNORECASE)
self._re_audio = re.compile(r"^.*\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\?.*)?$", re.IGNORECASE)
self._re_material_in_mdl = re.compile(r"export\s+material\s+([^\s]+)\s*\(")
self._read_material_tasks_or_futures = []
def destroy(self):
for task in self._read_material_tasks_or_futures:
if not task.done():
task.cancel()
self._read_material_tasks_or_futures.clear()
def is_usd(self, asset):
return omni.usd.is_usd_readable_filetype(asset)
def is_mdl(self, asset):
return self._re_mdl.match(asset)
def is_audio(self, asset):
return self._re_audio.match(asset)
def add_future(self, obj):
"""Add a future-like object to the global list, so it's not destroyed"""
# Destroy the objects that are done or canceled
self._read_material_tasks_or_futures = [
task_or_future for task_or_future in self._read_material_tasks_or_futures if not task_or_future.done() and not task_or_future.cancelled()
]
self._read_material_tasks_or_futures.append(run_coroutine(obj))
async def get_first_material_name(self, mdl_file):
"""Parse the MDL asset and return the name of the first shader"""
subid_list = await omni.kit.material.library.get_subidentifier_from_mdl(mdl_file, show_alert=True)
if subid_list:
return str(subid_list[0])
return None
class StageDragAndDropHandler:
def __init__(self, stage_model):
self.__stage_model = stage_model
self.__asset_type = AssetType()
self.__reordering_prim = False
self.__children_reorder_supported = False
@property
def children_reorder_supported(self):
return self.__children_reorder_supported
@children_reorder_supported.setter
def children_reorder_supported(self, enabled):
self.__children_reorder_supported = enabled
@property
def is_reordering_prim(self):
return self.__reordering_prim
@handle_exception
async def __apply_mdl(self, mdl_name, target_path):
"""Import and apply MDL asset to the specified prim"""
if mdl_name.startswith("material::"):
mdl_name = mdl_name[10:]
mtl_name = None
encoded_subid = False
# does the mdl name have the sub identifier encoded in it?
if "@" in mdl_name:
split = mdl_name.rfind("@")
if split > 0 and mdl_name[split+1:].isidentifier():
mtl_name = mdl_name[split+1:]
mdl_name = mdl_name[:split]
encoded_subid = True
if not mtl_name:
mtl_name = await self.__asset_type.get_first_material_name(mdl_name)
if not mtl_name:
carb.log_warn(f"[Stage Widget] the MDL Asset '{mdl_name}' doesn't have any material")
return
try:
import omni.usd
import omni.kit.material.library
stage = self.__stage_model.stage
subids = await omni.kit.material.library.get_subidentifier_from_mdl(mdl_name)
if not encoded_subid and len(subids) > 1:
# empty drops have target_path as /World - Fix
root_path = Sdf.Path.absoluteRootPath.pathString
if stage.HasDefaultPrim():
root_path = stage.GetDefaultPrim().GetPath().pathString
omni.kit.material.library.custom_material_dialog(
mdl_path=mdl_name, bind_prim_paths=[target_path] if target_path != root_path else None
)
return
except Exception as exc:
carb.log_error(f"error {exc}")
import traceback, sys
traceback.print_exc(file=sys.stdout)
except Exception:
carb.log_warn(f"Failed to use omni.kit.material.library custom_material_dialog")
# Create material with one sub-id
with omni.kit.undo.group():
# Create material. Despite the name, it only can bind to selection.
mtl_created_list = []
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name=mdl_name,
mtl_name=mtl_name,
mtl_created_list=mtl_created_list,
select_new_prim=False,
)
# Bind created material to the target prim
# Special case: don't bind it to /World and to /World/Looks
if target_path and target_path not in ["/World", "/World/Looks"]:
omni.kit.commands.execute(
"BindMaterial", prim_path=target_path, material_path=mtl_created_list[0], strength=None
)
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
# Don't support drag and drop if the stage is not attached to any usd context.
stage_model = self.__stage_model
if not stage_model.usd_context:
return False
if source == target_item:
return False
# Skips it if reordering prims are not supported.
if not self.__children_reorder_supported and drop_location != -1:
return False
if isinstance(source, StageItem):
# Drag and drop from inside the StageView
if not target_item:
target_item = stage_model.root
if source.stage and source.stage == target_item.stage:
# It cannot move from parent into child.
# It stops if target_item already includes the source item.
target_parent = target_item.path.GetParentPath() or target_item.path
source_parent = source.path.GetParentPath() or source.path
if (
target_item.path.HasPrefix(source.path) or
(source in target_item.children and drop_location == -1) or
(target_parent != source_parent and drop_location != -1)
):
return False
else:
return True
else:
return not Sdf.Layer.IsAnonymousLayerIdentifier(source.root_identifier)
if isinstance(source, str):
# Drag and drop from the content browser
return True
try:
from omni.kit.widget.filebrowser import FileSystemItem
from omni.kit.widget.filebrowser import NucleusItem
if isinstance(source, FileSystemItem) or isinstance(source, NucleusItem):
# Drag and drop from the TreeView of Content Browser
return True
except Exception:
pass
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(source, CheckpointItem):
return True
except Exception:
pass
return False
def __drop_location_to_prim_index(self, prim_path, drop_location, new_item=False):
"""
Gets the real prim index inside the children list of parent as drop location
only shows the UI location while some of the children are possibly
hidden in the stage window.
"""
parent = prim_path.GetParentPath() or Sdf.Path.absoluteRootPath
parent_item = self.__stage_model.find(parent)
total_children = len(parent_item.children)
# For new item, it needs to exclude current new item as the drop location is
# got before this item is created.
if new_item:
total_children -= 1
if drop_location >= total_children:
drop_item_name = parent_item.children[-1].path.name
else:
drop_item_name = parent_item.children[drop_location].path.name
parent_prim = parent_item.prim
children_names = parent_prim.GetAllChildrenNames()
if drop_item_name not in children_names:
return None
index = children_names.index(drop_item_name)
if drop_location >= total_children:
index += 1
return index
def __reorder_prim_to_drop_location(self, prim_path, drop_location, new_item):
if not self.__children_reorder_supported:
return
stage_model = self.__stage_model
stage = stage_model.stage
if prim_path and stage.GetPrimAtPath(prim_path) and drop_location != -1:
index = self.__drop_location_to_prim_index(prim_path, drop_location, new_item)
if index is None:
carb.log_error(f"Failed to re-order prim {prim_path} as it cannot be found in its parent.")
return
try:
self.__reordering_prim = True
success, _ = omni.kit.commands.execute(
"ReorderPrim", stage=stage, prim_path=prim_path, move_to_location=index
)
finally:
self.__reordering_prim = False
if success:
parent_item = stage_model.find(prim_path.GetParentPath())
if parent_item == stage_model.root:
parent_item = None
stage_model._item_changed(parent_item)
def drop(self, target_item, source, drop_location=-1):
"""
Reimplemented from AbstractItemModel. Called when dropping something to the item.
When drop_location is -1, it means to drop the source item on top of the target item.
When drop_location is not -1, it means to drop the source item between items.
"""
stage_model = self.__stage_model
stage = stage_model.stage
if not stage_model.root or not stage:
return
if isinstance(source, str) and source.startswith("env::"):
# Drop from environment window
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action("omni.kit.window.environment", "drop")
if action:
action.execute(source)
return
if isinstance(source, str) and source.startswith("SimReady::"):
# Drop from SimReady explorer
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action("omni.simready.explorer", "add_asset_from_drag")
if action:
if isinstance(target_item, StageItem):
if not target_item:
target_item = stage_model.root
path_to = target_item.path
else:
path_to = None
action.execute(source, path_to=path_to)
return
# Check type without importing if we have NucleusItem or FileSystemItem, we imported them in drop_accepted.
if type(source).__name__ in ["NucleusItem", "FileSystemItem"]:
# Drag and drop from the TreeView of Content Browser
source = source._path
# Check type without importing if we have CheckpointItem, we imported them in drop_accepted.
if type(source).__name__ == "CheckpointItem":
# Drag and drop from the TreeView of Content Browser
source = source.get_full_url()
with omni.kit.undo.group():
import_method = carb.settings.get_settings().get(STAGE_DRAGDROP_IMPORT) or "payload"
new_prim_path = None
new_item_added = False
if isinstance(source, StageItem):
if not target_item:
target_item = stage_model.root
if source.root_identifier == target_item.root_identifier:
# Drop the source item as a child item of target.
if drop_location == -1:
new_path = target_item.path.AppendChild(source.path.name)
settings = carb.settings.get_settings()
keep_transform = settings.get(KEEP_TRANSFORM_FOR_REPARENTING)
if keep_transform is None:
keep_transform = True
omni.kit.commands.execute(
"MovePrim",
path_from=str(source.path),
path_to=str(new_path),
keep_world_transform=keep_transform,
destructive=False
)
else:
# It's to drag and drop to re-order the children.
new_prim_path = source.path
else:
# Drag and drop from external stage
new_item_added = True
if import_method.lower() == "reference":
_, new_prim_path = omni.kit.commands.execute(
"CreateReference",
path_to=target_item.path.AppendChild(source.path.name),
asset_path=source.root_identifier,
prim_path=source.path,
usd_context=stage_model.usd_context
)
else:
_, new_prim_path = omni.kit.commands.execute(
"CreatePayload",
path_to=target_item.path.AppendChild(source.path.name),
asset_path=source.root_identifier,
prim_path=source.path,
usd_context=stage_model.usd_context
)
elif isinstance(source, str):
defaultedToDefaultPrim = False
# Don't drop it to default prim when it's to drop with location.
if not target_item and stage.HasDefaultPrim() and drop_location == -1:
default_prim = stage.GetDefaultPrim()
default_prim_path = default_prim.GetPath()
if (
not default_prim.IsA(UsdGeom.Gprim)
and not omni.usd.is_ancestor_prim_type(stage, default_prim_path, UsdGeom.Gprim)
):
target_item = stage_model.find(default_prim_path)
defaultedToDefaultPrim = True
if not target_item:
target_item = stage_model.root
defaultedToDefaultPrim = True
# Drag and drop from the content browser
for source_url in source.splitlines():
if source_url.endswith(".sbsar"):
new_item_added = True
if "AddSbsarReferenceAndBind" in omni.kit.commands.get_commands():
# mimic viewport drag & drop behaviour and not assign material to
# /World if we defaulted to it in the code above
targetPrimPath = target_item.path if not defaultedToDefaultPrim else None
success, sbar_mat_prim = omni.kit.commands.execute(
"AddSbsarReferenceAndBind", sbsar_path=source_url, target_prim_path=targetPrimPath
)
if success and sbar_mat_prim:
omni.usd.get_context().get_selection().set_selected_prim_paths([sbar_mat_prim], True)
new_prim_path = sbar_mat_prim.GetPath()
else:
nm.post_notification(
"To drag&drop sbsar files please enable the omni.kit.property.sbsar extension first.",
status=nm.NotificationStatus.WARNING
)
elif source_url.startswith("flow::"):
# mimic viewport drag & drop behaviour
(name, preset_url) = source_url[len("flow::"):].split("::")
omni.kit.commands.execute(
"FlowCreatePresetsCommand",
preset_name=name,
url=preset_url,
paths=[str(target_item.path)],
layer=-1)
elif omni.usd.is_usd_readable_filetype(source_url):
new_item_added = True
stem = Path(source_url).stem
# It drops as child.
if drop_location == -1:
path = target_item.path.AppendChild(Tf.MakeValidIdentifier(stem))
else:
# It drops between items.
path = target_item.path.GetParentPath()
if not path:
path = Sdf.Path.absoluteRootPath
path = path.AppendChild(Tf.MakeValidIdentifier(stem))
if import_method == "reference":
success, new_prim_path = omni.kit.commands.execute(
"CreateReference", path_to=path, asset_path=source_url, usd_context=stage_model.usd_context
)
else:
success, new_prim_path = omni.kit.commands.execute(
"CreatePayload", path_to=path, asset_path=source_url, usd_context=stage_model.usd_context
)
elif self.__asset_type.is_mdl(source_url):
self.__asset_type.add_future(self.__apply_mdl(source_url, target_item.path))
elif self.__asset_type.is_audio(source_url):
new_item_added = True
stem = Path(source_url).stem
path = target_item.path.AppendChild(Tf.MakeValidIdentifier(stem))
_, new_prim_path = omni.kit.commands.execute(
"CreateAudioPrimFromAssetPath",
path_to=path,
asset_path=source_url,
usd_context=stage_model.usd_context
)
if new_prim_path:
self.__reorder_prim_to_drop_location(new_prim_path, drop_location, new_item_added)
| 19,221 | Python | 43.49537 | 149 | 0.544821 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_settings.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.
#
# Selection Watch implementation has been moved omni.kit.widget.stage.
# Import it here for keeping back compatibility.
__all__ = ["StageSettings"]
class StageSettings:
def __init__(self):
super().__init__()
self.show_prim_displayname = False
self.auto_reload_prims = False
self.children_reorder_supported = False
self.flat_search = True
| 818 | Python | 36.227271 | 76 | 0.738386 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageModel", "StageItemSortPolicy"]
from pxr import Sdf, Tf, Trace, Usd, UsdGeom
from typing import List, Optional, Dict, Callable
from omni.kit.async_engine import run_coroutine
from .event import Event, EventSubscription
from .stage_item import StageItem
from .utils import handle_exception
from .stage_drag_and_drop_handler import StageDragAndDropHandler, AssetType
from enum import Enum
import carb
import carb.dictionary
import carb.settings
import omni.activity.core
import omni.client
import omni.ui as ui
import omni.usd
import omni.kit.usd.layers as layers
EXCLUSION_TYPES_SETTING = "ext/omni.kit.widget.stage/exclusion/types"
def should_prim_be_excluded_from_tree_view(prim, exclusion_types):
if (
not prim or not prim.IsActive()
or prim.GetMetadata("hide_in_stage_window")
or (exclusion_types and prim.GetTypeName() in exclusion_types)
):
return True
return False
class StageItemSortPolicy(Enum):
DEFAULT = 0
NAME_COLUMN_NEW_TO_OLD = 1
NAME_COLUMN_OLD_TO_NEW = 2
NAME_COLUMN_A_TO_Z = 3
NAME_COLUMN_Z_TO_A = 4
TYPE_COLUMN_A_TO_Z = 5
TYPE_COLUMN_Z_TO_A = 6
VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE = 7
VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE = 8
class StageModel(ui.AbstractItemModel):
"""The item model that watches the stage"""
def __init__(self, stage: Usd.Stage, flat=False, load_payloads=False, check_missing_references=False, **kwargs):
"""
StageModel provides the model for TreeView of Stage Widget, which also manages all StageItems.
Args:
stage (Usd.Stage): USD stage handle.
Flat (bool): If it's True, all the StageItems will be children of root node. This option only applies to
filtering mode.
load_payloads (bool): Whether it should load payloads during stage traversal automatically or not.
check_missing_references (bool): Deprecated.
Kwargs:
children_reorder_supported (bool): Whether to enable children reorder for drag and drop or not. False by default.
show_prim_displayname (bool): Whether to show prim's displayName from metadata or path name. False by default.
"""
super().__init__()
self.__flat_search = flat
self.load_payloads = load_payloads
# Stage item cache for quick access
self.__stage_item_cache: Dict[Sdf.Path, StageItem] = {}
self.__stage = stage
if self.__stage:
# Internal access that can be overrided.
self._root = StageItem(Sdf.Path.absoluteRootPath, self.stage, self)
self.__default_prim_name = self.__stage.GetRootLayer().defaultPrim
else:
self.__default_prim_name = None
self._root = None
# Stage watching
if self.__stage:
self.__stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__on_objects_changed, self.__stage)
self.__layer_listener = Tf.Notice.Register(
Sdf.Notice.LayerInfoDidChange, self.__on_layer_info_change, self.__stage.GetRootLayer()
)
else:
self.__stage_listener = None
self.__layer_listener = None
# Delayed paths to be refreshed.
self.__dirty_prim_paths = set()
self.__prim_changed_task_or_future = None
# The string that the shown objects should have.
self.__filter_name_text = None
# The dict of form {"type_name_string", lambda prim: True}. When lambda is True, the prim will be shown.
self.__filters = {}
self.__stage_item_value_model_count = 1
# Exclusion list allows to hide prims of specific types silently
settings = carb.settings.get_settings()
self.__exclusion_types: Optional[List[str]] = settings.get(EXCLUSION_TYPES_SETTING)
self.__setting_sub = omni.kit.app.SettingChangeSubscription(
EXCLUSION_TYPES_SETTING, self.__on_exclusion_types_changed
)
# It's possible that stage is not attached to any context.
if self.__stage:
self.__usd_context = omni.usd.get_context_from_stage(self.__stage)
if self.__usd_context:
layers_interface = layers.get_layers(self.__usd_context)
self.layers_state_interface = layers_interface.get_layers_state()
self.__layers_event_subs = []
for event in [
layers.LayerEventType.OUTDATE_STATE_CHANGED, layers.LayerEventType.AUTO_RELOAD_LAYERS_CHANGED
]:
layers_event_sub = layers_interface.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layer_event, name=f"omni.kit.widget.stage {str(event)}"
)
self.__layers_event_subs.append(layers_event_sub)
else:
self.layers_state_interface = None
self.__layers_event_subs = None
else:
self.__usd_context = None
# Notifies when stage items are destroyed.
self.__on_stage_items_destroyed = Event()
self.__drag_and_drop_handler = StageDragAndDropHandler(self)
self.__drag_and_drop_handler.children_reorder_supported = kwargs.get("children_reorder_supported", False)
# If it's in progress of renaming prim.
self.__renaming_prim = False
self.__show_prim_displayname = kwargs.get("show_prim_displayname", False)
# The sorting strategy to use. Only builtin columns (name, type, and visibility) support to
# change the sorting policy directly through StageModel.
self.__items_builtin_sort_policy = StageItemSortPolicy.DEFAULT
self.__settings_builtin_sort_policy = False
self.__items_sort_func = None
self.__items_sort_reversed = False
def __on_layer_event(self, event):
payload = layers.get_layer_event_payload(event)
if (
payload.event_type != layers.LayerEventType.OUTDATE_STATE_CHANGED and
payload.event_type != layers.LayerEventType.AUTO_RELOAD_LAYERS_CHANGED
):
return
all_stage_items = self._get_all_stage_items_from_cache()
to_refresh_items = [item for item in all_stage_items if item.payrefs]
# Notify all items to refresh its live and outdate status
self.__refresh_stage_items(to_refresh_items, [])
def __clear_stage_item_cache(self):
if self.__stage_item_cache:
all_items = list(self.__stage_item_cache.items())
if all_items:
self.__refresh_stage_items([], destroyed_items=all_items)
for _, item in self.__stage_item_cache.items():
item.destroy()
self.__stage_item_cache = {}
def _cache_stage_item(self, item: StageItem):
if item == self._root:
return
if item.path not in self.__stage_item_cache:
self.__stage_item_cache[item.path] = item
def _get_stage_item_from_cache(self, path: Sdf.Path, create_if_not_existed=False):
"""Gets or creates stage item."""
if path == Sdf.Path.absoluteRootPath:
return self._root
stage_item = self.__stage_item_cache.get(path, None)
if not stage_item and create_if_not_existed:
prim = self.__stage.GetPrimAtPath(path)
if should_prim_be_excluded_from_tree_view(prim, self.__exclusion_types):
return None
stage_item = StageItem(path, self.stage, self)
self._cache_stage_item(stage_item)
return stage_item
def _get_all_stage_items_from_cache(self):
return list(self.__stage_item_cache.values())
@Trace.TraceFunction
def __get_stage_item_children(self, path: Sdf.Path):
"""
Gets all children stage items of path. If those stage items are not
created, they will be created. This optimization is used to implement
lazy loading that only paths that are accessed will create corresponding
stage items.
"""
if path == Sdf.Path.absoluteRootPath:
stage_item = self._root
else:
stage_item = self.__stage_item_cache.get(path, None)
if not stage_item or not stage_item.prim:
return []
prim = stage_item.prim
if self.load_payloads and not prim.IsLoaded():
# Lazy load payloads
prim.Load(Usd.LoadWithoutDescendants)
# This appears to be working fastly after testing with 10k nodes under a single parent.
# It does not need to cache all the prent-children relationship to save memory.
children = []
display_predicate = Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)
children_iterator = prim.GetFilteredChildren(display_predicate)
for child_prim in children_iterator:
child_path = child_prim.GetPath()
child = self._get_stage_item_from_cache(child_path, True)
if child:
children.append(child)
return children
def _remove_stage_item_from_cache(self, prim_path: Sdf.Path):
item = self.__stage_item_cache.pop(prim_path, None)
if item:
item.destroy()
return True
return False
@property
def usd_context(self) -> omni.usd.UsdContext:
return self.__usd_context
@property
def stage(self):
return self.__stage
@property
def root(self):
"""Item that represents the absolute root."""
return self._root
@property
def flat(self):
"""
Whether the model is in flat search mode or not. When it's in flat search mode,
all items will be the children of the root item, and empty children
for other items.
"""
return self.__flat_search and self.__has_filters()
@flat.setter
def flat(self, value):
self.__flat_search = value
for item in self.__stage_item_cache.values():
item.is_flat = value
def find(self, path: Sdf.Path):
"""Return item with the given path if it's populated already."""
path = Sdf.Path(path)
if path == Sdf.Path.absoluteRootPath:
return self._root
return self._get_stage_item_from_cache(path)
@Trace.TraceFunction
def find_full_chain(self, path):
"""Return the list of all the parent nodes and the node representing the given path"""
if not self._root:
return None
if not path:
return None
if isinstance(path, str) and path[-1] == "/":
path = path[:-1]
path = Sdf.Path(path)
if path == Sdf.Path.absoluteRootPath:
return None
result = [self._root]
# Finds the full chain and creates stage item on demand to avoid expanding whole tree.
prefixes = path.GetPrefixes()
for child_path in prefixes:
child_item = self._get_stage_item_from_cache(child_path, True)
if child_item:
result.append(child_item)
else:
break
return result
@Trace.TraceFunction
def update_dirty(self):
"""
Create/remove dirty items that was collected from TfNotice. Can be
called any time to pump changes.
"""
if not self.__dirty_prim_paths:
return
stage_update_activity = "Stage|Update|Stage Widget Model"
omni.activity.core.began(stage_update_activity)
dirty_prim_paths = list(self.__dirty_prim_paths)
self.__dirty_prim_paths = set()
# Updates the common root as refreshing subtree will filter
# all cache items to find the old stage items. So iterating each
# single prim path is not efficient as it needs to traverse
# whole cache each time. Even it's possible that dirty prim paths
# are not close to each other that results more stage traverse,
# the time is still acceptable after testing stage over 100k prims.
common_prefix = dirty_prim_paths[0]
for path in dirty_prim_paths[1:]:
common_prefix = Sdf.Path.GetCommonPrefix(common_prefix, path)
(
info_changed_stage_items,
children_refreshed_items,
destroyed_items
) = self.__refresh_prim_subtree(common_prefix)
self.__refresh_stage_items(
info_changed_stage_items, children_refreshed_items, destroyed_items
)
omni.activity.core.ended(stage_update_activity)
def __refresh_stage_items(
self, info_changed_items, children_refreshed_items=[], destroyed_items=[]
):
"""
`info_changed_items` includes only items that have flags/attributes updated.
`children_refreshed_items` includes only items that have children updated.
`destroyed_items` includes only items that are removed from stage.
"""
if info_changed_items:
for item in info_changed_items:
item.update_flags()
# Refresh whole item for now to maintain back-compatibility
if self._root == item:
self._item_changed(None)
else:
self._item_changed(item)
if children_refreshed_items:
if self.flat:
self._item_changed(None)
else:
for stage_item in children_refreshed_items:
if self._root == stage_item:
self._item_changed(None)
else:
self._item_changed(stage_item)
if destroyed_items:
self.__on_stage_items_destroyed(destroyed_items)
@Trace.TraceFunction
def __refresh_prim_subtree(self, prim_path):
"""
Refresh prim subtree in lazy way. It will only refresh those
stage items that are populated already to not load them beforehand
to improve perf, except the absolute root node.
"""
carb.log_verbose(f"Refresh prim tree rooted from {prim_path}")
old_stage_items = []
refreshed_stage_items = set([])
children_updated_stage_items = set([])
item = self._get_stage_item_from_cache(prim_path)
# This is new item, returning and refreshing it immediately if its parent is existed.
if not item:
if self.__has_filters():
self.__prefilter(prim_path)
parent = self._get_stage_item_from_cache(prim_path.GetParentPath())
if parent:
children_updated_stage_items.add(parent)
return refreshed_stage_items, children_updated_stage_items, []
# If it's to refresh whole stage, it should always refresh absolute root
# as new root prim should always be populated.
if prim_path == Sdf.Path.absoluteRootPath:
children_updated_stage_items.add(self._root)
if self.__has_filters():
# OM-84576: Filtering all as it's possible that new sublayers are inserted.
should_update_items = self.__prefilter(prim_path)
children_updated_stage_items.update(should_update_items)
old_stage_items = list(self.__stage_item_cache.values())
else:
for path, item in self.__stage_item_cache.items():
if path.HasPrefix(prim_path):
old_stage_items.append(item)
# If no cached items, and it's the root prims refresh, it should
# alwasy populate root prims if they are not populated yet.
if not old_stage_items:
children_updated_stage_items.add(self._root)
all_removed_items = []
for stage_item in old_stage_items:
if stage_item.path == Sdf.Path.absoluteRootPath:
continue
prim = self.__stage.GetPrimAtPath(stage_item.path)
if prim and prim.IsActive():
refreshed_stage_items.add(stage_item)
else:
parent = self._get_stage_item_from_cache(stage_item.path.GetParentPath())
if parent:
children_updated_stage_items.add(parent)
# Removes it from filter list.
if self.flat and (stage_item.filtered or stage_item.child_filtered):
children_updated_stage_items.add(self._root)
if self._remove_stage_item_from_cache(stage_item.path):
all_removed_items.append(stage_item)
return refreshed_stage_items, children_updated_stage_items, all_removed_items
@Trace.TraceFunction
def __on_objects_changed(self, notice, stage):
"""Called by Usd.Notice.ObjectsChanged"""
if not stage or stage != self.__stage or self.__drag_and_drop_handler.is_reordering_prim:
return
if self.__renaming_prim:
return
dirty_prims_paths = []
for p in notice.GetResyncedPaths():
if p.IsAbsoluteRootOrPrimPath():
dirty_prims_paths.append(p)
for p in notice.GetChangedInfoOnlyPaths():
if not p.IsAbsoluteRootOrPrimPath():
if p.name == UsdGeom.Tokens.visibility:
dirty_prims_paths.append(p.GetPrimPath())
continue
for field in notice.GetChangedFields(p):
if field == omni.usd.editor.HIDE_IN_STAGE_WINDOW or field == omni.usd.editor.DISPLAY_NAME:
dirty_prims_paths.append(p)
break
if not dirty_prims_paths:
return
self.__dirty_prim_paths.update(dirty_prims_paths)
# Update in the next frame. We need it because we want to accumulate the affected prims
if self.__prim_changed_task_or_future is None or self.__prim_changed_task_or_future.done():
self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed())
@Trace.TraceFunction
def __on_layer_info_change(self, notice, sender):
"""Called by Sdf.Notice.LayerInfoDidChange when the metadata of the root layer is changed"""
if not sender or notice.key() != "defaultPrim":
return
new_default_prim = sender.defaultPrim
if new_default_prim == self.__default_prim_name:
return
# Unmark the old default
items_refreshed = []
if self.__default_prim_name:
found = self.find(Sdf.Path.absoluteRootPath.AppendChild(self.__default_prim_name))
if found:
items_refreshed.append(found)
# Mark the old default
if new_default_prim:
found = self.find(Sdf.Path.absoluteRootPath.AppendChild(new_default_prim))
if found:
items_refreshed.append(found)
self.__refresh_stage_items(items_refreshed)
self.__default_prim_name = new_default_prim
@handle_exception
@Trace.TraceFunction
async def __delayed_prim_changed(self):
await omni.kit.app.get_app().next_update_async()
# It's possible that stage is closed before coroutine
# is handled.
if not self.__stage:
return
# Pump the changes to the model.
self.update_dirty()
self.__prim_changed_task_or_future = None
@carb.profiler.profile
@Trace.TraceFunction
def get_item_children(self, item):
"""Reimplemented from AbstractItemModel"""
if item is None:
item = self._root
if not item:
return []
if self.flat:
# In flat mode, all stage items will be the children of root.
if item == self._root:
children = self._get_all_stage_items_from_cache()
else:
children = []
else:
children = self.__get_stage_item_children(item.path)
if self.__has_filters():
children = [child for child in children if (child.filtered or child.child_filtered)]
# Sort children
if self.__items_sort_func:
children.sort(key=self.__items_sort_func, reverse=self.__items_sort_reversed)
elif self.__items_sort_reversed:
children.reverse()
return children
@carb.profiler.profile
@Trace.TraceFunction
def can_item_have_children(self, item):
"""
By default, if can_item_have_children is not provided,
it will call get_item_children to get the count of children, so implementing
this function to make sure we do lazy load for all items.
"""
if item is None:
item = self._root
if not item or not item.prim:
return False
# Non-root item in flat mode has no children.
if self.flat and item != self._root:
return False
prim = item.prim
if self.load_payloads and not prim.IsLoaded():
# Lazy load payloads
prim.Load(Usd.LoadWithoutDescendants)
display_predicate = Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)
children_iterator = prim.GetFilteredChildren(display_predicate)
for child_prim in children_iterator:
if should_prim_be_excluded_from_tree_view(child_prim, self.__exclusion_types):
continue
if self.__has_filters():
child_item = self._get_stage_item_from_cache(child_prim.GetPath(), False)
if child_item and (child_item.filtered or child_item.child_filtered):
return True
else:
return True
return False
def get_item_value_model_count(self, item):
"""Reimplemented from AbstractItemModel"""
return self.__stage_item_value_model_count
def set_item_value_model_count(self, count):
"""Internal method to set column count."""
self.__stage_item_value_model_count = count
self._item_changed(None)
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
return self.__drag_and_drop_handler.drop_accepted(target_item, source, drop_location)
def drop(self, target_item, source, drop_location=-1):
"""
Reimplemented from AbstractItemModel. Called when dropping something to the item.
When drop_location is -1, it means to drop the source item on top of the target item.
When drop_location is not -1, it means to drop the source item between items.
"""
return self.__drag_and_drop_handler.drop(target_item, source, drop_location)
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 str(item.path) if item else "/"
def __has_filters(self):
return self.__filter_name_text or self.__filters
def filter_by_text(self, filter_name_text):
"""Filter stage by text. Currently, only single word that's case-insensitive or prim path are supported."""
if not self._root:
return
"""Specify the filter string that is used to reduce the model"""
if self.__filter_name_text == filter_name_text:
return
self.__filter_name_text = filter_name_text.strip() if filter_name_text else None
should_update_items = self.__prefilter(Sdf.Path.absoluteRootPath)
self.__refresh_stage_items([], should_update_items)
def filter(self, add=None, remove=None, clear=None):
"""
Set filtering by type. In most cases we need to filter with several types, so this method allows to add, remove
and set list of types and update the items if it's necessary.
Args:
add: The dictionary of this form: {"type_name_string", lambda prim: True}. When lambda is True, the prim
will be shown.
remove: Can be str, dict, list, set. Removes filter by name.
clear: Removes all the filters. When using with `add`, it will remove the filters first and then will add
the given ones.
Returns:
True if the model has filters. False otherwise.
"""
if not self._root:
return
changed = False
if clear:
if self.__filters:
self.__filters.clear()
changed = True
if remove:
if isinstance(remove, str):
remove = [remove]
for key in remove:
if key in self.__filters:
self.__filters.pop(key, None)
changed = True
if add:
self.__filters.update(add)
changed = True
if changed:
should_update_items = self.__prefilter(Sdf.Path.absoluteRootPath)
self.__refresh_stage_items([], should_update_items)
return not not self.__filters
def get_filters(self):
"""Return dict of filters"""
return self.__filters
def reset(self):
"""Force full re-update"""
if self._root:
self.__clear_stage_item_cache()
self._item_changed(None)
def destroy(self):
self.__drag_and_drop_handler = None
self.__on_stage_items_destroyed.clear()
self.__stage = None
if self._root:
self._root.destroy()
self._root = None
self.__layers_event_subs = []
if self.__stage_listener:
self.__stage_listener.Revoke()
self.__stage_listener = None
if self.__layer_listener:
self.__layer_listener.Revoke()
self.__layer_listener = None
self.__dirty_prim_paths = set()
if self.__prim_changed_task_or_future:
self.__prim_changed_task_or_future.cancel()
self.__prim_changed_task_or_future = None
self.__setting_sub = None
self.__clear_stage_item_cache()
self.layers_state_interface = None
self.__items_builtin_sort_policy = StageItemSortPolicy.DEFAULT
self.__items_sort_func = None
self.__items_sort_reversed = False
def __clear_filter_states(self, prim_path=None):
should_update_items = []
should_update_items.append(self.root)
for stage_item in self.__stage_item_cache.values():
if prim_path and not stage_item.path.HasPrefix(prim_path):
continue
if stage_item.filtered or stage_item.child_filtered:
should_update_items.append(stage_item)
stage_item.filtered = False
stage_item.child_filtered = False
return should_update_items
def __filter_prim(self, prim: Usd.Prim):
if not prim:
return False
if (
self.__filter_name_text
and Sdf.Path.IsValidPathString(self.__filter_name_text)
and Sdf.Path.IsAbsolutePath(Sdf.Path(self.__filter_name_text))
):
filter_text_is_prim_path = True
filter_path = Sdf.Path(self.__filter_name_text)
prim = self.__stage.GetPrimAtPath(filter_path)
if not prim:
return False
else:
filter_text_is_prim_path = False
filter_path = self.__filter_name_text.lower() if self.__filter_name_text else ""
# Has the search string in the name
if filter_text_is_prim_path:
filtered_with_string = prim.GetPath().HasPrefix(filter_path)
else:
filtered_with_string = filter_path in prim.GetName().lower() if filter_path else True
# Has the given type
if self.__filters:
filtered_with_lambda = False
for _, fn in self.__filters.items():
if fn(prim):
filtered_with_lambda = True
break
else:
filtered_with_lambda = True
# The result filter
return filtered_with_string and filtered_with_lambda
def __prefilter(self, prim_path: Sdf.Path):
"""Recursively mark items that meet the filtering rule"""
prim_path = Sdf.Path(prim_path)
prim = self.__stage.GetPrimAtPath(prim_path)
if not prim:
return set()
# Clears all filter states.
old_filtered_items = set(self.__clear_filter_states(prim_path))
should_update_items = set()
if self.__has_filters():
# Root should be refreshed always
should_update_items.add(self.root)
# and then creates stage items on demand when they are filtered to avoid
# perf issue to create stage items for whole stage.
display_predicate = Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)
children_iterator = iter(Usd.PrimRange(prim, display_predicate))
for child_prim in children_iterator:
if should_prim_be_excluded_from_tree_view(child_prim, self.__exclusion_types):
children_iterator.PruneChildren()
continue
if self.load_payloads and not prim.IsLoaded():
# Lazy load payloads
prim.Load(Usd.LoadWithoutDescendants)
filtered = self.__filter_prim(child_prim)
if not filtered:
continue
# Optimization: only prim path that's filtered will create corresponding
# stage item instead of whole subtree.
child_prim_path = child_prim.GetPath()
stage_item = self._get_stage_item_from_cache(child_prim_path, True)
if not stage_item:
continue
stage_item.filtered = True
stage_item.child_filtered = False
if not self.flat:
should_update_items.add(stage_item)
old_filtered_items.discard(stage_item)
parent_path = child_prim_path.GetParentPath()
# Creates all parents if they are not there and mark their children filtered.
while parent_path:
parent_item = self._get_stage_item_from_cache(parent_path, True)
if not parent_item or parent_item.child_filtered:
break
should_update_items.add(parent_item)
old_filtered_items.discard(parent_item)
parent_item.child_filtered = True
parent_path = parent_path.GetParentPath()
else:
self.root.child_filtered = True
should_update_items.update(old_filtered_items)
return should_update_items
def __on_exclusion_types_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType):
"""Called when the exclusion list is changed"""
if event_type == carb.settings.ChangeEventType.CHANGED:
settings = carb.settings.get_settings()
self.__exclusion_types = settings.get(EXCLUSION_TYPES_SETTING)
elif event_type == carb.settings.ChangeEventType.DESTROYED:
self.__exclusion_types = None
else:
return
self.reset()
@property
def children_reorder_supported(self):
"""Whether to support reorder children by drag and drop."""
return self.__drag_and_drop_handler.children_reorder_supported
@children_reorder_supported.setter
def children_reorder_supported(self, value):
self.__drag_and_drop_handler.children_reorder_supported = value
@property
def show_prim_displayname(self):
"""Instructs stage delegate to show prim's displayName from USD or path name."""
return self.__show_prim_displayname
@show_prim_displayname.setter
def show_prim_displayname(self, value):
if value != self.__show_prim_displayname:
self.__show_prim_displayname = value
all_stage_items = self._get_all_stage_items_from_cache()
self.__refresh_stage_items(all_stage_items)
def subscribe_stage_items_destroyed(self, fn: Callable[[List[StageItem]], None]) -> EventSubscription:
"""
Subscribe changes when stage items are destroyed.
Return the object that will automatically unsubscribe when destroyed.
"""
return EventSubscription(self.__on_stage_items_destroyed, fn)
def rename_prim(self, prim_path: Sdf.Path, new_name: str):
"""Rename prim to new name."""
if not self.stage or not self.stage.GetPrimAtPath(prim_path):
return False
if not Tf.IsValidIdentifier(new_name):
carb.log_error(f"Cannot rename prim {prim_path} to name {new_name} as new name is invalid.")
return False
if prim_path.name == new_name:
return True
parent_path = prim_path.GetParentPath()
created_path = parent_path.AppendElementString(new_name)
if self.stage.GetPrimAtPath(created_path):
carb.log_error(f"Cannot rename prim {prim_path} to name {new_name} as new prim exists already.")
return False
def prim_renamed(old_prim_name: Sdf.Path, new_prim_name: Sdf.Path):
async def select_prim(prim_path):
# Waits for two frames until stage item is created
app = omni.kit.app.get_app()
await app.next_update_async()
await app.next_update_async()
if self.__usd_context:
self.__usd_context.get_selection().set_selected_prim_paths(
[prim_path.pathString], True
)
run_coroutine(select_prim(new_prim_name))
stage_item = self._get_stage_item_from_cache(prim_path)
on_move_fn = prim_renamed if stage_item else None
# Move the prim to the new name
try:
self.__renaming_prim = True
move_dict = {prim_path: created_path.pathString}
omni.kit.commands.execute("MovePrims", paths_to_move=move_dict, on_move_fn=on_move_fn, destructive=False)
# If stage item exists.
if stage_item:
self.__stage_item_cache.pop(stage_item.path, None)
# Change internal path and refresh old path.
stage_item._path = created_path
stage_item.update_flags()
# Cache new path
self._cache_stage_item(stage_item)
# Refreshes search list
if (
self.__has_filters() and not stage_item.child_filtered and
stage_item.filtered and not self.__filter_prim(stage_item.prim)
):
stage_item.filtered = False
if self.flat:
self._item_changed(None)
else:
parent_path = prim_path.GetParentPath()
parent_item = self._get_stage_item_from_cache(parent_path)
if parent_item:
self.__refresh_stage_items([], children_refreshed_items=[parent_item])
else:
self.__refresh_stage_items([], children_refreshed_items=[stage_item])
except Exception as e:
import traceback
carb.log_error(traceback.format_exc())
carb.log_error(f"Failed to rename prim {prim_path}: {str(e)}")
return False
finally:
self.__renaming_prim = False
return True
def set_items_sort_key_func(self, key_fn: Callable[[StageItem], None], reverse=False):
"""
Sets key function to sort item children.
Args:
key_fn (Callable[[StageItem], None]): The function that's used to sort children of item, which
be passed to list.sort as key function, for example, `lambda item: item.name`. If `key_fn` is
None and `reverse` is True, it will reverse items only. Or if `key_fn` is None and `reverse` is
False, it will clear sort function.
reverse (bool): By default, it's ascending order to sort with key_fn. If this flag is True,
it will sort children in reverse order.
clear_existing (bool): If it's True, it will clear all existing sort key functions, including
resetting builtin column sort policy to StageItemSortPolicy.DEFAULT. False by default.
Returns:
Handle that maintains the lifecycle of the sort function. Releasing it will remove the sort function
and trigger widget refresh.
"""
notify = False
if not self.__settings_builtin_sort_policy and self.__items_builtin_sort_policy != StageItemSortPolicy.DEFAULT:
self.__items_builtin_sort_policy = StageItemSortPolicy.DEFAULT
if self.__items_sort_func:
self.__items_sort_func = None
notify = True
if self.__items_sort_func or self.__items_sort_reversed:
self.__items_sort_func = None
self.__items_sort_reversed = False
notify = True
if key_fn or reverse:
self.__items_sort_func = key_fn
self.__items_sort_reversed = reverse
notify = True
# Refresh all items to sort their children
if notify:
all_stage_items = self._get_all_stage_items_from_cache()
all_stage_items.append(self.root)
self.__refresh_stage_items([], all_stage_items)
def set_items_sort_policy(self, items_sort_policy: StageItemSortPolicy):
"""
This is old way to sort builtin columns (name, type, and visibility), which can only sort one
builtin column at the same time, and it will clear all existing sorting functions customized by
append_column_sort_key_func and only sort column specified by `items_sort_policy`. For more advanced sort,
see function `append_column_sort_key_func`, which supports to chain sort for multiple columns.
"""
try:
self.__settings_builtin_sort_policy = True
if self.__items_builtin_sort_policy != items_sort_policy:
self.__items_builtin_sort_policy = items_sort_policy
if self.__items_builtin_sort_policy == StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD:
self.set_items_sort_key_func(None, True)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.NAME_COLUMN_A_TO_Z:
self.set_items_sort_key_func(lambda item: (item.name_model._name_prefix, item.name_model._suffix_order), False)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.NAME_COLUMN_Z_TO_A:
self.set_items_sort_key_func(lambda item: (item.name_model._name_prefix, item.name_model._suffix_order), True)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.TYPE_COLUMN_A_TO_Z:
self.set_items_sort_key_func(lambda item: item.type_name.lower(), False)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.TYPE_COLUMN_Z_TO_A:
self.set_items_sort_key_func(lambda item: item.type_name.lower(), True)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE:
self.set_items_sort_key_func(lambda item: 1 if item.visible else 0, False)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE:
self.set_items_sort_key_func(lambda item: 0 if item.visible else 1, False)
else:
self.set_items_sort_key_func(None, False)
finally:
self.__settings_builtin_sort_policy = False
def get_items_sort_policy(self) -> StageItemSortPolicy:
"""Gets builtin columns sort policy."""
return self.__items_builtin_sort_policy
# Deprecated APIs
def refresh_item_names(self): # pragma: no cover
"""Deprecated."""
for item in self.__stage_item_cache.values():
item.name_model.rebuild()
self._item_changed(item)
@property
def check_missing_references(self): # pragma: no cover
"""Deprecated: It will always check missing references now."""
return True
@check_missing_references.setter
def check_missing_references(self, value): # pragma: no cover
"""Deprecated."""
pass
| 41,453 | Python | 37.960526 | 131 | 0.599667 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_filter.py | from functools import partial
from typing import Optional
from pxr import UsdGeom, UsdSkel, OmniAudioSchema, UsdLux, UsdShade, OmniSkelSchema, UsdPhysics
from omni.kit.widget.filter import FilterButton
from omni.kit.widget.options_menu import OptionItem, OptionSeparator
class StageFilterButton(FilterButton):
"""
Filter button used in stage widget.
Args:
filter_provider: Provider where filter functions defined. Use stage widget.
"""
def __init__(self, filter_provider):
self.__filter_provider = filter_provider
items = [
OptionItem("Hidden", on_value_changed_fn=self._filter_by_visibility),
OptionSeparator(),
OptionItem("Animations", on_value_changed_fn=partial(self._filter_by_type, UsdSkel.Animation)),
OptionItem("Audio", on_value_changed_fn=partial(self._filter_by_type, OmniAudioSchema.OmniSound)),
OptionItem("Cameras", on_value_changed_fn=partial(self._filter_by_type, UsdGeom.Camera)),
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
OptionItem(
"Lights",
on_value_changed_fn=partial(self._filter_by_api_type, UsdLux.LightAPI) if hasattr(UsdLux, 'LightAPI') else partial(self._filter_by_type, UsdLux.Light)
),
OptionItem("Materials",on_value_changed_fn=partial(self._filter_by_type, [UsdShade.Material, UsdShade.Shader])),
OptionItem("Meshes", on_value_changed_fn=partial(self._filter_by_type, UsdGeom.Mesh)),
OptionItem("Xforms", on_value_changed_fn=partial(self._filter_by_type, UsdGeom.Xform)),
OptionSeparator(),
OptionItem("Material Flattener Base Meshes", on_value_changed_fn=self._filter_by_flattener_basemesh),
OptionItem("Material Flattener Decals", on_value_changed_fn=self._filter_by_flattener_decal),
OptionSeparator(),
OptionItem("Physics Articulation Roots",on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.ArticulationRootAPI)),
OptionItem("Physics Colliders", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.CollisionAPI)),
OptionItem("Physics Collision Groups", on_value_changed_fn=partial(self._filter_by_type, UsdPhysics.CollisionGroup)),
OptionItem("Physics Filtered Pairs", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.FilteredPairsAPI)),
OptionItem("Physics Joints", on_value_changed_fn=partial(self._filter_by_type, UsdPhysics.Joint)),
OptionItem("Physics Drives", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.DriveAPI)),
OptionItem("Physics Materials", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.MaterialAPI)),
OptionItem("Physics Rigid Bodies", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.RigidBodyAPI)),
OptionItem("Physics Scenes", on_value_changed_fn=partial(self._filter_by_type, UsdPhysics.Scene)),
OptionSeparator(),
OptionItem("Skeleton", on_value_changed_fn=partial(self._filter_by_type, [UsdSkel.Skeleton, OmniSkelSchema.OmniSkelBaseType, OmniSkelSchema.OmniJoint]) or partial(self._filter_by_api_type, [OmniSkelSchema.OmniSkelBaseAPI, OmniSkelSchema.OmniJointLimitsAPI])),
]
super().__init__(items, width=20, height=20)
def enable_filters(self, usd_type_list: list) -> list:
"""
Enable filters.
Args:
usd_type_list (list): List of usd types to be enabled.
Returns:
returns usd types not supported
"""
self.model.reset()
unknown_usd_types = []
for usd_type in usd_type_list:
name = None
if usd_type == UsdSkel.Animation:
name = "Animations"
elif usd_type == OmniAudioSchema.OmniSound:
name = "Audio"
elif usd_type == UsdGeom.Camera:
name = "Cameras"
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
elif (hasattr(UsdLux, 'LightAPI') and usd_type == UsdLux.LightAPI) or (hasattr(UsdLux, 'Light') and usd_type == UsdLux.Light):
name = "Lights"
elif usd_type == UsdShade.Material or usd_type == UsdShade.Shader:
name = "Materials"
elif usd_type == UsdGeom.Mesh:
name = "Meshes"
elif usd_type == UsdGeom.Xform:
name = "Xforms"
elif usd_type == UsdPhysics.ArticulationRootAPI:
name = "Physics Articulation Roots"
elif usd_type == UsdPhysics.CollisionAPI:
name = "Physics Colliders"
elif usd_type == UsdPhysics.CollisionGroup:
name = "Physics Collision Groups"
elif usd_type == UsdPhysics.FilteredPairsAPI:
name = "Physics Filtered Pairs"
elif usd_type == UsdPhysics.Joint:
name = "Physics Joints"
elif usd_type == UsdPhysics.DriveAPI:
name = "Physics Drives"
elif usd_type == UsdPhysics.MaterialAPI:
name = "Physics Materials"
elif usd_type == UsdPhysics.RigidBodyAPI:
name = "Physics Rigid Bodies"
elif usd_type == UsdPhysics.Scene:
name = "Physics Scenes"
elif usd_type == OmniSkelSchema.OmniSkelBaseType or usd_type == OmniSkelSchema.OmniSkelBaseAPI or usd_type == OmniSkelSchema.OmniJoint or usd_type == OmniSkelSchema.OmniJointLimitsAPI:
name = "Skeleton"
item = self._get_item(name) if name else None
if item:
item.value = True
else:
unknown_usd_types.append(usd_type)
# If there is any unknow usd types, unhide filter button
if unknown_usd_types and self.button:
self.button.visible = False
return unknown_usd_types
def _filter_by_visibility(self, enabled):
"""Filter Hidden On/Off"""
self.__filter_provider._filter_by_visibility(enabled)
def _filter_by_type(self, usd_types, enabled):
"""
Set filtering by USD type.
Args:
usd_types: The type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
self.__filter_provider._filter_by_type(usd_types, enabled)
def _filter_by_api_type(self, api_types, enabled):
"""
Set filtering by USD api type.
Args:
api_types: The api type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
self.__filter_provider._filter_by_api_type(api_types, enabled)
def _filter_by_flattener_basemesh(self, enabled):
self.__filter_provider._filter_by_flattener_basemesh(enabled)
def _filter_by_flattener_decal(self, enabled):
self.__filter_provider._filter_by_flattener_decal(enabled)
def _get_item(self, name: str) -> Optional[OptionItem]:
for item in self.model.get_item_children():
if item.name == name:
return item
return None
| 7,471 | Python | 48.157894 | 271 | 0.630572 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/usd_property_watch.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 .stage_helper import UsdStageHelper
from pxr import Sdf
from pxr import Tf
from pxr import Trace
from pxr import Usd
from typing import Any
from typing import Dict
from typing import List
from typing import Optional, Union
from typing import Type
import asyncio
import carb
import functools
import omni.kit.app
from omni.kit.async_engine import run_coroutine
import omni.kit.commands
import omni.ui as ui
import traceback
import concurrent.futures
def handle_exception(func): # pragma: no cover
"""
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
class UsdPropertyWatchModel(ui.AbstractValueModel, UsdStageHelper): # pragma: no cover
"""
DEPRECATED: A helper model of UsdPropertyWatch that behaves like a model that watches
a USD property. It doesn't work properly if UsdPropertyWatch does not
create it.
"""
def __init__(self, stage: Usd.Stage, path: Sdf.Path):
"""
## Arguments:
`stage`: USD Stage
`path`: The full path to the watched property
"""
ui.AbstractValueModel.__init__(self)
UsdStageHelper.__init__(self, stage)
if stage:
prop = stage.GetObjectAtPath(path)
else:
prop = None
if prop:
self._path = path
self._type = prop.GetTypeName().type
else:
self._path = None
self._type = None
def destroy(self):
"""Called before destroying"""
pass
def _get_prop(self):
"""Get the property this model holds"""
if not self._path:
return
stage = self._get_stage()
if not stage:
return
return stage.GetObjectAtPath(self._path)
def on_usd_changed(self):
"""Called by the stage model when the visibility is changed"""
self._value_changed()
def get_value_as_bool(self) -> Optional[bool]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return not not prop.Get()
def get_value_as_float(self) -> Optional[float]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return float(prop.Get())
def get_value_as_int(self) -> Optional[int]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return int(prop.Get())
def get_value_as_string(self) -> Optional[str]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return str(prop.Get())
def set_value(self, value: Any):
"""Reimplemented set bool"""
prop = self._get_prop()
if not prop:
return
omni.kit.commands.execute("ChangeProperty", prop_path=self._path, value=value)
class UsdPropertyWatch(UsdStageHelper): # pragma: no cover
"""
DEPRECATED: The purpose of this class is to keep a large number of models.
`Usd.Notice.ObjectsChanged` is pretty slow, and to remain fast, we need
to register as few `Tf.Notice` as possible. Thus, we can't put the
`Tf.Notice` logic to the model. Instead, this class creates and
coordinates the models.
"""
def __init__(
self,
stage: Usd.Stage,
property_name: str,
model_type: Type[UsdPropertyWatchModel] = UsdPropertyWatchModel,
):
"""
## Arguments:
`stage`: USD Stage
`property_name`: The name of the property to watch
`model_type`: The name of the property to watch
"""
UsdStageHelper.__init__(self, stage)
self.__prim_changed_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None
self.__dirty_property_paths: List[Sdf.Path] = []
self.__watch_property: str = property_name
self.__model_type: Type[UsdPropertyWatchModel] = model_type
self.__stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, stage)
self.__models: Dict[str, UsdPropertyWatchModel] = {}
def destroy(self):
"""Called before destroying"""
self.__stage_listener = None
for _, model in self.__models.items():
model.destroy()
self.__models = {}
if self.__prim_changed_task_or_future is not None:
self.__prim_changed_task_or_future.cancel()
self.__prim_changed_task_or_future = None
@Trace.TraceFunction
def _on_objects_changed(self, notice, sender):
"""Called by Tf.Notice"""
# We only watch the property self.__watch_property
prims_resynced = [
p for p in notice.GetChangedInfoOnlyPaths() if p.IsPropertyPath() and p.name == self.__watch_property
]
if prims_resynced:
# It's important to return as soon as possible, because
# Usd.Notice.ObjectsChanged can be called thousands times a frame.
# We collect the paths change and will work with them the next
# frame at once.
self.__dirty_property_paths += prims_resynced
if self.__prim_changed_task_or_future is None or self.__prim_changed_task_or_future.done():
self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed())
# TODO: Do something when the watched object is removed
@handle_exception
@Trace.TraceFunction
async def __delayed_prim_changed(self):
"""Called in the next frame when the object is changed"""
await omni.kit.app.get_app().next_update_async()
# Pump the changes to the model.
self.update_dirty()
self.__prim_changed_task_or_future = None
def update_dirty(self):
"""
Create/remove dirty items that was collected from TfNotice. Can be
called any time to pump changes.
"""
dirty_property_paths = set(self.__dirty_property_paths)
self.__dirty_property_paths = []
dirty_prim_paths = [p.GetParentPath() for p in dirty_property_paths]
for path in dirty_prim_paths:
model = self.__models.get(path, None)
if model is None:
continue
model.on_usd_changed()
def _create_model(self, path: Sdf.Path):
"""Creates a new model and puts in to the cache"""
model = self.__model_type(self._get_stage(), path.AppendProperty(self.__watch_property))
self.__models[path] = model
return model
def get_model(self, path):
model = self.__models.get(path, None)
if model is None:
model = self._create_model(path)
return model
| 7,502 | Python | 30.792373 | 113 | 0.61317 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/models/type_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TypeModel"]
import omni.ui as ui
class TypeModel(ui.AbstractValueModel):
def __init__(self, stage_item):
super().__init__()
self.__stage_item = stage_item
def destroy(self):
self.__stage_item = None
def get_value_as_string(self) -> str:
return self.__stage_item.type_name
def set_value(self, value: str):
pass
| 817 | Python | 29.296295 | 76 | 0.70257 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/models/visibility_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["VisibilityModel"]
import omni.ui as ui
import omni.usd
class VisibilityModel(ui.AbstractValueModel):
def __init__(self, stage_item):
super().__init__()
self.__stage_item = stage_item
def destroy(self):
self.__stage_item = None
def get_value_as_bool(self) -> bool:
"""Reimplemented get bool"""
# Invisible when it's checked.
return not self.__stage_item.visible
def set_value(self, value: bool):
"""Reimplemented set bool"""
prim = self.__stage_item.prim
if not prim:
return
usd_context = omni.usd.get_context_from_stage(prim.GetStage())
if usd_context:
selection_paths = usd_context.get_selection().get_selected_prim_paths()
else:
selection_paths = []
# If the updating prim path is one of the selection path, we change all selected path. Otherwise, only change itself
prim_path = prim.GetPath()
stage = prim.GetStage()
update_paths = selection_paths if prim_path in selection_paths else [prim_path]
omni.kit.commands.execute(
"ToggleVisibilitySelectedPrims", selected_paths=update_paths, stage=stage
)
| 1,665 | Python | 33.708333 | 124 | 0.664264 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/models/name_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["PrimNameModel"]
import omni.ui as ui
from pxr import Sdf, Tf
class PrimNameModel(ui.AbstractValueModel):
"""The model that changes the prim name"""
def __init__(self, stage_item):
super().__init__()
self.__stage_item = stage_item
self.__label_on_begin = None
self.__old_label = None
self.__name_prefix = None
self.__suffix_order = None
self.rebuild()
self.__refresh_name_prefix_and_suffix()
def __refresh_name_prefix_and_suffix(self):
parts = self.__stage_item.name.rpartition("_")
self.__name_prefix = None
self.__suffix_order = None
if parts and len(parts) > 1:
suffix_order = parts[-1]
are_all_digits = True
for c in suffix_order:
if not c.isdigit():
are_all_digits = False
break
if are_all_digits and suffix_order:
self.__name_prefix = parts[0].lower()
self.__suffix_order = int(suffix_order)
if self.__suffix_order is None:
self.__name_prefix = self.__stage_item.name.lower()
self.__suffix_order = 0
@property
def _prim_path(self):
"""DEPRECATED: to ensure back-compatibility."""
return self.path
@property
def _name_prefix(self):
"""Name prefix without suffix number, e.g, `abc_01` will return abc. It's used for column sort."""
return self.__name_prefix
@property
def _suffix_order(self):
"""Number suffix, e.g, `abc_01` will return 01. It's used for column sort."""
return self.__suffix_order
@property
def path(self):
return self.__stage_item.path
def destroy(self):
self.__stage_item = None
def get_value_as_string(self):
"""Reimplemented get string"""
return self.__label
def rebuild(self):
if self.__stage_item.stage_model.flat:
self.__label = str(self.__stage_item.path)
else:
if self.__stage_item.path == Sdf.Path.absoluteRootPath:
self.__label = "Root:"
elif self.__stage_item.stage_model.show_prim_displayname:
self.__label = self.__stage_item.display_name
else:
self.__label = self.__stage_item.name
def begin_edit(self):
self.__old_label = self.__label
self.__label_on_begin = self.__stage_item.name
self.__label = self.__label_on_begin
if self.__old_label != self.__label:
self._value_changed()
def set_value(self, value):
"""Reimplemented set"""
try:
value = str(value)
except ValueError:
value = ""
if value != self.__label:
self.__label = value
self._value_changed()
def end_edit(self):
if self.__label_on_begin == self.__label:
if self.__label != self.__old_label:
self.__label = self.__old_label
self._value_changed()
return
# Get the unique name
# replacing invalid characters with '_' if it's to display path name.
parent_path = self.__stage_item.path.GetParentPath()
valid_label_identifier = Tf.MakeValidIdentifier(self.__label)
new_prim_name = valid_label_identifier
counter = 1
while True:
created_path = parent_path.AppendElementString(new_prim_name)
if not self.__stage_item.stage.GetPrimAtPath(created_path):
break
new_prim_name = "{}_{:02d}".format(valid_label_identifier, counter)
counter += 1
stage_model = self.__stage_item.stage_model
if stage_model.rename_prim(self.__stage_item.path, new_prim_name):
self.__refresh_name_prefix_and_suffix()
self._value_changed()
if not stage_model.show_prim_displayname:
self.__label = new_prim_name
| 4,442 | Python | 32.156716 | 106 | 0.576317 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_drag_drop.py | import pathlib
import omni.kit.test
from pxr import UsdShade
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class TestStageDragDrop(OmniUiTest):
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_prim_reparent(self):
app = omni.kit.app.get_app()
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
world_prim = stage.DefinePrim("/World2", "Xform")
cube_prim = stage.DefinePrim("/cube", "Cube")
await app.next_update_async()
await app.next_update_async()
stage_window = ui_test.find("Stage")
await stage_window.focus()
stage_window.window._stage_widget._tree_view.root_visible=True
await app.next_update_async()
await app.next_update_async()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
absolute_prim_item = stage_tree.find("**/Label[*].text=='Root:'")
world_prim_item = stage_tree.find("**/Label[*].text=='World2'")
cube_prim_item = stage_tree.find("**/Label[*].text=='cube'")
self.assertTrue(absolute_prim_item)
self.assertTrue(cube_prim_item)
self.assertTrue(world_prim_item)
await cube_prim_item.drag_and_drop(world_prim_item.center)
await app.next_update_async()
await app.next_update_async()
self.assertTrue(stage.GetPrimAtPath("/World2/cube"))
self.assertFalse(stage.GetPrimAtPath("/cube"))
cube_prim_item = stage_tree.find("**/Label[*].text=='cube'")
self.assertTrue(cube_prim_item)
await cube_prim_item.drag_and_drop(absolute_prim_item.center)
await app.next_update_async()
await app.next_update_async()
self.assertFalse(stage.GetPrimAtPath("/World2/cube"))
self.assertTrue(stage.GetPrimAtPath("/cube"))
async def test_material_drag_drop_preview(self):
await arrange_windows(hide_viewport=True)
usd_context = omni.usd.get_context()
test_file_path = self._test_path.joinpath("usd/cube.usda").absolute()
test_material_path = self._test_path.joinpath("mtl/mahogany_floorboards.mdl").absolute()
await usd_context.open_stage_async(str(test_file_path))
await ui_test.human_delay()
# get cube prim
stage = omni.usd.get_context().get_stage()
world_prim = stage.GetPrimAtPath("/World")
cube_prim = stage.GetPrimAtPath("/World/Cube")
# select cube prim to expand the stage list...
usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True)
await ui_test.human_delay()
usd_context.get_selection().clear_selected_prim_paths()
await ui_test.human_delay()
# check bound material
bound_material, _ = UsdShade.MaterialBindingAPI(cube_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
stage_window = ui_test.find("Stage")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
await content_browser_helper.drag_and_drop_tree_view(str(test_material_path), drag_target=drag_target)
# select new material prim
mahogany_prim = stage.GetPrimAtPath("/World/Looks/mahogany_floorboards")
self.assertTrue(mahogany_prim.GetPrim().IsValid())
await ui_test.human_delay()
# check /World isn't bound
bound_material, _ = UsdShade.MaterialBindingAPI(world_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# check /World/Cube isn't bound
bound_material, _ = UsdShade.MaterialBindingAPI(cube_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
for widget in stage_tree.find_all("**/Label[*].text=='Cube'"):
await content_browser_helper.drag_and_drop_tree_view(str(test_material_path), drag_target=widget.center)
break
# select cube prim
usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True)
await ui_test.human_delay()
# check bound material
bound_material, _ = UsdShade.MaterialBindingAPI(cube_prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid())
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == "/World/Looks/mahogany_floorboards_01")
# check /World isn't bound
bound_material, _ = UsdShade.MaterialBindingAPI(world_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
| 5,432 | Python | 42.814516 | 120 | 0.658689 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/drag_drop_path.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import os
import omni.kit.app
import omni.usd
import carb
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class DragDropFileStagePath(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows(hide_viewport=True)
await open_stage(get_test_data_path(__name__, "usd/cube.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
async def test_l1_drag_drop_path_usd_stage_absolute(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_window = ui_test.find("Stage")
await stage_window.focus()
# drag/drop from content browser to stage window
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertTrue(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_usd_stage_relative(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_window = ui_test.find("Stage")
await stage_window.focus()
# drag/drop from content browser to stage window
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertFalse(os.path.isabs(asset.path))
| 3,407 | Python | 45.054053 | 119 | 0.706487 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_export_selected.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import os
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
from omni.kit.window.file_exporter import get_instance as get_file_exporter
class TestExportSelected(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
stage_window = ui_test.find("Stage")
await stage_window.focus()
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_stage_menu_export_selected_single_prim(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Cone"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_single_selected_prim.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/Cone'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_l1_stage_menu_export_selected_multiple_prims(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Cone", "/World/Cube", "/World/Sphere", "/World/Cylinder"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_multiple_selected_prim.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/Cone', '/Root/Cone/Cone', '/Root/Cube', '/Root/Cube/Cube', '/Root/Sphere', '/Root/Sphere/Sphere', '/Root/Cylinder', '/Root/Cylinder/Cylinder'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_l1_stage_menu_export_selected_single_material(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Looks/OmniPBR"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_single_selected_material.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/OmniPBR', '/Root/OmniPBR/Shader'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_l1_stage_menu_export_selected_multiple_materials(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Looks/OmniPBR", "/World/Looks/OmniGlass", "/World/Looks/OmniSurface_Plastic"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_multiple_selected_material.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/OmniPBR', '/Root/OmniPBR/Shader', '/Root/OmniGlass', '/Root/OmniGlass/Shader', '/Root/OmniSurface_Plastic', '/Root/OmniSurface_Plastic/Shader'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_stage_menu_export_selected_prefill(self):
"""Test that export selected pre-fill prim name and save directory."""
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Cone", "/World/Cube", "/World/Sphere", "/World/Cylinder"]
output_dir = omni.kit.test.get_test_output_path()
test_file = os.path.join(output_dir, "test_prefill.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
# check that prim name is pre-fill with the first prim name
exporter = get_file_exporter()
filename = exporter._dialog.get_filename()
self.assertEqual(filename, "Cone")
# check that current directory is the same as the stage directory
dirname = exporter._dialog.get_current_directory()
self.assertEqual(dirname.rstrip("/").lower(),
os.path.dirname(stage.GetRootLayer().realPath).replace("\\", "/").lower())
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# right click again, now the default directory for save should update to the last save directory
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
exporter = get_file_exporter()
# check that current directory is the same as the stage directory
dirname = exporter._dialog.get_current_directory()
self.assertEqual(dirname.rstrip("/").lower(), output_dir.replace("\\", "/").lower())
await file_export_helper.click_cancel_async()
# load another file
output_dir = get_test_data_path(__name__, "usd")
await open_stage(os.path.join(output_dir, "cube.usda"))
await wait_stage_loading()
stage = omni.usd.get_context().get_stage()
# check that current directory is the same as the stage directory
to_select = ["/World/Cube"]
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
# check that prim name is pre-fill with the selected prim name
exporter = get_file_exporter()
filename = exporter._dialog.get_filename()
self.assertEqual(filename, "Cube")
# check that current directory is the same as the stage directory
dirname = exporter._dialog.get_current_directory()
self.assertEqual(dirname.rstrip("/").lower(),
os.path.dirname(stage.GetRootLayer().realPath).replace("\\", "/").lower())
await file_export_helper.click_cancel_async()
# close stage & delete file
await omni.usd.get_context().new_stage_async() | 10,890 | Python | 46.147186 | 193 | 0.645087 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/drag_drop_single.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.usd
from pxr import UsdGeom
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
get_prims,
wait_stage_loading,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropFileStageSingle(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows(hide_viewport=True)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_single_usd_stage(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
await ui_test.find("Content").focus()
await ui_test.find("Stage").focus()
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader'])
# drag/drop files to stage window
async with ContentBrowserTestHelper() as content_browser_helper:
stage_window = ui_test.find("Stage")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
for file_path in ["4Lights.usda", "quatCube.usda"]:
await content_browser_helper.drag_and_drop_tree_view(get_test_data_path(__name__, file_path), drag_target=drag_target)
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube'])
async def test_drag_drop_to_default_prim(self):
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
await ui_test.find("Content").focus()
await ui_test.find("Stage").focus()
stage = usd_context.get_stage()
prim = stage.DefinePrim("/test", "Xform")
prim2 = stage.DefinePrim("/test2", "Xform")
prim3 = UsdGeom.Mesh.Define(stage, "/test3").GetPrim()
total_root_prims = 3
"""
OM-66707
Rules:
1. When it has no default prim, it will create pseudo root prim reference.
2. When it has default prim, it will create reference under default prim.
3. When the default prim is a gprim, it will create reference under pseudo root prim too as gprims
cannot have children.
"""
for default_prim in [None, prim, prim2, prim3]:
if default_prim:
stage.SetDefaultPrim(default_prim)
else:
stage.ClearDefaultPrim()
# drag/drop files to stage window
async with ContentBrowserTestHelper() as content_browser_helper:
stage_window = ui_test.find("Stage")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
for file_path in ["4Lights.usda", "quatCube.usda"]:
await content_browser_helper.drag_and_drop_tree_view(get_test_data_path(__name__, file_path), drag_target=drag_target)
if default_prim and default_prim != prim3:
self.assertEqual(len(prim.GetChildren()), 2)
else:
total_root_prims += 2
all_root_prims = [prim for prim in stage.GetPseudoRoot().GetChildren() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(len(all_root_prims), total_root_prims)
| 4,963 | Python | 46.730769 | 557 | 0.659279 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_stage_widget.py | import carb
import omni
import omni.kit.test
import omni.usd
import omni.client
import omni.kit.widget.stage
import omni.kit.app
import omni.kit.ui_test as ui_test
from omni.kit.test_suite.helpers import arrange_windows
from pxr import UsdGeom
class TestStageWidget(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.app = omni.kit.app.get_app()
await arrange_windows("Stage", 800, 600)
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
self.stage = omni.usd.get_context().get_stage()
async def tearDown(self):
pass
async def wait(self, frames=4):
for i in range(frames):
await self.app.next_update_async()
async def test_visibility_toggle(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
prim = self.stage.DefinePrim("/prim0", "Xform")
await self.wait()
prim_visibility_widget = stage_tree.find("**/ToolButton[*].name=='visibility'")
self.assertTrue(prim_visibility_widget)
await prim_visibility_widget.click()
await self.wait()
self.assertEqual(UsdGeom.Imageable(prim).ComputeVisibility(), UsdGeom.Tokens.invisible)
prim_visibility_widget = stage_tree.find("**/ToolButton[*].name=='visibility'")
self.assertTrue(prim_visibility_widget)
await prim_visibility_widget.click()
await self.wait()
self.assertEqual(UsdGeom.Imageable(prim).ComputeVisibility(), UsdGeom.Tokens.inherited)
async def test_search_widget(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
search_field = ui_test.find("Stage//Frame/**/StringField[*].name=='search'")
self.assertTrue(search_field)
prim1 = self.stage.DefinePrim("/prim", "Xform")
prim2 = self.stage.DefinePrim("/prim/prim1", "Xform")
prim3 = self.stage.DefinePrim("/prim/prim2", "Xform")
prim4 = self.stage.DefinePrim("/other", "Xform")
await self.wait()
await search_field.input("prim")
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await self.wait()
all_children = stage_model.get_item_children(None)
all_names = [child.name for child in all_children]
search_field.widget.model.set_value("")
await search_field.input("")
await self.wait()
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await self.wait()
self.assertTrue(prim4.GetName() not in all_names)
| 2,703 | Python | 36.041095 | 95 | 0.659267 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_stage_model.py | import carb
import os
import tempfile
import omni
import omni.kit.test
import omni.usd
import omni.client
import string
import random
import omni.ui as ui
# Don't remove. Including those two deprecated modules for code coverage.
from omni.kit.widget.stage.stage_helper import *
from omni.kit.widget.stage.usd_property_watch import *
from omni.kit.widget.stage import StageWidget
from omni.kit.widget.stage import StageItem, StageItemSortPolicy
from omni.kit.widget.stage import StageColumnDelegateRegistry, AbstractStageColumnDelegate, StageColumnItem
from pxr import Sdf, Usd, UsdGeom, Gf
SETTINGS_KEEP_CHILDREN_ORDER = "/persistent/ext/omni.usd/keep_children_order"
class TestColumnDelegate(AbstractStageColumnDelegate):
def __init__(self):
super().__init__()
def destroy(self):
pass
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(20)
def build_header(self, **kwargs):
"""Build the header"""
pass
async def build_widget(self, item: StageColumnItem, **kwargs):
pass
class TestStageModel(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
self.stage = self.usd_context.get_stage()
self.stage.GetRootLayer().Clear()
self.stage_widget = StageWidget(self.stage)
self.app = omni.kit.app.get_app()
self.old_keep_children_order = carb.settings.get_settings().get(SETTINGS_KEEP_CHILDREN_ORDER)
async def tearDown(self):
if self.old_keep_children_order is not None:
carb.settings.get_settings().set(SETTINGS_KEEP_CHILDREN_ORDER, self.old_keep_children_order)
self.stage_widget.destroy()
self.stage_widget = None
await self.usd_context.close_stage_async()
async def test_prim_item_api(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
self.assertTrue(root_stage_item.visibility_model)
self.assertTrue(root_stage_item.type_model)
self.assertTrue(root_stage_item.name_model)
async def test_show_prim_displayname(self):
self.stage_widget.show_prim_display_name = False
prim = self.stage.DefinePrim("/test", "Xform")
self.stage.DefinePrim("/test100", "Xform")
self.stage.DefinePrim("/test200", "Xform")
omni.usd.editor.set_display_name(prim, "display name test")
await self.app.next_update_async()
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
stage_items = stage_model.get_item_children(root_stage_item)
self.assertTrue(stage_items)
prim_item = stage_items[0]
self.assertTrue(prim_item)
self.assertEqual(prim_item.name, "test")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), "test")
# Change it to display name will show its display name instead
self.stage_widget.show_prim_display_name = True
await self.app.next_update_async()
await self.app.next_update_async()
self.assertEqual(prim_item.name, "test")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.display_name)
# Empty display name will show path name instead
omni.usd.editor.set_display_name(prim, "")
await self.app.next_update_async()
self.assertEqual(prim_item.name, "test")
self.assertEqual(prim_item.display_name, prim_item.name)
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.display_name)
# Emulate rename, it will rename prim name even it shows display name.
stage_items = stage_model.get_item_children(root_stage_item)
omni.usd.editor.set_display_name(prim, "display name test")
await self.app.next_update_async()
prim_item.name_model.begin_edit()
prim_item.name_model.set_value("test3")
prim_item.name_model.end_edit()
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertTrue(stage_items)
prim_item = stage_items[-1]
self.assertEqual(prim_item.name, "test3")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.display_name)
# Make sure change display name will not influence prim path.
self.assertFalse(self.stage.GetPrimAtPath("/test"))
self.assertTrue(self.stage.GetPrimAtPath("/test3"))
self.assertEqual(stage_items[0].path, Sdf.Path("/test100"))
self.assertEqual(stage_items[1].path, Sdf.Path("/test200"))
self.assertEqual(stage_items[2].path, Sdf.Path("/test3"))
self.stage_widget.show_prim_display_name = False
prim_item.name_model.begin_edit()
prim_item.name_model.set_value("test2")
prim_item.name_model.end_edit()
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertTrue(stage_items)
prim_item = stage_items[-1]
self.assertEqual(prim_item.name, "test2")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.name)
self.assertFalse(self.stage.GetPrimAtPath("/test3"))
self.assertTrue(self.stage.GetPrimAtPath("/test2"))
def create_flat_prims(self, stage, parent_path, num):
prim_paths = set([])
for i in range(num):
prim = stage.DefinePrim(parent_path.AppendElementString(f"xform{i}"), "Xform")
translation = Gf.Vec3d(-200, 0.0, 0.0)
common_api = UsdGeom.XformCommonAPI(prim)
common_api.SetTranslate(translation)
prim_paths.add(prim.GetPath())
return prim_paths
def get_all_stage_items(self, stage_item: StageItem):
stage_items = set([])
q = [stage_item]
if stage_item.path != Sdf.Path.absoluteRootPath:
stage_items.add(stage_item)
while len(q) > 0:
item = q.pop()
# Populating it if it's not.
children = item.stage_model.get_item_children(item)
for child in children:
stage_items.add(child)
q.append(child)
return stage_items
def get_all_stage_item_paths(self, stage_item):
stage_items = self.get_all_stage_items(stage_item)
paths = [item.path for item in stage_items]
return set(paths)
def create_prims(self, stage, parent_prim_path, level=[]):
if not level:
return set([])
prim_paths = self.create_flat_prims(stage, parent_prim_path, level[0])
all_child_paths = set([])
for prim_path in prim_paths:
all_child_paths.update(self.create_prims(stage, prim_path, level[1:]))
prim_paths.update(all_child_paths)
return prim_paths
def check_prim_children(self, prim_item: StageItem, expected_children_prim_paths):
paths = set({})
children = prim_item.stage_model.get_item_children(prim_item)
for child in children:
paths.add(child.path)
if children:
self.assertTrue(prim_item.stage_model.can_item_have_children(prim_item))
else:
self.assertFalse(prim_item.stage_model.can_item_have_children(prim_item))
self.assertEqual(paths, set(expected_children_prim_paths))
def check_prim_tree(self, prim_item: StageItem, expected_prim_paths):
paths = self.get_all_stage_item_paths(prim_item)
self.assertEqual(set(paths), set(expected_prim_paths))
async def test_prims_create(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, prim_paths)
async def test_prims_edits(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
# Populate children of root prim
stage_model.get_item_children(None)
prim1_of_root = root_stage_item.children[0].path
omni.kit.commands.execute(
"DeletePrims",
paths=[prim1_of_root]
)
await self.app.next_update_async()
changed_prims = prim_paths.copy()
for path in prim_paths:
if path.HasPrefix(prim1_of_root):
changed_prims.discard(path)
self.check_prim_tree(root_stage_item, changed_prims)
omni.kit.undo.undo()
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, prim_paths)
async def test_layer_flush(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, prim_paths)
self.stage.GetRootLayer().Clear()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set([]))
async def test_parenting_prim_refresh(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
# Creates 3 prims
prim_paths = list(self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [3]))
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set(prim_paths))
# Moves first two prims as the children of the 3rd one.
new_path0 = prim_paths[2].AppendElementString(prim_paths[0].name)
new_path1 = prim_paths[2].AppendElementString(prim_paths[1].name)
omni.kit.commands.execute("MovePrim", path_from=prim_paths[0], path_to=new_path0)
omni.kit.commands.execute("MovePrim", path_from=prim_paths[1], path_to=new_path1)
await self.app.next_update_async()
await self.app.next_update_async()
self.assertEqual(len(root_stage_item.children), 1)
self.assertEqual(root_stage_item.children[0].path, prim_paths[2])
self.check_prim_children(root_stage_item.children[0], set([new_path0, new_path1]))
omni.kit.undo.undo()
await self.app.next_update_async()
self.check_prim_children(root_stage_item, set(prim_paths[1:3]))
self.check_prim_tree(root_stage_item, set([new_path0, prim_paths[1], prim_paths[2]]))
omni.kit.undo.undo()
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set(prim_paths))
async def test_filter_prim(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
# Flat search
stage_model.flat = True
stage_model.filter_by_text("xform")
self.check_prim_children(root_stage_item, prim_paths)
children = root_stage_item.children
for child in children:
self.assertTrue(not child.children)
children = stage_model.get_item_children(root_stage_item)
paths = []
for child in children:
paths.append(child.path)
self.assertEqual(set(paths), set(prim_paths))
expected_paths = set([])
for path in prim_paths:
if str(path).endswith("xform0"):
expected_paths.add(path)
stage_model.filter_by_text("xform0")
children = stage_model.get_item_children(root_stage_item)
paths = []
for child in children:
paths.append(child.path)
self.assertEqual(set(paths), set(expected_paths))
# Non-flat search
stage_model.flat = False
stage_model.filter_by_text("xform")
self.check_prim_tree(root_stage_item, prim_paths)
children = root_stage_item.children
for child in children:
self.assertFalse(not child.children)
# Filtering with lambda
# Reset all states
stage_model.filter_by_text(None)
stage_model.filter(add={"Camera" : lambda prim: prim.IsA(UsdGeom.Camera)})
self.check_prim_tree(root_stage_item, [])
stage_model.filter(remove=["Camera"])
self.check_prim_tree(root_stage_item, prim_paths)
children = root_stage_item.children
for child in children:
self.assertFalse(not child.children)
stage_model.filter(add={"Xform" : lambda prim: prim.IsA(UsdGeom.Xform)})
self.check_prim_tree(root_stage_item, prim_paths)
camera = self.stage.DefinePrim("/new_group/camera0", "Camera")
await self.app.next_update_async()
await self.app.next_update_async()
# Adds new camera will still not be filtered as only xform is filtered currently
self.check_prim_tree(root_stage_item, prim_paths)
# Filters camera also
stage_model.filter(add={"Camera" : lambda prim: prim.IsA(UsdGeom.Camera)})
all_paths = []
all_paths.extend(prim_paths)
all_paths.append(camera.GetPath())
# Needs to add parent also as it's in non-flat mode
all_paths.append(camera.GetPath().GetParentPath())
self.check_prim_tree(root_stage_item, all_paths)
# Creates another camera and filter it.
camera1 = self.stage.DefinePrim("/new_group2/camera1", "Camera")
all_paths.append(camera1.GetPath())
all_paths.append(camera1.GetPath().GetParentPath())
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, all_paths)
# Filters with both types and texts.
stage_model.filter_by_text("camera")
all_paths = [
camera.GetPath(), camera.GetPath().GetParentPath(),
camera1.GetPath(), camera1.GetPath().GetParentPath()
]
self.check_prim_tree(root_stage_item, all_paths)
# Add new reference layer will be filtered also
reference_layer = Sdf.Layer.CreateAnonymous()
ref_stage = Usd.Stage.Open(reference_layer)
prim = ref_stage.DefinePrim("/root/camera_reference", "Camera")
default_prim = prim.GetParent()
ref_stage.SetDefaultPrim(default_prim)
reference_prim = self.stage.DefinePrim("/root", "Xform")
reference_prim.GetReferences().AddReference(reference_layer.identifier)
await self.app.next_update_async()
await self.app.next_update_async()
all_paths.append(prim.GetPath())
all_paths.append(default_prim.GetPath())
self.check_prim_tree(root_stage_item, all_paths)
# Add new sublayer too.
reference_layer = Sdf.Layer.CreateAnonymous()
sublayer_stage = Usd.Stage.Open(reference_layer)
prim = sublayer_stage.DefinePrim("/root/camera_sublayer", "Camera")
self.stage.GetRootLayer().subLayerPaths.append(reference_layer.identifier)
await self.app.next_update_async()
await self.app.next_update_async()
all_paths.append(prim.GetPath())
self.check_prim_tree(root_stage_item, all_paths)
# Clear all
stage_model.filter(clear=True)
stage_model.filter_by_text("")
prim_paths.update(all_paths)
self.check_prim_tree(root_stage_item, prim_paths)
async def test_find_full_chain(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
path = Sdf.Path("/xform0/xform0/xform0/xform0")
full_chain = stage_model.find_full_chain("/xform0/xform0/xform0/xform0")
self.assertEqual(len(full_chain), 5)
self.assertEqual(full_chain[0], root_stage_item)
prefixes = path.GetPrefixes()
for i in range(len(prefixes)):
self.assertEqual(full_chain[i + 1].path, prefixes[i])
async def test_has_missing_references(self):
stage_model = self.stage_widget.get_model()
self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [1])
path = Sdf.Path("/xform0")
full_chain = stage_model.find_full_chain(path)
self.assertEqual(len(full_chain), 2)
# Prim /xform0
prim_item = full_chain[1]
self.assertFalse(prim_item.has_missing_references)
prim = self.stage.GetPrimAtPath(path)
prim.GetReferences().AddReference("./face-invalid-non-existed-file.usd")
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(prim_item.has_missing_references)
async def test_instanceable_flag_change(self):
# OM-70714: Change instanceable flag will refresh children's instance_proxy flag.
with tempfile.TemporaryDirectory() as tmpdirname:
# save the file
tmp_file_path = os.path.join(tmpdirname, "tmp.usda")
result = await omni.usd.get_context().save_as_stage_async(tmp_file_path)
self.assertTrue(result)
stage = omni.usd.get_context().get_stage()
prim = stage.DefinePrim("/World/cube", "Xform")
stage.SetDefaultPrim(prim)
stage.Save()
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
prim = stage.DefinePrim("/World/Reference", "Xform")
prim.GetReferences().AddReference(tmp_file_path)
omni.kit.commands.execute("CopyPrim", path_from="/World/Reference", path_to="/World/Reference2")
prim2 = stage.GetPrimAtPath("/World/Reference2")
self.assertTrue(prim2)
prim.SetInstanceable(True)
prim2.SetInstanceable(True)
await self.app.next_update_async()
await self.app.next_update_async()
self.stage_widget = StageWidget(stage)
stage_model = self.stage_widget.get_model()
# Populate all childrens
stage_model.find_full_chain("/World/Reference/cube")
stage_model.find_full_chain("/World/Reference2/cube")
reference_item = stage_model.find("/World/Reference")
reference2_item = stage_model.find("/World/Reference2")
self.assertTrue(reference_item and reference2_item)
for item in [reference_item, reference2_item]:
self.assertTrue(item.instanceable)
for child in item.children:
self.assertTrue(child.instance_proxy)
prim2.SetInstanceable(False)
await self.app.next_update_async()
for child in reference_item.children:
self.assertTrue(child.instance_proxy)
for child in reference2_item.children:
self.assertFalse(child.instance_proxy)
async def _test_sorting_internal(self, prim_paths, sort_policy, sort_func, reverse):
self.stage_widget = StageWidget(self.stage)
stage_model = self.stage_widget.get_model()
stage_model.set_items_sort_policy(sort_policy)
await self.app.next_update_async()
await self.app.next_update_async()
# Checkes all items to see if their children are sorted correctly.
root_stage_item = stage_model.root
queue = [root_stage_item]
while queue:
item = queue.pop()
children = stage_model.get_item_children(item)
if not children:
continue
queue.extend(children)
if item == root_stage_item:
expected_children_paths = list(prim_paths.keys())
else:
expected_children_paths = list(prim_paths[str(item.path)])
if sort_func:
expected_children_paths.sort(key=sort_func, reverse=reverse)
elif reverse:
expected_children_paths.reverse()
children_paths = [str(child.path) for child in children]
self.assertEqual(children_paths, expected_children_paths)
async def test_sorting(self):
# Generating test data
prim_paths = {}
types = ["Cube", "Cone", "Sphere", "Xform", "Cylinder", "Capsule"]
prim_types = {}
prim_visibilities = {}
with Sdf.ChangeBlock():
for i in range(0, 26):
letter = random.choice(string.ascii_letters)
parent_path = f"/{letter}{i}"
prim_type = random.choice(types)
spec = Sdf.CreatePrimInLayer(self.stage.GetRootLayer(), parent_path)
spec.typeName = prim_type
children_paths = []
prim_types[parent_path] = prim_type
prim_visibilities[parent_path] = True
for j in range(0, 100):
letter = random.choice(string.ascii_letters)
prim_type = random.choice(types)
spec = Sdf.CreatePrimInLayer(self.stage.GetRootLayer(), f"{parent_path}/{letter}{j}")
spec.typeName = prim_type
children_paths.append(str(spec.path))
prim_types[str(spec.path)] = prim_type
visible = random.choice([True, False])
prim_visibilities[str(spec.path)] = visible
prim_paths[parent_path] = children_paths
for path, value in prim_visibilities.items():
prim = self.stage.GetPrimAtPath(path)
if prim:
imageable = UsdGeom.Imageable(prim)
if not value:
imageable.MakeInvisible()
visiblity = imageable.ComputeVisibility()
await self._test_sorting_internal(prim_paths, StageItemSortPolicy.DEFAULT, None, False)
await self._test_sorting_internal(prim_paths, StageItemSortPolicy.NAME_COLUMN_OLD_TO_NEW, None, False)
await self._test_sorting_internal(prim_paths, StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD, None, True)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.NAME_COLUMN_A_TO_Z, lambda x: Sdf.Path(x).name.lower(), False
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.NAME_COLUMN_Z_TO_A, lambda x: Sdf.Path(x).name.lower(), True
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.TYPE_COLUMN_A_TO_Z,
lambda x, p=prim_types: p[x].lower(),
False
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.TYPE_COLUMN_Z_TO_A,
lambda x, p=prim_types: p[x].lower(),
True,
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE,
lambda x, p=prim_visibilities: 1 if p[x] else 0,
False
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE,
lambda x, p=prim_visibilities: 0 if p[x] else 1,
False
)
async def test_column_delegate(self):
sub = StageColumnDelegateRegistry().register_column_delegate("test", TestColumnDelegate)
self.assertEqual(StageColumnDelegateRegistry().get_column_delegate("test"), TestColumnDelegate)
names = StageColumnDelegateRegistry().get_column_delegate_names()
self.assertTrue("test" in names)
async def test_item_destroy(self):
destroyed_paths = []
def on_items_destroyed(items):
nonlocal destroyed_paths
for item in items:
destroyed_paths.append(item.path)
stage_model = self.stage_widget.get_model()
prim_paths = list(self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [3]))
root_stage_item = stage_model.root
# Populate root node
stage_model.get_item_children(root_stage_item)
sub = stage_model.subscribe_stage_items_destroyed(on_items_destroyed)
self.stage.RemovePrim(prim_paths[0])
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(len(destroyed_paths) == 1)
self.assertEqual(destroyed_paths[0], prim_paths[0])
async def test_stage_item_properties(self):
stage_model = self.stage_widget.get_model()
stage = stage_model.stage
xform_prim = stage.DefinePrim("/test_prim", "Xform")
await self.app.next_update_async()
await self.app.next_update_async()
# Populate root node
stage_model.get_item_children(stage_model.root)
stage_item = stage_model.find(xform_prim.GetPath())
self.assertTrue(stage_item)
self.assertEqual(stage_item.name, "test_prim")
self.assertEqual(stage_item.type_name, "Xform")
self.assertTrue(stage_item.active)
self.assertFalse(stage_item.has_missing_references)
self.assertFalse(stage_item.payrefs)
self.assertFalse(stage_item.is_default)
self.assertFalse(stage_item.is_outdated)
self.assertFalse(stage_item.in_session)
self.assertFalse(stage_item.auto_reload)
self.assertEqual(stage_item.root_identifier, stage.GetRootLayer().identifier)
self.assertFalse(stage_item.instance_proxy)
self.assertFalse(stage_item.instanceable)
self.assertTrue(stage_item.visible)
self.assertFalse(stage_item.payloads)
self.assertFalse(stage_item.references)
self.assertTrue(stage_item.prim)
stage.SetDefaultPrim(xform_prim)
xform_prim.SetInstanceable(True)
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.is_default)
self.assertTrue(stage_item.instanceable)
xform_prim.SetActive(False)
await self.app.next_update_async()
await self.app.next_update_async()
self.assertFalse(stage_item.active)
xform_prim = stage.GetPrimAtPath("/test_prim")
xform_prim.SetActive(True)
xform_prim = stage.GetPrimAtPath("/test_prim")
# Changes active property will resync stage_item
stage_model.get_item_children(stage_model.root)
stage_item = stage_model.find(xform_prim.GetPath())
UsdGeom.Imageable(xform_prim).MakeInvisible()
await self.app.next_update_async()
await self.app.next_update_async()
self.assertFalse(stage_item.visible)
UsdGeom.Imageable(xform_prim).MakeVisible()
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.visible)
xform_prim.GetReferences().AddReference("__non_existed_reference.usd")
xform_prim.GetReferences().AddInternalReference("/non_existed_prim")
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.has_missing_references)
self.assertEqual(stage_item.payrefs, ["__non_existed_reference.usd"])
self.assertTrue(stage_item.references)
self.assertFalse(stage_item.payloads)
xform_prim.GetPayloads().AddPayload("__non_existed_payload.usd")
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.has_missing_references)
# Internal references will not be listed.
self.assertEqual(
set(stage_item.payrefs),
set(["__non_existed_reference.usd", "__non_existed_payload.usd"])
)
self.assertTrue(stage_item.references)
self.assertTrue(stage_item.payloads)
async def test_reorder_prim(self):
self.stage_widget.children_reorder_supported = True
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
# Creates 3 prims
prim_paths = list(self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [3]))
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set(prim_paths))
# Moves first two prims as the children of the 3rd one.
self.assertTrue(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=2))
self.assertTrue(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=1))
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=-1))
children = root_stage_item.children
prim_paths = [item.path for item in children]
stage_model.drop(root_stage_item, root_stage_item.children[0], drop_location=2)
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, prim_paths[1])
self.assertEqual(stage_items[1].path, prim_paths[0])
self.assertEqual(stage_items[2].path, prim_paths[2])
omni.kit.undo.undo()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, prim_paths[0])
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
# Disable reorder
self.stage_widget.children_reorder_supported = False
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=2))
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=1))
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=-1))
self.stage_widget.children_reorder_supported = True
# Renaming prim will still keep the location of prim.
# Enable setting to keep children order after rename.
carb.settings.get_settings().set(SETTINGS_KEEP_CHILDREN_ORDER, True)
stage_item = root_stage_item.children[0]
stage_item.name_model.begin_edit()
stage_item.name_model.set_value("renamed_item")
stage_item.name_model.end_edit()
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, Sdf.Path("/renamed_item"))
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
omni.kit.undo.undo()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, prim_paths[0])
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
with tempfile.TemporaryDirectory() as tmpdirname:
# save the file
tmp_file_path = os.path.join(tmpdirname, "tmp.usda")
layer = Sdf.Layer.CreateNew(tmp_file_path)
stage = Usd.Stage.Open(layer)
prim = stage.DefinePrim("/World/cube", "Xform")
stage.SetDefaultPrim(prim)
stage.Save()
stage = None
layer = None
stage_model.drop(root_stage_item, tmp_file_path, drop_location=3)
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 4)
self.assertEqual(stage_items[0].path, prim_paths[0])
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
self.assertEqual(stage_items[3].path, Sdf.Path("/tmp"))
stage_model.drop(root_stage_item, tmp_file_path, drop_location=1)
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 5)
self.assertEqual(stage_items[1].path, Sdf.Path("/tmp_01"))
await omni.usd.get_context().new_stage_async()
| 33,311 | Python | 40.901887 | 115 | 0.636727 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_helper.py | import unittest
import pathlib
import carb
import omni.kit.test
from pxr import UsdShade
from omni.ui.tests.test_base import OmniUiTest
from .inspector_query import InspectorQuery
class TestMouseUIHelper(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._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
self._inspector_query = InspectorQuery()
# After running each test
async def tearDown(self):
await super().tearDown()
async def wait_for_update(self, usd_context=omni.usd.get_context(), wait_frames=10):
max_loops = 0
while max_loops < wait_frames:
_, files_loaded, total_files = usd_context.get_stage_loading_status()
await omni.kit.app.get_app().next_update_async()
if files_loaded or total_files:
continue
max_loops = max_loops + 1
async def _simulate_mouse(self, data):
import omni.appwindow
import omni.ui as ui
mouse = omni.appwindow.get_default_app_window().get_mouse()
input_provider = carb.input.acquire_input_provider()
window_width = ui.Workspace.get_main_window_width()
window_height = ui.Workspace.get_main_window_height()
for type, x, y in data:
input_provider.buffer_mouse_event(mouse, type, (x / window_width, y / window_height), 0, (x, y))
await self.wait_for_update()
async def _debug_capture(self, image_name: str):
from pathlib import Path
import omni.renderer_capture
capture_next_frame = omni.renderer_capture.acquire_renderer_capture_interface().capture_next_frame_swapchain(image_name)
await self.wait_for_update()
wait_async_capture = omni.renderer_capture.acquire_renderer_capture_interface().wait_async_capture()
await self.wait_for_update()
| 2,027 | Python | 37.999999 | 128 | 0.662062 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_context_menu.py | import carb
import omni
import omni.kit.test
import omni.usd
import omni.client
import omni.kit.widget.stage
import omni.kit.app
import omni.kit.ui_test as ui_test
import pathlib
from omni.kit.test_suite.helpers import arrange_windows
from pxr import Sdf, UsdShade
class TestContextMenu(omni.kit.test.AsyncTestCase):
async def setUp(self):
await arrange_windows("Stage", 800, 600)
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
self.stage = omni.usd.get_context().get_stage()
self.layer = Sdf.Layer.CreateAnonymous()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
self._cube_usd_path = str(self._test_path.joinpath("usd/cube.usda"))
self.ref_prim = self.stage.DefinePrim("/reference0", "Xform")
self.ref_prim.GetReferences().AddReference(self.layer.identifier)
self.child_prim = self.stage.DefinePrim("/reference0/child0", "Xform")
self.payload_prim = self.stage.DefinePrim("/payload0", "Xform")
self.payload_prim.GetPayloads().AddPayload(self.layer.identifier)
self.rf_prim = self.stage.DefinePrim("/reference_and_payload0", "Xform")
self.rf_prim.GetReferences().AddReference(self.layer.identifier)
self.rf_prim.GetPayloads().AddPayload(self.layer.identifier)
await self.wait()
async def tearDown(self):
pass
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def _find_all_prim_items(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
reference_widget = stage_tree.find("**/Label[*].text=='reference0'")
payload_widget = stage_tree.find("**/Label[*].text=='payload0'")
reference_and_payload_widget = stage_tree.find("**/Label[*].text=='reference_and_payload0'")
return reference_widget, payload_widget, reference_and_payload_widget
async def test_expand_collapse_tree(self):
rf_widget, _, _ = await self._find_all_prim_items()
for name in ["All", "Component", "Group", "Assembly", "SubComponent"]:
await rf_widget.right_click()
await ui_test.select_context_menu(f"Collapse/{name}")
await rf_widget.right_click()
await ui_test.select_context_menu(f"Expand/{name}")
async def test_default_prim(self):
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Clear Default Prim")
await rf_widget.right_click()
await ui_test.select_context_menu("Set as Default Prim")
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
ref_widget = stage_tree.find("**/Label[*].text=='reference0 (defaultPrim)'")
self.assertTrue(ref_widget)
ref_widget_old = stage_tree.find("**/Label[*].text=='reference0'")
self.assertFalse(ref_widget_old)
with self.assertRaises(Exception):
await ui_test.select_context_menu("Set as Default Prim")
await rf_widget.right_click()
await ui_test.select_context_menu("Clear Default Prim")
await self.wait()
ref_widget_old = stage_tree.find("**/Label[*].text=='reference0 (defaultPrim)'")
self.assertFalse(ref_widget_old)
ref_widget = stage_tree.find("**/Label[*].text=='reference0'")
self.assertTrue(ref_widget)
async def test_find_in_browser(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
# If there are no on-disk references
with self.assertRaises(Exception):
await ui_test.select_context_menu("Find in Content Browser")
# Adds a reference that's on disk.
self.ref_prim.GetReferences().ClearReferences()
self.ref_prim.GetReferences().AddReference(self._cube_usd_path)
await self.wait()
await rf_widget.right_click()
await ui_test.select_context_menu("Find in Content Browser")
async def test_group_selected(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath()), str(self.payload_prim.GetPath())], True
)
await self.wait()
old_ref_path = self.ref_prim.GetPath()
old_payload_path = self.payload_prim.GetPath()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Group Selected")
await self.wait()
new_ref_path = Sdf.Path("/Group").AppendElementString(old_ref_path.name)
new_payload_path = Sdf.Path("/Group").AppendElementString(old_payload_path.name)
self.assertFalse(self.stage.GetPrimAtPath(old_ref_path))
self.assertFalse(self.stage.GetPrimAtPath(old_payload_path))
self.assertTrue(self.stage.GetPrimAtPath(new_ref_path))
self.assertTrue(self.stage.GetPrimAtPath(new_payload_path))
self.usd_context.get_selection().set_selected_prim_paths(
[str(new_ref_path), str(new_payload_path)], True
)
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
ref_widget = stage_tree.find("**/Label[*].text=='reference0'")
self.assertTrue(ref_widget)
await rf_widget.right_click()
await ui_test.select_context_menu("Ungroup Selected")
await self.wait()
self.assertTrue(self.stage.GetPrimAtPath(old_ref_path))
self.assertTrue(self.stage.GetPrimAtPath(old_payload_path))
self.assertFalse(self.stage.GetPrimAtPath(new_ref_path))
self.assertFalse(self.stage.GetPrimAtPath(new_payload_path))
async def test_duplicate_prim(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath()), str(self.payload_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Duplicate")
self.assertTrue(self.stage.GetPrimAtPath("/reference0_01"))
self.assertTrue(self.stage.GetPrimAtPath("/payload0_01"))
async def test_delete_prim(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath()), str(self.payload_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Delete")
self.assertFalse(self.ref_prim)
self.assertFalse(self.payload_prim)
async def test_refresh_reference_or_payload(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Refresh Reference")
async def test_convert_between_ref_and_payload(self):
rf_widget, payload_widget, ref_and_payload_widget = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Convert Payloads to References")
await rf_widget.right_click()
await ui_test.select_context_menu("Convert References to Payloads")
ref_prim = self.stage.GetPrimAtPath("/reference0")
ref_and_layers = omni.usd.get_composed_references_from_prim(ref_prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(ref_prim)
self.assertTrue(len(ref_and_layers) == 0)
self.assertTrue(len(payload_and_layers) == 1)
await payload_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Convert References to Payloads")
await payload_widget.right_click()
await ui_test.select_context_menu("Convert Payloads to References")
payload_prim = self.stage.GetPrimAtPath("/payload0")
ref_and_layers = omni.usd.get_composed_references_from_prim(payload_prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(payload_prim)
self.assertTrue(len(ref_and_layers) == 1)
self.assertTrue(len(payload_and_layers) == 0)
await ref_and_payload_widget.right_click()
await ui_test.select_context_menu("Convert References to Payloads")
prim = self.stage.GetPrimAtPath("/reference_and_payload0")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim)
self.assertEqual(len(ref_and_layers), 0)
self.assertEqual(len(payload_and_layers), 1)
await ref_and_payload_widget.right_click()
await ui_test.select_context_menu("Convert Payloads to References")
prim = self.stage.GetPrimAtPath("/reference_and_payload0")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim)
self.assertEqual(len(ref_and_layers), 1)
self.assertEqual(len(payload_and_layers), 0)
async def test_select_bound_objects(self):
menu_name = "Select Bound Objects"
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu(menu_name)
material = UsdShade.Material.Define(self.stage, "/material0")
UsdShade.MaterialBindingAPI(self.payload_prim).Bind(material)
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
material_widget = stage_tree.find("**/Label[*].text=='material0'")
await material_widget.right_click()
await ui_test.select_context_menu(menu_name)
await self.wait()
self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), [str(self.payload_prim.GetPath())])
async def test_binding_material(self):
menu_name = "Bind Material To Selected Objects"
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu(menu_name)
material = UsdShade.Material.Define(self.stage, "/material0")
UsdShade.MaterialBindingAPI(self.payload_prim).Bind(material)
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
material_widget = stage_tree.find("**/Label[*].text=='material0'")
await material_widget.right_click()
# No valid selection
with self.assertRaises(Exception):
await ui_test.select_context_menu(menu_name)
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.payload_prim.GetPath())], True
)
await self.wait()
await material_widget.right_click()
await ui_test.select_context_menu(menu_name)
await self.wait()
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
self.assertEqual(selected_paths, [str(self.payload_prim.GetPath())])
async def test_set_kind(self):
rf_widget, _, _ = await self._find_all_prim_items()
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath())], True
)
await self.wait()
for name in ["Assembly", "Group", "Component", "Subcomponent"]:
await rf_widget.right_click()
await ui_test.select_context_menu(f"Set Kind/{name}")
async def test_lock_specs(self):
rf_widget, _, _ = await self._find_all_prim_items()
for menu_name in ["Lock Selected", "Unlock Selected", "Lock Selected Hierarchy", "Unlock Selected Hierarchy"]:
await rf_widget.right_click()
await ui_test.select_context_menu(f"Locks/{menu_name}")
await rf_widget.right_click()
await ui_test.select_context_menu("Locks/Lock Selected Hierarchy")
await rf_widget.right_click()
await ui_test.select_context_menu("Locks/Select Locked Prims")
await self.wait()
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
self.assertEqual(selected_paths, [str(self.ref_prim.GetPath()), str(self.child_prim.GetPath())])
async def test_assign_material(self):
menu_name = "Assign Material"
rf_widget, _, _ = await self._find_all_prim_items()
material = UsdShade.Material.Define(self.stage, "/material0")
UsdShade.MaterialBindingAPI(self.payload_prim).Bind(material)
await self.wait()
await rf_widget.right_click()
await ui_test.select_context_menu(menu_name)
dialog = ui_test.find("Bind material to reference0###context_menu_bind")
self.assertTrue(dialog)
button = dialog.find("**/Button[*].text=='Ok'")
self.assertTrue(button)
await button.click()
async def test_rename_prim(self):
await ui_test.find("Stage").focus()
menu_name = "Rename"
rf_widget, _, _ = await self._find_all_prim_items()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await rf_widget.right_click(rf_widget.center)
await ui_test.select_context_menu(menu_name)
await self.wait(10)
string_fields = stage_tree.find_all("**/StringField[*].identifier=='rename_field'")
self.assertTrue(len(string_fields) > 0)
string_field = string_fields[0]
# FIXME: Cannot make it visible in tests, but have to do it manually
string_field.widget.visible = True
await string_field.input("test")
self.assertTrue(self.stage.GetPrimAtPath("/reference0test"))
self.assertFalse(self.stage.GetPrimAtPath("/reference0"))
| 14,680 | Python | 42.95509 | 126 | 0.64673 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_stage.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 pathlib import Path
from omni.kit.widget.stage import StageWidget
from omni.kit.widget.stage.stage_icons import StageIcons
from omni.ui.tests.test_base import OmniUiTest
from pxr import Usd, UsdGeom
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading
import omni.kit.app
CURRENT_PATH = Path(__file__).parent
REPO_PATH = CURRENT_PATH
for i in range(10):
REPO_PATH = REPO_PATH.parent
BOWL_STAGE = REPO_PATH.joinpath("data/usd/tests/bowl.usd")
STYLE = {"Field": {"background_color": 0xFF24211F, "border_radius": 2}}
class TestStage(OmniUiTest):
# Before running each test
async def setUp(self):
await arrange_windows(hide_viewport=True)
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_general(self):
"""Testing general look of StageWidget"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.Open(f"{BOWL_STAGE}")
if not stage:
self.fail(f"Stage {BOWL_STAGE} doesn't exist")
return
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_visibility(self):
"""Testing visibility of StageWidget"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.CreateInMemory("test.usd")
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
UsdGeom.Mesh.Define(stage, "/A")
UsdGeom.Mesh.Define(stage, "/A/B")
UsdGeom.Mesh.Define(stage, "/C").MakeInvisible()
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_dynamic(self):
"""Testing the ability to watch the stage"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.CreateInMemory("test.usd")
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
UsdGeom.Mesh.Define(stage, "/A")
# Wait one frame to be sure other objects created after initialization
await omni.kit.app.get_app().next_update_async()
UsdGeom.Mesh.Define(stage, "/B")
mesh = UsdGeom.Mesh.Define(stage, "/C")
# Wait one frame to be sure other objects created after initialization
await omni.kit.app.get_app().next_update_async()
mesh.MakeInvisible()
UsdGeom.Mesh.Define(stage, "/D")
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_instanceable(self):
"""Testing the ability to watch the instanceable state"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.CreateInMemory("test.usd")
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
UsdGeom.Xform.Define(stage, "/A")
UsdGeom.Mesh.Define(stage, "/A/Shape")
prim = UsdGeom.Xform.Define(stage, "/B").GetPrim()
prim.GetReferences().AddInternalReference("/A")
# Wait one frame to be sure other objects created after initialization
await omni.kit.app.get_app().next_update_async()
stage_widget.expand("/B")
await omni.kit.app.get_app().next_update_async()
prim.SetInstanceable(True)
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
| 4,390 | Python | 30.141844 | 78 | 0.645103 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/drag_drop_multi.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
get_prims,
wait_stage_loading,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropFileStageMulti(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_multi_usd_stage(self):
from carb.input import KeyboardInput
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_window = ui_test.find("Stage")
await stage_window.focus()
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader'])
# drag/drop files to stage window
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 96)
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__)
await content_browser_helper.drag_and_drop_tree_view(
usd_path, names=["4Lights.usda", "quatCube.usda"], drag_target=drag_target)
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube'])
| 3,064 | Python | 49.245901 | 557 | 0.698107 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_header.py | import carb
import omni
import omni.kit.test
import omni.usd
import omni.client
import omni.kit.widget.stage
import omni.kit.app
import omni.kit.ui_test as ui_test
from omni.kit.test_suite.helpers import arrange_windows
from ..stage_model import StageItemSortPolicy
class TestHeader(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.app = omni.kit.app.get_app()
await arrange_windows("Stage", 800, 600)
async def tearDown(self):
pass
async def wait(self, frames=4):
for i in range(frames):
await self.app.next_update_async()
async def test_name_header(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
name_label = stage_tree.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (A to Z)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (Z to A)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (New to Old)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_label)
async def test_visibility_header(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
visibility_image = stage_tree.find("**/Image[*].name=='visibility_header'")
self.assertTrue(visibility_image)
await visibility_image.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE)
await visibility_image.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE)
await visibility_image.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
async def test_type_header(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
type_label = stage_tree.find("**/Label[*].text=='Type'")
self.assertTrue(type_label)
await type_label.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.TYPE_COLUMN_A_TO_Z)
await type_label.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.TYPE_COLUMN_Z_TO_A)
await type_label.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
| 3,679 | Python | 36.938144 | 121 | 0.660506 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/inspector_query.py | from typing import Optional, Union
import omni.ui as ui
import carb
class InspectorQuery:
def __init__(self) -> None:
pass
@classmethod
def child_widget(cls, widget: ui.Widget, predicate: str, last=False) -> Union[ui.Widget, None]:
adjusted_predicate = predicate
# when we don't have index we assume it is the first one
index = None
if "[" in adjusted_predicate:
index = int(adjusted_predicate.split("[")[-1].split("]")[0])
adjusted_predicate = adjusted_predicate.split("[")[0]
if last and index is None:
if widget.__class__.__name__ == adjusted_predicate:
return widget
else:
carb.log_warn(f"Widget {widget} is not matching predicate {adjusted_predicate}")
return None
if not widget.__class__.__name__ == adjusted_predicate:
carb.log_warn(f"Widget {widget} is not matching predicate {adjusted_predicate}")
return None
children = ui.Inspector.get_children(widget)
if not index:
index = 0
if index >= len(children):
carb.log_warn(f"Widget {widget} only as {len(children)}, asked for index {index}")
return None
return children[index]
@classmethod
def find_widget_path(cls, window: ui.Window, widget: ui.Widget) -> Union[str, None]:
def traverse_widget_tree_for_match(
location: ui.Widget, current_path: str, searched_widget: ui.Widget
) -> Union[str, None]:
current_index = 0
current_children = ui.Inspector.get_children(location)
for a_child in current_children:
class_name = a_child.__class__.__name__
if a_child == widget:
return f"{current_path}[{current_index}]/{class_name}"
if isinstance(a_child, ui.Container):
path = traverse_widget_tree_for_match(
a_child, f"{current_path}[{current_index}]/{class_name}", searched_widget
)
if path:
return path
current_index = current_index + 1
return None
if window:
start_path = f"{window.title}/Frame"
return traverse_widget_tree_for_match(window.frame, start_path, widget)
else:
return None
@classmethod
def find_menu_item(cls, query: str) -> Optional[ui.Widget]:
from omni.kit.mainwindow import get_main_window
main_menu_bar = get_main_window().get_main_menu_bar()
if not main_menu_bar:
carb.log_warn("Current App doesn't have a MainMenuBar")
return None
tokens = query.split("/")
current_children = main_menu_bar
for i in range(1, len(tokens)):
last = i == len(tokens) - 1
child = InspectorQuery.child_widget(current_children, tokens[i], last)
if not child:
carb.log_warn(f"Failed to find Child Widget at level {tokens[i]}")
return None
current_children = child
return current_children
@classmethod
def find_context_menu_item(cls, query: str, menu_root: ui.Menu) -> Optional[ui.Widget]:
menu_items = ui.Inspector.get_children(menu_root)
for menu_item in menu_items:
if isinstance(menu_item, ui.MenuItem):
if query in menu_item.text:
return menu_item
return None
@classmethod
def find_widget(cls, query: str) -> Union[ui.Widget, None]:
if not query:
return None
tokens = query.split("/")
window = ui.Workspace.get_window(tokens[0])
if not window:
carb.log_warn(f"Failed to find window: {tokens[0]}")
return None
if not isinstance(window, ui.Window):
carb.log_warn(f"window: {tokens[0]} is not a ui.Window, query only work on ui.Window")
return None
if not (tokens[1] == "Frame" or tokens[1] == "Frame[0]"):
carb.log_warn("Query currently only Support '<WindowName>/Frame/* or <WindowName>/Frame[0]/ type of query")
return None
frame = window.frame
if len(tokens) == 2:
return frame
if tokens[-1] == "":
tokens = tokens[:-1]
current_children = ui.Inspector.get_children(frame)[0]
for i in range(2, len(tokens)):
last = i == len(tokens) - 1
child = InspectorQuery.child_widget(current_children, tokens[i], last)
if not child:
carb.log_warn(f"Failed to find Child Widget at level {tokens[i]}")
return None
current_children = child
return current_children
| 4,854 | Python | 33.928057 | 119 | 0.559333 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/delegates/type_column_delegate.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__ = ["TypeColumnDelegate"]
from ..abstract_stage_column_delegate import AbstractStageColumnDelegate
from ..stage_model import StageModel, StageItemSortPolicy
from ..stage_item import StageItem
from typing import List
from enum import Enum
import omni.ui as ui
class TypeColumnSortPolicy(Enum):
DEFAULT = 0
A_TO_Z = 1
Z_TO_A = 2
class TypeColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the type column"""
def __init__(self):
super().__init__()
self.__name_label_layout = None
self.__name_label = None
self.__items_sort_policy = TypeColumnSortPolicy.DEFAULT
self.__stage_model: StageModel = None
def destroy(self):
if self.__name_label_layout:
self.__name_label_layout.set_mouse_pressed_fn(None)
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(100)
def __initialize_policy_from_model(self):
stage_model = self.__stage_model
if not stage_model:
return
if stage_model.get_items_sort_policy() == StageItemSortPolicy.TYPE_COLUMN_A_TO_Z:
self.__items_sort_policy = TypeColumnSortPolicy.A_TO_Z
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.TYPE_COLUMN_Z_TO_A:
self.__items_sort_policy = TypeColumnSortPolicy.Z_TO_A
else:
self.__items_sort_policy = TypeColumnSortPolicy.DEFAULT
self.__update_label_from_policy()
def __update_label_from_policy(self):
if not self.__name_label:
return
if self.__name_label:
if self.__items_sort_policy == TypeColumnSortPolicy.A_TO_Z:
name = "Type (A to Z)"
elif self.__items_sort_policy == TypeColumnSortPolicy.Z_TO_A:
name = "Type (Z to A)"
else:
name = "Type"
self.__name_label.text = name
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == TypeColumnSortPolicy.A_TO_Z:
stage_model.set_items_sort_policy(StageItemSortPolicy.TYPE_COLUMN_A_TO_Z)
elif self.__items_sort_policy == TypeColumnSortPolicy.Z_TO_A:
stage_model.set_items_sort_policy(StageItemSortPolicy.TYPE_COLUMN_Z_TO_A)
else:
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
self.__update_label_from_policy()
def __on_name_label_clicked(self, x, y, b, m):
stage_model = self.__stage_model
if b != 0 or not stage_model:
return
if self.__items_sort_policy == TypeColumnSortPolicy.A_TO_Z:
self.__items_sort_policy = TypeColumnSortPolicy.Z_TO_A
elif self.__items_sort_policy == TypeColumnSortPolicy.Z_TO_A:
self.__items_sort_policy = TypeColumnSortPolicy.DEFAULT
else:
self.__items_sort_policy = TypeColumnSortPolicy.A_TO_Z
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
stage_model = kwargs.get("stage_model", None)
self.__stage_model = stage_model
if stage_model:
self.__name_label_layout = ui.HStack()
with self.__name_label_layout:
ui.Spacer(width=10)
self.__name_label = ui.Label(
"Type", name="columnname", style_type_name_override="TreeView.Header"
)
self.__initialize_policy_from_model()
self.__name_label_layout.set_mouse_pressed_fn(self.__on_name_label_clicked)
else:
self.__name_label_layout.set_mouse_pressed_fn(None)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("Type", name="columnname", style_type_name_override="TreeView.Header")
async def build_widget(self, _, **kwargs):
"""Build the type widget"""
item = kwargs.get("stage_item", None)
if not item or not item.stage:
return
prim = item.stage.GetPrimAtPath(item.path)
if not prim or not prim.IsValid():
return
with ui.HStack(enabled=not item.instance_proxy, spacing=4, height=20):
ui.Spacer(width=4)
ui.Label(item.type_name, width=0, name="object_name", style_type_name_override="TreeView.Item")
def on_stage_items_destroyed(self, items: List[StageItem]):
pass
@property
def sortable(self):
return True
@property
def order(self):
return -100
@property
def minimum_width(self):
return ui.Pixel(20)
| 5,139 | Python | 33.039735 | 107 | 0.616852 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/delegates/visibility_column_delegate.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__ = ["VisibilityColumnDelegate"]
from ..abstract_stage_column_delegate import AbstractStageColumnDelegate
from ..stage_model import StageModel, StageItemSortPolicy
from ..stage_item import StageItem
from pxr import UsdGeom
from typing import List
from functools import partial
from enum import Enum
import weakref
import omni.ui as ui
class VisibilityColumnSortPolicy(Enum):
DEFAULT = 0
INVISIBLE_TO_VISIBLE = 1
VISIBLE_TO_INVISIBLE = 2
class VisibilityColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the visibility column"""
def __init__(self):
super().__init__()
self.__visibility_layout = None
self.__items_sort_policy = VisibilityColumnSortPolicy.DEFAULT
self.__stage_model: StageModel = None
def destroy(self):
if self.__visibility_layout:
self.__visibility_layout.set_mouse_pressed_fn(None)
self.__visibility_layout = None
self.__stage_model = None
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(24)
def __initialize_policy_from_model(self):
stage_model = self.__stage_model
if not stage_model:
return
if stage_model.get_items_sort_policy() == StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE
else:
self.__items_sort_policy = VisibilityColumnSortPolicy.DEFAULT
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE:
stage_model.set_items_sort_policy(StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE)
elif self.__items_sort_policy == VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE:
stage_model.set_items_sort_policy(StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE)
else:
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
def __on_visiblity_clicked(self, x, y, b, m):
if b != 0 or not self.__stage_model:
return
if self.__items_sort_policy == VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE
elif self.__items_sort_policy == VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.DEFAULT
else:
self.__items_sort_policy = VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
stage_model = kwargs.get("stage_model", None)
self.__stage_model = stage_model
self.__initialize_policy_from_model()
if stage_model:
with ui.ZStack():
ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header")
self.__visibility_layout = ui.HStack()
with self.__visibility_layout:
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="visibility_header", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
self.__visibility_layout.set_mouse_pressed_fn(self.__on_visiblity_clicked)
else:
with ui.HStack():
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="visibility_header", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
async def build_widget(self, _, **kwargs):
"""Build the eye widget"""
item = kwargs.get("stage_item", None)
if not item or not item.prim or not item.prim.IsA(UsdGeom.Imageable):
return
with ui.ZStack(height=20):
# Min size
ui.Spacer(width=22)
# TODO the way to make this widget grayed out
ui.ToolButton(item.visibility_model, enabled=not item.instance_proxy, name="visibility")
@property
def order(self):
# Ensure it's always to the leftmost column except the name column.
return -101
@property
def sortable(self):
return True
def on_stage_items_destroyed(self, items: List[StageItem]):
pass
@property
def minimum_width(self):
return ui.Pixel(20)
| 5,352 | Python | 36.964539 | 123 | 0.640882 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/delegates/name_column_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["NameColumnDelegate"]
import asyncio
import math
import omni.ui as ui
from ..abstract_stage_column_delegate import AbstractStageColumnDelegate
from ..stage_model import StageModel, StageItemSortPolicy
from ..stage_item import StageItem
from ..stage_icons import StageIcons
from functools import partial
from typing import List
from enum import Enum
class NameColumnSortPolicy(Enum):
NEW_TO_OLD = 0
OLD_TO_NEW = 1
A_TO_Z = 2
Z_TO_A = 3
def split_selection(text, selection):
"""
Split given text to substrings to draw selected text. Result starts with unselected text.
Example: "helloworld" "o" -> ["hell", "o", "w", "o", "rld"]
Example: "helloworld" "helloworld" -> ["", "helloworld"]
"""
if not selection or text == selection:
return ["", text]
selection = selection.lower()
selection_len = len(selection)
result = []
while True:
found = text.lower().find(selection)
result.append(text if found < 0 else text[:found])
if found < 0:
break
else:
result.append(text[found : found + selection_len])
text = text[found + selection_len :]
return result
class NameColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the type column"""
def __init__(self):
super().__init__()
self.__name_label_layout = None
self.__name_label = None
self.__drop_down_layout = None
self.__name_sort_options_menu = None
self.__items_sort_policy = NameColumnSortPolicy.OLD_TO_NEW
self.__highlighting_enabled = None
# Text that is highlighted in flat mode
self.__highlighting_text = None
self.__stage_model: StageModel = None
def set_highlighting(self, enable: bool = None, text: str = None):
"""
Specify if the widgets should consider highlighting. Also set the text that should be highlighted in flat mode.
"""
if enable is not None:
self.__highlighting_enabled = enable
if text is not None:
self.__highlighting_text = text.lower()
@property
def sort_policy(self):
return self.__items_sort_policy
@sort_policy.setter
def sort_policy(self, value):
if self.__items_sort_policy != value:
self.__items_sort_policy = value
self.__on_policy_changed()
def destroy(self):
if self.__name_label_layout:
self.__name_label_layout.set_mouse_pressed_fn(None)
if self.__drop_down_layout:
self.__drop_down_layout.set_mouse_pressed_fn(None)
self.__drop_down_layout = None
self.__name_sort_options_menu = None
if self.__name_label_layout:
self.__name_label_layout.set_mouse_pressed_fn(None)
self.__name_label_layout = None
self.__stage_model = None
@property
def initial_width(self):
"""The width of the column"""
return ui.Fraction(1)
def __initialize_policy_from_model(self):
stage_model = self.__stage_model
if not stage_model:
return
if stage_model.get_items_sort_policy() == StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD:
self.__items_sort_policy = NameColumnSortPolicy.NEW_TO_OLD
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.NAME_COLUMN_A_TO_Z:
self.__items_sort_policy = NameColumnSortPolicy.A_TO_Z
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.NAME_COLUMN_Z_TO_A:
self.__items_sort_policy = NameColumnSortPolicy.Z_TO_A
else:
self.__items_sort_policy = NameColumnSortPolicy.OLD_TO_NEW
self.__update_label_from_policy()
def __update_label_from_policy(self):
if not self.__name_label:
return
if self.__items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD:
name = "Name (New to Old)"
elif self.__items_sort_policy == NameColumnSortPolicy.A_TO_Z:
name = "Name (A to Z)"
elif self.__items_sort_policy == NameColumnSortPolicy.Z_TO_A:
name = "Name (Z to A)"
else:
name = "Name (Old to New)"
self.__name_label.text = name
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD)
elif self.__items_sort_policy == NameColumnSortPolicy.A_TO_Z:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_A_TO_Z)
elif self.__items_sort_policy == NameColumnSortPolicy.Z_TO_A:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_Z_TO_A)
else:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_OLD_TO_NEW)
self.__update_label_from_policy()
def __on_name_label_clicked(self, x, y, b, m):
if b != 0 or not self.__stage_model:
return
if self.__items_sort_policy == NameColumnSortPolicy.A_TO_Z:
self.__items_sort_policy = NameColumnSortPolicy.Z_TO_A
elif self.__items_sort_policy == NameColumnSortPolicy.Z_TO_A:
self.__items_sort_policy = NameColumnSortPolicy.NEW_TO_OLD
elif self.__items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD:
self.__items_sort_policy = NameColumnSortPolicy.OLD_TO_NEW
else:
self.__items_sort_policy = NameColumnSortPolicy.A_TO_Z
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
style_type_name = "TreeView.Header"
stage_model = kwargs.get("stage_model", None)
self.__stage_model = stage_model
if stage_model:
with ui.HStack():
self.__name_label_layout = ui.HStack()
self.__name_label_layout.set_mouse_pressed_fn(self.__on_name_label_clicked)
with self.__name_label_layout:
ui.Spacer(width=10)
self.__name_label = ui.Label(
"Name", name="columnname", style_type_name_override=style_type_name
)
self.__initialize_policy_from_model()
ui.Spacer()
with ui.ZStack(width=16):
ui.Rectangle(name="drop_down_hovered_area", style_type_name_override=style_type_name)
self.__drop_down_layout = ui.ZStack(width=0)
with self.__drop_down_layout:
ui.Rectangle(width=16, name="drop_down_background", style_type_name_override=style_type_name)
with ui.HStack():
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer(height=4)
ui.Triangle(
name="drop_down_button",
width=8, height=8,
style_type_name_override=style_type_name,
alignment=ui.Alignment.CENTER_BOTTOM
)
ui.Spacer(height=2)
ui.Spacer()
ui.Spacer(width=4)
def on_sort_policy_changed(policy, value):
if self.sort_policy != policy:
self.sort_policy = policy
self.__on_policy_changed()
def on_mouse_pressed_fn(x, y, b, m):
if b != 0:
return
items_sort_policy = self.__items_sort_policy
self.__name_sort_options_menu = ui.Menu("Sort Options")
with self.__name_sort_options_menu:
ui.MenuItem("Sort By", enabled=False)
ui.Separator()
ui.MenuItem(
"New to Old",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.NEW_TO_OLD
),
hide_on_click=False,
)
ui.MenuItem(
"Old to New",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.OLD_TO_NEW,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.OLD_TO_NEW
),
hide_on_click=False,
)
ui.MenuItem(
"A to Z",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.A_TO_Z,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.A_TO_Z
),
hide_on_click=False
)
ui.MenuItem(
"Z to A",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.Z_TO_A,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.Z_TO_A
),
hide_on_click=False
)
self.__name_sort_options_menu.show()
self.__drop_down_layout.set_mouse_pressed_fn(on_mouse_pressed_fn)
self.__drop_down_layout.visible = False
else:
self.__name_label_layout.set_mouse_pressed_fn(None)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("Name", name="columnname", style_type_name_override="TreeView.Header")
def get_type_icon(self, node_type):
"""Convert USD Type to icon file name"""
icons = StageIcons()
if node_type in ["DistantLight", "SphereLight", "RectLight", "DiskLight", "CylinderLight", "DomeLight"]:
return icons.get(node_type, "Light")
if node_type == "":
node_type = "Xform"
return icons.get(node_type, "Prim")
async def build_widget(self, _, **kwargs):
self.build_widget_async(_, **kwargs)
def __get_all_icons_to_draw(self, item: StageItem, item_is_native):
# Get the node type
node_type = item.type_name if item != item.stage_model.root else None
icon_filenames = [self.get_type_icon(node_type)]
# Get additional icons based on the properties of StageItem
if item_is_native:
if item.references:
icon_filenames.append(StageIcons().get("Reference"))
if item.payloads:
icon_filenames.append(StageIcons().get("Payload"))
if item.instanceable:
icon_filenames.append(StageIcons().get("Instance"))
return icon_filenames
def __draw_all_icons(self, item: StageItem, item_is_native, is_highlighted):
icon_filenames = self.__get_all_icons_to_draw(item, item_is_native)
# Gray out the icon if the filter string is not in the text
iconname = "object_icon" if is_highlighted else "object_icon_grey"
parent_layout = ui.ZStack(width=20, height=20)
with parent_layout:
for icon_filename in icon_filenames:
ui.Image(icon_filename, name=iconname, style_type_name_override="TreeView.Image")
if item.instance_proxy:
parent_layout.set_tooltip("Instance Proxy")
def __build_rename_field(self, item: StageItem, name_labels, parent_stack):
def on_end_edit(name_labels, field):
for label in name_labels:
label.visible = True
field.visible = False
self.end_edit_subscription = None
def on_mouse_double_clicked(button, name_labels, field):
if button != 0 or item.instance_proxy:
return
for label in name_labels:
label.visible = False
field.visible = True
self.end_edit_subscription = field.model.subscribe_end_edit_fn(lambda _: on_end_edit(name_labels, field))
import omni.kit.app
async def focus(field):
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard()
asyncio.ensure_future(focus(field))
field = ui.StringField(item.name_model, identifier="rename_field", visible=False)
parent_stack.set_mouse_double_clicked_fn(
lambda x, y, b, _: on_mouse_double_clicked(b, name_labels, field)
)
item._ui_widget = parent_stack
def build_widget_sync(self, _, **kwargs):
"""Build the type widget"""
# True if it's StageItem. We need it to determine if it's a Root item (which is None).
model = kwargs.get("stage_model", None)
item = kwargs.get("stage_item", None)
if not item:
item = model.root
item_is_native = False
else:
item_is_native = True
if not item:
return
# If highlighting disabled completley, all the items should be light
is_highlighted = not self.__highlighting_enabled and not self.__highlighting_text
if not is_highlighted:
# If it's not disabled completley
is_highlighted = item_is_native and item.filtered
with ui.HStack(enabled=not item.instance_proxy, spacing=4, height=20):
# Draw all icons on top of each other
self.__draw_all_icons(item, item_is_native, is_highlighted)
value_model = item.name_model
text = value_model.get_value_as_string()
stack = ui.HStack()
name_labels = []
# We have three different text draw model depending on the column and on the highlighting state
if item_is_native and model.flat:
# Flat search mode. We need to highlight only the part that is is the search field
selection_chain = split_selection(text, self.__highlighting_text)
labelnames_chain = ["object_name_grey", "object_name"]
# Extend the label names depending on the size of the selection chain. Example, if it was [a, b]
# and selection_chain is [z,y,x,w], it will become [a, b, a, b].
labelnames_chain *= int(math.ceil(len(selection_chain) / len(labelnames_chain)))
with stack:
for current_text, current_name in zip(selection_chain, labelnames_chain):
if not current_text:
continue
label = ui.Label(
current_text,
name=current_name,
width=0,
style_type_name_override="TreeView.Item",
hide_text_after_hash=False
)
name_labels.append(label)
if hasattr(item, "_callback_id"):
item._callback_id = None
else:
with stack:
if item.has_missing_references:
name = "object_name_missing"
else:
name = "object_name" if is_highlighted else "object_name_grey"
if item.is_outdated:
name = "object_name_outdated"
if item.in_session:
name = "object_name_live"
if item.is_outdated:
style_override = "TreeView.Item.Outdated"
elif item.in_session:
style_override = "TreeView.Item.Live"
else:
style_override = "TreeView.Item"
text = value_model.get_value_as_string()
if item.is_default:
text += " (defaultPrim)"
label = ui.Label(
text, hide_text_after_hash=False,
name=name, style_type_name_override=style_override
)
if item.has_missing_references:
label.set_tooltip("Missing references found.")
name_labels.append(label)
# The hidden field for renaming the prim
if item != model.root and not item.instance_proxy:
self.__build_rename_field(item, name_labels, stack)
elif hasattr(item, "_ui_widget"):
item._ui_widget = None
def rename_item(self, item: StageItem):
if not item or not hasattr(item, "_ui_widget") or not item._ui_widget or item.instance_proxy:
return
item._ui_widget.call_mouse_double_clicked_fn(0, 0, 0, 0)
def on_stage_items_destroyed(self, items: List[StageItem]):
for item in items:
if hasattr(item, "_ui_widget"):
item._ui_widget = None
def on_header_hovered(self, hovered):
self.__drop_down_layout.visible = hovered
@property
def sortable(self):
return True
@property
def order(self):
return -100000
@property
def minimum_width(self):
return ui.Pixel(40)
| 18,548 | Python | 38.050526 | 119 | 0.537578 |
omniverse-code/kit/exts/omni.kit.widget.stage/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [2.7.24] - 2023-02-21
### Fixed
- OM-82577: Drag&drop of flowusd presets will call flowusd command to add a reference.
## [2.7.23] - 2023-02-16
### Fixed
- OM-81767: Drag&drop behaviour of sbsar files now consistent with viewport's behaviour.
## [2.7.22] - 2023-01-11
### Updated
- Allow to select children under instance.
- Fix selection issue after clearing search text.
- Move SelectionWatch from omni.kit.window.stage to provide default implementation.
## [2.7.21] - 2022-12-9
### Updated
- Fixed issue where drag & drop material urls with encoded subidentifiers were not being handled.
## [2.7.20] - 2022-12-14
### Updated
- Improve drag and drop style.
## [2.7.19] - 2022-12-09
### Updated
- Improve filter and search.
- Fix issue that creates new prims will not be filtered when it's in filtering mode.
- Add support to search with prim path.
## [2.7.18] - 2022-12-08
### Updated
- Fix style of search results in stage window.
## [2.7.17] - 2022-11-29
### Updated
- Don't show context menu for converting references or payloads if they are not in the local layer stack.
## [2.7.16] - 2022-11-29
### Updated
- Don't show context menu for header of stage widget.
## [2.7.15] - 2022-11-15
### Updated
- Fixed issue with context menu & not hovering over label
## [2.7.14] - 2022-11-14
### Updated
- Supports sorting by name/visibility/type.
## [2.7.13] - 2022-11-14
### Updated
- Fix issue to search or filter stage window.
## [2.7.12] - 2022-11-07
### Updated
- Optimize more loading time to avoid populating tree item when it's to get children count.
## [2.7.11] - 2022-11-04
### Updated
- Refresh prim handle when it's resyced to avoid access staled prim.
## [2.7.10] - 2022-11-03
### Updated
- Support to show 'displayName' of prim from metadata.
## [2.7.9] - 2022-11-02
### Updated
- Drag and drop assets to default prim from content browser if default prim is existed.
## [2.7.8] - 2022-11-01
### Updated
- Fix rename issue.
## [2.7.7] - 2022-10-25
### Updated
- More optimization to stage window refresh without traversing.
## [2.7.6] - 2022-09-13
### Updated
- Don't use "use_hovered" for context menu objects when user click nowhere
## [2.7.5] - 2022-09-10
- Add TreeView drop style to show hilighting.
## [2.7.4] - 2022-09-08
### Updated
- Added "use_hovered" to context menu objects so menu can create child prims
## [2.7.3] - 2022-08-31
### Fixed
- Moved eye icon to front of ZStack to receive mouse clicks.
## [2.7.2] - 2022-08-12
### Fixed
- Updated context menu behaviour
## [2.7.1] - 2022-08-13
- Fix prims filter.
- Clear prims filter after stage switching.
## [2.7.0] - 2022-08-06
- Refactoring stage model to improve perf and fix issue of refresh.
## [2.6.26] - 2022-08-04
- Support multi-selection for toggling visibility
## [2.6.25] - 2022-08-02
### Fixed
- Show non-defined prims as well.
## [2.6.24] - 2022-07-28
### Fixed
- Fix regression to drag and drop prim to absolute root.
## [2.6.23] - 2022-07-28
### Fixed
- Ensure rename operation non-destructive.
## [2.6.23] - 2022-07-25
### Changes
- Refactored unittests to make use of content_browser test helpers
## [2.6.22] - 2022-07-18
### Fixed
- Restored the arguments of ExportPrimUSD
## [2.6.21] - 2022-07-05
- Replaced filepicker dialog with file exporter
## [2.6.20] - 2022-06-23
- Make material paths relative if "/persistent/app/material/dragDropMaterialPath" is set to "relative"
## [2.6.19] - 2022-06-22
- Multiple drag and drop support.
## [2.6.18] - 2022-05-31
- Changed "Export Selected" to "Save Selected"
## [2.6.17] - 2022-05-20
- Support multi-selection for toggling visibility
## [2.6.16] - 2022-05-17
- Support multi-file drag & drop
## [2.6.15] - 2022-04-28
- Drag & Drop can create payload or reference based on /persistent/app/stage/dragDropImport setting
## [2.6.14] - 2022-03-09
- Updated unittests to retrieve the treeview widget from content browser.
## [2.6.13] - 2022-03-07
- Expand default prim
## [2.6.12] - 2022-02-09
- Fix stage window refresh after sublayer is inserted/removed.
## [2.6.11] - 2022-01-26
- Fix the columns item not able to reorder
## [2.6.10] - 2022-01-05
- Support drag/drop from material browser
## [2.6.9] - 2021-11-03
- Updated to use new omni.kit.material.library `get_subidentifier_from_mdl`
## [2.6.8] - 2021-09-24
- Fix export selected prims if it has external dependences outside of the copy prim tree.
## [2.6.7] - 2021-09-17
- Copy axis after export selected prims.
## [2.6.6] - 2021-08-11
- Updated drag/drop material to no-prim to not bind to /World
- Added drag/drop test
## [2.6.5] - 2021-08-11
- Updated to lastest omni.kit.material.library
## [2.6.4] - 2021-07-26
- Added "Refesh Payload" to context menu
- Added Payload icon
- Added "Convert Payloads to References" to context menu
- Added "Convert References to Payloads" to context menu
## [2.6.3] - 2021-07-21
- Added "Refesh Reference" to context menu
## [2.6.2] - 2021-06-30
- Changed "Assign Material" to use async show function as it could be slow on large scenes
## [2.6.1] - 2021-06-02
- Changed export prim as usd, postfix name now lowercase
## [2.6.0] - 2021-06-16
### Added
- "Show Missing Reference" that is off by default. When it's on, missing
references are displayed with red color in the tree.
### Changed
- Indentation level. There is no offset on the left anymore.
## [2.5.0] - 2021-06-02
- Added export prim as usd
## [2.4.2] - 2021-04-29
- Use sub-material selector on material import
## [2.4.1] - 2021-04-09
### Fixed
- Context menu in extensions that are not omni.kit.window.stage
## [2.4.0] - 2021-03-19
### Added
- Supported accepting drag and drop to create versioned reference.
## [2.3.7] - 2021-03-17
### Changed
- Updated to new context_menu and how custom functions are added
## [2.3.6] - 2021-03-01
### Changed
- Additional check if the stage and prim are still valid
## [2.3.5] - 2021-02-23
### Added
- Exclusion list allows to hide prims of specific types silently. To hide the
prims of specific type, set the string array setting
`ext/omni.kit.widget.stage/exclusion/types`
```
[settings]
ext."omni.kit.widget.stage".exclusion.types = ["Mesh"]
```
## [2.3.4] - 2021-02-10
### Changes
- Updated StyleUI handling
## [2.3.3] - 2020-11-16
### Changed
- Updated Find In Browser
## [2.3.2] - 2020-11-13
### Changed
- Fixed disappearing the "eye" icon when searched objects are toggled off
## [2.3.1] - 2020-10-22
### Added
- An interface to add and remove the icons in the TreeView dependin on the prim type
### Removed
- The standard prim icons are moved to omni.kit.widget.stage_icons
## [2.3.0] - 2020-09-16
### Changed
- Split to two parts: omni.kit.widget.stage and omni.kit.window.stage
## [2.2.0] - 2020-09-15
### Changed - Detached from Editor and using UsdNotice for notifications
| 6,926 | Markdown | 25.438931 | 105 | 0.6838 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/omni/kit/test_suite/layout/tests/__init__.py | from .compare_layout import *
from .verify_dockspace import *
| 62 | Python | 19.999993 | 31 | 0.774194 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/omni/kit/test_suite/layout/tests/verify_dockspace.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import carb
import omni.kit.test
import omni.kit.app
import omni.ui as ui
import omni.kit.commands
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows
class VerifyDockspace(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 256)
await omni.usd.get_context().new_stage_async()
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere", select_new_prim=True)
# After running each test
async def tearDown(self):
pass
async def test_verify_dockspace(self):
# verify "Dockspace" window doesn't disapear when a prim is selected as this breaks layout load/save
omni.usd.get_context().get_selection().set_selected_prim_paths([], True)
await ui_test.human_delay(100)
self.assertNotEqual(ui.Workspace.get_window("DockSpace"), None)
omni.usd.get_context().get_selection().set_selected_prim_paths(["/Sphere"], True)
await ui_test.human_delay(100)
self.assertNotEqual(ui.Workspace.get_window("DockSpace"), None)
async def test_verify_dockspace_shutdown(self):
self._hooks = []
self._hooks.append(omni.kit.app.get_app().get_shutdown_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.POST_QUIT_EVENT_TYPE,
self._on_shutdown_handler,
name="omni.create.app.setup shutdown for layout",
order=0))
omni.usd.get_context().get_selection().set_selected_prim_paths(["/Sphere"], True)
await ui_test.human_delay(100)
def _on_shutdown_handler(self, e: carb.events.IEvent):
# verify "Dockspace" window hasn't disapeared as prims are selected as this breaks layout load/save
print("running _on_shutdown_handler test")
self.assertNotEqual(ui.Workspace.get_window("DockSpace"), None)
| 2,418 | Python | 42.981817 | 113 | 0.702233 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/omni/kit/test_suite/layout/tests/compare_layout.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.ui as ui
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows
from omni.kit.quicklayout import QuickLayout
from omni.ui.workspace_utils import CompareDelegate
class CompareLayout(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 256)
# After running each test
async def tearDown(self):
pass
async def test_compare_layout(self):
layout_path = get_test_data_path(__name__, "layout.json")
# compare layout, this should fail
result = QuickLayout.compare_file(layout_path)
self.assertNotEqual(result, [])
# load layout
QuickLayout.load_file(layout_path)
# need to pause as load_file does some async stuff
await ui_test.human_delay(10)
# compare layout, this should pass
result = QuickLayout.compare_file(layout_path)
self.assertEqual(result, [])
async def test_compare_layout_delegate(self):
called_delegate = False
layout_path = get_test_data_path(__name__, "layout.json")
class TestCompareDelegate(CompareDelegate):
def failed_get_window(self, error_list: list, target: dict):
nonlocal called_delegate
called_delegate = True
return super().failed_get_window(error_list, target)
def failed_window_key(self, error_list: list, key: str, target: dict, target_window: ui.Window):
nonlocal called_delegate
called_delegate = True
return super().failed_window_key(error_list, key, target, target_window)
def failed_window_value(self, error_list: list, key: str, value, target: dict, target_window: ui.Window):
nonlocal called_delegate
called_delegate = True
return super().failed_window_value(error_list, key, value, target, target_window)
def compare_value(self, key:str, value, target):
nonlocal called_delegate
called_delegate = True
return super().compare_value(key, value, target)
self.assertFalse(called_delegate)
# compare layout, this should fail
result = QuickLayout.compare_file(layout_path, compare_delegate=TestCompareDelegate())
self.assertNotEqual(result, [])
# load layout
QuickLayout.load_file(layout_path)
# need to pause as load_file does some async stuff
await ui_test.human_delay(10)
# compare layout, this should pass
result = QuickLayout.compare_file(layout_path, compare_delegate=TestCompareDelegate())
self.assertEqual(result, [])
self.assertTrue(called_delegate)
| 3,328 | Python | 36.829545 | 117 | 0.666166 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/docs/index.rst | omni.kit.test_suite.layout
############################
layout tests
.. toctree::
:maxdepth: 1
CHANGELOG
| 114 | reStructuredText | 10.499999 | 28 | 0.508772 |
omniverse-code/kit/exts/omni.resourcemonitor/config/extension.toml | [package]
title = "Resource Monitor"
description = "Monitor utility for device and host memory"
authors = ["NVIDIA"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
category = "Internal"
preview_image = "data/preview.png"
icon = "data/icon.png"
version = "1.0.0"
[dependencies]
"omni.kit.renderer.core" = {}
"omni.kit.window.preferences" = {}
[[python.module]]
name = "omni.resourcemonitor"
[[native.plugin]]
path = "bin/*.plugin"
# Additional python module with tests, to make them discoverable by test system
[[python.module]]
name = "omni.resourcemonitor.tests"
[[test]]
timeout = 300
| 603 | TOML | 20.571428 | 79 | 0.713101 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/_resourceMonitor.pyi | """pybind11 omni.resourcemonitor bindings"""
from __future__ import annotations
import omni.resourcemonitor._resourceMonitor
import typing
import carb.events._events
__all__ = [
"IResourceMonitor",
"ResourceMonitorEventType",
"acquire_resource_monitor_interface",
"deviceMemoryWarnFractionSettingName",
"deviceMemoryWarnMBSettingName",
"hostMemoryWarnFractionSettingName",
"hostMemoryWarnMBSettingName",
"release_resource_monitor_interface",
"sendDeviceMemoryWarningSettingName",
"sendHostMemoryWarningSettingName",
"timeBetweenQueriesSettingName"
]
class IResourceMonitor():
def get_available_device_memory(self, arg0: int) -> int: ...
def get_available_host_memory(self) -> int: ...
def get_event_stream(self) -> carb.events._events.IEventStream: ...
def get_total_device_memory(self, arg0: int) -> int: ...
def get_total_host_memory(self) -> int: ...
pass
class ResourceMonitorEventType():
"""
ResourceMonitor notification.
Members:
DEVICE_MEMORY
HOST_MEMORY
LOW_DEVICE_MEMORY
LOW_HOST_MEMORY
"""
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
"""
DEVICE_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.DEVICE_MEMORY: 0>
HOST_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.HOST_MEMORY: 1>
LOW_DEVICE_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.LOW_DEVICE_MEMORY: 2>
LOW_HOST_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.LOW_HOST_MEMORY: 3>
__members__: dict # value = {'DEVICE_MEMORY': <ResourceMonitorEventType.DEVICE_MEMORY: 0>, 'HOST_MEMORY': <ResourceMonitorEventType.HOST_MEMORY: 1>, 'LOW_DEVICE_MEMORY': <ResourceMonitorEventType.LOW_DEVICE_MEMORY: 2>, 'LOW_HOST_MEMORY': <ResourceMonitorEventType.LOW_HOST_MEMORY: 3>}
pass
def acquire_resource_monitor_interface(plugin_name: str = None, library_path: str = None) -> IResourceMonitor:
pass
def release_resource_monitor_interface(arg0: IResourceMonitor) -> None:
pass
deviceMemoryWarnFractionSettingName = '/persistent/resourcemonitor/deviceMemoryWarnFraction'
deviceMemoryWarnMBSettingName = '/persistent/resourcemonitor/deviceMemoryWarnMB'
hostMemoryWarnFractionSettingName = '/persistent/resourcemonitor/hostMemoryWarnFraction'
hostMemoryWarnMBSettingName = '/persistent/resourcemonitor/hostMemoryWarnMB'
sendDeviceMemoryWarningSettingName = '/persistent/resourcemonitor/sendDeviceMemoryWarning'
sendHostMemoryWarningSettingName = '/persistent/resourcemonitor/sendHostMemoryWarning'
timeBetweenQueriesSettingName = '/persistent/resourcemonitor/timeBetweenQueries'
| 3,333 | unknown | 40.674999 | 288 | 0.712571 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/scripts/extension.py | import omni.ext
from .._resourceMonitor import *
class PublicExtension(omni.ext.IExt):
def on_startup(self):
self._resourceMonitor = acquire_resource_monitor_interface()
def on_shutdown(self):
release_resource_monitor_interface(self._resourceMonitor)
| 277 | Python | 26.799997 | 68 | 0.729242 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/scripts/resource_monitor_page.py | import omni.ui as ui
from omni.kit.window.preferences import PreferenceBuilder, SettingType
from .. import _resourceMonitor
class ResourceMonitorPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Resource Monitor")
def build(self):
""" Resource Monitor """
with ui.VStack(height=0):
with self.add_frame("Resource Monitor"):
with ui.VStack():
self.create_setting_widget(
"Time Between Queries",
_resourceMonitor.timeBetweenQueriesSettingName,
SettingType.FLOAT,
)
self.create_setting_widget(
"Send Device Memory Warnings",
_resourceMonitor.sendDeviceMemoryWarningSettingName,
SettingType.BOOL,
)
self.create_setting_widget(
"Device Memory Warning Threshold (MB)",
_resourceMonitor.deviceMemoryWarnMBSettingName,
SettingType.INT,
)
self.create_setting_widget(
"Device Memory Warning Threshold (Fraction)",
_resourceMonitor.deviceMemoryWarnFractionSettingName,
SettingType.FLOAT,
range_from=0.,
range_to=1.,
)
self.create_setting_widget(
"Send Host Memory Warnings",
_resourceMonitor.sendHostMemoryWarningSettingName,
SettingType.BOOL
)
self.create_setting_widget(
"Host Memory Warning Threshold (MB)",
_resourceMonitor.hostMemoryWarnMBSettingName,
SettingType.INT,
)
self.create_setting_widget(
"Host Memory Warning Threshold (Fraction)",
_resourceMonitor.hostMemoryWarnFractionSettingName,
SettingType.FLOAT,
range_from=0.,
range_to=1.,
)
| 2,300 | Python | 41.61111 | 77 | 0.475652 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/tests/__init__.py | """
Presence of this file allows the tests directory to be imported as a module so that all of its contents
can be scanned to automatically add tests that are placed into this directory.
"""
scan_for_test_modules = True
| 220 | Python | 35.833327 | 103 | 0.777273 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/tests/test_resource_monitor.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 numpy as np
import carb.settings
import omni.kit.test
import omni.resourcemonitor as rm
class TestResourceSettings(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self._savedSettings = {}
self._rm_interface = rm.acquire_resource_monitor_interface()
self._settings = carb.settings.get_settings()
# Save current settings
self._savedSettings[rm.timeBetweenQueriesSettingName] = \
self._settings.get_as_float(rm.timeBetweenQueriesSettingName)
self._savedSettings[rm.sendDeviceMemoryWarningSettingName] = \
self._settings.get_as_bool(rm.sendDeviceMemoryWarningSettingName)
self._savedSettings[rm.deviceMemoryWarnMBSettingName] = \
self._settings.get_as_int(rm.deviceMemoryWarnMBSettingName)
self._savedSettings[rm.deviceMemoryWarnFractionSettingName] = \
self._settings.get_as_float(rm.deviceMemoryWarnFractionSettingName)
self._savedSettings[rm.sendHostMemoryWarningSettingName] = \
self._settings.get_as_bool(rm.sendHostMemoryWarningSettingName)
self._savedSettings[rm.hostMemoryWarnMBSettingName] = \
self._settings.get_as_int(rm.hostMemoryWarnMBSettingName)
self._savedSettings[rm.hostMemoryWarnFractionSettingName] = \
self._settings.get_as_float(rm.hostMemoryWarnFractionSettingName)
# After running each test
async def tearDown(self):
# Restore settings
self._settings.set_float(
rm.timeBetweenQueriesSettingName,
self._savedSettings[rm.timeBetweenQueriesSettingName])
self._settings.set_bool(
rm.sendDeviceMemoryWarningSettingName,
self._savedSettings[rm.sendDeviceMemoryWarningSettingName])
self._settings.set_int(
rm.deviceMemoryWarnMBSettingName,
self._savedSettings[rm.deviceMemoryWarnMBSettingName])
self._settings.set_float(
rm.deviceMemoryWarnFractionSettingName,
self._savedSettings[rm.deviceMemoryWarnFractionSettingName])
self._settings.set_bool(
rm.sendHostMemoryWarningSettingName,
self._savedSettings[rm.sendHostMemoryWarningSettingName])
self._settings.set_int(
rm.hostMemoryWarnMBSettingName,
self._savedSettings[rm.hostMemoryWarnMBSettingName])
self._settings.set_float(
rm.hostMemoryWarnFractionSettingName,
self._savedSettings[rm.hostMemoryWarnFractionSettingName])
async def test_resource_monitor(self):
"""
Test host memory warnings by setting the warning threshold to slightly
less than 10 GB below current memory usage then allocating a 10 GB buffer
"""
hostBytesAvail = self._rm_interface.get_available_host_memory()
memoryToAlloc = 10 * 1024 * 1024 * 1024
queryTime = 0.1
fudge = 512 * 1024 * 1024 # make sure we go below the warning threshold
warnHostThresholdBytes = hostBytesAvail - memoryToAlloc + fudge
self._settings.set_float(
rm.timeBetweenQueriesSettingName,
queryTime)
self._settings.set_bool(
rm.sendHostMemoryWarningSettingName,
True)
self._settings.set_int(
rm.hostMemoryWarnMBSettingName,
warnHostThresholdBytes // (1024 * 1024)) # bytes to MB
hostMemoryWarningOccurred = False
def on_rm_update(event):
nonlocal hostMemoryWarningOccurred
hostBytesAvail = self._rm_interface.get_available_host_memory()
if event.type == int(rm.ResourceMonitorEventType.LOW_HOST_MEMORY):
hostMemoryWarningOccurred = True
sub = self._rm_interface.get_event_stream().create_subscription_to_pop(on_rm_update, name='resource monitor update')
self.assertIsNotNone(sub)
# allocate something
numElements = memoryToAlloc // np.dtype(np.int64).itemsize
array = np.zeros(numElements, dtype=np.int64)
array[:] = 1
time = 0.
while time < 2. * queryTime: # give time for a resourcemonitor event to come through
dt = await omni.kit.app.get_app().next_update_async()
time = time + dt
self.assertTrue(hostMemoryWarningOccurred)
| 4,789 | Python | 37.015873 | 124 | 0.683441 |
omniverse-code/kit/exts/omni.resourcemonitor/docs/CHANGELOG.md | # CHANGELOG
## [1.0.0] - 2021-09-14
### Added
- Initial implementation.
- Provide event stream for low memory warnings.
- Provide convenience functions for host and device memory queries.
| 189 | Markdown | 22.749997 | 67 | 0.740741 |
omniverse-code/kit/exts/omni.resourcemonitor/docs/README.md | # [omni.resourcemonitor]
Utility extension for host and device memory updates.
Clients can subscribe to this extension's event stream to receive updates on available memory and/or receive warnings when available memory falls below specified thresholds.
| 254 | Markdown | 49.99999 | 173 | 0.830709 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnVersionedDeformerPy.rst | .. _omni_graph_examples_python_VersionedDeformerPy_2:
.. _omni_graph_examples_python_VersionedDeformerPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: VersionedDeformerPy
:keywords: lang-en omnigraph node examples python versioned-deformer-py
VersionedDeformerPy
===================
.. <description>
Test node to confirm version upgrading works. Performs a basic deformation on some points.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:points", "``pointf[3][]``", "Set of points to be deformed", "[]"
"inputs:wavelength", "``float``", "Wavelength of sinusodal deformer function", "50.0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:points", "``pointf[3][]``", "Set of deformed points", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.VersionedDeformerPy"
"Version", "2"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "VersionedDeformerPy"
"Categories", "examples"
"Generated Class Name", "OgnVersionedDeformerPyDatabase"
"Python Module", "omni.graph.examples.python"
| 1,775 | reStructuredText | 24.73913 | 115 | 0.590986 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnPyUniversalAdd.rst | .. _omni_graph_examples_python_UniversalAdd_1:
.. _omni_graph_examples_python_UniversalAdd:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Universal Add For All Types (Python)
:keywords: lang-en omnigraph node examples python universal-add
Universal Add For All Types (Python)
====================================
.. <description>
Python-based universal add node for all types. This file is generated using UniversalAddGenerator.py
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:bool_0", "``bool``", "Input of type bool", "False"
"inputs:bool_1", "``bool``", "Input of type bool", "False"
"inputs:bool_arr_0", "``bool[]``", "Input of type bool[]", "[]"
"inputs:bool_arr_1", "``bool[]``", "Input of type bool[]", "[]"
"inputs:colord3_0", "``colord[3]``", "Input of type colord[3]", "[0.0, 0.0, 0.0]"
"inputs:colord3_1", "``colord[3]``", "Input of type colord[3]", "[0.0, 0.0, 0.0]"
"inputs:colord3_arr_0", "``colord[3][]``", "Input of type colord[3][]", "[]"
"inputs:colord3_arr_1", "``colord[3][]``", "Input of type colord[3][]", "[]"
"inputs:colord4_0", "``colord[4]``", "Input of type colord[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colord4_1", "``colord[4]``", "Input of type colord[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colord4_arr_0", "``colord[4][]``", "Input of type colord[4][]", "[]"
"inputs:colord4_arr_1", "``colord[4][]``", "Input of type colord[4][]", "[]"
"inputs:colorf3_0", "``colorf[3]``", "Input of type colorf[3]", "[0.0, 0.0, 0.0]"
"inputs:colorf3_1", "``colorf[3]``", "Input of type colorf[3]", "[0.0, 0.0, 0.0]"
"inputs:colorf3_arr_0", "``colorf[3][]``", "Input of type colorf[3][]", "[]"
"inputs:colorf3_arr_1", "``colorf[3][]``", "Input of type colorf[3][]", "[]"
"inputs:colorf4_0", "``colorf[4]``", "Input of type colorf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorf4_1", "``colorf[4]``", "Input of type colorf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorf4_arr_0", "``colorf[4][]``", "Input of type colorf[4][]", "[]"
"inputs:colorf4_arr_1", "``colorf[4][]``", "Input of type colorf[4][]", "[]"
"inputs:colorh3_0", "``colorh[3]``", "Input of type colorh[3]", "[0.0, 0.0, 0.0]"
"inputs:colorh3_1", "``colorh[3]``", "Input of type colorh[3]", "[0.0, 0.0, 0.0]"
"inputs:colorh3_arr_0", "``colorh[3][]``", "Input of type colorh[3][]", "[]"
"inputs:colorh3_arr_1", "``colorh[3][]``", "Input of type colorh[3][]", "[]"
"inputs:colorh4_0", "``colorh[4]``", "Input of type colorh[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorh4_1", "``colorh[4]``", "Input of type colorh[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorh4_arr_0", "``colorh[4][]``", "Input of type colorh[4][]", "[]"
"inputs:colorh4_arr_1", "``colorh[4][]``", "Input of type colorh[4][]", "[]"
"inputs:double2_0", "``double[2]``", "Input of type double[2]", "[0.0, 0.0]"
"inputs:double2_1", "``double[2]``", "Input of type double[2]", "[0.0, 0.0]"
"inputs:double2_arr_0", "``double[2][]``", "Input of type double[2][]", "[]"
"inputs:double2_arr_1", "``double[2][]``", "Input of type double[2][]", "[]"
"inputs:double3_0", "``double[3]``", "Input of type double[3]", "[0.0, 0.0, 0.0]"
"inputs:double3_1", "``double[3]``", "Input of type double[3]", "[0.0, 0.0, 0.0]"
"inputs:double3_arr_0", "``double[3][]``", "Input of type double[3][]", "[]"
"inputs:double3_arr_1", "``double[3][]``", "Input of type double[3][]", "[]"
"inputs:double4_0", "``double[4]``", "Input of type double[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:double4_1", "``double[4]``", "Input of type double[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:double4_arr_0", "``double[4][]``", "Input of type double[4][]", "[]"
"inputs:double4_arr_1", "``double[4][]``", "Input of type double[4][]", "[]"
"inputs:double_0", "``double``", "Input of type double", "0.0"
"inputs:double_1", "``double``", "Input of type double", "0.0"
"inputs:double_arr_0", "``double[]``", "Input of type double[]", "[]"
"inputs:double_arr_1", "``double[]``", "Input of type double[]", "[]"
"inputs:float2_0", "``float[2]``", "Input of type float[2]", "[0.0, 0.0]"
"inputs:float2_1", "``float[2]``", "Input of type float[2]", "[0.0, 0.0]"
"inputs:float2_arr_0", "``float[2][]``", "Input of type float[2][]", "[]"
"inputs:float2_arr_1", "``float[2][]``", "Input of type float[2][]", "[]"
"inputs:float3_0", "``float[3]``", "Input of type float[3]", "[0.0, 0.0, 0.0]"
"inputs:float3_1", "``float[3]``", "Input of type float[3]", "[0.0, 0.0, 0.0]"
"inputs:float3_arr_0", "``float[3][]``", "Input of type float[3][]", "[]"
"inputs:float3_arr_1", "``float[3][]``", "Input of type float[3][]", "[]"
"inputs:float4_0", "``float[4]``", "Input of type float[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:float4_1", "``float[4]``", "Input of type float[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:float4_arr_0", "``float[4][]``", "Input of type float[4][]", "[]"
"inputs:float4_arr_1", "``float[4][]``", "Input of type float[4][]", "[]"
"inputs:float_0", "``float``", "Input of type float", "0.0"
"inputs:float_1", "``float``", "Input of type float", "0.0"
"inputs:float_arr_0", "``float[]``", "Input of type float[]", "[]"
"inputs:float_arr_1", "``float[]``", "Input of type float[]", "[]"
"inputs:frame4_0", "``frame[4]``", "Input of type frame[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:frame4_1", "``frame[4]``", "Input of type frame[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:frame4_arr_0", "``frame[4][]``", "Input of type frame[4][]", "[]"
"inputs:frame4_arr_1", "``frame[4][]``", "Input of type frame[4][]", "[]"
"inputs:half2_0", "``half[2]``", "Input of type half[2]", "[0.0, 0.0]"
"inputs:half2_1", "``half[2]``", "Input of type half[2]", "[0.0, 0.0]"
"inputs:half2_arr_0", "``half[2][]``", "Input of type half[2][]", "[]"
"inputs:half2_arr_1", "``half[2][]``", "Input of type half[2][]", "[]"
"inputs:half3_0", "``half[3]``", "Input of type half[3]", "[0.0, 0.0, 0.0]"
"inputs:half3_1", "``half[3]``", "Input of type half[3]", "[0.0, 0.0, 0.0]"
"inputs:half3_arr_0", "``half[3][]``", "Input of type half[3][]", "[]"
"inputs:half3_arr_1", "``half[3][]``", "Input of type half[3][]", "[]"
"inputs:half4_0", "``half[4]``", "Input of type half[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:half4_1", "``half[4]``", "Input of type half[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:half4_arr_0", "``half[4][]``", "Input of type half[4][]", "[]"
"inputs:half4_arr_1", "``half[4][]``", "Input of type half[4][]", "[]"
"inputs:half_0", "``half``", "Input of type half", "0.0"
"inputs:half_1", "``half``", "Input of type half", "0.0"
"inputs:half_arr_0", "``half[]``", "Input of type half[]", "[]"
"inputs:half_arr_1", "``half[]``", "Input of type half[]", "[]"
"inputs:int2_0", "``int[2]``", "Input of type int[2]", "[0, 0]"
"inputs:int2_1", "``int[2]``", "Input of type int[2]", "[0, 0]"
"inputs:int2_arr_0", "``int[2][]``", "Input of type int[2][]", "[]"
"inputs:int2_arr_1", "``int[2][]``", "Input of type int[2][]", "[]"
"inputs:int3_0", "``int[3]``", "Input of type int[3]", "[0, 0, 0]"
"inputs:int3_1", "``int[3]``", "Input of type int[3]", "[0, 0, 0]"
"inputs:int3_arr_0", "``int[3][]``", "Input of type int[3][]", "[]"
"inputs:int3_arr_1", "``int[3][]``", "Input of type int[3][]", "[]"
"inputs:int4_0", "``int[4]``", "Input of type int[4]", "[0, 0, 0, 0]"
"inputs:int4_1", "``int[4]``", "Input of type int[4]", "[0, 0, 0, 0]"
"inputs:int4_arr_0", "``int[4][]``", "Input of type int[4][]", "[]"
"inputs:int4_arr_1", "``int[4][]``", "Input of type int[4][]", "[]"
"inputs:int64_0", "``int64``", "Input of type int64", "0"
"inputs:int64_1", "``int64``", "Input of type int64", "0"
"inputs:int64_arr_0", "``int64[]``", "Input of type int64[]", "[]"
"inputs:int64_arr_1", "``int64[]``", "Input of type int64[]", "[]"
"inputs:int_0", "``int``", "Input of type int", "0"
"inputs:int_1", "``int``", "Input of type int", "0"
"inputs:int_arr_0", "``int[]``", "Input of type int[]", "[]"
"inputs:int_arr_1", "``int[]``", "Input of type int[]", "[]"
"inputs:matrixd2_0", "``matrixd[2]``", "Input of type matrixd[2]", "[[0.0, 0.0], [0.0, 0.0]]"
"inputs:matrixd2_1", "``matrixd[2]``", "Input of type matrixd[2]", "[[0.0, 0.0], [0.0, 0.0]]"
"inputs:matrixd2_arr_0", "``matrixd[2][]``", "Input of type matrixd[2][]", "[]"
"inputs:matrixd2_arr_1", "``matrixd[2][]``", "Input of type matrixd[2][]", "[]"
"inputs:matrixd3_0", "``matrixd[3]``", "Input of type matrixd[3]", "[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]"
"inputs:matrixd3_1", "``matrixd[3]``", "Input of type matrixd[3]", "[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]"
"inputs:matrixd3_arr_0", "``matrixd[3][]``", "Input of type matrixd[3][]", "[]"
"inputs:matrixd3_arr_1", "``matrixd[3][]``", "Input of type matrixd[3][]", "[]"
"inputs:matrixd4_0", "``matrixd[4]``", "Input of type matrixd[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:matrixd4_1", "``matrixd[4]``", "Input of type matrixd[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:matrixd4_arr_0", "``matrixd[4][]``", "Input of type matrixd[4][]", "[]"
"inputs:matrixd4_arr_1", "``matrixd[4][]``", "Input of type matrixd[4][]", "[]"
"inputs:normald3_0", "``normald[3]``", "Input of type normald[3]", "[0.0, 0.0, 0.0]"
"inputs:normald3_1", "``normald[3]``", "Input of type normald[3]", "[0.0, 0.0, 0.0]"
"inputs:normald3_arr_0", "``normald[3][]``", "Input of type normald[3][]", "[]"
"inputs:normald3_arr_1", "``normald[3][]``", "Input of type normald[3][]", "[]"
"inputs:normalf3_0", "``normalf[3]``", "Input of type normalf[3]", "[0.0, 0.0, 0.0]"
"inputs:normalf3_1", "``normalf[3]``", "Input of type normalf[3]", "[0.0, 0.0, 0.0]"
"inputs:normalf3_arr_0", "``normalf[3][]``", "Input of type normalf[3][]", "[]"
"inputs:normalf3_arr_1", "``normalf[3][]``", "Input of type normalf[3][]", "[]"
"inputs:normalh3_0", "``normalh[3]``", "Input of type normalh[3]", "[0.0, 0.0, 0.0]"
"inputs:normalh3_1", "``normalh[3]``", "Input of type normalh[3]", "[0.0, 0.0, 0.0]"
"inputs:normalh3_arr_0", "``normalh[3][]``", "Input of type normalh[3][]", "[]"
"inputs:normalh3_arr_1", "``normalh[3][]``", "Input of type normalh[3][]", "[]"
"inputs:pointd3_0", "``pointd[3]``", "Input of type pointd[3]", "[0.0, 0.0, 0.0]"
"inputs:pointd3_1", "``pointd[3]``", "Input of type pointd[3]", "[0.0, 0.0, 0.0]"
"inputs:pointd3_arr_0", "``pointd[3][]``", "Input of type pointd[3][]", "[]"
"inputs:pointd3_arr_1", "``pointd[3][]``", "Input of type pointd[3][]", "[]"
"inputs:pointf3_0", "``pointf[3]``", "Input of type pointf[3]", "[0.0, 0.0, 0.0]"
"inputs:pointf3_1", "``pointf[3]``", "Input of type pointf[3]", "[0.0, 0.0, 0.0]"
"inputs:pointf3_arr_0", "``pointf[3][]``", "Input of type pointf[3][]", "[]"
"inputs:pointf3_arr_1", "``pointf[3][]``", "Input of type pointf[3][]", "[]"
"inputs:pointh3_0", "``pointh[3]``", "Input of type pointh[3]", "[0.0, 0.0, 0.0]"
"inputs:pointh3_1", "``pointh[3]``", "Input of type pointh[3]", "[0.0, 0.0, 0.0]"
"inputs:pointh3_arr_0", "``pointh[3][]``", "Input of type pointh[3][]", "[]"
"inputs:pointh3_arr_1", "``pointh[3][]``", "Input of type pointh[3][]", "[]"
"inputs:quatd4_0", "``quatd[4]``", "Input of type quatd[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatd4_1", "``quatd[4]``", "Input of type quatd[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatd4_arr_0", "``quatd[4][]``", "Input of type quatd[4][]", "[]"
"inputs:quatd4_arr_1", "``quatd[4][]``", "Input of type quatd[4][]", "[]"
"inputs:quatf4_0", "``quatf[4]``", "Input of type quatf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatf4_1", "``quatf[4]``", "Input of type quatf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatf4_arr_0", "``quatf[4][]``", "Input of type quatf[4][]", "[]"
"inputs:quatf4_arr_1", "``quatf[4][]``", "Input of type quatf[4][]", "[]"
"inputs:quath4_0", "``quath[4]``", "Input of type quath[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quath4_1", "``quath[4]``", "Input of type quath[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quath4_arr_0", "``quath[4][]``", "Input of type quath[4][]", "[]"
"inputs:quath4_arr_1", "``quath[4][]``", "Input of type quath[4][]", "[]"
"inputs:texcoordd2_0", "``texcoordd[2]``", "Input of type texcoordd[2]", "[0.0, 0.0]"
"inputs:texcoordd2_1", "``texcoordd[2]``", "Input of type texcoordd[2]", "[0.0, 0.0]"
"inputs:texcoordd2_arr_0", "``texcoordd[2][]``", "Input of type texcoordd[2][]", "[]"
"inputs:texcoordd2_arr_1", "``texcoordd[2][]``", "Input of type texcoordd[2][]", "[]"
"inputs:texcoordd3_0", "``texcoordd[3]``", "Input of type texcoordd[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordd3_1", "``texcoordd[3]``", "Input of type texcoordd[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordd3_arr_0", "``texcoordd[3][]``", "Input of type texcoordd[3][]", "[]"
"inputs:texcoordd3_arr_1", "``texcoordd[3][]``", "Input of type texcoordd[3][]", "[]"
"inputs:texcoordf2_0", "``texcoordf[2]``", "Input of type texcoordf[2]", "[0.0, 0.0]"
"inputs:texcoordf2_1", "``texcoordf[2]``", "Input of type texcoordf[2]", "[0.0, 0.0]"
"inputs:texcoordf2_arr_0", "``texcoordf[2][]``", "Input of type texcoordf[2][]", "[]"
"inputs:texcoordf2_arr_1", "``texcoordf[2][]``", "Input of type texcoordf[2][]", "[]"
"inputs:texcoordf3_0", "``texcoordf[3]``", "Input of type texcoordf[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordf3_1", "``texcoordf[3]``", "Input of type texcoordf[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordf3_arr_0", "``texcoordf[3][]``", "Input of type texcoordf[3][]", "[]"
"inputs:texcoordf3_arr_1", "``texcoordf[3][]``", "Input of type texcoordf[3][]", "[]"
"inputs:texcoordh2_0", "``texcoordh[2]``", "Input of type texcoordh[2]", "[0.0, 0.0]"
"inputs:texcoordh2_1", "``texcoordh[2]``", "Input of type texcoordh[2]", "[0.0, 0.0]"
"inputs:texcoordh2_arr_0", "``texcoordh[2][]``", "Input of type texcoordh[2][]", "[]"
"inputs:texcoordh2_arr_1", "``texcoordh[2][]``", "Input of type texcoordh[2][]", "[]"
"inputs:texcoordh3_0", "``texcoordh[3]``", "Input of type texcoordh[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordh3_1", "``texcoordh[3]``", "Input of type texcoordh[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordh3_arr_0", "``texcoordh[3][]``", "Input of type texcoordh[3][]", "[]"
"inputs:texcoordh3_arr_1", "``texcoordh[3][]``", "Input of type texcoordh[3][]", "[]"
"inputs:timecode_0", "``timecode``", "Input of type timecode", "0.0"
"inputs:timecode_1", "``timecode``", "Input of type timecode", "0.0"
"inputs:timecode_arr_0", "``timecode[]``", "Input of type timecode[]", "[]"
"inputs:timecode_arr_1", "``timecode[]``", "Input of type timecode[]", "[]"
"inputs:token_0", "``token``", "Input of type token", "default_token"
"inputs:token_1", "``token``", "Input of type token", "default_token"
"inputs:token_arr_0", "``token[]``", "Input of type token[]", "[]"
"inputs:token_arr_1", "``token[]``", "Input of type token[]", "[]"
"inputs:transform4_0", "``transform[4]``", "Input of type transform[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:transform4_1", "``transform[4]``", "Input of type transform[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:transform4_arr_0", "``transform[4][]``", "Input of type transform[4][]", "[]"
"inputs:transform4_arr_1", "``transform[4][]``", "Input of type transform[4][]", "[]"
"inputs:uchar_0", "``uchar``", "Input of type uchar", "0"
"inputs:uchar_1", "``uchar``", "Input of type uchar", "0"
"inputs:uchar_arr_0", "``uchar[]``", "Input of type uchar[]", "[]"
"inputs:uchar_arr_1", "``uchar[]``", "Input of type uchar[]", "[]"
"inputs:uint64_0", "``uint64``", "Input of type uint64", "0"
"inputs:uint64_1", "``uint64``", "Input of type uint64", "0"
"inputs:uint64_arr_0", "``uint64[]``", "Input of type uint64[]", "[]"
"inputs:uint64_arr_1", "``uint64[]``", "Input of type uint64[]", "[]"
"inputs:uint_0", "``uint``", "Input of type uint", "0"
"inputs:uint_1", "``uint``", "Input of type uint", "0"
"inputs:uint_arr_0", "``uint[]``", "Input of type uint[]", "[]"
"inputs:uint_arr_1", "``uint[]``", "Input of type uint[]", "[]"
"inputs:vectord3_0", "``vectord[3]``", "Input of type vectord[3]", "[0.0, 0.0, 0.0]"
"inputs:vectord3_1", "``vectord[3]``", "Input of type vectord[3]", "[0.0, 0.0, 0.0]"
"inputs:vectord3_arr_0", "``vectord[3][]``", "Input of type vectord[3][]", "[]"
"inputs:vectord3_arr_1", "``vectord[3][]``", "Input of type vectord[3][]", "[]"
"inputs:vectorf3_0", "``vectorf[3]``", "Input of type vectorf[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorf3_1", "``vectorf[3]``", "Input of type vectorf[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorf3_arr_0", "``vectorf[3][]``", "Input of type vectorf[3][]", "[]"
"inputs:vectorf3_arr_1", "``vectorf[3][]``", "Input of type vectorf[3][]", "[]"
"inputs:vectorh3_0", "``vectorh[3]``", "Input of type vectorh[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorh3_1", "``vectorh[3]``", "Input of type vectorh[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorh3_arr_0", "``vectorh[3][]``", "Input of type vectorh[3][]", "[]"
"inputs:vectorh3_arr_1", "``vectorh[3][]``", "Input of type vectorh[3][]", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:bool_0", "``bool``", "Output of type bool", "False"
"outputs:bool_arr_0", "``bool[]``", "Output of type bool[]", "[]"
"outputs:colord3_0", "``colord[3]``", "Output of type colord[3]", "[0.0, 0.0, 0.0]"
"outputs:colord3_arr_0", "``colord[3][]``", "Output of type colord[3][]", "[]"
"outputs:colord4_0", "``colord[4]``", "Output of type colord[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:colord4_arr_0", "``colord[4][]``", "Output of type colord[4][]", "[]"
"outputs:colorf3_0", "``colorf[3]``", "Output of type colorf[3]", "[0.0, 0.0, 0.0]"
"outputs:colorf3_arr_0", "``colorf[3][]``", "Output of type colorf[3][]", "[]"
"outputs:colorf4_0", "``colorf[4]``", "Output of type colorf[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:colorf4_arr_0", "``colorf[4][]``", "Output of type colorf[4][]", "[]"
"outputs:colorh3_0", "``colorh[3]``", "Output of type colorh[3]", "[0.0, 0.0, 0.0]"
"outputs:colorh3_arr_0", "``colorh[3][]``", "Output of type colorh[3][]", "[]"
"outputs:colorh4_0", "``colorh[4]``", "Output of type colorh[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:colorh4_arr_0", "``colorh[4][]``", "Output of type colorh[4][]", "[]"
"outputs:double2_0", "``double[2]``", "Output of type double[2]", "[0.0, 0.0]"
"outputs:double2_arr_0", "``double[2][]``", "Output of type double[2][]", "[]"
"outputs:double3_0", "``double[3]``", "Output of type double[3]", "[0.0, 0.0, 0.0]"
"outputs:double3_arr_0", "``double[3][]``", "Output of type double[3][]", "[]"
"outputs:double4_0", "``double[4]``", "Output of type double[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:double4_arr_0", "``double[4][]``", "Output of type double[4][]", "[]"
"outputs:double_0", "``double``", "Output of type double", "0.0"
"outputs:double_arr_0", "``double[]``", "Output of type double[]", "[]"
"outputs:float2_0", "``float[2]``", "Output of type float[2]", "[0.0, 0.0]"
"outputs:float2_arr_0", "``float[2][]``", "Output of type float[2][]", "[]"
"outputs:float3_0", "``float[3]``", "Output of type float[3]", "[0.0, 0.0, 0.0]"
"outputs:float3_arr_0", "``float[3][]``", "Output of type float[3][]", "[]"
"outputs:float4_0", "``float[4]``", "Output of type float[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:float4_arr_0", "``float[4][]``", "Output of type float[4][]", "[]"
"outputs:float_0", "``float``", "Output of type float", "0.0"
"outputs:float_arr_0", "``float[]``", "Output of type float[]", "[]"
"outputs:frame4_0", "``frame[4]``", "Output of type frame[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"outputs:frame4_arr_0", "``frame[4][]``", "Output of type frame[4][]", "[]"
"outputs:half2_0", "``half[2]``", "Output of type half[2]", "[0.0, 0.0]"
"outputs:half2_arr_0", "``half[2][]``", "Output of type half[2][]", "[]"
"outputs:half3_0", "``half[3]``", "Output of type half[3]", "[0.0, 0.0, 0.0]"
"outputs:half3_arr_0", "``half[3][]``", "Output of type half[3][]", "[]"
"outputs:half4_0", "``half[4]``", "Output of type half[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:half4_arr_0", "``half[4][]``", "Output of type half[4][]", "[]"
"outputs:half_0", "``half``", "Output of type half", "0.0"
"outputs:half_arr_0", "``half[]``", "Output of type half[]", "[]"
"outputs:int2_0", "``int[2]``", "Output of type int[2]", "[0, 0]"
"outputs:int2_arr_0", "``int[2][]``", "Output of type int[2][]", "[]"
"outputs:int3_0", "``int[3]``", "Output of type int[3]", "[0, 0, 0]"
"outputs:int3_arr_0", "``int[3][]``", "Output of type int[3][]", "[]"
"outputs:int4_0", "``int[4]``", "Output of type int[4]", "[0, 0, 0, 0]"
"outputs:int4_arr_0", "``int[4][]``", "Output of type int[4][]", "[]"
"outputs:int64_0", "``int64``", "Output of type int64", "0"
"outputs:int64_arr_0", "``int64[]``", "Output of type int64[]", "[]"
"outputs:int_0", "``int``", "Output of type int", "0"
"outputs:int_arr_0", "``int[]``", "Output of type int[]", "[]"
"outputs:matrixd2_0", "``matrixd[2]``", "Output of type matrixd[2]", "[[0.0, 0.0], [0.0, 0.0]]"
"outputs:matrixd2_arr_0", "``matrixd[2][]``", "Output of type matrixd[2][]", "[]"
"outputs:matrixd3_0", "``matrixd[3]``", "Output of type matrixd[3]", "[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]"
"outputs:matrixd3_arr_0", "``matrixd[3][]``", "Output of type matrixd[3][]", "[]"
"outputs:matrixd4_0", "``matrixd[4]``", "Output of type matrixd[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"outputs:matrixd4_arr_0", "``matrixd[4][]``", "Output of type matrixd[4][]", "[]"
"outputs:normald3_0", "``normald[3]``", "Output of type normald[3]", "[0.0, 0.0, 0.0]"
"outputs:normald3_arr_0", "``normald[3][]``", "Output of type normald[3][]", "[]"
"outputs:normalf3_0", "``normalf[3]``", "Output of type normalf[3]", "[0.0, 0.0, 0.0]"
"outputs:normalf3_arr_0", "``normalf[3][]``", "Output of type normalf[3][]", "[]"
"outputs:normalh3_0", "``normalh[3]``", "Output of type normalh[3]", "[0.0, 0.0, 0.0]"
"outputs:normalh3_arr_0", "``normalh[3][]``", "Output of type normalh[3][]", "[]"
"outputs:pointd3_0", "``pointd[3]``", "Output of type pointd[3]", "[0.0, 0.0, 0.0]"
"outputs:pointd3_arr_0", "``pointd[3][]``", "Output of type pointd[3][]", "[]"
"outputs:pointf3_0", "``pointf[3]``", "Output of type pointf[3]", "[0.0, 0.0, 0.0]"
"outputs:pointf3_arr_0", "``pointf[3][]``", "Output of type pointf[3][]", "[]"
"outputs:pointh3_0", "``pointh[3]``", "Output of type pointh[3]", "[0.0, 0.0, 0.0]"
"outputs:pointh3_arr_0", "``pointh[3][]``", "Output of type pointh[3][]", "[]"
"outputs:quatd4_0", "``quatd[4]``", "Output of type quatd[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:quatd4_arr_0", "``quatd[4][]``", "Output of type quatd[4][]", "[]"
"outputs:quatf4_0", "``quatf[4]``", "Output of type quatf[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:quatf4_arr_0", "``quatf[4][]``", "Output of type quatf[4][]", "[]"
"outputs:quath4_0", "``quath[4]``", "Output of type quath[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:quath4_arr_0", "``quath[4][]``", "Output of type quath[4][]", "[]"
"outputs:texcoordd2_0", "``texcoordd[2]``", "Output of type texcoordd[2]", "[0.0, 0.0]"
"outputs:texcoordd2_arr_0", "``texcoordd[2][]``", "Output of type texcoordd[2][]", "[]"
"outputs:texcoordd3_0", "``texcoordd[3]``", "Output of type texcoordd[3]", "[0.0, 0.0, 0.0]"
"outputs:texcoordd3_arr_0", "``texcoordd[3][]``", "Output of type texcoordd[3][]", "[]"
"outputs:texcoordf2_0", "``texcoordf[2]``", "Output of type texcoordf[2]", "[0.0, 0.0]"
"outputs:texcoordf2_arr_0", "``texcoordf[2][]``", "Output of type texcoordf[2][]", "[]"
"outputs:texcoordf3_0", "``texcoordf[3]``", "Output of type texcoordf[3]", "[0.0, 0.0, 0.0]"
"outputs:texcoordf3_arr_0", "``texcoordf[3][]``", "Output of type texcoordf[3][]", "[]"
"outputs:texcoordh2_0", "``texcoordh[2]``", "Output of type texcoordh[2]", "[0.0, 0.0]"
"outputs:texcoordh2_arr_0", "``texcoordh[2][]``", "Output of type texcoordh[2][]", "[]"
"outputs:texcoordh3_0", "``texcoordh[3]``", "Output of type texcoordh[3]", "[0.0, 0.0, 0.0]"
"outputs:texcoordh3_arr_0", "``texcoordh[3][]``", "Output of type texcoordh[3][]", "[]"
"outputs:timecode_0", "``timecode``", "Output of type timecode", "0.0"
"outputs:timecode_arr_0", "``timecode[]``", "Output of type timecode[]", "[]"
"outputs:token_0", "``token``", "Output of type token", "default_token"
"outputs:token_arr_0", "``token[]``", "Output of type token[]", "[]"
"outputs:transform4_0", "``transform[4]``", "Output of type transform[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"outputs:transform4_arr_0", "``transform[4][]``", "Output of type transform[4][]", "[]"
"outputs:uchar_0", "``uchar``", "Output of type uchar", "0"
"outputs:uchar_arr_0", "``uchar[]``", "Output of type uchar[]", "[]"
"outputs:uint64_0", "``uint64``", "Output of type uint64", "0"
"outputs:uint64_arr_0", "``uint64[]``", "Output of type uint64[]", "[]"
"outputs:uint_0", "``uint``", "Output of type uint", "0"
"outputs:uint_arr_0", "``uint[]``", "Output of type uint[]", "[]"
"outputs:vectord3_0", "``vectord[3]``", "Output of type vectord[3]", "[0.0, 0.0, 0.0]"
"outputs:vectord3_arr_0", "``vectord[3][]``", "Output of type vectord[3][]", "[]"
"outputs:vectorf3_0", "``vectorf[3]``", "Output of type vectorf[3]", "[0.0, 0.0, 0.0]"
"outputs:vectorf3_arr_0", "``vectorf[3][]``", "Output of type vectorf[3][]", "[]"
"outputs:vectorh3_0", "``vectorh[3]``", "Output of type vectorh[3]", "[0.0, 0.0, 0.0]"
"outputs:vectorh3_arr_0", "``vectorh[3][]``", "Output of type vectorh[3][]", "[]"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.UniversalAdd"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "usd"
"uiName", "Universal Add For All Types (Python)"
"Categories", "examples"
"Generated Class Name", "OgnPyUniversalAddDatabase"
"Python Module", "omni.graph.examples.python"
| 27,714 | reStructuredText | 72.320106 | 169 | 0.526665 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnBouncingCubesGpu.rst | .. _omni_graph_examples_python_BouncingCubesGpu_1:
.. _omni_graph_examples_python_BouncingCubesGpu:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Deprecated Node - Bouncing Cubes (GPU)
:keywords: lang-en omnigraph node examples python bouncing-cubes-gpu
Deprecated Node - Bouncing Cubes (GPU)
======================================
.. <description>
Deprecated node - no longer supported
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.BouncingCubesGpu"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cuda"
"Generated Code Exclusions", "usd, test"
"uiName", "Deprecated Node - Bouncing Cubes (GPU)"
"__memoryType", "cuda"
"Categories", "examples"
"Generated Class Name", "OgnBouncingCubesGpuDatabase"
"Python Module", "omni.graph.examples.python"
| 1,346 | reStructuredText | 25.411764 | 115 | 0.57578 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnCountTo.rst | .. _omni_graph_examples_python_CountTo_1:
.. _omni_graph_examples_python_CountTo:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Count To
:keywords: lang-en omnigraph node examples python count-to
Count To
========
.. <description>
Example stateful node that counts to countTo by a certain increment
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:countTo", "``double``", "The ceiling to count to", "3"
"inputs:increment", "``double``", "Increment to count by", "0.1"
"inputs:reset", "``bool``", "Whether to reset the count", "False"
"inputs:trigger", "``double[3]``", "Position to be used as a trigger for the counting", "[0.0, 0.0, 0.0]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:count", "``double``", "The current count", "0.0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.CountTo"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Count To"
"Categories", "examples"
"Generated Class Name", "OgnCountToDatabase"
"Python Module", "omni.graph.examples.python"
| 1,784 | reStructuredText | 24.140845 | 115 | 0.567265 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnPositionToColor.rst | .. _omni_graph_examples_python_PositionToColor_1:
.. _omni_graph_examples_python_PositionToColor:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: PositionToColor
:keywords: lang-en omnigraph node examples python position-to-color
PositionToColor
===============
.. <description>
This node takes positional data (double3) and converts to a color, and outputs as color3f[] (which seems to be the default color connection in USD)
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:color_offset", "``colorf[3]``", "Offset added to the scaled color to get the final result", "[0.0, 0.0, 0.0]"
"inputs:position", "``double[3]``", "Position to be converted to a color", "[0.0, 0.0, 0.0]"
"inputs:scale", "``float``", "Constant by which to multiply the position to get the color", "1.0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:color", "``colorf[3][]``", "Color value extracted from the position", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.PositionToColor"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "PositionToColor"
"Categories", "examples"
"Generated Class Name", "OgnPositionToColorDatabase"
"Python Module", "omni.graph.examples.python"
| 1,967 | reStructuredText | 27.114285 | 148 | 0.593798 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnDeformerYAxis.rst | .. _omni_graph_examples_python_DeformerYAxis_1:
.. _omni_graph_examples_python_DeformerYAxis:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sine Wave Deformer Y-axis (Python)
:keywords: lang-en omnigraph node examples python deformer-y-axis
Sine Wave Deformer Y-axis (Python)
==================================
.. <description>
Example node applying a sine wave deformation to a set of points, written in Python. Deforms along Y-axis instead of Z
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:multiplier", "``double``", "The multiplier for the amplitude of the sine wave", "1"
"inputs:offset", "``double``", "The offset of the sine wave", "0"
"inputs:points", "``pointf[3][]``", "The input points to be deformed", "[]"
"inputs:wavelength", "``double``", "The wavelength of the sine wave", "1"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:points", "``pointf[3][]``", "The deformed output points", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.DeformerYAxis"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Sine Wave Deformer Y-axis (Python)"
"Categories", "examples"
"Generated Class Name", "OgnDeformerYAxisDatabase"
"Python Module", "omni.graph.examples.python"
| 1,995 | reStructuredText | 27.112676 | 119 | 0.582957 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnComposeDouble3.rst | .. _omni_graph_examples_python_ComposeDouble3_1:
.. _omni_graph_examples_python_ComposeDouble3:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Compose Double3 (Python)
:keywords: lang-en omnigraph node examples python compose-double3
Compose Double3 (Python)
========================
.. <description>
Example node that takes in the components of three doubles and outputs a double3
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:x", "``double``", "The x component of the input double3", "0"
"inputs:y", "``double``", "The y component of the input double3", "0"
"inputs:z", "``double``", "The z component of the input double3", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:double3", "``double[3]``", "Output double3", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.ComposeDouble3"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Compose Double3 (Python)"
"Categories", "examples"
"Generated Class Name", "OgnComposeDouble3Database"
"Python Module", "omni.graph.examples.python"
| 1,805 | reStructuredText | 24.8 | 115 | 0.577839 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnMultDouble.rst | .. _omni_graph_examples_python_MultDouble_1:
.. _omni_graph_examples_python_MultDouble:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Multiply Double (Python)
:keywords: lang-en omnigraph node examples python mult-double
Multiply Double (Python)
========================
.. <description>
Example node that multiplies 2 doubles together
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a", "``double``", "Input a", "0"
"inputs:b", "``double``", "Input b", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:out", "``double``", "The result of a * b", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.MultDouble"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Multiply Double (Python)"
"Categories", "examples"
"Generated Class Name", "OgnMultDoubleDatabase"
"Python Module", "omni.graph.examples.python"
| 1,618 | reStructuredText | 22.463768 | 115 | 0.556242 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnDynamicSwitch.rst | .. _omni_graph_examples_python_DynamicSwitch_1:
.. _omni_graph_examples_python_DynamicSwitch:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Dynamic Switch
:keywords: lang-en omnigraph node examples python dynamic-switch
Dynamic Switch
==============
.. <description>
A switch node that will enable the left side or right side depending on the input. Requires dynamic scheduling to work
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:left_value", "``int``", "Left value to output", "-1"
"inputs:right_value", "``int``", "Right value to output", "1"
"inputs:switch", "``int``", "Enables right value if greater than 0, else left value", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:left_out", "``int``", "Left side output", "0"
"outputs:right_out", "``int``", "Right side output", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.DynamicSwitch"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "usd"
"uiName", "Dynamic Switch"
"Categories", "examples"
"Generated Class Name", "OgnDynamicSwitchDatabase"
"Python Module", "omni.graph.examples.python"
| 1,856 | reStructuredText | 25.154929 | 119 | 0.579741 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnBouncingCubesCpu.rst | .. _omni_graph_examples_python_BouncingCubes_1:
.. _omni_graph_examples_python_BouncingCubes:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Deprecated Node - Bouncing Cubes (GPU)
:keywords: lang-en omnigraph node examples python bouncing-cubes
Deprecated Node - Bouncing Cubes (GPU)
======================================
.. <description>
Deprecated node - no longer supported
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Translations (*state:translations*)", "``float[3][]``", "Set of translation attributes gathered from the inputs. Translations have velocities applied to them each evaluation.", "None"
"Velocities (*state:velocities*)", "``float[]``", "Set of velocity attributes gathered from the inputs", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.BouncingCubes"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Deprecated Node - Bouncing Cubes (GPU)"
"Categories", "examples"
"Generated Class Name", "OgnBouncingCubesCpuDatabase"
"Python Module", "omni.graph.examples.python"
| 1,716 | reStructuredText | 27.616666 | 188 | 0.594406 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnExecSwitch.rst | .. _omni_graph_examples_python_ExecSwitch_1:
.. _omni_graph_examples_python_ExecSwitch:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Exec Switch
:keywords: lang-en omnigraph node examples python exec-switch
Exec Switch
===========
.. <description>
A switch node that will enable the left side or right side depending on the input
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Exec In (*inputs:execIn*)", "``execution``", "Trigger the output", "None"
"inputs:switch", "``bool``", "Enables right value if greater than 0, else left value", "False"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:execLeftOut", "``execution``", "Left execution", "None"
"outputs:execRightOut", "``execution``", "Right execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.ExecSwitch"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "usd"
"uiName", "Exec Switch"
"Categories", "examples"
"Generated Class Name", "OgnExecSwitchDatabase"
"Python Module", "omni.graph.examples.python"
| 1,764 | reStructuredText | 24.214285 | 115 | 0.579932 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnTestInitNode.rst | .. _omni_graph_examples_python_TestInitNode_1:
.. _omni_graph_examples_python_TestInitNode:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: TestInitNode
:keywords: lang-en omnigraph node examples python test-init-node
TestInitNode
============
.. <description>
Test Init Node
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:value", "``float``", "Value", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.TestInitNode"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "TestInitNode"
"Categories", "examples"
"Generated Class Name", "OgnTestInitNodeDatabase"
"Python Module", "omni.graph.examples.python"
| 1,332 | reStructuredText | 21.59322 | 115 | 0.563814 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnIntCounter.rst | .. _omni_graph_examples_python_IntCounter_1:
.. _omni_graph_examples_python_IntCounter:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Int Counter
:keywords: lang-en omnigraph node examples python int-counter
Int Counter
===========
.. <description>
Example stateful node that increments every time it's evaluated
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:increment", "``int``", "Increment to count by", "1"
"inputs:reset", "``bool``", "Whether to reset the count", "False"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:count", "``int``", "The current count", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.IntCounter"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Int Counter"
"Categories", "examples"
"Generated Class Name", "OgnIntCounterDatabase"
"Python Module", "omni.graph.examples.python"
| 1,620 | reStructuredText | 22.492753 | 115 | 0.567901 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnTestSingleton.rst | .. _omni_graph_examples_python_TestSingleton_1:
.. _omni_graph_examples_python_TestSingleton:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Test Singleton
:keywords: lang-en omnigraph node examples python test-singleton
Test Singleton
==============
.. <description>
Example node that showcases the use of singleton nodes (nodes that can have only 1 instance)
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:out", "``double``", "The unique output of the only instance of this node", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.TestSingleton"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"singleton", "1"
"uiName", "Test Singleton"
"Categories", "examples"
"Generated Class Name", "OgnTestSingletonDatabase"
"Python Module", "omni.graph.examples.python"
| 1,488 | reStructuredText | 23.816666 | 115 | 0.583333 |
omniverse-code/kit/exts/omni.graph.examples.python/config/extension.toml | [package]
title = "OmniGraph Python Examples"
version = "1.3.2"
category = "Graph"
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
description = "Contains a set of sample OmniGraph nodes implemented in Python."
repository = ""
keywords = ["kit", "omnigraph", "nodes", "python"]
# Main module for the Python interface
[[python.module]]
name = "omni.graph.examples.python"
# Watch the .ogn files for hot reloading (only works for Python files)
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Python array data uses numpy as its format
[python.pipapi]
requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231
# Other extensions that need to load in order for this one to work
[dependencies]
"omni.graph" = {}
"omni.graph.tools" = {}
"omni.kit.test" = {}
"omni.kit.pipapi" = {}
[[test]]
stdoutFailPatterns.exclude = [
"*[omni.graph.core.plugin] getTypes called on non-existent path*",
"*Trying to create multiple instances of singleton*"
]
[documentation]
deps = [
["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph refs until that workflow is moved
]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 1,199 | TOML | 25.666666 | 108 | 0.69558 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/__init__.py | """Module containing example nodes written in pure Python.
There is no public API to this module.
"""
__all__ = []
from ._impl.extension import _PublicExtension # noqa: F401
| 177 | Python | 21.249997 | 59 | 0.711864 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/OgnBouncingCubesGpuDatabase.py | """Support for simplified access to data on nodes of type omni.graph.examples.python.BouncingCubesGpu
Deprecated node - no longer supported
"""
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnBouncingCubesGpuDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.examples.python.BouncingCubesGpu
Class Members:
node: Node being evaluated
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnBouncingCubesGpuDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnBouncingCubesGpuDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnBouncingCubesGpuDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.examples.python.BouncingCubesGpu'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnBouncingCubesGpuDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnBouncingCubesGpuDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnBouncingCubesGpuDatabase(node)
try:
compute_function = getattr(OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnBouncingCubesGpuDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnBouncingCubesGpuDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnBouncingCubesGpuDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnBouncingCubesGpuDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.examples.python")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Deprecated Node - Bouncing Cubes (GPU)")
node_type.set_metadata(ogn.MetadataKeys.MEMORY_TYPE, "cuda")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "examples")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Deprecated node - no longer supported")
node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "usd,test")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
node_type.set_metadata(ogn.MetadataKeys.MEMORY_TYPE, "cuda")
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnBouncingCubesGpuDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnBouncingCubesGpuDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.examples.python.BouncingCubesGpu")
| 9,183 | Python | 47.336842 | 138 | 0.653055 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/OgnBouncingCubesCpuDatabase.py | """Support for simplified access to data on nodes of type omni.graph.examples.python.BouncingCubes
Deprecated node - no longer supported
"""
import numpy
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnBouncingCubesCpuDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.examples.python.BouncingCubes
Class Members:
node: Node being evaluated
Attribute Value Properties:
State:
state.translations
state.velocities
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('state:translations', 'float3[]', 0, 'Translations', 'Set of translation attributes gathered from the inputs.\nTranslations have velocities applied to them each evaluation.', {}, True, None, False, ''),
('state:velocities', 'float[]', 0, 'Velocities', 'Set of velocity attributes gathered from the inputs', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.translations_size = None
self.velocities_size = None
@property
def translations(self):
data_view = og.AttributeValueHelper(self._attributes.translations)
self.translations_size = data_view.get_array_size()
return data_view.get()
@translations.setter
def translations(self, value):
data_view = og.AttributeValueHelper(self._attributes.translations)
data_view.set(value)
self.translations_size = data_view.get_array_size()
@property
def velocities(self):
data_view = og.AttributeValueHelper(self._attributes.velocities)
self.velocities_size = data_view.get_array_size()
return data_view.get()
@velocities.setter
def velocities(self, value):
data_view = og.AttributeValueHelper(self._attributes.velocities)
data_view.set(value)
self.velocities_size = data_view.get_array_size()
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnBouncingCubesCpuDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnBouncingCubesCpuDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnBouncingCubesCpuDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.examples.python.BouncingCubes'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnBouncingCubesCpuDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnBouncingCubesCpuDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnBouncingCubesCpuDatabase(node)
try:
compute_function = getattr(OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnBouncingCubesCpuDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnBouncingCubesCpuDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnBouncingCubesCpuDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnBouncingCubesCpuDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.examples.python")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Deprecated Node - Bouncing Cubes (GPU)")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "examples")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Deprecated node - no longer supported")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnBouncingCubesCpuDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnBouncingCubesCpuDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnBouncingCubesCpuDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.examples.python.BouncingCubes")
| 10,508 | Python | 46.337838 | 211 | 0.649505 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/OgnPositionToColorDatabase.py | """Support for simplified access to data on nodes of type omni.graph.examples.python.PositionToColor
This node takes positional data (double3) and converts to a color, and outputs as color3f[] (which seems to be the default
color connection in USD)
"""
import numpy
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnPositionToColorDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.examples.python.PositionToColor
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.color_offset
inputs.position
inputs.scale
Outputs:
outputs.color
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:color_offset', 'color3f', 0, None, 'Offset added to the scaled color to get the final result', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:position', 'double3', 0, None, 'Position to be converted to a color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:scale', 'float', 0, None, 'Constant by which to multiply the position to get the color', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('outputs:color', 'color3f[]', 0, None, 'Color value extracted from the position', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.color_offset = og.AttributeRole.COLOR
role_data.outputs.color = og.AttributeRole.COLOR
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"color_offset", "position", "scale", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.color_offset, self._attributes.position, self._attributes.scale]
self._batchedReadValues = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], 1.0]
@property
def color_offset(self):
return self._batchedReadValues[0]
@color_offset.setter
def color_offset(self, value):
self._batchedReadValues[0] = value
@property
def position(self):
return self._batchedReadValues[1]
@position.setter
def position(self, value):
self._batchedReadValues[1] = value
@property
def scale(self):
return self._batchedReadValues[2]
@scale.setter
def scale(self, value):
self._batchedReadValues[2] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.color_size = None
self._batchedWriteValues = { }
@property
def color(self):
data_view = og.AttributeValueHelper(self._attributes.color)
return data_view.get(reserved_element_count=self.color_size)
@color.setter
def color(self, value):
data_view = og.AttributeValueHelper(self._attributes.color)
data_view.set(value)
self.color_size = data_view.get_array_size()
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnPositionToColorDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnPositionToColorDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnPositionToColorDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnPositionToColorDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.examples.python.PositionToColor'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnPositionToColorDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnPositionToColorDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnPositionToColorDatabase(node)
try:
compute_function = getattr(OgnPositionToColorDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnPositionToColorDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnPositionToColorDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnPositionToColorDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnPositionToColorDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnPositionToColorDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnPositionToColorDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnPositionToColorDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnPositionToColorDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnPositionToColorDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.examples.python")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "PositionToColor")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "examples")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This node takes positional data (double3) and converts to a color, and outputs as color3f[] (which seems to be the default color connection in USD)")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnPositionToColorDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnPositionToColorDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnPositionToColorDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnPositionToColorDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.examples.python.PositionToColor")
| 12,043 | Python | 45.863813 | 220 | 0.639708 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnAbsDouble.py | """
Implementation of an OmniGraph node takes the absolute value of a number
"""
class OgnAbsDouble:
@staticmethod
def compute(db):
db.outputs.out = abs(db.inputs.num)
return True
| 206 | Python | 17.81818 | 72 | 0.669903 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnComposeDouble3.py | """
Implementation of an OmniGraph node that composes a double3 from its components
"""
class OgnComposeDouble3:
@staticmethod
def compute(db):
db.outputs.double3 = (db.inputs.x, db.inputs.y, db.inputs.z)
return True
| 243 | Python | 21.181816 | 79 | 0.687243 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnDeformerYAxis.py | """
Implementation of an OmniGraph node that deforms a surface using a sine wave
"""
import numpy as np
class OgnDeformerYAxis:
@staticmethod
def compute(db):
"""Deform the input points by a multiple of the sine wave"""
points = db.inputs.points
multiplier = db.inputs.multiplier
wavelength = db.inputs.wavelength
offset = db.inputs.offset
db.outputs.points_size = points.shape[0]
# Nothing to evaluate if there are no input points
if db.outputs.points_size == 0:
return True
output_points = db.outputs.points
if wavelength <= 0:
wavelength = 1.0
pt = points.copy() # we still need to do a copy here because we do not want to modify points
tx = pt[:, 0]
offset_tx = tx + offset
disp = np.sin(offset_tx / wavelength)
pt[:, 1] += disp * multiplier
output_points[:] = pt[:] # we modify output_points in memory so we do not need to set the value again
return True
| 1,037 | Python | 29.529411 | 110 | 0.612343 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnClampDouble.py | """
Implementation of an OmniGraph node that clamps a double value
"""
class OgnClampDouble:
@staticmethod
def compute(db):
if db.inputs.num < db.inputs.min:
db.outputs.out = db.inputs.min
elif db.inputs.num > db.inputs.max:
db.outputs.out = db.inputs.max
else:
db.outputs.out = db.inputs.num
return True
| 384 | Python | 21.647058 | 62 | 0.596354 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnDecomposeDouble3.py | """
Implementation of an OmniGraph node that decomposes a double3 into its comonents
"""
class OgnDecomposeDouble3:
@staticmethod
def compute(db):
in_double3 = db.inputs.double3
db.outputs.x = in_double3[0]
db.outputs.y = in_double3[1]
db.outputs.z = in_double3[2]
return True
| 327 | Python | 22.42857 | 80 | 0.64526 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnMultDouble.py | """
Implementation of an OmniGraph node that calculates a * b
"""
class OgnMultDouble:
@staticmethod
def compute(db):
db.outputs.out = db.inputs.a * db.inputs.b
return True
| 199 | Python | 17.181817 | 57 | 0.648241 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnSubtractDouble.py | """
Implementation of an OmniGraph node that subtracts b from a
"""
class OgnSubtractDouble:
@staticmethod
def compute(db):
db.outputs.out = db.inputs.a - db.inputs.b
return True
| 205 | Python | 17.727271 | 59 | 0.663415 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tutorial1/OgnPositionToColor.py | """
Implementation of the node algorith to convert a position to a color
"""
class OgnPositionToColor:
"""
This node takes positional data (double3) and converts to a color, and outputs
as color3f[] (which seems to be the default color connection in USD)
"""
@staticmethod
def compute(db):
"""Run the algorithm to convert a position to a color"""
position = db.inputs.position
scale_value = db.inputs.scale
color_offset = db.inputs.color_offset
color = (abs(position[:])) / scale_value
color += color_offset
ramp = (scale_value - abs(position[0])) / scale_value
ramp = max(ramp, 0)
color[0] -= ramp
if color[0] < 0:
color[0] = 0
color[1] += ramp
if color[1] > 1:
color[1] = 1
color[2] -= ramp
if color[2] < 0:
color[2] = 0
db.outputs.color_size = 1
db.outputs.color[0] = color
return True
| 993 | Python | 24.487179 | 82 | 0.558912 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/realtime/OgnBouncingCubesCpu.py | """
Example node showing realtime update from gathered data.
"""
class OgnBouncingCubesCpu:
@staticmethod
def compute(db):
velocities = db.state.velocities
translations = db.state.translations
# Empty input means nothing to do
if translations.size == 0 or velocities.size == 0:
return True
h = 1.0 / 60.0
g = -1000.0
for ii, velocity in enumerate(velocities):
velocity += h * g
translations[ii][2] += h * velocity
if translations[ii][2] < 1.0:
translations[ii][2] = 1.0
velocity = -5 * h * g
translations[0][0] += 0.03
translations[1][0] += 0.03
# We no longer need to set values because we do not copy memory of the numpy arrays
# Mutating the numpy array will also mutate the attribute data
# Alternative, setting values using the below lines will also work
# context.set_attr_value(translations, attr_translations)
# context.set_attr_value(velocities, attr_translations)
return True
| 1,102 | Python | 29.638888 | 91 | 0.598004 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/realtime/OgnBouncingCubesGpu.py | """
Example node showing realtime update from gathered data computed on the GPU.
"""
class OgnBouncingCubesGpu:
@staticmethod
def compute(db):
# This is how it should work when gather is fully supported
# velocities = db.state.velocities
# translations = db.state.translations
attr_velocities = db.node.get_attribute("state:velocities")
attr_translations = db.node.get_attribute("state:translations")
velocities = db.context_helper.get_attr_value(attr_velocities, isGPU=True, isTensor=True)
translations = db.context_helper.get_attr_value(attr_translations, isGPU=True, isTensor=True)
# When there is no data there is nothing to do
if velocities.size == 0 or translations.size == 0:
return True
h = 1.0 / 60.0
g = -1000.0
velocities += h * g
translations[:, 2] += h * velocities
translations_z = translations.split(1, dim=1)[2].squeeze(-1)
update_idx = (translations_z < 1.0).nonzero().squeeze(-1)
if update_idx.shape[0] > 0:
translations[update_idx, 2] = 1
velocities[update_idx] = -5 * h * g
translations[:, 0] += 0.03
# We no longer need to set values because we do not copy memory of the numpy arrays
# Mutating the numpy array will also mutate the attribute data
# Computegraph APIs using torch tensors currently do not have support for setting values.
# context.set_attr_value(translations, attr_translations)
# context.set_attr_value(velocities, attr_translations)
return True
| 1,624 | Python | 35.11111 | 101 | 0.644089 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/utility/OgnPyUniversalAdd.py | class OgnPyUniversalAdd:
@staticmethod
def compute(db):
db.outputs.bool_0 = db.inputs.bool_0 ^ db.inputs.bool_1
db.outputs.bool_arr_0 = [
db.inputs.bool_arr_0[i] ^ db.inputs.bool_arr_1[i] for i in range(len(db.inputs.bool_arr_0))
]
db.outputs.colord3_0 = db.inputs.colord3_0 + db.inputs.colord3_1
db.outputs.colord4_0 = db.inputs.colord4_0 + db.inputs.colord4_1
db.outputs.colord3_arr_0 = db.inputs.colord3_arr_0 + db.inputs.colord3_arr_1
db.outputs.colord4_arr_0 = db.inputs.colord4_arr_0 + db.inputs.colord4_arr_1
db.outputs.colorf3_0 = db.inputs.colorf3_0 + db.inputs.colorf3_1
db.outputs.colorf4_0 = db.inputs.colorf4_0 + db.inputs.colorf4_1
db.outputs.colorf3_arr_0 = db.inputs.colorf3_arr_0 + db.inputs.colorf3_arr_1
db.outputs.colorf4_arr_0 = db.inputs.colorf4_arr_0 + db.inputs.colorf4_arr_1
db.outputs.colorh3_0 = db.inputs.colorh3_0 + db.inputs.colorh3_1
db.outputs.colorh4_0 = db.inputs.colorh4_0 + db.inputs.colorh4_1
db.outputs.colorh3_arr_0 = db.inputs.colorh3_arr_0 + db.inputs.colorh3_arr_1
db.outputs.colorh4_arr_0 = db.inputs.colorh4_arr_0 + db.inputs.colorh4_arr_1
db.outputs.double_0 = db.inputs.double_0 + db.inputs.double_1
db.outputs.double2_0 = db.inputs.double2_0 + db.inputs.double2_1
db.outputs.double3_0 = db.inputs.double3_0 + db.inputs.double3_1
db.outputs.double4_0 = db.inputs.double4_0 + db.inputs.double4_1
db.outputs.double_arr_0 = db.inputs.double_arr_0 + db.inputs.double_arr_1
db.outputs.double2_arr_0 = db.inputs.double2_arr_0 + db.inputs.double2_arr_1
db.outputs.double3_arr_0 = db.inputs.double3_arr_0 + db.inputs.double3_arr_1
db.outputs.double4_arr_0 = db.inputs.double4_arr_0 + db.inputs.double4_arr_1
db.outputs.float_0 = db.inputs.float_0 + db.inputs.float_1
db.outputs.float2_0 = db.inputs.float2_0 + db.inputs.float2_1
db.outputs.float3_0 = db.inputs.float3_0 + db.inputs.float3_1
db.outputs.float4_0 = db.inputs.float4_0 + db.inputs.float4_1
db.outputs.float_arr_0 = db.inputs.float_arr_0 + db.inputs.float_arr_1
db.outputs.float2_arr_0 = db.inputs.float2_arr_0 + db.inputs.float2_arr_1
db.outputs.float3_arr_0 = db.inputs.float3_arr_0 + db.inputs.float3_arr_1
db.outputs.float4_arr_0 = db.inputs.float4_arr_0 + db.inputs.float4_arr_1
db.outputs.frame4_0 = db.inputs.frame4_0 + db.inputs.frame4_1
db.outputs.frame4_arr_0 = db.inputs.frame4_arr_0 + db.inputs.frame4_arr_1
db.outputs.half_0 = db.inputs.half_0 + db.inputs.half_1
db.outputs.half2_0 = db.inputs.half2_0 + db.inputs.half2_1
db.outputs.half3_0 = db.inputs.half3_0 + db.inputs.half3_1
db.outputs.half4_0 = db.inputs.half4_0 + db.inputs.half4_1
db.outputs.half_arr_0 = db.inputs.half_arr_0 + db.inputs.half_arr_1
db.outputs.half2_arr_0 = db.inputs.half2_arr_0 + db.inputs.half2_arr_1
db.outputs.half3_arr_0 = db.inputs.half3_arr_0 + db.inputs.half3_arr_1
db.outputs.half4_arr_0 = db.inputs.half4_arr_0 + db.inputs.half4_arr_1
db.outputs.int_0 = db.inputs.int_0 + db.inputs.int_1
db.outputs.int2_0 = db.inputs.int2_0 + db.inputs.int2_1
db.outputs.int3_0 = db.inputs.int3_0 + db.inputs.int3_1
db.outputs.int4_0 = db.inputs.int4_0 + db.inputs.int4_1
db.outputs.int_arr_0 = db.inputs.int_arr_0 + db.inputs.int_arr_1
db.outputs.int2_arr_0 = db.inputs.int2_arr_0 + db.inputs.int2_arr_1
db.outputs.int3_arr_0 = db.inputs.int3_arr_0 + db.inputs.int3_arr_1
db.outputs.int4_arr_0 = db.inputs.int4_arr_0 + db.inputs.int4_arr_1
db.outputs.int64_0 = db.inputs.int64_0 + db.inputs.int64_1
db.outputs.int64_arr_0 = db.inputs.int64_arr_0 + db.inputs.int64_arr_1
db.outputs.matrixd2_0 = db.inputs.matrixd2_0 + db.inputs.matrixd2_1
db.outputs.matrixd3_0 = db.inputs.matrixd3_0 + db.inputs.matrixd3_1
db.outputs.matrixd4_0 = db.inputs.matrixd4_0 + db.inputs.matrixd4_1
db.outputs.matrixd2_arr_0 = db.inputs.matrixd2_arr_0 + db.inputs.matrixd2_arr_1
db.outputs.matrixd3_arr_0 = db.inputs.matrixd3_arr_0 + db.inputs.matrixd3_arr_1
db.outputs.matrixd4_arr_0 = db.inputs.matrixd4_arr_0 + db.inputs.matrixd4_arr_1
db.outputs.normald3_0 = db.inputs.normald3_0 + db.inputs.normald3_1
db.outputs.normald3_arr_0 = db.inputs.normald3_arr_0 + db.inputs.normald3_arr_1
db.outputs.normalf3_0 = db.inputs.normalf3_0 + db.inputs.normalf3_1
db.outputs.normalf3_arr_0 = db.inputs.normalf3_arr_0 + db.inputs.normalf3_arr_1
db.outputs.normalh3_0 = db.inputs.normalh3_0 + db.inputs.normalh3_1
db.outputs.normalh3_arr_0 = db.inputs.normalh3_arr_0 + db.inputs.normalh3_arr_1
db.outputs.pointd3_0 = db.inputs.pointd3_0 + db.inputs.pointd3_1
db.outputs.pointd3_arr_0 = db.inputs.pointd3_arr_0 + db.inputs.pointd3_arr_1
db.outputs.pointf3_0 = db.inputs.pointf3_0 + db.inputs.pointf3_1
db.outputs.pointf3_arr_0 = db.inputs.pointf3_arr_0 + db.inputs.pointf3_arr_1
db.outputs.pointh3_0 = db.inputs.pointh3_0 + db.inputs.pointh3_1
db.outputs.pointh3_arr_0 = db.inputs.pointh3_arr_0 + db.inputs.pointh3_arr_1
db.outputs.quatd4_0 = db.inputs.quatd4_0 + db.inputs.quatd4_1
db.outputs.quatd4_arr_0 = db.inputs.quatd4_arr_0 + db.inputs.quatd4_arr_1
db.outputs.quatf4_0 = db.inputs.quatf4_0 + db.inputs.quatf4_1
db.outputs.quatf4_arr_0 = db.inputs.quatf4_arr_0 + db.inputs.quatf4_arr_1
db.outputs.quath4_0 = db.inputs.quath4_0 + db.inputs.quath4_1
db.outputs.quath4_arr_0 = db.inputs.quath4_arr_0 + db.inputs.quath4_arr_1
db.outputs.texcoordd2_0 = db.inputs.texcoordd2_0 + db.inputs.texcoordd2_1
db.outputs.texcoordd3_0 = db.inputs.texcoordd3_0 + db.inputs.texcoordd3_1
db.outputs.texcoordd2_arr_0 = db.inputs.texcoordd2_arr_0 + db.inputs.texcoordd2_arr_1
db.outputs.texcoordd3_arr_0 = db.inputs.texcoordd3_arr_0 + db.inputs.texcoordd3_arr_1
db.outputs.texcoordf2_0 = db.inputs.texcoordf2_0 + db.inputs.texcoordf2_1
db.outputs.texcoordf3_0 = db.inputs.texcoordf3_0 + db.inputs.texcoordf3_1
db.outputs.texcoordf2_arr_0 = db.inputs.texcoordf2_arr_0 + db.inputs.texcoordf2_arr_1
db.outputs.texcoordf3_arr_0 = db.inputs.texcoordf3_arr_0 + db.inputs.texcoordf3_arr_1
db.outputs.texcoordh2_0 = db.inputs.texcoordh2_0 + db.inputs.texcoordh2_1
db.outputs.texcoordh3_0 = db.inputs.texcoordh3_0 + db.inputs.texcoordh3_1
db.outputs.texcoordh2_arr_0 = db.inputs.texcoordh2_arr_0 + db.inputs.texcoordh2_arr_1
db.outputs.texcoordh3_arr_0 = db.inputs.texcoordh3_arr_0 + db.inputs.texcoordh3_arr_1
db.outputs.timecode_0 = db.inputs.timecode_0 + db.inputs.timecode_1
db.outputs.timecode_arr_0 = db.inputs.timecode_arr_0 + db.inputs.timecode_arr_1
db.outputs.token_0 = db.inputs.token_0 + db.inputs.token_1
db.outputs.token_arr_0 = [
db.inputs.token_arr_0[i] + db.inputs.token_arr_1[i] for i in range(len(db.inputs.token_arr_0))
]
db.outputs.transform4_0 = db.inputs.transform4_0 + db.inputs.transform4_1
db.outputs.transform4_arr_0 = db.inputs.transform4_arr_0 + db.inputs.transform4_arr_1
db.outputs.uchar_0 = db.inputs.uchar_0 + db.inputs.uchar_1
db.outputs.uchar_arr_0 = db.inputs.uchar_arr_0 + db.inputs.uchar_arr_1
db.outputs.uint_0 = db.inputs.uint_0 + db.inputs.uint_1
db.outputs.uint_arr_0 = db.inputs.uint_arr_0 + db.inputs.uint_arr_1
db.outputs.uint64_0 = db.inputs.uint64_0 + db.inputs.uint64_1
db.outputs.uint64_arr_0 = db.inputs.uint64_arr_0 + db.inputs.uint64_arr_1
db.outputs.vectord3_0 = db.inputs.vectord3_0 + db.inputs.vectord3_1
db.outputs.vectord3_arr_0 = db.inputs.vectord3_arr_0 + db.inputs.vectord3_arr_1
db.outputs.vectorf3_0 = db.inputs.vectorf3_0 + db.inputs.vectorf3_1
db.outputs.vectorf3_arr_0 = db.inputs.vectorf3_arr_0 + db.inputs.vectorf3_arr_1
db.outputs.vectorh3_0 = db.inputs.vectorh3_0 + db.inputs.vectorh3_1
db.outputs.vectorh3_arr_0 = db.inputs.vectorh3_arr_0 + db.inputs.vectorh3_arr_1
return True
| 8,362 | Python | 72.359648 | 106 | 0.669816 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/utility/OgnDynamicSwitch.py | """
Implementation of an stateful OmniGraph node that enables 1 branch or another using dynamic scheduling
"""
class OgnDynamicSwitch:
@staticmethod
def compute(db):
db.node.set_dynamic_downstream_control(True)
left_out_attr = db.node.get_attribute("outputs:left_out")
right_out_attr = db.node.get_attribute("outputs:right_out")
if db.inputs.switch > 0:
left_out_attr.set_disable_dynamic_downstream_work(True)
right_out_attr.set_disable_dynamic_downstream_work(False)
else:
left_out_attr.set_disable_dynamic_downstream_work(False)
right_out_attr.set_disable_dynamic_downstream_work(True)
db.outputs.left_out = db.inputs.left_value
db.outputs.right_out = db.inputs.right_value
return True
| 812 | Python | 34.347825 | 102 | 0.671182 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/stateful/OgnCountTo.py | """
Implementation of an stateful OmniGraph node that counts to a number defined by countTo
"""
class OgnCountTo:
@staticmethod
def compute(db):
if db.inputs.reset:
db.outputs.count = 0
else:
db.outputs.count = db.outputs.count + db.inputs.increment
if db.outputs.count > db.inputs.countTo:
db.outputs.count = db.inputs.countTo
else:
db.node.set_compute_incomplete()
return True
| 495 | Python | 23.799999 | 87 | 0.589899 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/stateful/OgnIntCounter.py | """
Implementation of an stateful OmniGraph node that counts up by an increment
"""
class OgnIntCounter:
@staticmethod
def compute(db):
if db.inputs.reset:
db.outputs.count = 0
else:
db.outputs.count = db.outputs.count + db.inputs.increment
return True
| 312 | Python | 19.866665 | 75 | 0.625 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tests/OgnTestInitNode.py | import omni.graph.core as og
class OgnTestInitNode:
@staticmethod
def initialize(context, node):
_ = og.Controller()
@staticmethod
def release(node):
pass
@staticmethod
def compute(db):
db.outputs.value = 1.0
return True
| 281 | Python | 15.588234 | 34 | 0.608541 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/tests/OgnTestSingleton.py | class OgnTestSingleton:
@staticmethod
def compute(db):
db.outputs.out = 88.8
return True
| 113 | Python | 17.999997 | 29 | 0.619469 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/deformers/OgnVersionedDeformerPy.py | """
Implementation of a Python node that handles a simple version upgrade where the different versions contain
different attributes:
Version 0: multiplier
Version 1: multiplier, wavelength
Version 2: wavelength
Depending on the version that was received the upgrade will remove the obsolete "multiplier" attribute and/or
insert the new "wavelength" attribute.
"""
import numpy as np
import omni.graph.core as og
class OgnVersionedDeformerPy:
@staticmethod
def compute(db):
input_points = db.inputs.points
if len(input_points) <= 0:
return False
wavelength = db.inputs.wavelength
if wavelength <= 0.0:
wavelength = 310.0
db.outputs.points_size = input_points.shape[0]
# Nothing to evaluate if there are no input points
if db.outputs.points_size == 0:
return True
output_points = db.outputs.points
pt = input_points.copy() # we still need to do a copy here because we do not want to modify points
tx = (pt[:, 0] - wavelength) / wavelength
ty = (pt[:, 1] - wavelength) / wavelength
disp = 10.0 * (np.sin(tx * 10.0) + np.cos(ty * 15.0))
pt[:, 2] += disp * 5
output_points[:] = pt[:] # we modify output_points in memory so we do not need to set the value again
return True
@staticmethod
def update_node_version(context, node, old_version, new_version):
if old_version < new_version:
if old_version < 1:
node.create_attribute(
"inputs:wavelength",
og.Type(og.BaseDataType.FLOAT),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
50.0,
)
if old_version < 2:
node.remove_attribute("inputs:multiplier")
return True
return False
@staticmethod
def initialize_type(node_type):
node_type.add_input("test_input", "int", True)
node_type.add_output("test_output", "float", True)
node_type.add_extended_input(
"test_union_input", "float,double", True, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION
)
return True
| 2,233 | Python | 33.906249 | 110 | 0.605911 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/python/nodes/deformers/OgnDeformerGpu.py | """
Implementation of an OmniGraph node that runs a simple deformer on the GPU
"""
from contextlib import suppress
with suppress(ImportError):
import torch
class OgnDeformerGpu:
@staticmethod
def compute(db) -> bool:
try:
# TODO: This method of GPU compute isn't recommended. Use CPU compute or Warp.
if torch:
input_points = db.inputs.points
multiplier = db.inputs.multiplier
db.outputs.points_size = input_points.shape[0]
# Nothing to evaluate if there are no input points
if db.outputs.points_size == 0:
return True
output_points = db.outputs.points
pt = input_points.copy()
tx = (pt[:, 0] - 310.0) / 310.0
ty = (pt[:, 1] - 310.0) / 310.0
disp = 10.0 * (torch.sin(tx * 10.0) + torch.cos(ty * 15.0))
pt[:, 2] += disp * multiplier
output_points[:] = pt[:]
return True
except NameError:
db.log_warning("Torch not found, no compute")
return False
| 1,153 | Python | 30.189188 | 90 | 0.525585 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/tests/TestOgnDynamicSwitch.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.examples.python.ogn.OgnDynamicSwitchDatabase import OgnDynamicSwitchDatabase
(_, (test_node,), _, _) = og.Controller.edit("/TestGraph", {
og.Controller.Keys.CREATE_NODES: ("Template_omni_graph_examples_python_DynamicSwitch", "omni.graph.examples.python.DynamicSwitch")
})
database = OgnDynamicSwitchDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:left_value"))
attribute = test_node.get_attribute("inputs:left_value")
db_value = database.inputs.left_value
expected_value = -1
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:right_value"))
attribute = test_node.get_attribute("inputs:right_value")
db_value = database.inputs.right_value
expected_value = 1
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:switch"))
attribute = test_node.get_attribute("inputs:switch")
db_value = database.inputs.switch
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:left_out"))
attribute = test_node.get_attribute("outputs:left_out")
db_value = database.outputs.left_out
self.assertTrue(test_node.get_attribute_exists("outputs:right_out"))
attribute = test_node.get_attribute("outputs:right_out")
db_value = database.outputs.right_out
| 2,527 | Python | 47.615384 | 142 | 0.695291 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/ogn/tests/TestOgnPyUniversalAdd.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode
from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene
from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene
class TestOgn(ogts.OmniGraphTestCase):
async def test_data_access(self):
from omni.graph.examples.python.ogn.OgnPyUniversalAddDatabase import OgnPyUniversalAddDatabase
(_, (test_node,), _, _) = og.Controller.edit("/TestGraph", {
og.Controller.Keys.CREATE_NODES: ("Template_omni_graph_examples_python_UniversalAdd", "omni.graph.examples.python.UniversalAdd")
})
database = OgnPyUniversalAddDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:bool_0"))
attribute = test_node.get_attribute("inputs:bool_0")
db_value = database.inputs.bool_0
expected_value = False
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:bool_1"))
attribute = test_node.get_attribute("inputs:bool_1")
db_value = database.inputs.bool_1
expected_value = False
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:bool_arr_0"))
attribute = test_node.get_attribute("inputs:bool_arr_0")
db_value = database.inputs.bool_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:bool_arr_1"))
attribute = test_node.get_attribute("inputs:bool_arr_1")
db_value = database.inputs.bool_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord3_0"))
attribute = test_node.get_attribute("inputs:colord3_0")
db_value = database.inputs.colord3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord3_1"))
attribute = test_node.get_attribute("inputs:colord3_1")
db_value = database.inputs.colord3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord3_arr_0"))
attribute = test_node.get_attribute("inputs:colord3_arr_0")
db_value = database.inputs.colord3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord3_arr_1"))
attribute = test_node.get_attribute("inputs:colord3_arr_1")
db_value = database.inputs.colord3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord4_0"))
attribute = test_node.get_attribute("inputs:colord4_0")
db_value = database.inputs.colord4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord4_1"))
attribute = test_node.get_attribute("inputs:colord4_1")
db_value = database.inputs.colord4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord4_arr_0"))
attribute = test_node.get_attribute("inputs:colord4_arr_0")
db_value = database.inputs.colord4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colord4_arr_1"))
attribute = test_node.get_attribute("inputs:colord4_arr_1")
db_value = database.inputs.colord4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf3_0"))
attribute = test_node.get_attribute("inputs:colorf3_0")
db_value = database.inputs.colorf3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf3_1"))
attribute = test_node.get_attribute("inputs:colorf3_1")
db_value = database.inputs.colorf3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf3_arr_0"))
attribute = test_node.get_attribute("inputs:colorf3_arr_0")
db_value = database.inputs.colorf3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf3_arr_1"))
attribute = test_node.get_attribute("inputs:colorf3_arr_1")
db_value = database.inputs.colorf3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf4_0"))
attribute = test_node.get_attribute("inputs:colorf4_0")
db_value = database.inputs.colorf4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf4_1"))
attribute = test_node.get_attribute("inputs:colorf4_1")
db_value = database.inputs.colorf4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf4_arr_0"))
attribute = test_node.get_attribute("inputs:colorf4_arr_0")
db_value = database.inputs.colorf4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorf4_arr_1"))
attribute = test_node.get_attribute("inputs:colorf4_arr_1")
db_value = database.inputs.colorf4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh3_0"))
attribute = test_node.get_attribute("inputs:colorh3_0")
db_value = database.inputs.colorh3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh3_1"))
attribute = test_node.get_attribute("inputs:colorh3_1")
db_value = database.inputs.colorh3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh3_arr_0"))
attribute = test_node.get_attribute("inputs:colorh3_arr_0")
db_value = database.inputs.colorh3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh3_arr_1"))
attribute = test_node.get_attribute("inputs:colorh3_arr_1")
db_value = database.inputs.colorh3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh4_0"))
attribute = test_node.get_attribute("inputs:colorh4_0")
db_value = database.inputs.colorh4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh4_1"))
attribute = test_node.get_attribute("inputs:colorh4_1")
db_value = database.inputs.colorh4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh4_arr_0"))
attribute = test_node.get_attribute("inputs:colorh4_arr_0")
db_value = database.inputs.colorh4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:colorh4_arr_1"))
attribute = test_node.get_attribute("inputs:colorh4_arr_1")
db_value = database.inputs.colorh4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double2_0"))
attribute = test_node.get_attribute("inputs:double2_0")
db_value = database.inputs.double2_0
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double2_1"))
attribute = test_node.get_attribute("inputs:double2_1")
db_value = database.inputs.double2_1
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double2_arr_0"))
attribute = test_node.get_attribute("inputs:double2_arr_0")
db_value = database.inputs.double2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double2_arr_1"))
attribute = test_node.get_attribute("inputs:double2_arr_1")
db_value = database.inputs.double2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double3_0"))
attribute = test_node.get_attribute("inputs:double3_0")
db_value = database.inputs.double3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double3_1"))
attribute = test_node.get_attribute("inputs:double3_1")
db_value = database.inputs.double3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double3_arr_0"))
attribute = test_node.get_attribute("inputs:double3_arr_0")
db_value = database.inputs.double3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double3_arr_1"))
attribute = test_node.get_attribute("inputs:double3_arr_1")
db_value = database.inputs.double3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double4_0"))
attribute = test_node.get_attribute("inputs:double4_0")
db_value = database.inputs.double4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double4_1"))
attribute = test_node.get_attribute("inputs:double4_1")
db_value = database.inputs.double4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double4_arr_0"))
attribute = test_node.get_attribute("inputs:double4_arr_0")
db_value = database.inputs.double4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double4_arr_1"))
attribute = test_node.get_attribute("inputs:double4_arr_1")
db_value = database.inputs.double4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double_0"))
attribute = test_node.get_attribute("inputs:double_0")
db_value = database.inputs.double_0
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double_1"))
attribute = test_node.get_attribute("inputs:double_1")
db_value = database.inputs.double_1
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double_arr_0"))
attribute = test_node.get_attribute("inputs:double_arr_0")
db_value = database.inputs.double_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:double_arr_1"))
attribute = test_node.get_attribute("inputs:double_arr_1")
db_value = database.inputs.double_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float2_0"))
attribute = test_node.get_attribute("inputs:float2_0")
db_value = database.inputs.float2_0
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float2_1"))
attribute = test_node.get_attribute("inputs:float2_1")
db_value = database.inputs.float2_1
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float2_arr_0"))
attribute = test_node.get_attribute("inputs:float2_arr_0")
db_value = database.inputs.float2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float2_arr_1"))
attribute = test_node.get_attribute("inputs:float2_arr_1")
db_value = database.inputs.float2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float3_0"))
attribute = test_node.get_attribute("inputs:float3_0")
db_value = database.inputs.float3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float3_1"))
attribute = test_node.get_attribute("inputs:float3_1")
db_value = database.inputs.float3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float3_arr_0"))
attribute = test_node.get_attribute("inputs:float3_arr_0")
db_value = database.inputs.float3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float3_arr_1"))
attribute = test_node.get_attribute("inputs:float3_arr_1")
db_value = database.inputs.float3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float4_0"))
attribute = test_node.get_attribute("inputs:float4_0")
db_value = database.inputs.float4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float4_1"))
attribute = test_node.get_attribute("inputs:float4_1")
db_value = database.inputs.float4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float4_arr_0"))
attribute = test_node.get_attribute("inputs:float4_arr_0")
db_value = database.inputs.float4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float4_arr_1"))
attribute = test_node.get_attribute("inputs:float4_arr_1")
db_value = database.inputs.float4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float_0"))
attribute = test_node.get_attribute("inputs:float_0")
db_value = database.inputs.float_0
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float_1"))
attribute = test_node.get_attribute("inputs:float_1")
db_value = database.inputs.float_1
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float_arr_0"))
attribute = test_node.get_attribute("inputs:float_arr_0")
db_value = database.inputs.float_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:float_arr_1"))
attribute = test_node.get_attribute("inputs:float_arr_1")
db_value = database.inputs.float_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:frame4_0"))
attribute = test_node.get_attribute("inputs:frame4_0")
db_value = database.inputs.frame4_0
expected_value = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:frame4_1"))
attribute = test_node.get_attribute("inputs:frame4_1")
db_value = database.inputs.frame4_1
expected_value = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:frame4_arr_0"))
attribute = test_node.get_attribute("inputs:frame4_arr_0")
db_value = database.inputs.frame4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:frame4_arr_1"))
attribute = test_node.get_attribute("inputs:frame4_arr_1")
db_value = database.inputs.frame4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half2_0"))
attribute = test_node.get_attribute("inputs:half2_0")
db_value = database.inputs.half2_0
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half2_1"))
attribute = test_node.get_attribute("inputs:half2_1")
db_value = database.inputs.half2_1
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half2_arr_0"))
attribute = test_node.get_attribute("inputs:half2_arr_0")
db_value = database.inputs.half2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half2_arr_1"))
attribute = test_node.get_attribute("inputs:half2_arr_1")
db_value = database.inputs.half2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half3_0"))
attribute = test_node.get_attribute("inputs:half3_0")
db_value = database.inputs.half3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half3_1"))
attribute = test_node.get_attribute("inputs:half3_1")
db_value = database.inputs.half3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half3_arr_0"))
attribute = test_node.get_attribute("inputs:half3_arr_0")
db_value = database.inputs.half3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half3_arr_1"))
attribute = test_node.get_attribute("inputs:half3_arr_1")
db_value = database.inputs.half3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half4_0"))
attribute = test_node.get_attribute("inputs:half4_0")
db_value = database.inputs.half4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half4_1"))
attribute = test_node.get_attribute("inputs:half4_1")
db_value = database.inputs.half4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half4_arr_0"))
attribute = test_node.get_attribute("inputs:half4_arr_0")
db_value = database.inputs.half4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half4_arr_1"))
attribute = test_node.get_attribute("inputs:half4_arr_1")
db_value = database.inputs.half4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half_0"))
attribute = test_node.get_attribute("inputs:half_0")
db_value = database.inputs.half_0
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half_1"))
attribute = test_node.get_attribute("inputs:half_1")
db_value = database.inputs.half_1
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half_arr_0"))
attribute = test_node.get_attribute("inputs:half_arr_0")
db_value = database.inputs.half_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:half_arr_1"))
attribute = test_node.get_attribute("inputs:half_arr_1")
db_value = database.inputs.half_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int2_0"))
attribute = test_node.get_attribute("inputs:int2_0")
db_value = database.inputs.int2_0
expected_value = [0, 0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int2_1"))
attribute = test_node.get_attribute("inputs:int2_1")
db_value = database.inputs.int2_1
expected_value = [0, 0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int2_arr_0"))
attribute = test_node.get_attribute("inputs:int2_arr_0")
db_value = database.inputs.int2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int2_arr_1"))
attribute = test_node.get_attribute("inputs:int2_arr_1")
db_value = database.inputs.int2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int3_0"))
attribute = test_node.get_attribute("inputs:int3_0")
db_value = database.inputs.int3_0
expected_value = [0, 0, 0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int3_1"))
attribute = test_node.get_attribute("inputs:int3_1")
db_value = database.inputs.int3_1
expected_value = [0, 0, 0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int3_arr_0"))
attribute = test_node.get_attribute("inputs:int3_arr_0")
db_value = database.inputs.int3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int3_arr_1"))
attribute = test_node.get_attribute("inputs:int3_arr_1")
db_value = database.inputs.int3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int4_0"))
attribute = test_node.get_attribute("inputs:int4_0")
db_value = database.inputs.int4_0
expected_value = [0, 0, 0, 0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int4_1"))
attribute = test_node.get_attribute("inputs:int4_1")
db_value = database.inputs.int4_1
expected_value = [0, 0, 0, 0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int4_arr_0"))
attribute = test_node.get_attribute("inputs:int4_arr_0")
db_value = database.inputs.int4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int4_arr_1"))
attribute = test_node.get_attribute("inputs:int4_arr_1")
db_value = database.inputs.int4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int64_0"))
attribute = test_node.get_attribute("inputs:int64_0")
db_value = database.inputs.int64_0
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int64_1"))
attribute = test_node.get_attribute("inputs:int64_1")
db_value = database.inputs.int64_1
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int64_arr_0"))
attribute = test_node.get_attribute("inputs:int64_arr_0")
db_value = database.inputs.int64_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int64_arr_1"))
attribute = test_node.get_attribute("inputs:int64_arr_1")
db_value = database.inputs.int64_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int_0"))
attribute = test_node.get_attribute("inputs:int_0")
db_value = database.inputs.int_0
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int_1"))
attribute = test_node.get_attribute("inputs:int_1")
db_value = database.inputs.int_1
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int_arr_0"))
attribute = test_node.get_attribute("inputs:int_arr_0")
db_value = database.inputs.int_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:int_arr_1"))
attribute = test_node.get_attribute("inputs:int_arr_1")
db_value = database.inputs.int_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd2_0"))
attribute = test_node.get_attribute("inputs:matrixd2_0")
db_value = database.inputs.matrixd2_0
expected_value = [[0.0, 0.0], [0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd2_1"))
attribute = test_node.get_attribute("inputs:matrixd2_1")
db_value = database.inputs.matrixd2_1
expected_value = [[0.0, 0.0], [0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd2_arr_0"))
attribute = test_node.get_attribute("inputs:matrixd2_arr_0")
db_value = database.inputs.matrixd2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd2_arr_1"))
attribute = test_node.get_attribute("inputs:matrixd2_arr_1")
db_value = database.inputs.matrixd2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd3_0"))
attribute = test_node.get_attribute("inputs:matrixd3_0")
db_value = database.inputs.matrixd3_0
expected_value = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd3_1"))
attribute = test_node.get_attribute("inputs:matrixd3_1")
db_value = database.inputs.matrixd3_1
expected_value = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd3_arr_0"))
attribute = test_node.get_attribute("inputs:matrixd3_arr_0")
db_value = database.inputs.matrixd3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd3_arr_1"))
attribute = test_node.get_attribute("inputs:matrixd3_arr_1")
db_value = database.inputs.matrixd3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd4_0"))
attribute = test_node.get_attribute("inputs:matrixd4_0")
db_value = database.inputs.matrixd4_0
expected_value = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd4_1"))
attribute = test_node.get_attribute("inputs:matrixd4_1")
db_value = database.inputs.matrixd4_1
expected_value = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd4_arr_0"))
attribute = test_node.get_attribute("inputs:matrixd4_arr_0")
db_value = database.inputs.matrixd4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:matrixd4_arr_1"))
attribute = test_node.get_attribute("inputs:matrixd4_arr_1")
db_value = database.inputs.matrixd4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normald3_0"))
attribute = test_node.get_attribute("inputs:normald3_0")
db_value = database.inputs.normald3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normald3_1"))
attribute = test_node.get_attribute("inputs:normald3_1")
db_value = database.inputs.normald3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normald3_arr_0"))
attribute = test_node.get_attribute("inputs:normald3_arr_0")
db_value = database.inputs.normald3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normald3_arr_1"))
attribute = test_node.get_attribute("inputs:normald3_arr_1")
db_value = database.inputs.normald3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalf3_0"))
attribute = test_node.get_attribute("inputs:normalf3_0")
db_value = database.inputs.normalf3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalf3_1"))
attribute = test_node.get_attribute("inputs:normalf3_1")
db_value = database.inputs.normalf3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalf3_arr_0"))
attribute = test_node.get_attribute("inputs:normalf3_arr_0")
db_value = database.inputs.normalf3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalf3_arr_1"))
attribute = test_node.get_attribute("inputs:normalf3_arr_1")
db_value = database.inputs.normalf3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalh3_0"))
attribute = test_node.get_attribute("inputs:normalh3_0")
db_value = database.inputs.normalh3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalh3_1"))
attribute = test_node.get_attribute("inputs:normalh3_1")
db_value = database.inputs.normalh3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalh3_arr_0"))
attribute = test_node.get_attribute("inputs:normalh3_arr_0")
db_value = database.inputs.normalh3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:normalh3_arr_1"))
attribute = test_node.get_attribute("inputs:normalh3_arr_1")
db_value = database.inputs.normalh3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointd3_0"))
attribute = test_node.get_attribute("inputs:pointd3_0")
db_value = database.inputs.pointd3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointd3_1"))
attribute = test_node.get_attribute("inputs:pointd3_1")
db_value = database.inputs.pointd3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointd3_arr_0"))
attribute = test_node.get_attribute("inputs:pointd3_arr_0")
db_value = database.inputs.pointd3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointd3_arr_1"))
attribute = test_node.get_attribute("inputs:pointd3_arr_1")
db_value = database.inputs.pointd3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointf3_0"))
attribute = test_node.get_attribute("inputs:pointf3_0")
db_value = database.inputs.pointf3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointf3_1"))
attribute = test_node.get_attribute("inputs:pointf3_1")
db_value = database.inputs.pointf3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointf3_arr_0"))
attribute = test_node.get_attribute("inputs:pointf3_arr_0")
db_value = database.inputs.pointf3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointf3_arr_1"))
attribute = test_node.get_attribute("inputs:pointf3_arr_1")
db_value = database.inputs.pointf3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointh3_0"))
attribute = test_node.get_attribute("inputs:pointh3_0")
db_value = database.inputs.pointh3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointh3_1"))
attribute = test_node.get_attribute("inputs:pointh3_1")
db_value = database.inputs.pointh3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointh3_arr_0"))
attribute = test_node.get_attribute("inputs:pointh3_arr_0")
db_value = database.inputs.pointh3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:pointh3_arr_1"))
attribute = test_node.get_attribute("inputs:pointh3_arr_1")
db_value = database.inputs.pointh3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatd4_0"))
attribute = test_node.get_attribute("inputs:quatd4_0")
db_value = database.inputs.quatd4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatd4_1"))
attribute = test_node.get_attribute("inputs:quatd4_1")
db_value = database.inputs.quatd4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatd4_arr_0"))
attribute = test_node.get_attribute("inputs:quatd4_arr_0")
db_value = database.inputs.quatd4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatd4_arr_1"))
attribute = test_node.get_attribute("inputs:quatd4_arr_1")
db_value = database.inputs.quatd4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatf4_0"))
attribute = test_node.get_attribute("inputs:quatf4_0")
db_value = database.inputs.quatf4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatf4_1"))
attribute = test_node.get_attribute("inputs:quatf4_1")
db_value = database.inputs.quatf4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatf4_arr_0"))
attribute = test_node.get_attribute("inputs:quatf4_arr_0")
db_value = database.inputs.quatf4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quatf4_arr_1"))
attribute = test_node.get_attribute("inputs:quatf4_arr_1")
db_value = database.inputs.quatf4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quath4_0"))
attribute = test_node.get_attribute("inputs:quath4_0")
db_value = database.inputs.quath4_0
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quath4_1"))
attribute = test_node.get_attribute("inputs:quath4_1")
db_value = database.inputs.quath4_1
expected_value = [0.0, 0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quath4_arr_0"))
attribute = test_node.get_attribute("inputs:quath4_arr_0")
db_value = database.inputs.quath4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:quath4_arr_1"))
attribute = test_node.get_attribute("inputs:quath4_arr_1")
db_value = database.inputs.quath4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd2_0"))
attribute = test_node.get_attribute("inputs:texcoordd2_0")
db_value = database.inputs.texcoordd2_0
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd2_1"))
attribute = test_node.get_attribute("inputs:texcoordd2_1")
db_value = database.inputs.texcoordd2_1
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd2_arr_0"))
attribute = test_node.get_attribute("inputs:texcoordd2_arr_0")
db_value = database.inputs.texcoordd2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd2_arr_1"))
attribute = test_node.get_attribute("inputs:texcoordd2_arr_1")
db_value = database.inputs.texcoordd2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd3_0"))
attribute = test_node.get_attribute("inputs:texcoordd3_0")
db_value = database.inputs.texcoordd3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd3_1"))
attribute = test_node.get_attribute("inputs:texcoordd3_1")
db_value = database.inputs.texcoordd3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd3_arr_0"))
attribute = test_node.get_attribute("inputs:texcoordd3_arr_0")
db_value = database.inputs.texcoordd3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordd3_arr_1"))
attribute = test_node.get_attribute("inputs:texcoordd3_arr_1")
db_value = database.inputs.texcoordd3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf2_0"))
attribute = test_node.get_attribute("inputs:texcoordf2_0")
db_value = database.inputs.texcoordf2_0
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf2_1"))
attribute = test_node.get_attribute("inputs:texcoordf2_1")
db_value = database.inputs.texcoordf2_1
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf2_arr_0"))
attribute = test_node.get_attribute("inputs:texcoordf2_arr_0")
db_value = database.inputs.texcoordf2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf2_arr_1"))
attribute = test_node.get_attribute("inputs:texcoordf2_arr_1")
db_value = database.inputs.texcoordf2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf3_0"))
attribute = test_node.get_attribute("inputs:texcoordf3_0")
db_value = database.inputs.texcoordf3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf3_1"))
attribute = test_node.get_attribute("inputs:texcoordf3_1")
db_value = database.inputs.texcoordf3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf3_arr_0"))
attribute = test_node.get_attribute("inputs:texcoordf3_arr_0")
db_value = database.inputs.texcoordf3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordf3_arr_1"))
attribute = test_node.get_attribute("inputs:texcoordf3_arr_1")
db_value = database.inputs.texcoordf3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh2_0"))
attribute = test_node.get_attribute("inputs:texcoordh2_0")
db_value = database.inputs.texcoordh2_0
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh2_1"))
attribute = test_node.get_attribute("inputs:texcoordh2_1")
db_value = database.inputs.texcoordh2_1
expected_value = [0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh2_arr_0"))
attribute = test_node.get_attribute("inputs:texcoordh2_arr_0")
db_value = database.inputs.texcoordh2_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh2_arr_1"))
attribute = test_node.get_attribute("inputs:texcoordh2_arr_1")
db_value = database.inputs.texcoordh2_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh3_0"))
attribute = test_node.get_attribute("inputs:texcoordh3_0")
db_value = database.inputs.texcoordh3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh3_1"))
attribute = test_node.get_attribute("inputs:texcoordh3_1")
db_value = database.inputs.texcoordh3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh3_arr_0"))
attribute = test_node.get_attribute("inputs:texcoordh3_arr_0")
db_value = database.inputs.texcoordh3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:texcoordh3_arr_1"))
attribute = test_node.get_attribute("inputs:texcoordh3_arr_1")
db_value = database.inputs.texcoordh3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:timecode_0"))
attribute = test_node.get_attribute("inputs:timecode_0")
db_value = database.inputs.timecode_0
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:timecode_1"))
attribute = test_node.get_attribute("inputs:timecode_1")
db_value = database.inputs.timecode_1
expected_value = 0.0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:timecode_arr_0"))
attribute = test_node.get_attribute("inputs:timecode_arr_0")
db_value = database.inputs.timecode_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:timecode_arr_1"))
attribute = test_node.get_attribute("inputs:timecode_arr_1")
db_value = database.inputs.timecode_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:token_0"))
attribute = test_node.get_attribute("inputs:token_0")
db_value = database.inputs.token_0
expected_value = "default_token"
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:token_1"))
attribute = test_node.get_attribute("inputs:token_1")
db_value = database.inputs.token_1
expected_value = "default_token"
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:token_arr_0"))
attribute = test_node.get_attribute("inputs:token_arr_0")
db_value = database.inputs.token_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:token_arr_1"))
attribute = test_node.get_attribute("inputs:token_arr_1")
db_value = database.inputs.token_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:transform4_0"))
attribute = test_node.get_attribute("inputs:transform4_0")
db_value = database.inputs.transform4_0
expected_value = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:transform4_1"))
attribute = test_node.get_attribute("inputs:transform4_1")
db_value = database.inputs.transform4_1
expected_value = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:transform4_arr_0"))
attribute = test_node.get_attribute("inputs:transform4_arr_0")
db_value = database.inputs.transform4_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:transform4_arr_1"))
attribute = test_node.get_attribute("inputs:transform4_arr_1")
db_value = database.inputs.transform4_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uchar_0"))
attribute = test_node.get_attribute("inputs:uchar_0")
db_value = database.inputs.uchar_0
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uchar_1"))
attribute = test_node.get_attribute("inputs:uchar_1")
db_value = database.inputs.uchar_1
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uchar_arr_0"))
attribute = test_node.get_attribute("inputs:uchar_arr_0")
db_value = database.inputs.uchar_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uchar_arr_1"))
attribute = test_node.get_attribute("inputs:uchar_arr_1")
db_value = database.inputs.uchar_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint64_0"))
attribute = test_node.get_attribute("inputs:uint64_0")
db_value = database.inputs.uint64_0
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint64_1"))
attribute = test_node.get_attribute("inputs:uint64_1")
db_value = database.inputs.uint64_1
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint64_arr_0"))
attribute = test_node.get_attribute("inputs:uint64_arr_0")
db_value = database.inputs.uint64_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint64_arr_1"))
attribute = test_node.get_attribute("inputs:uint64_arr_1")
db_value = database.inputs.uint64_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint_0"))
attribute = test_node.get_attribute("inputs:uint_0")
db_value = database.inputs.uint_0
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint_1"))
attribute = test_node.get_attribute("inputs:uint_1")
db_value = database.inputs.uint_1
expected_value = 0
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint_arr_0"))
attribute = test_node.get_attribute("inputs:uint_arr_0")
db_value = database.inputs.uint_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:uint_arr_1"))
attribute = test_node.get_attribute("inputs:uint_arr_1")
db_value = database.inputs.uint_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectord3_0"))
attribute = test_node.get_attribute("inputs:vectord3_0")
db_value = database.inputs.vectord3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectord3_1"))
attribute = test_node.get_attribute("inputs:vectord3_1")
db_value = database.inputs.vectord3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectord3_arr_0"))
attribute = test_node.get_attribute("inputs:vectord3_arr_0")
db_value = database.inputs.vectord3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectord3_arr_1"))
attribute = test_node.get_attribute("inputs:vectord3_arr_1")
db_value = database.inputs.vectord3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorf3_0"))
attribute = test_node.get_attribute("inputs:vectorf3_0")
db_value = database.inputs.vectorf3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorf3_1"))
attribute = test_node.get_attribute("inputs:vectorf3_1")
db_value = database.inputs.vectorf3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorf3_arr_0"))
attribute = test_node.get_attribute("inputs:vectorf3_arr_0")
db_value = database.inputs.vectorf3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorf3_arr_1"))
attribute = test_node.get_attribute("inputs:vectorf3_arr_1")
db_value = database.inputs.vectorf3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorh3_0"))
attribute = test_node.get_attribute("inputs:vectorh3_0")
db_value = database.inputs.vectorh3_0
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorh3_1"))
attribute = test_node.get_attribute("inputs:vectorh3_1")
db_value = database.inputs.vectorh3_1
expected_value = [0.0, 0.0, 0.0]
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorh3_arr_0"))
attribute = test_node.get_attribute("inputs:vectorh3_arr_0")
db_value = database.inputs.vectorh3_arr_0
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("inputs:vectorh3_arr_1"))
attribute = test_node.get_attribute("inputs:vectorh3_arr_1")
db_value = database.inputs.vectorh3_arr_1
expected_value = []
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:bool_0"))
attribute = test_node.get_attribute("outputs:bool_0")
db_value = database.outputs.bool_0
self.assertTrue(test_node.get_attribute_exists("outputs:bool_arr_0"))
attribute = test_node.get_attribute("outputs:bool_arr_0")
db_value = database.outputs.bool_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:colord3_0"))
attribute = test_node.get_attribute("outputs:colord3_0")
db_value = database.outputs.colord3_0
self.assertTrue(test_node.get_attribute_exists("outputs:colord3_arr_0"))
attribute = test_node.get_attribute("outputs:colord3_arr_0")
db_value = database.outputs.colord3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:colord4_0"))
attribute = test_node.get_attribute("outputs:colord4_0")
db_value = database.outputs.colord4_0
self.assertTrue(test_node.get_attribute_exists("outputs:colord4_arr_0"))
attribute = test_node.get_attribute("outputs:colord4_arr_0")
db_value = database.outputs.colord4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorf3_0"))
attribute = test_node.get_attribute("outputs:colorf3_0")
db_value = database.outputs.colorf3_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorf3_arr_0"))
attribute = test_node.get_attribute("outputs:colorf3_arr_0")
db_value = database.outputs.colorf3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorf4_0"))
attribute = test_node.get_attribute("outputs:colorf4_0")
db_value = database.outputs.colorf4_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorf4_arr_0"))
attribute = test_node.get_attribute("outputs:colorf4_arr_0")
db_value = database.outputs.colorf4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorh3_0"))
attribute = test_node.get_attribute("outputs:colorh3_0")
db_value = database.outputs.colorh3_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorh3_arr_0"))
attribute = test_node.get_attribute("outputs:colorh3_arr_0")
db_value = database.outputs.colorh3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorh4_0"))
attribute = test_node.get_attribute("outputs:colorh4_0")
db_value = database.outputs.colorh4_0
self.assertTrue(test_node.get_attribute_exists("outputs:colorh4_arr_0"))
attribute = test_node.get_attribute("outputs:colorh4_arr_0")
db_value = database.outputs.colorh4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:double2_0"))
attribute = test_node.get_attribute("outputs:double2_0")
db_value = database.outputs.double2_0
self.assertTrue(test_node.get_attribute_exists("outputs:double2_arr_0"))
attribute = test_node.get_attribute("outputs:double2_arr_0")
db_value = database.outputs.double2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:double3_0"))
attribute = test_node.get_attribute("outputs:double3_0")
db_value = database.outputs.double3_0
self.assertTrue(test_node.get_attribute_exists("outputs:double3_arr_0"))
attribute = test_node.get_attribute("outputs:double3_arr_0")
db_value = database.outputs.double3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:double4_0"))
attribute = test_node.get_attribute("outputs:double4_0")
db_value = database.outputs.double4_0
self.assertTrue(test_node.get_attribute_exists("outputs:double4_arr_0"))
attribute = test_node.get_attribute("outputs:double4_arr_0")
db_value = database.outputs.double4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:double_0"))
attribute = test_node.get_attribute("outputs:double_0")
db_value = database.outputs.double_0
self.assertTrue(test_node.get_attribute_exists("outputs:double_arr_0"))
attribute = test_node.get_attribute("outputs:double_arr_0")
db_value = database.outputs.double_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:float2_0"))
attribute = test_node.get_attribute("outputs:float2_0")
db_value = database.outputs.float2_0
self.assertTrue(test_node.get_attribute_exists("outputs:float2_arr_0"))
attribute = test_node.get_attribute("outputs:float2_arr_0")
db_value = database.outputs.float2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:float3_0"))
attribute = test_node.get_attribute("outputs:float3_0")
db_value = database.outputs.float3_0
self.assertTrue(test_node.get_attribute_exists("outputs:float3_arr_0"))
attribute = test_node.get_attribute("outputs:float3_arr_0")
db_value = database.outputs.float3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:float4_0"))
attribute = test_node.get_attribute("outputs:float4_0")
db_value = database.outputs.float4_0
self.assertTrue(test_node.get_attribute_exists("outputs:float4_arr_0"))
attribute = test_node.get_attribute("outputs:float4_arr_0")
db_value = database.outputs.float4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:float_0"))
attribute = test_node.get_attribute("outputs:float_0")
db_value = database.outputs.float_0
self.assertTrue(test_node.get_attribute_exists("outputs:float_arr_0"))
attribute = test_node.get_attribute("outputs:float_arr_0")
db_value = database.outputs.float_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:frame4_0"))
attribute = test_node.get_attribute("outputs:frame4_0")
db_value = database.outputs.frame4_0
self.assertTrue(test_node.get_attribute_exists("outputs:frame4_arr_0"))
attribute = test_node.get_attribute("outputs:frame4_arr_0")
db_value = database.outputs.frame4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:half2_0"))
attribute = test_node.get_attribute("outputs:half2_0")
db_value = database.outputs.half2_0
self.assertTrue(test_node.get_attribute_exists("outputs:half2_arr_0"))
attribute = test_node.get_attribute("outputs:half2_arr_0")
db_value = database.outputs.half2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:half3_0"))
attribute = test_node.get_attribute("outputs:half3_0")
db_value = database.outputs.half3_0
self.assertTrue(test_node.get_attribute_exists("outputs:half3_arr_0"))
attribute = test_node.get_attribute("outputs:half3_arr_0")
db_value = database.outputs.half3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:half4_0"))
attribute = test_node.get_attribute("outputs:half4_0")
db_value = database.outputs.half4_0
self.assertTrue(test_node.get_attribute_exists("outputs:half4_arr_0"))
attribute = test_node.get_attribute("outputs:half4_arr_0")
db_value = database.outputs.half4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:half_0"))
attribute = test_node.get_attribute("outputs:half_0")
db_value = database.outputs.half_0
self.assertTrue(test_node.get_attribute_exists("outputs:half_arr_0"))
attribute = test_node.get_attribute("outputs:half_arr_0")
db_value = database.outputs.half_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:int2_0"))
attribute = test_node.get_attribute("outputs:int2_0")
db_value = database.outputs.int2_0
self.assertTrue(test_node.get_attribute_exists("outputs:int2_arr_0"))
attribute = test_node.get_attribute("outputs:int2_arr_0")
db_value = database.outputs.int2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:int3_0"))
attribute = test_node.get_attribute("outputs:int3_0")
db_value = database.outputs.int3_0
self.assertTrue(test_node.get_attribute_exists("outputs:int3_arr_0"))
attribute = test_node.get_attribute("outputs:int3_arr_0")
db_value = database.outputs.int3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:int4_0"))
attribute = test_node.get_attribute("outputs:int4_0")
db_value = database.outputs.int4_0
self.assertTrue(test_node.get_attribute_exists("outputs:int4_arr_0"))
attribute = test_node.get_attribute("outputs:int4_arr_0")
db_value = database.outputs.int4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:int64_0"))
attribute = test_node.get_attribute("outputs:int64_0")
db_value = database.outputs.int64_0
self.assertTrue(test_node.get_attribute_exists("outputs:int64_arr_0"))
attribute = test_node.get_attribute("outputs:int64_arr_0")
db_value = database.outputs.int64_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:int_0"))
attribute = test_node.get_attribute("outputs:int_0")
db_value = database.outputs.int_0
self.assertTrue(test_node.get_attribute_exists("outputs:int_arr_0"))
attribute = test_node.get_attribute("outputs:int_arr_0")
db_value = database.outputs.int_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:matrixd2_0"))
attribute = test_node.get_attribute("outputs:matrixd2_0")
db_value = database.outputs.matrixd2_0
self.assertTrue(test_node.get_attribute_exists("outputs:matrixd2_arr_0"))
attribute = test_node.get_attribute("outputs:matrixd2_arr_0")
db_value = database.outputs.matrixd2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:matrixd3_0"))
attribute = test_node.get_attribute("outputs:matrixd3_0")
db_value = database.outputs.matrixd3_0
self.assertTrue(test_node.get_attribute_exists("outputs:matrixd3_arr_0"))
attribute = test_node.get_attribute("outputs:matrixd3_arr_0")
db_value = database.outputs.matrixd3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:matrixd4_0"))
attribute = test_node.get_attribute("outputs:matrixd4_0")
db_value = database.outputs.matrixd4_0
self.assertTrue(test_node.get_attribute_exists("outputs:matrixd4_arr_0"))
attribute = test_node.get_attribute("outputs:matrixd4_arr_0")
db_value = database.outputs.matrixd4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:normald3_0"))
attribute = test_node.get_attribute("outputs:normald3_0")
db_value = database.outputs.normald3_0
self.assertTrue(test_node.get_attribute_exists("outputs:normald3_arr_0"))
attribute = test_node.get_attribute("outputs:normald3_arr_0")
db_value = database.outputs.normald3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:normalf3_0"))
attribute = test_node.get_attribute("outputs:normalf3_0")
db_value = database.outputs.normalf3_0
self.assertTrue(test_node.get_attribute_exists("outputs:normalf3_arr_0"))
attribute = test_node.get_attribute("outputs:normalf3_arr_0")
db_value = database.outputs.normalf3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:normalh3_0"))
attribute = test_node.get_attribute("outputs:normalh3_0")
db_value = database.outputs.normalh3_0
self.assertTrue(test_node.get_attribute_exists("outputs:normalh3_arr_0"))
attribute = test_node.get_attribute("outputs:normalh3_arr_0")
db_value = database.outputs.normalh3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:pointd3_0"))
attribute = test_node.get_attribute("outputs:pointd3_0")
db_value = database.outputs.pointd3_0
self.assertTrue(test_node.get_attribute_exists("outputs:pointd3_arr_0"))
attribute = test_node.get_attribute("outputs:pointd3_arr_0")
db_value = database.outputs.pointd3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:pointf3_0"))
attribute = test_node.get_attribute("outputs:pointf3_0")
db_value = database.outputs.pointf3_0
self.assertTrue(test_node.get_attribute_exists("outputs:pointf3_arr_0"))
attribute = test_node.get_attribute("outputs:pointf3_arr_0")
db_value = database.outputs.pointf3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:pointh3_0"))
attribute = test_node.get_attribute("outputs:pointh3_0")
db_value = database.outputs.pointh3_0
self.assertTrue(test_node.get_attribute_exists("outputs:pointh3_arr_0"))
attribute = test_node.get_attribute("outputs:pointh3_arr_0")
db_value = database.outputs.pointh3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:quatd4_0"))
attribute = test_node.get_attribute("outputs:quatd4_0")
db_value = database.outputs.quatd4_0
self.assertTrue(test_node.get_attribute_exists("outputs:quatd4_arr_0"))
attribute = test_node.get_attribute("outputs:quatd4_arr_0")
db_value = database.outputs.quatd4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:quatf4_0"))
attribute = test_node.get_attribute("outputs:quatf4_0")
db_value = database.outputs.quatf4_0
self.assertTrue(test_node.get_attribute_exists("outputs:quatf4_arr_0"))
attribute = test_node.get_attribute("outputs:quatf4_arr_0")
db_value = database.outputs.quatf4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:quath4_0"))
attribute = test_node.get_attribute("outputs:quath4_0")
db_value = database.outputs.quath4_0
self.assertTrue(test_node.get_attribute_exists("outputs:quath4_arr_0"))
attribute = test_node.get_attribute("outputs:quath4_arr_0")
db_value = database.outputs.quath4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordd2_0"))
attribute = test_node.get_attribute("outputs:texcoordd2_0")
db_value = database.outputs.texcoordd2_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordd2_arr_0"))
attribute = test_node.get_attribute("outputs:texcoordd2_arr_0")
db_value = database.outputs.texcoordd2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordd3_0"))
attribute = test_node.get_attribute("outputs:texcoordd3_0")
db_value = database.outputs.texcoordd3_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordd3_arr_0"))
attribute = test_node.get_attribute("outputs:texcoordd3_arr_0")
db_value = database.outputs.texcoordd3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordf2_0"))
attribute = test_node.get_attribute("outputs:texcoordf2_0")
db_value = database.outputs.texcoordf2_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordf2_arr_0"))
attribute = test_node.get_attribute("outputs:texcoordf2_arr_0")
db_value = database.outputs.texcoordf2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordf3_0"))
attribute = test_node.get_attribute("outputs:texcoordf3_0")
db_value = database.outputs.texcoordf3_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordf3_arr_0"))
attribute = test_node.get_attribute("outputs:texcoordf3_arr_0")
db_value = database.outputs.texcoordf3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordh2_0"))
attribute = test_node.get_attribute("outputs:texcoordh2_0")
db_value = database.outputs.texcoordh2_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordh2_arr_0"))
attribute = test_node.get_attribute("outputs:texcoordh2_arr_0")
db_value = database.outputs.texcoordh2_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordh3_0"))
attribute = test_node.get_attribute("outputs:texcoordh3_0")
db_value = database.outputs.texcoordh3_0
self.assertTrue(test_node.get_attribute_exists("outputs:texcoordh3_arr_0"))
attribute = test_node.get_attribute("outputs:texcoordh3_arr_0")
db_value = database.outputs.texcoordh3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:timecode_0"))
attribute = test_node.get_attribute("outputs:timecode_0")
db_value = database.outputs.timecode_0
self.assertTrue(test_node.get_attribute_exists("outputs:timecode_arr_0"))
attribute = test_node.get_attribute("outputs:timecode_arr_0")
db_value = database.outputs.timecode_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:token_0"))
attribute = test_node.get_attribute("outputs:token_0")
db_value = database.outputs.token_0
self.assertTrue(test_node.get_attribute_exists("outputs:token_arr_0"))
attribute = test_node.get_attribute("outputs:token_arr_0")
db_value = database.outputs.token_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:transform4_0"))
attribute = test_node.get_attribute("outputs:transform4_0")
db_value = database.outputs.transform4_0
self.assertTrue(test_node.get_attribute_exists("outputs:transform4_arr_0"))
attribute = test_node.get_attribute("outputs:transform4_arr_0")
db_value = database.outputs.transform4_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:uchar_0"))
attribute = test_node.get_attribute("outputs:uchar_0")
db_value = database.outputs.uchar_0
self.assertTrue(test_node.get_attribute_exists("outputs:uchar_arr_0"))
attribute = test_node.get_attribute("outputs:uchar_arr_0")
db_value = database.outputs.uchar_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:uint64_0"))
attribute = test_node.get_attribute("outputs:uint64_0")
db_value = database.outputs.uint64_0
self.assertTrue(test_node.get_attribute_exists("outputs:uint64_arr_0"))
attribute = test_node.get_attribute("outputs:uint64_arr_0")
db_value = database.outputs.uint64_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:uint_0"))
attribute = test_node.get_attribute("outputs:uint_0")
db_value = database.outputs.uint_0
self.assertTrue(test_node.get_attribute_exists("outputs:uint_arr_0"))
attribute = test_node.get_attribute("outputs:uint_arr_0")
db_value = database.outputs.uint_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:vectord3_0"))
attribute = test_node.get_attribute("outputs:vectord3_0")
db_value = database.outputs.vectord3_0
self.assertTrue(test_node.get_attribute_exists("outputs:vectord3_arr_0"))
attribute = test_node.get_attribute("outputs:vectord3_arr_0")
db_value = database.outputs.vectord3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:vectorf3_0"))
attribute = test_node.get_attribute("outputs:vectorf3_0")
db_value = database.outputs.vectorf3_0
self.assertTrue(test_node.get_attribute_exists("outputs:vectorf3_arr_0"))
attribute = test_node.get_attribute("outputs:vectorf3_arr_0")
db_value = database.outputs.vectorf3_arr_0
self.assertTrue(test_node.get_attribute_exists("outputs:vectorh3_0"))
attribute = test_node.get_attribute("outputs:vectorh3_0")
db_value = database.outputs.vectorh3_0
self.assertTrue(test_node.get_attribute_exists("outputs:vectorh3_arr_0"))
attribute = test_node.get_attribute("outputs:vectorh3_arr_0")
db_value = database.outputs.vectorh3_arr_0
| 86,139 | Python | 49.970414 | 140 | 0.666191 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/_impl/extension.py | """
Support required by the Carbonite extension loader
"""
import omni.ext
class _PublicExtension(omni.ext.IExt):
"""Object that tracks the lifetime of the Python part of the extension loading"""
def on_startup(self):
"""Set up initial conditions for the Python part of the extension"""
def on_shutdown(self):
"""Shutting down this part of the extension prepares it for hot reload"""
| 416 | Python | 26.799998 | 85 | 0.701923 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/tests/test_api.py | """Testing the stability of the API in this module"""
import omni.graph.core.tests as ogts
import omni.graph.examples.python as ogep
from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents
# ======================================================================
class _TestOmniGraphExamplesPythonApi(ogts.OmniGraphTestCase):
_UNPUBLISHED = ["bindings", "ogn", "tests"]
async def test_api(self):
_check_module_api_consistency(ogep, self._UNPUBLISHED) # noqa: PLW0212
_check_module_api_consistency(ogep.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(ogep, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212
_check_public_api_contents(ogep.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
| 947 | Python | 48.894734 | 108 | 0.661035 |
omniverse-code/kit/exts/omni.graph.examples.python/omni/graph/examples/python/tests/test_omnigraph_python_examples.py | import math
import os
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.timeline
import omni.usd
from pxr import Gf, Sdf, UsdGeom
def example_deformer1(input_point, width, height, freq):
"""Implement simple deformation on the input point with the given wavelength, wave height, and frequency"""
tx = freq * (input_point[0] - width) / width
ty = 1.5 * freq * (input_point[1] - width) / width
tz = height * (math.sin(tx) + math.cos(ty))
return Gf.Vec3f(input_point[0], input_point[1], input_point[2] + tz)
class TestOmniGraphPythonExamples(ogts.OmniGraphTestCase):
# ----------------------------------------------------------------------
async def verify_example_deformer(self):
"""Compare the actual deformation against the expected values using example_deformer1"""
stage = omni.usd.get_context().get_stage()
input_grid = stage.GetPrimAtPath("/defaultPrim/inputGrid")
self.assertEqual(input_grid.GetTypeName(), "Mesh")
input_points_attr = input_grid.GetAttribute("points")
self.assertIsNotNone(input_points_attr)
output_grid = stage.GetPrimAtPath("/defaultPrim/outputGrid")
self.assertEqual(output_grid.GetTypeName(), "Mesh")
output_points_attr = output_grid.GetAttribute("points")
self.assertIsNotNone(output_points_attr)
await omni.kit.app.get_app().next_update_async()
await og.Controller.evaluate()
multiplier_attr = og.Controller.attribute("inputs:multiplier", "/defaultPrim/DeformerGraph/testDeformer")
multiplier = og.Controller.get(multiplier_attr)
# TODO: Should really be using hardcoded values from the file to ensure correct operation
# multiplier = 3.0
width = 310.0
height = multiplier * 10.0
freq = 10.0
# check that the deformer applies the correct deformation
input_points = input_points_attr.Get()
output_points = output_points_attr.Get()
actual_points = []
for input_point, output_point in zip(input_points, output_points):
point = example_deformer1(input_point, width, height, freq)
self.assertEqual(point[0], output_point[0])
self.assertEqual(point[1], output_point[1])
# verify that the z-coordinates computed by the test and the deformer match to three decimal places
actual_points.append(point)
self.assertAlmostEqual(point[2], output_point[2], 3)
# need to wait for next update to propagate the attribute change from USD
og.Controller.set(multiplier_attr, 0.0)
await omni.kit.app.get_app().next_update_async()
# check that the deformer with a zero multiplier leaves the grid undeformed
input_points = input_points_attr.Get()
output_points = output_points_attr.Get()
for input_point, output_point in zip(input_points, output_points):
self.assertEqual(input_point, output_point)
# ----------------------------------------------------------------------
async def test_example_deformer_python(self):
"""Tests the omnigraph.examples.deformerPy node"""
(result, error) = await og.load_example_file("ExampleGridDeformerPython.usda")
self.assertTrue(result, error)
await omni.kit.app.get_app().next_update_async()
await self.verify_example_deformer()
# ----------------------------------------------------------------------
async def run_python_node_creation_by_command(self, node_backed_by_usd=True):
"""
This tests the creation of python nodes through the node definition mechanism
We have a python node type that defines the inputs and outputs of a python node
type. Here, without pre-declaring these attributes in USD, we will create the
node using its node type definition only. The required attributes should
automatically be created for the node. We then wire it up to make sure it works.
"""
graph = og.Controller.create_graph("/defaultPrim/TestGraph")
new_node_path = "/defaultPrim/TestGraph/new_node"
omni.kit.commands.execute(
"CreateNode",
graph=graph,
node_path=new_node_path,
node_type="omni.graph.examples.python.VersionedDeformerPy",
create_usd=node_backed_by_usd,
)
node = graph.get_node(new_node_path)
self.assertEqual(node.get_prim_path(), new_node_path)
# ----------------------------------------------------------------------
async def test_python_node_creation_by_command_usd(self):
"""Test that USD commands creating Python nodes also create OmniGraph nodes"""
await self.run_python_node_creation_by_command(node_backed_by_usd=True)
# ----------------------------------------------------------------------
async def test_python_node_creation_by_command_no_usd(self):
"""Test that USD commands creating Python nodes also create OmniGraph nodes"""
await self.run_python_node_creation_by_command(node_backed_by_usd=False)
# ----------------------------------------------------------------------
async def test_update_node_version(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
(input_grid, output_grid) = ogts.create_input_and_output_grid_meshes(stage)
input_points_attr = input_grid.GetPointsAttr()
output_points_attr = output_grid.GetPointsAttr()
keys = og.Controller.Keys
controller = og.Controller()
(push_graph, _, _, _) = controller.edit(
"/defaultPrim/pushGraph",
{
keys.CREATE_NODES: [
("ReadPoints", "omni.graph.nodes.ReadPrimAttribute"),
("WritePoints", "omni.graph.nodes.WritePrimAttribute"),
],
keys.SET_VALUES: [
("ReadPoints.inputs:name", input_points_attr.GetName()),
("ReadPoints.inputs:primPath", "/defaultPrim/inputGrid"),
("ReadPoints.inputs:usePath", True),
("WritePoints.inputs:name", output_points_attr.GetName()),
("WritePoints.inputs:primPath", "/defaultPrim/outputGrid"),
("WritePoints.inputs:usePath", True),
],
},
)
test_deformer = stage.DefinePrim("/defaultPrim/pushGraph/testVersionedDeformer", "OmniGraphNode")
test_deformer.GetAttribute("node:type").Set("omni.graph.examples.python.VersionedDeformerPy")
test_deformer.GetAttribute("node:typeVersion").Set(0)
deformer_input_points = test_deformer.CreateAttribute("inputs:points", Sdf.ValueTypeNames.Point3fArray)
deformer_input_points.Set([(0, 0, 0)] * 1024)
deformer_output_points = test_deformer.CreateAttribute("outputs:points", Sdf.ValueTypeNames.Point3fArray)
deformer_output_points.Set([(0, 0, 0)] * 1024)
multiplier_attr = test_deformer.CreateAttribute("inputs:multiplier", Sdf.ValueTypeNames.Float)
multiplier_attr.Set(3)
await controller.evaluate()
controller.edit(
push_graph,
{
keys.CONNECT: [
("ReadPoints.outputs:value", deformer_input_points.GetPath().pathString),
(deformer_output_points.GetPath().pathString, "WritePoints.inputs:value"),
]
},
)
# Wait for USD notice handler to construct the underlying compute graph
await controller.evaluate()
# This node has 2 attributes declared as part of its node definition. We didn't create these attributes
# above, but the code should have automatically filled them in
version_deformer_node = push_graph.get_node("/defaultPrim/pushGraph/testVersionedDeformer")
input_attr = version_deformer_node.get_attribute("test_input")
output_attr = version_deformer_node.get_attribute("test_output")
self.assertTrue(input_attr is not None and input_attr.is_valid())
self.assertTrue(output_attr is not None and output_attr.is_valid())
self.assertEqual(input_attr.get_name(), "test_input")
self.assertEqual(input_attr.get_type_name(), "int")
self.assertEqual(output_attr.get_name(), "test_output")
self.assertEqual(output_attr.get_type_name(), "float")
# We added an union type input to this node as well, so test that is here:
union_attr = version_deformer_node.get_attribute("test_union_input")
self.assertTrue(union_attr is not None and union_attr.is_valid())
self.assertEqual(union_attr.get_name(), "test_union_input")
self.assertEqual(union_attr.get_type_name(), "token")
self.assertEqual(union_attr.get_extended_type(), og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION)
self.assertEqual(union_attr.get_resolved_type().base_type, og.BaseDataType.UNKNOWN)
union_attr.set_resolved_type(og.Type(og.BaseDataType.FLOAT))
self.assertEqual(union_attr.get_resolved_type(), og.Type(og.BaseDataType.FLOAT))
union_attr.set(32)
self.assertEqual(union_attr.get(), 32)
# Node version update happens as the nodes are constructed and checked against the node type
multiplier_attr = test_deformer.GetAttribute("inputs:multiplier")
self.assertFalse(multiplier_attr.IsValid())
wavelength_attr = test_deformer.GetAttribute("inputs:wavelength")
self.assertIsNotNone(wavelength_attr)
self.assertEqual(wavelength_attr.GetTypeName(), Sdf.ValueTypeNames.Float)
# attrib value should be initialized to 50
og_attr = controller.node("/defaultPrim/pushGraph/testVersionedDeformer").get_attribute("inputs:wavelength")
self.assertEqual(og_attr.get(), 50.0)
# ----------------------------------------------------------------------
async def test_example_tutorial1_finished(self):
"""Tests the deforming_text_tutorial_finished.usda file"""
ext_dir = os.path.dirname(__file__) + ("/.." * 5)
file_path = os.path.join(ext_dir, "data", "deforming_text_tutorial_finished.usda")
(result, error) = await ogts.load_test_file(file_path)
self.assertTrue(result, error)
await omni.kit.app.get_app().next_update_async()
await og.Controller.evaluate()
# Verify the test graph is functional. We take a look at the location of the sphere and the 'G' mesh. When we
# move the sphere it should also move the 'G'. If the 'G' is not moved from it's orginal location we know
# something is wrong.
stage = omni.usd.get_context().get_stage()
sphere = UsdGeom.Xformable(stage.GetPrimAtPath("/World/Sphere"))
text_g_mesh = UsdGeom.Xformable(stage.GetPrimAtPath("/World/Text_G"))
text_g_x0 = text_g_mesh.GetLocalTransformation()[3]
# Move the sphere
sphere.ClearXformOpOrder()
sphere_translate_op = sphere.AddTranslateOp()
sphere_translate_op.Set(Gf.Vec3d(0, 0, 0))
# Check the 'G' position has changed
await omni.kit.app.get_app().next_update_async()
text_g_x1 = text_g_mesh.GetLocalTransformation()[3]
self.assertNotEqual(text_g_x0, text_g_x1)
# ----------------------------------------------------------------------
async def test_singleton(self):
"""
Basic idea of test: we define a node that's been tagged as singleton. We then try to add another
node of the same type. It should fail and not let us.
"""
(graph, (singleton_node,), _, _) = og.Controller.edit(
"/TestGraph",
{og.Controller.Keys.CREATE_NODES: ("testSingleton", "omni.graph.examples.python.TestSingleton")},
)
singleton_node = graph.get_node("/TestGraph/testSingleton")
self.assertTrue(singleton_node.is_valid())
with ogts.ExpectedError():
(_, (other_node,), _, _) = og.Controller.edit(
graph, {og.Controller.Keys.CREATE_NODES: ("testSingleton2", "omni.graph.examples.python.TestSingleton")}
)
self.assertFalse(other_node.is_valid())
node = graph.get_node("/TestGraph/testSingleton")
self.assertTrue(node.is_valid())
node = graph.get_node("/TestGraph/testSingleton2")
self.assertFalse(node.is_valid())
# ----------------------------------------------------------------------
async def test_set_compute_incomplete(self):
"""
Test usage of OgnCountTo which leverages set_compute_incomplete API.
"""
controller = og.Controller()
keys = og.Controller.Keys
(_, nodes, _, _,) = controller.edit(
{"graph_path": "/World/TestGraph", "evaluator_name": "dirty_push"},
{
keys.CREATE_NODES: [
("CountTo", "omni.graph.examples.python.CountTo"),
],
keys.SET_VALUES: [
("CountTo.inputs:increment", 1),
],
},
)
count_out = controller.attribute("outputs:count", nodes[0])
self.assertEqual(og.Controller.get(count_out), 0.0)
await controller.evaluate()
self.assertEqual(og.Controller.get(count_out), 1.0)
await controller.evaluate()
self.assertEqual(og.Controller.get(count_out), 2.0)
await controller.evaluate()
self.assertEqual(og.Controller.get(count_out), 3.0)
await controller.evaluate()
self.assertEqual(og.Controller.get(count_out), 3.0)
| 13,779 | Python | 48.568345 | 120 | 0.609768 |
omniverse-code/kit/exts/omni.graph.examples.python/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]
## [1.3.2] - 2022-08-31
### Fixed
- Refactored out use of a deprecated class
## [1.3.1] - 2022-08-09
### Fixed
- Applied formatting to all of the Python files
## [1.3.0] - 2022-07-07
### Added
- Test for public API consistency
## [1.2.0] - 2022-06-21
### Changed
- Made the imports and docstring more explicit in the top level __init__.py
- Deliberately emptied out the _impl/__init__.py since it should not be imported
- Changed the name of the extension class to emphasize that it is not part of an API
## [1.1.0] - 2022-04-29
### Removed
- Obsolete GPU Tests
### Changed
- Made tests derive from OmniGraphTestCase
## [1.0.2] - 2022-03-14
### Changed
- Added categories to node OGN
## [1.0.1] - 2022-01-13
### Changed
- Fixed the outdated OmniGraph tutorial
- Updated the USDA files, UI screenshots, and tutorial contents
## [1.0.0] - 2021-03-01
### Initial Version
- Started changelog with initial released version of the OmniGraph core
| 1,217 | Markdown | 25.47826 | 87 | 0.703369 |
omniverse-code/kit/exts/omni.graph.examples.python/docs/README.md | # OmniGraph Python Examples [omni.graph.examples.python]
This extension contains example implementations for OmniGraph nodes written in Python.
| 145 | Markdown | 35.499991 | 86 | 0.834483 |
omniverse-code/kit/exts/omni.graph.examples.python/docs/index.rst | .. _ogn_omni_graph_examples_python:
OmniGraph Python Example Nodes
##############################
.. tabularcolumns:: |L|R|
.. csv-table::
:width: 100%
**Extension**: omni.graph.examples.python,**Documentation Generated**: |today|
.. toctree::
:maxdepth: 1
CHANGELOG
This extension includes a miscellaneous collection of examples that exercise
some of the functionality of the OmniGraph nodes written in Python. Ulike the set of nodes implementing
common features found in :ref:`ogn_omni_graph_nodes` the nodes here do not serve a common purpose,
they are just used to illustrate the use of certain features of the OmniGraph.
For examples of nodes implemented in C++ see the extension :ref:`ogn_omni_graph_examples_cpp`.
For more comprehensive examples targeted at explaining the use of OmniGraph node features in detail see
:ref:`ogn_user_guide`.
| 875 | reStructuredText | 29.206896 | 105 | 0.730286 |
omniverse-code/kit/exts/omni.graph.examples.python/docs/Overview.md | # OmniGraph Python Example Nodes
```{csv-table}
**Extension**: omni.graph.examples.python,**Documentation Generated**: {sub-ref}`today`
```
This extension includes a miscellaneous collection of examples that exercise
some of the functionality of the OmniGraph nodes written in Python. Ulike the set of nodes implementing
common features found in {ref}`ogn_omni_graph_nodes` the nodes here do not serve a common purpose,
they are just used to illustrate the use of certain features of the OmniGraph.
For examples of nodes implemented in C++ see the extension {ref}`ogn_omni_graph_examples_cpp`.
For more comprehensive examples targeted at explaining the use of OmniGraph node features in detail see
{ref}`ogn_user_guide`. | 729 | Markdown | 44.624997 | 105 | 0.781893 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/options_model.py | from typing import List
import omni.ui as ui
from .option_item import OptionItem
class OptionsModel(ui.AbstractItemModel):
"""
Model for options items.
Args:
name (str): Model name to display in menu header.
items (List[OptionItem]): Items to show in menu.
"""
def __init__(self, name: str, items: List[OptionItem]):
self.name = name
self._items = items
self.__subs = {}
for item in self._items:
if item.name:
self.__subs[item] = item.model.subscribe_value_changed_fn(lambda m, i=item: self.__on_value_changed(i, m))
super().__init__()
def destroy(self):
self.__subs.clear()
@property
def dirty(self) -> bool:
"""
Flag if any item not in default value.
"""
for item in self._items:
if item.dirty:
return True
return False
def rebuild_items(self, items: List[OptionItem]) -> None:
"""
Rebuild option items.
Args:
items (List[OptionItem]): Items to show in menu.
"""
self.__subs.clear()
self._items = items
for item in self._items:
if item.name:
self.__subs[item] = item.model.subscribe_value_changed_fn(lambda m, i=item: self.__on_value_changed(i, m))
self._item_changed(None)
def reset(self) -> None:
"""
Reset all items to default value.
"""
for item in self._items:
item.reset()
def get_item_children(self) -> List[OptionItem]:
"""
Get items in this model.
"""
return self._items
def __on_value_changed(self, item: OptionItem, model: ui.SimpleBoolModel):
self._item_changed(item)
| 1,802 | Python | 25.910447 | 122 | 0.54384 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/option_menu_item.py | import omni.ui as ui
from .option_item import OptionItem
class OptionMenuItemDelegate(ui.MenuDelegate):
"""
Delegate for general option menu item.
A general option item includes a selected icon and item text.
Args:
option_item (OptionItem): Option item to show as menu item.
Keyword Args:
width (ui.Length): Menu item width. Default ui.Fraction(1).
"""
def __init__(self, option_item: OptionItem, width: ui.Length = ui.Fraction(1)):
self._option_item = option_item
self._width = width
super().__init__(propagate=True)
def destroy(self):
self.__sub = None
def build_item(self, item: ui.MenuItem):
model = self._option_item.model
self.__sub = model.subscribe_value_changed_fn(self._on_value_changed)
self._container = ui.HStack(height=24, width=self._width, content_clipping=False, checked=model.as_bool)
with self._container:
ui.ImageWithProvider(width = 24, style_type_name_override="MenuItem.Icon")
ui.Label(
item.text,
style_type_name_override="MenuItem.Label",
)
ui.Spacer(width=16)
self._container.set_mouse_pressed_fn(lambda x, y, b, a, m=model: m.set_value(not m.as_bool))
self._container.set_mouse_hovered_fn(self._on_mouse_hovered)
def _on_value_changed(self, model: ui.SimpleBoolModel) -> None:
self._container.checked = model.as_bool
def _on_mouse_hovered(self, hovered: bool) -> None:
# Here to set selected instead of hovered status for icon.
# Because there is margin in icon, there will be some blank at top/bottom as a result icon does not become hovered if mouse on these area.
self._container.selected = hovered
class OptionMenuItem(ui.MenuItem):
"""
Represent a menu item for a single option.
Args:
option_item (OptionItem): Option item to show as menu item.
Keyword Args:
hide_on_click (bool): Hide menu if item clicked. Default False.
width (ui.Length): Menu item width. Default ui.Fraction(1).
"""
def __init__(self, option_item: OptionItem, hide_on_click: bool = False, width: ui.Length = ui.Fraction(1)):
self._delegate = OptionMenuItemDelegate(option_item, width=width)
super().__init__(option_item.text, delegate=self._delegate, hide_on_click=hide_on_click, checkable=True)
def destroy(self):
self._delegate.destroy()
| 2,502 | Python | 36.924242 | 146 | 0.642286 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/style.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"data/icons")
OPTIONS_MENU_STYLE = {
"Title.Background": {"background_color": 0xFF23211F, "corner_flag": ui.CornerFlag.TOP, "margin": 0},
"Title.Header": {"margin_width": 3, "margin_height": 0},
"Title.Label": {"background_color": 0x0, "color": cl.shade(cl('#A1A1A1')), "margin_width": 5},
"ResetButton": {"background_color": 0},
"ResetButton:hovered": {"background_color": cl.shade(cl('323434'))},
"ResetButton.Label": {"color": cl.shade(cl('#34C7FF'))},
"ResetButton.Label:disabled": {"color": cl.shade(cl('#6E6E6E'))},
"ResetButton.Label:hovered": {"color": cl.shade(cl('#1A91C5'))},
"MenuItem.Icon": {"image_url": f"{ICON_PATH}/check_solid.svg", "color": 0, "margin": 7},
"MenuItem.Icon:checked": {"color": cl.shade(cl('#34C7FF'))},
"MenuItem.Icon:selected": {"color": cl.shade(cl('#1F2123'))},
"MenuItem.Label::title": {"color": cl.shade(cl('#A1A1A1')), "margin_width": 5},
"MenuItem.Separator": {"color": cl.shade(cl('#626363')), "border_width": 1.5},
}
| 1,205 | Python | 47.239998 | 104 | 0.640664 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/option_separator.py | import omni.ui as ui
class SeparatorDelegate(ui.MenuDelegate):
"""Menu delegate for separator"""
def build_item(self, _):
with ui.HStack():
ui.Spacer(width=24)
ui.Line(height=10, style_type_name_override="MenuItem.Separator")
ui.Spacer(width=8)
class OptionSeparator(ui.MenuItem):
"""A simple separator"""
def __init__(self):
super().__init__("##OPTION_SEPARATOR", delegate=SeparatorDelegate(), enabled=False)
| 482 | Python | 27.411763 | 91 | 0.628631 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/__init__.py | from .options_menu import OptionsMenu
from .options_model import OptionsModel
from .option_item import OptionItem, OptionSeparator
| 132 | Python | 25.599995 | 52 | 0.840909 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/option_item.py | from typing import Optional, Callable
import omni.ui as ui
class OptionItem(ui.AbstractItem):
"""
Represent an item for OptionsMenu.
Args:
name (str): Item name.
Keyword args:
text (str): Item text to show in menu item. Default None means using name.
default (bool): Default item value. Default False.
on_value_changed_fn (Callable[[bool], None]): Callback when item value changed.
"""
def __init__(self, name: Optional[str], text: Optional[str] = None, default: bool = False, on_value_changed_fn: Callable[[bool], None] = None):
self.name = name
self.text = text or name
self.default = default
self.model = ui.SimpleBoolModel(default)
if on_value_changed_fn:
self.__on_value_changed_fn = on_value_changed_fn
def __on_value_changed(model: ui.SimpleBoolModel):
self.__on_value_changed_fn(model.as_bool)
self.__sub = self.model.subscribe_value_changed_fn(__on_value_changed)
super().__init__()
def destroy(self):
self.__sub = None
@property
def value(self) -> bool:
"""
Item current value.
"""
return self.model.as_bool
@value.setter
def value(self, new_value: bool) -> None:
self.model.set_value(new_value)
@property
def dirty(self) -> bool:
"""
Flag of item value changed.
"""
return self.model.as_bool != self.default
def reset(self) -> None:
"""
Reset item value to default.
"""
self.model.set_value(self.default)
class OptionSeparator(OptionItem):
"""
A simple option item represents a separator in menu item.
"""
def __init__(self):
super().__init__(None) | 1,814 | Python | 26.5 | 147 | 0.579383 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/options_menu.py | from typing import Optional
import omni.ui as ui
from .option_item import OptionItem
from .option_menu_item import OptionMenuItem
from .options_model import OptionsModel
from .option_separator import OptionSeparator
from .style import OPTIONS_MENU_STYLE
class OptionsMenuDelegate(ui.MenuDelegate):
"""
Delegate for options menu.
It has a header to show label and reset button
Args:
model (OptionsModel): Model for options to show in this menu.
"""
def __init__(self, model: OptionsModel, **kwargs):
self._model = model
self._reset_all: Optional[ui.Button] = None
self.__sub = self._model.subscribe_item_changed_fn(self.__on_item_changed)
super().__init__(**kwargs)
def destroy(self) -> None:
self.__sub = None
def build_title(self, item: ui.Menu) -> None:
with ui.ZStack(content_clipping=True, height=24):
ui.Rectangle(style_type_name_override="Title.Background")
with ui.HStack(style_type_name_override="Title.Header"):
if item.text:
ui.Label(self._model.name, width=0, style_type_name_override="Title.Label")
# Extra spacer here to make sure menu window has min width
ui.Spacer(width=45)
ui.Spacer()
self._reset_all = ui.Button(
"Reset All",
width=0,
height=24,
enabled=self._model.dirty,
style_type_name_override="ResetButton",
clicked_fn=self._model.reset,
identifier="reset_all",
)
def __on_item_changed(self, model: OptionsModel, item: OptionItem) -> None:
if self._reset_all:
self._reset_all.enabled = self._model.dirty
class OptionsMenu(ui.Menu):
"""
Represent a menu to show options.
A options menu includes a header and a list of menu items for options.
Args:
model (OptionsModel): Model of option items to show in this menu.
hide_on_click (bool): Hide menu when item clicked. Default False.
width (ui.Length): Width of menu item. Default ui.Fraction(1).
style (dict): Additional style. Default empty.
"""
def __init__(self, model: OptionsModel, hide_on_click: bool = False, width: ui.Length = ui.Fraction(1), style: dict = {}):
self._model = model
self._hide_on_click = hide_on_click
self._width = width
menu_style = OPTIONS_MENU_STYLE.copy()
menu_style.update(style)
self._delegate = OptionsMenuDelegate(self._model)
super().__init__(self._model.name, delegate=self._delegate, menu_compatibility=False, on_build_fn=self._build_menu_items, style=menu_style)
self.__sub = self._model.subscribe_item_changed_fn(self.__on_model_changed)
def destroy(self):
self.__sub = None
self._delegate.destroy()
def show_by_widget(self, widget: ui.Widget) -> None:
"""
Show menu around widget (bottom left).
Args:
widget (ui.Widget): Widget to align for this menu.
"""
if widget:
x = widget.screen_position_x
y = widget.screen_position_y + widget.computed_height
self.show_at(x, y)
else:
self.show()
def _build_menu_items(self):
for item in self._model.get_item_children():
if item.text is None:
# Separator
OptionSeparator()
else:
OptionMenuItem(item, hide_on_click=self._hide_on_click, width=self._width)
def __on_model_changed(self, model: OptionsModel, item: Optional[OptionItem]) -> None:
if item is None:
self.invalidate()
| 3,803 | Python | 34.886792 | 147 | 0.591112 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/tests/__init__.py | from .test_ui import *
| 23 | Python | 10.999995 | 22 | 0.695652 |
omniverse-code/kit/exts/omni.kit.widget.options_menu/omni/kit/widget/options_menu/tests/test_ui.py | from pathlib import Path
import omni.kit.ui_test as ui_test
from omni.ui.tests.test_base import OmniUiTest
from ..options_menu import OptionsMenu
from ..options_model import OptionsModel
from ..option_item import OptionItem, OptionSeparator
CURRENT_PATH = Path(__file__).parent.absolute()
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests")
class TestOptions(OmniUiTest):
# Before running each test
async def setUp(self):
self._model = OptionsModel(
"Filter",
[
OptionItem("audio", text="Audio"),
OptionItem("materials", text="Materials"),
OptionItem("scripts", text="Scripts"),
OptionItem("textures", text="Textures"),
OptionItem("usd", text="USD"),
]
)
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden")
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
async def finalize_test(self, golden_img_name: str):
await self.wait_n_updates()
await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name)
await self.wait_n_updates()
async def test_ui_layout(self):
"""Test ui, reset and API to get/set value"""
items = self._model.get_item_children()
self._changed_names = []
def _on_item_changed(_, item: OptionItem):
self._changed_names.append(item.name)
self._sub = self._model.subscribe_item_changed_fn(_on_item_changed)
menu = OptionsMenu(self._model)
menu.show_at(0, 0)
try:
# Initial UI
await ui_test.emulate_mouse_move(ui_test.Vec2(0, 0))
await ui_test.human_delay()
await self.finalize_test("options_menu.png")
# Change first and last item via mouse click
await ui_test.human_delay()
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(50, 45))
await ui_test.human_delay()
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(50, 145))
await ui_test.human_delay()
self.assertEqual(len(self._changed_names), 2)
self.assertEqual(self._changed_names[0], items[0].name)
self.assertEqual(self._changed_names[1], items[-1].name)
await self.finalize_test("options_menu_click.png")
# Change value via item property
items[2].value = not items[2].value
items[3].value = not items[3].value
await self.finalize_test("options_menu_value_changed.png")
# Reset all
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(120, 20))
await self.finalize_test("options_menu.png")
finally:
menu.destroy()
async def test_ui_rebuild_items(self):
"""Test ui, reset and API to get/set value"""
items = self._model.get_item_children()
menu = OptionsMenu(self._model)
menu.show_at(0, 0)
try:
# Initial UI
await ui_test.emulate_mouse_move(ui_test.Vec2(0, 0))
await ui_test.human_delay()
await self.finalize_test("options_menu.png")
self._model.rebuild_items(
[
OptionItem("Test"),
OptionSeparator(),
OptionItem("More"),
]
)
await ui_test.human_delay()
await self.finalize_test("options_menu_rebuild.png")
self._model.rebuild_items(items)
await ui_test.human_delay()
await self.finalize_test("options_menu.png")
finally:
menu.destroy()
| 3,827 | Python | 33.486486 | 105 | 0.577215 |
omniverse-code/kit/exts/omni.kit.welcome.about/omni/kit/welcome/about/style.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
ABOUT_PAGE_STYLE = {
"Info": { "background_color": cl("#1F2123") },
"Title.Label": { "font_size": fl.welcome_title_font_size },
"Version.Label": { "font_size": 18, "margin_width": 5 },
"Plugin.Title": { "font_size": 16, "margin_width": 5 },
"Plugin.Label": { "font_size": 16, "margin_width": 5 },
"Plugin.Frame": { "background_color": 0xFF454545, "margin_width": 2, "margin_height": 3, "margin": 5 }
}
| 650 | Python | 35.166665 | 106 | 0.646154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.