file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnPrintTextDatabase.py | """Support for simplified access to data on nodes of type omni.graph.ui_nodes.PrintText
Prints some text to the system log or to the screen
"""
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 OgnPrintTextDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.PrintText
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.execIn
inputs.logLevel
inputs.text
inputs.toScreen
inputs.viewport
Outputs:
outputs.execOut
Predefined Tokens:
tokens.Info
tokens.Warning
tokens.Error
"""
# 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:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''),
('inputs:logLevel', 'token', 0, 'Log Level', 'The logging level for the message [Info, Warning, Error]', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Info,Warning,Error', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["Info", "Warning", "Error"]', ogn.MetadataKeys.DEFAULT: '"Info"'}, True, "Info", False, ''),
('inputs:text', 'string', 0, 'Text', 'The text to print', {}, True, "", False, ''),
('inputs:toScreen', 'bool', 0, 'To Screen', 'When true, displays the text on the viewport for a few seconds, as well as the log', {}, True, False, False, ''),
('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport if printing to screen, or empty for the default viewport', {}, True, "", False, ''),
('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''),
])
class tokens:
Info = "Info"
Warning = "Warning"
Error = "Error"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.inputs.text = og.AttributeRole.TEXT
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"execIn", "logLevel", "text", "toScreen", "viewport", "_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.execIn, self._attributes.logLevel, self._attributes.text, self._attributes.toScreen, self._attributes.viewport]
self._batchedReadValues = [None, "Info", "", False, ""]
@property
def execIn(self):
return self._batchedReadValues[0]
@execIn.setter
def execIn(self, value):
self._batchedReadValues[0] = value
@property
def logLevel(self):
return self._batchedReadValues[1]
@logLevel.setter
def logLevel(self, value):
self._batchedReadValues[1] = value
@property
def text(self):
return self._batchedReadValues[2]
@text.setter
def text(self, value):
self._batchedReadValues[2] = value
@property
def toScreen(self):
return self._batchedReadValues[3]
@toScreen.setter
def toScreen(self, value):
self._batchedReadValues[3] = value
@property
def viewport(self):
return self._batchedReadValues[4]
@viewport.setter
def viewport(self, value):
self._batchedReadValues[4] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execOut(self):
value = self._batchedWriteValues.get(self._attributes.execOut)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
self._batchedWriteValues[self._attributes.execOut] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnPrintTextDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnPrintTextDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnPrintTextDatabase.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(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.ui_nodes.PrintText'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnPrintTextDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnPrintTextDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnPrintTextDatabase(node)
try:
compute_function = getattr(OgnPrintTextDatabase.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 OgnPrintTextDatabase.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):
OgnPrintTextDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnPrintTextDatabase.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(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnPrintTextDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnPrintTextDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnPrintTextDatabase.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(OgnPrintTextDatabase.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.ui_nodes")
node_type.set_metadata(ogn.MetadataKeys.TAGS, "logging,toast,debug")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Print Text")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "debug")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Prints some text to the system log or to the screen")
node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnPrintTextDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnPrintTextDatabase.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):
OgnPrintTextDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnPrintTextDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.ui_nodes.PrintText")
| 13,270 | Python | 43.089701 | 300 | 0.62208 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnOnPickedDatabase.py | """Support for simplified access to data on nodes of type omni.graph.ui_nodes.OnPicked
Event node which fires when a picking event occurs in the specified viewport. Note that picking events must be enabled on
the specified viewport using a SetViewportMode node.
"""
import numpy
import usdrt
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnPickedDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.OnPicked
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.gesture
inputs.onlyPlayback
inputs.trackedPrims
inputs.viewport
Outputs:
outputs.isTrackedPrimPicked
outputs.missed
outputs.picked
outputs.pickedPrim
outputs.pickedPrimPath
outputs.pickedWorldPos
outputs.trackedPrimPaths
Predefined Tokens:
tokens.LeftMouseClick
tokens.RightMouseClick
tokens.MiddleMouseClick
tokens.LeftMousePress
tokens.RightMousePress
tokens.MiddleMousePress
"""
# 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:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger a picking event', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click,Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click", "LeftMousePress": "Left Mouse Press", "RightMousePress": "Right Mouse Press", "MiddleMousePress": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, "Left Mouse Click", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:trackedPrims', 'target', 0, 'Tracked Prims', "Optionally specify a set of tracked prims that will cause 'Picked' to fire when picked", {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, False, [], False, ''),
('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for picking events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''),
('outputs:isTrackedPrimPicked', 'bool', 0, 'Is Tracked Prim Picked', "True if a tracked prim got picked, or if any prim got picked if no tracked prims are specified\n(will always be true when 'Picked' fires, and false when 'Missed' fires)", {}, True, None, False, ''),
('outputs:missed', 'execution', 0, 'Missed', 'Enabled when an attempted picking did not pick a tracked prim,\nor when nothing gets picked if no tracked prims are specified', {}, True, None, False, ''),
('outputs:picked', 'execution', 0, 'Picked', 'Enabled when a tracked prim is picked,\nor when any prim is picked if no tracked prims are specified', {}, True, None, False, ''),
('outputs:pickedPrim', 'target', 0, 'Picked Prim', 'The picked prim, or an empty target if nothing got picked', {}, True, [], False, ''),
('outputs:pickedPrimPath', 'token', 0, 'Picked Prim Path', 'The path of the picked prim, or an empty string if nothing got picked', {}, True, None, True, 'Use the pickedPrim output instead'),
('outputs:pickedWorldPos', 'point3d', 0, 'Picked World Position', 'The XYZ-coordinates of the point in world space at which the prim got picked,\nor (0,0,0) if nothing got picked', {}, True, None, False, ''),
('outputs:trackedPrimPaths', 'token[]', 0, 'Tracked Prim Paths', "A list of the paths of the prims specified in 'Tracked Prims'", {}, True, None, False, ''),
])
class tokens:
LeftMouseClick = "Left Mouse Click"
RightMouseClick = "Right Mouse Click"
MiddleMouseClick = "Middle Mouse Click"
LeftMousePress = "Left Mouse Press"
RightMousePress = "Right Mouse Press"
MiddleMousePress = "Middle Mouse Press"
@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.trackedPrims = og.AttributeRole.TARGET
role_data.outputs.missed = og.AttributeRole.EXECUTION
role_data.outputs.picked = og.AttributeRole.EXECUTION
role_data.outputs.pickedPrim = og.AttributeRole.TARGET
role_data.outputs.pickedWorldPos = og.AttributeRole.POSITION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def gesture(self):
data_view = og.AttributeValueHelper(self._attributes.gesture)
return data_view.get()
@gesture.setter
def gesture(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gesture)
data_view = og.AttributeValueHelper(self._attributes.gesture)
data_view.set(value)
@property
def onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
data_view.set(value)
@property
def trackedPrims(self):
data_view = og.AttributeValueHelper(self._attributes.trackedPrims)
return data_view.get()
@trackedPrims.setter
def trackedPrims(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.trackedPrims)
data_view = og.AttributeValueHelper(self._attributes.trackedPrims)
data_view.set(value)
self.trackedPrims_size = data_view.get_array_size()
@property
def viewport(self):
data_view = og.AttributeValueHelper(self._attributes.viewport)
return data_view.get()
@viewport.setter
def viewport(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.viewport)
data_view = og.AttributeValueHelper(self._attributes.viewport)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.pickedPrim_size = None
self.trackedPrimPaths_size = None
self._batchedWriteValues = { }
@property
def isTrackedPrimPicked(self):
data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked)
return data_view.get()
@isTrackedPrimPicked.setter
def isTrackedPrimPicked(self, value):
data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked)
data_view.set(value)
@property
def missed(self):
data_view = og.AttributeValueHelper(self._attributes.missed)
return data_view.get()
@missed.setter
def missed(self, value):
data_view = og.AttributeValueHelper(self._attributes.missed)
data_view.set(value)
@property
def picked(self):
data_view = og.AttributeValueHelper(self._attributes.picked)
return data_view.get()
@picked.setter
def picked(self, value):
data_view = og.AttributeValueHelper(self._attributes.picked)
data_view.set(value)
@property
def pickedPrim(self):
data_view = og.AttributeValueHelper(self._attributes.pickedPrim)
return data_view.get(reserved_element_count=self.pickedPrim_size)
@pickedPrim.setter
def pickedPrim(self, value):
data_view = og.AttributeValueHelper(self._attributes.pickedPrim)
data_view.set(value)
self.pickedPrim_size = data_view.get_array_size()
@property
def pickedPrimPath(self):
data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath)
return data_view.get()
@pickedPrimPath.setter
def pickedPrimPath(self, value):
data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath)
data_view.set(value)
@property
def pickedWorldPos(self):
data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos)
return data_view.get()
@pickedWorldPos.setter
def pickedWorldPos(self, value):
data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos)
data_view.set(value)
@property
def trackedPrimPaths(self):
data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths)
return data_view.get(reserved_element_count=self.trackedPrimPaths_size)
@trackedPrimPaths.setter
def trackedPrimPaths(self, value):
data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths)
data_view.set(value)
self.trackedPrimPaths_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 = OgnOnPickedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnPickedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnPickedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,859 | Python | 48.844961 | 676 | 0.66226 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadMouseStateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.ui_nodes.ReadMouseState
Reads the current state of the mouse. You can choose which mouse element this node is associated with. When mouse element
is chosen to be a button, only outputs:isPressed is meaningful. When coordinates are chosen, only outputs:coords and outputs:window
are meaningful.
Pixel coordinates are the position of the mouse cursor in screen pixel units with (0,0) top left. Normalized
coordinates are values between 0-1 where 0 is top/left and 1 is bottom/right. By default, coordinates are relative to the
application window, but if 'Use Relative Coords' is set to true, then coordinates are relative to the workspace window containing
the mouse pointer.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnReadMouseStateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.ReadMouseState
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.mouseElement
inputs.useRelativeCoords
Outputs:
outputs.coords
outputs.isPressed
outputs.window
Predefined Tokens:
tokens.LeftButton
tokens.RightButton
tokens.MiddleButton
tokens.ForwardButton
tokens.BackButton
tokens.MouseCoordsNormalized
tokens.MouseCoordsPixel
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:mouseElement', 'token', 0, 'Mouse Element', 'The mouse input to check the state of', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Button,Right Button,Middle Button,Forward Button,Back Button,Normalized Mouse Coordinates,Pixel Mouse Coordinates', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftButton": "Left Button", "RightButton": "Right Button", "MiddleButton": "Middle Button", "ForwardButton": "Forward Button", "BackButton": "Back Button", "MouseCoordsNormalized": "Normalized Mouse Coordinates", "MouseCoordsPixel": "Pixel Mouse Coordinates"}', ogn.MetadataKeys.DEFAULT: '"Left Button"'}, True, "Left Button", False, ''),
('inputs:useRelativeCoords', 'bool', 0, 'Use Relative Coords', "When true, the output 'coords' is made relative to the workspace window containing the\nmouse pointer instead of the entire application window", {}, True, False, False, ''),
('outputs:coords', 'float2', 0, None, 'The coordinates of the mouse. If the mouse element selected is a button, this will output a zero vector.', {}, True, None, False, ''),
('outputs:isPressed', 'bool', 0, None, 'True if the button is currently pressed, false otherwise. If the mouse element selected\nis a coordinate, this will output false.', {}, True, None, False, ''),
('outputs:window', 'token', 0, None, "The name of the workspace window containing the mouse pointer if 'Use Relative Coords' is true\nand the mouse element selected is a coordinate", {}, True, None, False, ''),
])
class tokens:
LeftButton = "Left Button"
RightButton = "Right Button"
MiddleButton = "Middle Button"
ForwardButton = "Forward Button"
BackButton = "Back Button"
MouseCoordsNormalized = "Normalized Mouse Coordinates"
MouseCoordsPixel = "Pixel Mouse Coordinates"
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def mouseElement(self):
data_view = og.AttributeValueHelper(self._attributes.mouseElement)
return data_view.get()
@mouseElement.setter
def mouseElement(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.mouseElement)
data_view = og.AttributeValueHelper(self._attributes.mouseElement)
data_view.set(value)
@property
def useRelativeCoords(self):
data_view = og.AttributeValueHelper(self._attributes.useRelativeCoords)
return data_view.get()
@useRelativeCoords.setter
def useRelativeCoords(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.useRelativeCoords)
data_view = og.AttributeValueHelper(self._attributes.useRelativeCoords)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def coords(self):
data_view = og.AttributeValueHelper(self._attributes.coords)
return data_view.get()
@coords.setter
def coords(self, value):
data_view = og.AttributeValueHelper(self._attributes.coords)
data_view.set(value)
@property
def isPressed(self):
data_view = og.AttributeValueHelper(self._attributes.isPressed)
return data_view.get()
@isPressed.setter
def isPressed(self, value):
data_view = og.AttributeValueHelper(self._attributes.isPressed)
data_view.set(value)
@property
def window(self):
data_view = og.AttributeValueHelper(self._attributes.window)
return data_view.get()
@window.setter
def window(self, value):
data_view = og.AttributeValueHelper(self._attributes.window)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnReadMouseStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnReadMouseStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnReadMouseStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,753 | Python | 49.895349 | 666 | 0.681595 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadViewportHoverStateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportHoverState
Read the state of the last viewport hover event from the specified viewport. Note that viewport mouse events must be enabled
on the specified viewport using a SetViewportMode node.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnReadViewportHoverStateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportHoverState
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.useNormalizedCoords
inputs.viewport
Outputs:
outputs.isHovered
outputs.isValid
outputs.position
outputs.velocity
"""
# 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:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position and velocity outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for hover events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''),
('outputs:isHovered', 'bool', 0, 'Is Hovered', 'True if the specified viewport is currently hovered', {}, True, None, False, ''),
('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''),
('outputs:position', 'double2', 0, 'Position', 'The current mouse position if the specified viewport is currently hovered, otherwise (0,0)', {}, True, None, False, ''),
('outputs:velocity', 'double2', 0, 'Velocity', 'A vector representing the change in position of the mouse since the previous frame\nif the specified viewport is currently hovered, otherwise (0,0)', {}, 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 = []
@property
def useNormalizedCoords(self):
data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords)
return data_view.get()
@useNormalizedCoords.setter
def useNormalizedCoords(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.useNormalizedCoords)
data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords)
data_view.set(value)
@property
def viewport(self):
data_view = og.AttributeValueHelper(self._attributes.viewport)
return data_view.get()
@viewport.setter
def viewport(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.viewport)
data_view = og.AttributeValueHelper(self._attributes.viewport)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def isHovered(self):
data_view = og.AttributeValueHelper(self._attributes.isHovered)
return data_view.get()
@isHovered.setter
def isHovered(self, value):
data_view = og.AttributeValueHelper(self._attributes.isHovered)
data_view.set(value)
@property
def isValid(self):
data_view = og.AttributeValueHelper(self._attributes.isValid)
return data_view.get()
@isValid.setter
def isValid(self, value):
data_view = og.AttributeValueHelper(self._attributes.isValid)
data_view.set(value)
@property
def position(self):
data_view = og.AttributeValueHelper(self._attributes.position)
return data_view.get()
@position.setter
def position(self, value):
data_view = og.AttributeValueHelper(self._attributes.position)
data_view.set(value)
@property
def velocity(self):
data_view = og.AttributeValueHelper(self._attributes.velocity)
return data_view.get()
@velocity.setter
def velocity(self, value):
data_view = og.AttributeValueHelper(self._attributes.velocity)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnReadViewportHoverStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnReadViewportHoverStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnReadViewportHoverStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,873 | Python | 47.906832 | 342 | 0.668741 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnDrawDebugCurveDatabase.py | """Support for simplified access to data on nodes of type omni.graph.ui_nodes.DrawDebugCurve
Given a set of curve points, draw a curve in the viewport
"""
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 OgnDrawDebugCurveDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.DrawDebugCurve
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.closed
inputs.color
inputs.curvepoints
inputs.execIn
Outputs:
outputs.execOut
"""
# 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:closed', 'bool', 0, 'Closed', 'When true, connect the last point to the first', {}, True, False, False, ''),
('inputs:color', 'color3f', 0, 'Color', 'The color of the curve', {}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:curvepoints', 'double3[]', 0, 'Curve Points', 'The curve to be drawn', {}, True, [], False, ''),
('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, 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 = og.AttributeRole.COLOR
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"closed", "color", "execIn", "_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.closed, self._attributes.color, self._attributes.execIn]
self._batchedReadValues = [False, [0.0, 0.0, 0.0], None]
@property
def curvepoints(self):
data_view = og.AttributeValueHelper(self._attributes.curvepoints)
return data_view.get()
@curvepoints.setter
def curvepoints(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.curvepoints)
data_view = og.AttributeValueHelper(self._attributes.curvepoints)
data_view.set(value)
self.curvepoints_size = data_view.get_array_size()
@property
def closed(self):
return self._batchedReadValues[0]
@closed.setter
def closed(self, value):
self._batchedReadValues[0] = value
@property
def color(self):
return self._batchedReadValues[1]
@color.setter
def color(self, value):
self._batchedReadValues[1] = value
@property
def execIn(self):
return self._batchedReadValues[2]
@execIn.setter
def execIn(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 = {"execOut", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execOut(self):
value = self._batchedWriteValues.get(self._attributes.execOut)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
self._batchedWriteValues[self._attributes.execOut] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnDrawDebugCurveDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnDrawDebugCurveDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnDrawDebugCurveDatabase.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(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.ui_nodes.DrawDebugCurve'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnDrawDebugCurveDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnDrawDebugCurveDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnDrawDebugCurveDatabase(node)
try:
compute_function = getattr(OgnDrawDebugCurveDatabase.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 OgnDrawDebugCurveDatabase.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):
OgnDrawDebugCurveDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnDrawDebugCurveDatabase.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(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnDrawDebugCurveDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnDrawDebugCurveDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnDrawDebugCurveDatabase.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(OgnDrawDebugCurveDatabase.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.ui_nodes")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Draw Debug Curve")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "debug")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Given a set of curve points, draw a curve in the viewport")
node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnDrawDebugCurveDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnDrawDebugCurveDatabase.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):
OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnDrawDebugCurveDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.ui_nodes.DrawDebugCurve")
| 12,801 | Python | 43.762238 | 136 | 0.626357 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnSetViewportModeDatabase.py | """Support for simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportMode
Sets the mode of a specified viewport window to 'Scripted' mode or 'Default' mode when executed.
'Scripted' mode disables
default viewport interaction and enables placing UI elements over the viewport. 'Default' mode is the default state of the
viewport, and entering it will destroy any UI elements on the viewport.
Executing with 'Enable Viewport Mouse Events' set
to true in 'Scripted' mode is required to allow the specified viewport to be targeted by viewport mouse event nodes, including
'On Viewport Dragged' and 'Read Viewport Drag State'.
Executing with 'Enable Picking' set to true in 'Scripted' mode is
required to allow the specified viewport to be targeted by the 'On Picked' and 'Read Pick State' nodes.
"""
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 OgnSetViewportModeDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportMode
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.enablePicking
inputs.enableViewportMouseEvents
inputs.execIn
inputs.mode
inputs.passClicksThru
inputs.viewport
Outputs:
outputs.defaultMode
outputs.scriptedMode
outputs.widgetPath
"""
# 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:enablePicking', 'bool', 0, 'Enable Picking', "Enable/Disable picking prims in the specified viewport when in 'Scripted' mode", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:enableViewportMouseEvents', 'bool', 0, 'Enable Viewport Mouse Events', "Enable/Disable viewport mouse events on the specified viewport when in 'Scripted' mode", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('inputs:mode', 'int', 0, 'Mode', "The mode to set the specified viewport to when this node is executed (0: 'Default', 1: 'Scripted')", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:passClicksThru', 'bool', 0, 'Pass Clicks Thru', "Allow mouse clicks to affect the viewport while in 'Scripted' mode.\n\nIn 'Scripted' mode mouse clicks are prevented from reaching the viewport to avoid accidentally\nselecting prims or interacting with the viewport's own UI. Setting this attribute true will\nallow clicks to reach the viewport. This is in addition to interacting with the widgets created\nby UI nodes so if a button widget appears on top of some geometry in the viewport, clicking on\nthe button will not only trigger the button but could also select the geometry. To avoid this,\nput the button inside a Stack widget and use a WriteWidgetProperty node to set the Stack's\n'content_clipping' property to 1.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to set the mode of', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''),
('outputs:defaultMode', 'execution', 0, 'Default Mode', "Fires when this node is successfully executed with 'Mode' set to 'Default'", {}, True, None, False, ''),
('outputs:scriptedMode', 'execution', 0, 'Scripted Mode', "Fires when this node is successfully executed with 'Mode' set to 'Scripted'", {}, True, None, False, ''),
('outputs:widgetPath', 'token', 0, 'Widget Path', "When the viewport enters 'Scripted' mode, a container widget is created under which other UI may be parented.\nThis attribute provides the absolute path to that widget, which can be used as the 'parentWidgetPath'\ninput to various UI nodes, such as Button. When the viewport exits 'Scripted' mode,\nthe container widget and all the UI within it will be destroyed.", {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.defaultMode = og.AttributeRole.EXECUTION
role_data.outputs.scriptedMode = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"enablePicking", "enableViewportMouseEvents", "execIn", "mode", "passClicksThru", "viewport", "_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.enablePicking, self._attributes.enableViewportMouseEvents, self._attributes.execIn, self._attributes.mode, self._attributes.passClicksThru, self._attributes.viewport]
self._batchedReadValues = [False, False, None, 0, False, "Viewport"]
@property
def enablePicking(self):
return self._batchedReadValues[0]
@enablePicking.setter
def enablePicking(self, value):
self._batchedReadValues[0] = value
@property
def enableViewportMouseEvents(self):
return self._batchedReadValues[1]
@enableViewportMouseEvents.setter
def enableViewportMouseEvents(self, value):
self._batchedReadValues[1] = value
@property
def execIn(self):
return self._batchedReadValues[2]
@execIn.setter
def execIn(self, value):
self._batchedReadValues[2] = value
@property
def mode(self):
return self._batchedReadValues[3]
@mode.setter
def mode(self, value):
self._batchedReadValues[3] = value
@property
def passClicksThru(self):
return self._batchedReadValues[4]
@passClicksThru.setter
def passClicksThru(self, value):
self._batchedReadValues[4] = value
@property
def viewport(self):
return self._batchedReadValues[5]
@viewport.setter
def viewport(self, value):
self._batchedReadValues[5] = 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 = {"defaultMode", "scriptedMode", "widgetPath", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def defaultMode(self):
value = self._batchedWriteValues.get(self._attributes.defaultMode)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.defaultMode)
return data_view.get()
@defaultMode.setter
def defaultMode(self, value):
self._batchedWriteValues[self._attributes.defaultMode] = value
@property
def scriptedMode(self):
value = self._batchedWriteValues.get(self._attributes.scriptedMode)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.scriptedMode)
return data_view.get()
@scriptedMode.setter
def scriptedMode(self, value):
self._batchedWriteValues[self._attributes.scriptedMode] = value
@property
def widgetPath(self):
value = self._batchedWriteValues.get(self._attributes.widgetPath)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.widgetPath)
return data_view.get()
@widgetPath.setter
def widgetPath(self, value):
self._batchedWriteValues[self._attributes.widgetPath] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSetViewportModeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSetViewportModeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSetViewportModeDatabase.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(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.ui_nodes.SetViewportMode'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnSetViewportModeDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnSetViewportModeDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnSetViewportModeDatabase(node)
try:
compute_function = getattr(OgnSetViewportModeDatabase.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 OgnSetViewportModeDatabase.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):
OgnSetViewportModeDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnSetViewportModeDatabase.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(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnSetViewportModeDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnSetViewportModeDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnSetViewportModeDatabase.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(OgnSetViewportModeDatabase.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.ui_nodes")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Set Viewport Mode (BETA)")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Sets the mode of a specified viewport window to 'Scripted' mode or 'Default' mode when executed.\n 'Scripted' mode disables default viewport interaction and enables placing UI elements over the viewport. 'Default' mode is the default state of the viewport, and entering it will destroy any UI elements on the viewport.\n Executing with 'Enable Viewport Mouse Events' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by viewport mouse event nodes, including 'On Viewport Dragged' and 'Read Viewport Drag State'.\n Executing with 'Enable Picking' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by the 'On Picked' and 'Read Pick State' nodes.")
node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnSetViewportModeDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnSetViewportModeDatabase.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):
OgnSetViewportModeDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnSetViewportModeDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.ui_nodes.SetViewportMode")
| 17,641 | Python | 51.195266 | 804 | 0.655575 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnOnViewportDraggedDatabase.py | """Support for simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportDragged
Event node which fires when a viewport drag event occurs in the specified viewport. Note that viewport mouse events must
be enabled on the specified viewport using a SetViewportMode node.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnViewportDraggedDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportDragged
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.gesture
inputs.onlyPlayback
inputs.useNormalizedCoords
inputs.viewport
Outputs:
outputs.began
outputs.ended
outputs.finalPosition
outputs.initialPosition
Predefined Tokens:
tokens.LeftMouseDrag
tokens.RightMouseDrag
tokens.MiddleMouseDrag
"""
# 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:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport drag events', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Drag,Right Mouse Drag,Middle Mouse Drag', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Drag", "RightMouseDrag": "Right Mouse Drag", "MiddleMouseDrag": "Middle Mouse Drag"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Drag"'}, True, "Left Mouse Drag", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for drag events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''),
('outputs:began', 'execution', 0, 'Began', "Enabled when the drag begins, populating 'Initial Position' with the current mouse position", {}, True, None, False, ''),
('outputs:ended', 'execution', 0, 'Ended', "Enabled when the drag ends, populating 'Final Position' with the current mouse position", {}, True, None, False, ''),
('outputs:finalPosition', 'double2', 0, 'Final Position', "The mouse position at which the drag ended (valid when 'Ended' is enabled)", {}, True, None, False, ''),
('outputs:initialPosition', 'double2', 0, 'Initial Position', "The mouse position at which the drag began (valid when either 'Began' or 'Ended' is enabled)", {}, True, None, False, ''),
])
class tokens:
LeftMouseDrag = "Left Mouse Drag"
RightMouseDrag = "Right Mouse Drag"
MiddleMouseDrag = "Middle Mouse Drag"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.began = og.AttributeRole.EXECUTION
role_data.outputs.ended = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def gesture(self):
data_view = og.AttributeValueHelper(self._attributes.gesture)
return data_view.get()
@gesture.setter
def gesture(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gesture)
data_view = og.AttributeValueHelper(self._attributes.gesture)
data_view.set(value)
@property
def onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
data_view.set(value)
@property
def useNormalizedCoords(self):
data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords)
return data_view.get()
@useNormalizedCoords.setter
def useNormalizedCoords(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.useNormalizedCoords)
data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords)
data_view.set(value)
@property
def viewport(self):
data_view = og.AttributeValueHelper(self._attributes.viewport)
return data_view.get()
@viewport.setter
def viewport(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.viewport)
data_view = og.AttributeValueHelper(self._attributes.viewport)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def began(self):
data_view = og.AttributeValueHelper(self._attributes.began)
return data_view.get()
@began.setter
def began(self, value):
data_view = og.AttributeValueHelper(self._attributes.began)
data_view.set(value)
@property
def ended(self):
data_view = og.AttributeValueHelper(self._attributes.ended)
return data_view.get()
@ended.setter
def ended(self, value):
data_view = og.AttributeValueHelper(self._attributes.ended)
data_view.set(value)
@property
def finalPosition(self):
data_view = og.AttributeValueHelper(self._attributes.finalPosition)
return data_view.get()
@finalPosition.setter
def finalPosition(self, value):
data_view = og.AttributeValueHelper(self._attributes.finalPosition)
data_view.set(value)
@property
def initialPosition(self):
data_view = og.AttributeValueHelper(self._attributes.initialPosition)
return data_view.get()
@initialPosition.setter
def initialPosition(self, value):
data_view = og.AttributeValueHelper(self._attributes.initialPosition)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnOnViewportDraggedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnViewportDraggedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnViewportDraggedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,185 | Python | 48.207729 | 496 | 0.664507 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSlider.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.graph.core as og
import omni.kit.app
import omni.ui as ui
from . import UINodeCommon
class OgnSlider:
@staticmethod
def internal_state():
return UINodeCommon.OgnUINodeInternalState()
@staticmethod
def compute(db) -> bool:
# OM-97733: This node hasn't been converted to use the widget registry yet. Let's discourage
# its use.
db.log_warning("The Slider node is unsupported and may not behave as expected.")
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
min_value = db.inputs.min
max_value = db.inputs.max
step = db.inputs.step
if step <= 0:
db.log_error("The step size of the slider must be positive!")
return False
width = db.inputs.width
if width <= 0:
db.log_error("The width of the slider must be positive!")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
parent_widget = UINodeCommon.get_parent_widget(db)
if parent_widget is None:
return False
# Tear down previously created widget
if db.internal_state.created_widget is not None:
UINodeCommon.tear_down_widget(db)
def on_slider_finished_dragging(model):
if not db.internal_state.created_widget.enabled:
return
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
event_name = "value_changed_" + widget_identifier
reg_event_name = UINodeCommon.registered_event_name(event_name)
payload = {"newValue": model.get_value_as_float(), "valueType": "float"}
message_bus.push(reg_event_name, payload=payload)
# Now create the button widget and register callbacks
with parent_widget:
db.internal_state.created_frame = ui.Frame()
with db.internal_state.created_frame:
with ui.HStack(content_clipping=1):
db.internal_state.created_widget = ui.FloatSlider(
identifier=widget_identifier,
width=width,
min=min_value,
max=max_value,
step=step,
)
db.internal_state.created_widget.model.set_value((min_value + max_value) / 2)
db.internal_state.created_widget.model.add_end_edit_fn(on_slider_finished_dragging)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(db.internal_state.created_widget)
return True
if db.inputs.tearDown != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.tear_down_widget(db)
if db.inputs.show != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.show_widget(db)
if db.inputs.hide != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.hide_widget(db)
if db.inputs.enable != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.enable_widget(db)
if db.inputs.disable != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.disable_widget(db)
db.log_warning("Unexpected execution with no execution input enabled")
return False
| 3,974 | Python | 39.979381 | 107 | 0.614494 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnLockViewportRender.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.
#
from enum import Enum, auto
from omni.graph.core import ExecutionAttributeState
from omni.graph.ui_nodes.ogn.OgnLockViewportRenderDatabase import OgnLockViewportRenderDatabase
from omni.kit.viewport.utility import get_active_viewport_window
class LockState(Enum):
"""Enum for lock state"""
UNLOCKED = auto()
"""The target has been unlocked."""
LOCKED = auto()
"""The target has been locked."""
UNLOCKING = auto()
"""The target is being unlocked."""
class OgnLockViewportRenderInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
self._lock_state = LockState.UNLOCKED
self._viewport_name = ""
self._viewport_api = None
self._viewport_widget = None
self._previous_freeze_frame = None
self._previous_display_delegate = None
self._elapsed_time = 0.0
self._fading_time = 1.0
@property
def lock_state(self) -> LockState:
return self._lock_state
@lock_state.setter
def lock_state(self, state: LockState):
self._lock_state = state
@property
def viewport_name(self):
return self._viewport_name
@viewport_name.setter
def viewport_name(self, name):
self._viewport_name = name
@property
def viewport_api(self):
return self._viewport_api
@viewport_api.setter
def viewport_api(self, api):
assert api is not None
self._viewport_api = api
@property
def viewport_widget(self):
return self._viewport_widget
@viewport_widget.setter
def viewport_widget(self, widget):
assert widget is not None
self._viewport_widget = widget
@property
def previous_freeze_frame(self):
return self._previous_freeze_frame
@previous_freeze_frame.setter
def previous_freeze_frame(self, freeze_frame):
assert isinstance(freeze_frame, bool)
self._previous_freeze_frame = freeze_frame
@property
def previous_display_delegate(self):
return self._previous_display_delegate
@previous_display_delegate.setter
def previous_display_delegate(self, display_delegate):
assert display_delegate is not None
self._previous_display_delegate = display_delegate
@property
def elapsed_time(self) -> float:
return self._elapsed_time
@elapsed_time.setter
def elapsed_time(self, time: float):
self._elapsed_time = time
@property
def fading_time(self) -> float:
return self._fading_time
@fading_time.setter
def fading_time(self, time: float):
self._fading_time = time
def restore_freeze_frame(self):
if self._viewport_api is not None:
assert isinstance(self._previous_freeze_frame, bool)
self._viewport_api.freeze_frame = self._previous_freeze_frame
self._viewport_api = None
self._previous_freeze_frame = None
def restore_display_delegate(self):
if self._viewport_widget is not None:
self._viewport_widget.display_delegate = self._previous_display_delegate
self._viewport_widget = None
self._previous_display_delegate = None
class OgnLockViewportRender:
"""
Locks and unlocks viewport render.
"""
@staticmethod
def internal_state():
"""Return an object that will contain per-node state information"""
return OgnLockViewportRenderInternalState()
@staticmethod
def unlock_immediately_if_locked(internal_state):
"""Unlock viewport render immediately if locked"""
assert isinstance(internal_state, OgnLockViewportRenderInternalState)
if internal_state.lock_state != LockState.UNLOCKED:
internal_state.restore_display_delegate()
internal_state.restore_freeze_frame()
internal_state.lock_state = LockState.UNLOCKED
@staticmethod
def release(node):
"""When a node is removed it will get a release call for cleanup"""
internal_state = OgnLockViewportRenderDatabase.per_node_internal_state(node)
if internal_state is not None:
OgnLockViewportRender.unlock_immediately_if_locked(internal_state)
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current inputs"""
try:
# An extension is generally not allowed to force a specific viewport backend like omni.kit.widget.viewport
# to be loaded; instead it is the application that controls which viewport to be loaded. If the following
# import fails at runtime, it is because omni.kit.widget.viewport is not loaded by the application, then
# the node won't be supported to lock and unlock viewport render.
from omni.kit.widget.viewport.display_delegate import OverlayViewportDisplayDelegate
locked_exec_attr_state = ExecutionAttributeState.DISABLED
fade_started_exec_attr_state = ExecutionAttributeState.DISABLED
fade_complete_exec_attr_state = ExecutionAttributeState.DISABLED
internal_state = db.internal_state
# If target viewport is changed, make sure viewport render is unlocked for the previous viewport
viewport_name = db.inputs.viewport
if internal_state.viewport_name != viewport_name:
OgnLockViewportRender.unlock_immediately_if_locked(internal_state)
internal_state.viewport_name = viewport_name
if db.inputs.lock == ExecutionAttributeState.ENABLED:
if internal_state.lock_state == LockState.UNLOCKED:
# sanity check
assert (
internal_state.viewport_api is None
and internal_state.viewport_widget is None
and internal_state.previous_freeze_frame is None
and internal_state.previous_display_delegate is None
), "Invalid internal state"
viewport_window = get_active_viewport_window(viewport_name)
assert viewport_window, f"Unknown viewport window {viewport_name}"
viewport_api = viewport_window.viewport_api
viewport_widget = viewport_window.viewport_widget
# We need to restore the display delegate to the previous one when unlocking viewport render
internal_state.viewport_api = viewport_api
internal_state.viewport_widget = viewport_widget
internal_state.previous_freeze_frame = viewport_api.freeze_frame
internal_state.previous_display_delegate = viewport_widget.display_delegate
# Signal other viewport elements that the viewport is locked so certain things won't update
viewport_api.freeze_frame = True
# Set to a new display delegate that overlays the locked frame on top of the renderer output
viewport_widget.display_delegate = OverlayViewportDisplayDelegate(viewport_api)
locked_exec_attr_state = ExecutionAttributeState.ENABLED
internal_state.lock_state = LockState.LOCKED
else:
if internal_state.lock_state == LockState.LOCKED:
# Start updating relevant parts of the viewport now that the transition has begun
internal_state.restore_freeze_frame()
internal_state.elapsed_time = 0.0
internal_state.fading_time = max(db.inputs.fadeTime, 0.0)
# Push this node in a latent state. Note the output connection of the `fadeStarted` attribute
# can't be activated at the same tick because only 1 activated output is permited per compute,
# therefore it has to be activated until the next tick.
fade_complete_exec_attr_state = ExecutionAttributeState.LATENT_PUSH
internal_state.lock_state = LockState.UNLOCKING
elif internal_state.lock_state == LockState.UNLOCKING:
elapsed_time = internal_state.elapsed_time
fading_time = internal_state.fading_time
assert elapsed_time >= 0.0 and fading_time >= 0.0
if elapsed_time == 0.0:
fade_started_exec_attr_state = ExecutionAttributeState.ENABLED
elif elapsed_time < fading_time:
display_delegate = internal_state.viewport_widget.display_delegate
assert isinstance(display_delegate, OverlayViewportDisplayDelegate)
display_delegate.set_overlay_alpha(1.0 - elapsed_time / fading_time)
elif elapsed_time >= fading_time:
# Reset the display delegate to the previous one that was used before locking viewport render
internal_state.restore_display_delegate()
# Output attribute connection is activated and the latent state is finished for this node
fade_complete_exec_attr_state = ExecutionAttributeState.LATENT_FINISH
internal_state.lock_state = LockState.UNLOCKED
internal_state.elapsed_time += db.abi_context.get_elapsed_time()
db.outputs.locked = locked_exec_attr_state
db.outputs.fadeStarted = fade_started_exec_attr_state
db.outputs.fadeComplete = fade_complete_exec_attr_state
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 10,244 | Python | 38.555984 | 118 | 0.640863 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnComboBox.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.graph.core as og
import omni.kit.app
import omni.ui as ui
from . import UINodeCommon
class ComboBoxItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = ui.SimpleStringModel(text)
class ComboBoxModel(ui.AbstractItemModel):
def __init__(self, item_list):
super().__init__()
self._current_index = ui.SimpleIntModel(0)
self._current_index.add_value_changed_fn(lambda index_model: self._item_changed(None))
self._items = [ComboBoxItem(text) for text in item_list]
def get_item_children(self, item=None):
return self._items
def get_item_value_model(self, item=None, column_id=0):
if item is None:
return self._current_index
return item.model
class OgnComboBox:
@staticmethod
def internal_state():
return UINodeCommon.OgnUINodeInternalState()
@staticmethod
def compute(db) -> bool:
# OM-97733: This node hasn't been converted to use the widget registry yet. Let's discourage
# its use.
db.log_warning("The ComboBox node is unsupported and may not behave as expected.")
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
item_list = db.inputs.itemList
if not item_list:
db.log_error("The combo box must have at least one item!")
return False
width = db.inputs.width
if width <= 0:
db.log_error("The width of the combo box must be positive!")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
parent_widget = UINodeCommon.get_parent_widget(db)
if parent_widget is None:
return False
# Tear down previously created widget
if db.internal_state.created_widget is not None:
UINodeCommon.tear_down_widget(db)
def on_combox_box_item_changed(model, item):
if not db.internal_state.created_widget.enabled:
return
current_index = model.get_item_value_model().as_int
selected_child = model.get_item_children()[current_index]
selected_value = model.get_item_value_model(selected_child).as_string
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
event_name = "value_changed_" + widget_identifier
reg_event_name = UINodeCommon.registered_event_name(event_name)
payload = {"newValue": selected_value, "valueType": "string"}
message_bus.push(reg_event_name, payload=payload)
# Now create the button widget and register callbacks
with parent_widget:
db.internal_state.created_frame = ui.Frame()
with db.internal_state.created_frame:
with ui.HStack(content_clipping=1):
db.internal_state.created_widget = ui.ComboBox(
ComboBoxModel(item_list),
identifier=widget_identifier,
width=width,
)
db.internal_state.created_widget.model.add_item_changed_fn(on_combox_box_item_changed)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(db.internal_state.created_widget)
return True
if db.inputs.tearDown != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.tear_down_widget(db)
if db.inputs.show != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.show_widget(db)
if db.inputs.hide != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.hide_widget(db)
if db.inputs.enable != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.enable_widget(db)
if db.inputs.disable != og.ExecutionAttributeState.DISABLED:
return UINodeCommon.disable_widget(db)
db.log_warning("Unexpected execution with no execution input enabled")
return False
| 4,651 | Python | 38.092437 | 110 | 0.627607 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnWriteWidgetStyle.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.graph.core as og
from . import UINodeCommon
class OgnWriteWidgetStyle:
@staticmethod
def compute(db) -> bool:
if db.inputs.write != og.ExecutionAttributeState.DISABLED:
widget_path = db.inputs.widgetPath
if not widget_path:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
db.log_warning("No widgetIdentifier or widgetPath provided.")
return False
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget:
db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.")
return False
else:
widget = UINodeCommon.find_widget_among_all_windows(widget_path)
if not widget:
db.log_warning(f"No widget found at path '{widget_path}'.")
return False
# For error messages only.
widget_identifier = widget_path
style_string = db.inputs.style
if not style_string:
db.log_error("No style provided.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget.set_style(style)
db.outputs.written = og.ExecutionAttributeState.ENABLED
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
| 2,150 | Python | 37.410714 | 107 | 0.607907 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportDragManipulator.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportDragManipulatorFactory"]
from typing import Any
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME_BEGAN = "omni.graph.viewport.drag.began"
EVENT_NAME_CHANGED = "omni.graph.viewport.drag.changed"
EVENT_NAME_ENDED = "omni.graph.viewport.drag.ended"
GESTURE_NAMES = ["Left Mouse Drag", "Right Mouse Drag", "Middle Mouse Drag"]
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
class ViewportDragGesture(sc.DragGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str, mouse_button: int):
super().__init__(mouse_button=mouse_button, manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._gesture_name = GESTURE_NAMES[mouse_button]
self._event_type_began = carb.events.type_from_string(EVENT_NAME_BEGAN)
self._event_type_changed = carb.events.type_from_string(EVENT_NAME_CHANGED)
self._event_type_ended = carb.events.type_from_string(EVENT_NAME_ENDED)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self._start_pos_valid = False
self._started_moving = False
self._start_pos_norm = None
self._start_pos_pixel = None
def on_began(self):
mouse = self.sender.gesture_payload.mouse
resolution = self._viewport_api.resolution
# Start position in normalized coords
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
if not all(0.0 <= x <= 1.0 for x in pos_norm):
self._start_pos_valid = False
return
# Start position in viewport resolution pixels
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
# Store start position and wait for on_changed to send
self._start_pos_valid = True
self._started_moving = False
self._start_pos_norm = pos_norm
self._start_pos_pixel = pos_pixel
def on_changed(self):
if not self._start_pos_valid:
return
mouse = self.sender.gesture_payload.mouse
mouse_moved = self.sender.gesture_payload.mouse_moved
resolution = self._viewport_api.resolution
# Current position in normalized coords
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
if not all(0.0 <= x <= 1.0 for x in pos_norm):
return
# Current position in viewport resolution pixels
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
# Velocity in normalized coords
vel_norm = self._viewport_api.map_ndc_to_texture(mouse_moved)[0]
origin_norm = self._viewport_api.map_ndc_to_texture((0, 0))[0]
vel_norm = (vel_norm[0] - origin_norm[0], origin_norm[1] - vel_norm[1])
# Velocity in viewport resolution pixels
vel_pixel = (vel_norm[0] * resolution[0], vel_norm[1] * resolution[1])
if not self._started_moving:
payload = {
"viewport": self._viewport_window_name,
"gesture": self._gesture_name,
"start_pos_norm_x": self._start_pos_norm[0],
"start_pos_norm_y": self._start_pos_norm[1],
"start_pos_pixel_x": self._start_pos_pixel[0],
"start_pos_pixel_y": self._start_pos_pixel[1],
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
"vel_norm_x": vel_norm[0],
"vel_norm_y": vel_norm[1],
"vel_pixel_x": vel_pixel[0],
"vel_pixel_y": vel_pixel[1],
}
self._message_bus.push(self._event_type_began, payload=payload)
self._started_moving = True
else:
payload = {
"viewport": self._viewport_window_name,
"gesture": self._gesture_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
"vel_norm_x": vel_norm[0],
"vel_norm_y": vel_norm[1],
"vel_pixel_x": vel_pixel[0],
"vel_pixel_y": vel_pixel[1],
}
self._message_bus.push(self._event_type_changed, payload=payload)
def on_ended(self):
if self._start_pos_valid and self._started_moving:
payload = {
"viewport": self._viewport_window_name,
"gesture": self._gesture_name,
}
self._message_bus.push(self._event_type_ended, payload=payload)
self._start_pos_valid = False
# Custom manipulator containing a Screen that contains the gestures
class ViewportDragManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [
ViewportDragGesture(viewport_api, viewport_window_name, 0), # left mouse drag
ViewportDragGesture(viewport_api, viewport_window_name, 1), # right mouse drag
ViewportDragGesture(viewport_api, viewport_window_name, 2), # middle mouse drag
]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
self._transform = sc.Transform()
with self._transform:
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def ViewportDragManipulatorFactory(desc: dict) -> ViewportDragManipulator: # noqa: N802
manip = ViewportDragManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"ViewportDragManipulator.{desc.get('viewport_window_name')}"
return manip
| 6,711 | Python | 38.482353 | 95 | 0.60453 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/PickingManipulator.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["PickingManipulatorFactory"]
from typing import Any, List, Optional
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME = "omni.graph.picking"
CLICK_GESTURE_NAMES = ["Left Mouse Click", "Right Mouse Click", "Middle Mouse Click"]
PRESS_GESTURE_NAMES = ["Left Mouse Press", "Right Mouse Press", "Middle Mouse Press"]
SEQ_LIMIT = 128
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
# Custom gesture that triggers a picking query on mouse press, and sends the result on both mouse press and end of click
class PickingGesture(sc.DragGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str, mouse_button: int):
super().__init__(mouse_button=mouse_button, manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._click_gesture_name = CLICK_GESTURE_NAMES[mouse_button]
self._press_gesture_name = PRESS_GESTURE_NAMES[mouse_button]
self._event_type = carb.events.type_from_string(EVENT_NAME)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
# Sequence number for associating picking queries with gestures
self._seq = 0
# Bool to track whether the mouse button was initially pressed over the 3D viewport or not
# (does not need to be an array like the rest since _query_completed does not need to check it)
self._began = False
# Sequence number indexed bools to control the following execution order cases for mouse click:
# 1: on_began -> _query_completed -> on_ended
# 2: on_began -> _query_completed -> on_changed (cancelled) -> on_ended
# 3: on_began -> on_ended -> _query_completed
# 4: on_began -> on_changed (cancelled) -> _query_completed -> on_ended
# 5: on_began -> on_changed (cancelled) -> on_ended -> _query_completed
self._ended = [False] * SEQ_LIMIT # True if the mouse button has been released without moving the mouse
self._cancelled = [False] * SEQ_LIMIT # True if the mouse was moved while pressed, cancelling the click
self._result_stored = [False] * SEQ_LIMIT # True if the picking query has completed and stored its result
# Sequence number indexed temporary buffers to hold the picking result
self._picked_prim_path = [None] * SEQ_LIMIT
self._world_space_pos = [None] * SEQ_LIMIT
# Callback to request_query called when the picking query completes
def _query_completed(self, seq: int, picked_prim_path: str, world_space_pos: Optional[List[float]], *args):
# Handle mouse press:
# Send the picked prim path and picked world position in an event payload
# Include the viewport window name and gesture name to filter on the receiving end
press_payload = {
"viewport": self._viewport_window_name,
"gesture": self._press_gesture_name,
"path": picked_prim_path,
"pos_x": world_space_pos[0] if world_space_pos else 0.0,
"pos_y": world_space_pos[1] if world_space_pos else 0.0,
"pos_z": world_space_pos[2] if world_space_pos else 0.0,
}
self._message_bus.push(self._event_type, payload=press_payload)
# Handle cases for mouse click
if self._cancelled[seq]:
return
if self._ended[seq]:
# Case 3: Click has already ended and we were waiting on the query to complete, so send the payload now
click_payload = {
"viewport": self._viewport_window_name,
"gesture": self._click_gesture_name,
"path": picked_prim_path,
"pos_x": world_space_pos[0] if world_space_pos else 0.0,
"pos_y": world_space_pos[1] if world_space_pos else 0.0,
"pos_z": world_space_pos[2] if world_space_pos else 0.0,
}
self._message_bus.push(self._event_type, payload=click_payload)
else:
# Case 1 or 2: Click has not completed yet, so save the picking result and wait until mouse is released
self._picked_prim_path[seq] = picked_prim_path
self._world_space_pos[seq] = world_space_pos
self._result_stored[seq] = True
def _query_completed_seq(self, seq: int):
return lambda *args: self._query_completed(seq, *args)
# Called when the specified mouse button is pressed
def on_began(self):
# Get the next sequence number and reset the control bools
self._seq = (self._seq + 1) % SEQ_LIMIT
self._began = False
self._ended[self._seq] = False
self._cancelled[self._seq] = False
self._result_stored[self._seq] = False
self._picked_prim_path[self._seq] = None
self._world_space_pos[self._seq] = None
# Get the mouse position in normalized coords and check if the mouse is actually over the 3D viewport
mouse = self.sender.gesture_payload.mouse
resolution = self._viewport_api.resolution
pos_norm, _ = self._viewport_api.map_ndc_to_texture(mouse)
if pos_norm is None or not all(0.0 <= x <= 1.0 for x in pos_norm):
return
self._began = True
# Get the mouse position in viewport resolution pixels and request a picking query
pos_pixel = (int(pos_norm[0] * resolution[0]), int((1.0 - pos_norm[1]) * resolution[1]))
self._viewport_api.request_query(
pos_pixel,
self._query_completed_seq(self._seq),
query_name=f"omni.graph.ui_nodes.PickingManipulator.{id(self)}",
)
# Called when the mouse is moved while pressed, cancelling the click
def on_changed(self):
if not self._began:
return
self._cancelled[self._seq] = True
# Called when the specified mouse button is released
def on_ended(self):
if not self._began or self._cancelled[self._seq]:
return
if self._result_stored[self._seq]:
# Case 1: The picking query has already completed and we have the result saved, so send the payload now
picked_prim_path = self._picked_prim_path[self._seq]
world_space_pos = self._world_space_pos[self._seq]
click_payload = {
"viewport": self._viewport_window_name,
"gesture": self._click_gesture_name,
"path": picked_prim_path,
"pos_x": world_space_pos[0] if world_space_pos else 0.0,
"pos_y": world_space_pos[1] if world_space_pos else 0.0,
"pos_z": world_space_pos[2] if world_space_pos else 0.0,
}
self._message_bus.push(self._event_type, payload=click_payload)
else:
# Case 3: The picking query has not completed yet, so wait until it completes to send the payload
self._ended[self._seq] = True
# Custom manipulator containing a screen that contains the gestures
class PickingManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [
PickingGesture(viewport_api, viewport_window_name, 0), # left mouse click/press
PickingGesture(viewport_api, viewport_window_name, 1), # right mouse click/press
PickingGesture(viewport_api, viewport_window_name, 2), # middle mouse click/press
]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
# Create a transform and put a screen in it (must hold a reference to keep the sc.Screen alive)
self._transform = sc.Transform()
with self._transform:
# sc.Screen is an invisible rectangle that is always in front of and entirely covers the viewport camera
# By attaching the gestures to this screen, the gestures can be triggered by clicking anywhere
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def PickingManipulatorFactory(desc: dict) -> PickingManipulator: # noqa: N802
manip = PickingManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"PickingManipulator.{desc.get('viewport_window_name')}"
return manip
| 9,093 | Python | 45.397959 | 120 | 0.638953 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnWidgetValueChanged.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from contextlib import suppress
import omni.graph.core as og
from omni.graph.ui_nodes.ogn.OgnOnWidgetValueChangedDatabase import OgnOnWidgetValueChangedDatabase
from . import UINodeCommon
class OgnOnWidgetValueChanged:
@staticmethod
def try_resolve_output_attribute(node, attr_name, attr_type):
out_attr = node.get_attribute(attr_name)
attr_type_valid = attr_type.base_type != og.BaseDataType.UNKNOWN
if out_attr.get_resolved_type().base_type != og.BaseDataType.UNKNOWN and (
not attr_type_valid or attr_type != out_attr.get_resolved_type()
):
out_attr.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN))
if attr_type_valid and out_attr.get_resolved_type().base_type == og.BaseDataType.UNKNOWN:
out_attr.set_resolved_type(attr_type)
@staticmethod
def internal_state():
return UINodeCommon.OgnUIEventNodeInternalState()
@staticmethod
def compute(db) -> bool:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
return True
event_name = "value_changed_" + widget_identifier
if db.internal_state.first_time_subscribe(db.node, event_name):
return True
payload = db.internal_state.try_pop_event()
if payload is None:
return True
if "valueType" in payload.get_keys():
value_type = payload["valueType"]
OgnOnWidgetValueChanged.try_resolve_output_attribute(
db.node, "outputs:newValue", og.AttributeType.type_from_ogn_type_name(value_type)
)
if "newValue" in payload.get_keys():
new_value = payload["newValue"]
db.outputs.newValue = new_value
db.outputs.valueChanged = og.ExecutionAttributeState.ENABLED
return True
# ----------------------------------------------------------------------------
@staticmethod
def release(node):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
with suppress(og.OmniGraphError):
state = OgnOnWidgetValueChangedDatabase.per_node_internal_state(node)
state.release()
| 2,695 | Python | 35.931506 | 101 | 0.66308 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnDrawDebugCurve.py | """
This is the implementation of the OGN node defined in OgnDrawDebugCurve.ogn
"""
import carb
import numpy as np
import omni.debugdraw as dd
import omni.graph.core as og
class OgnDrawDebugCurve:
"""
Draws a curve using omni.debugdraw
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
curvepoints = db.inputs.curvepoints
color = db.inputs.color
closed = db.inputs.closed
try:
ddi = dd._debugDraw.acquire_debug_draw_interface() # noqa: PLW0212
rgb_bytes = (np.clip(color, 0, 1.0) * 255).astype("uint8").tobytes()
argb_bytes = b"\xff" + rgb_bytes
argb = int.from_bytes(argb_bytes, byteorder="big")
carbpoints = [carb.Float3(p.tolist()) for p in curvepoints]
# carb.log_warn(f'{color} = {argb_bytes} = {argb}, {carbpoints[0]}, {carbpoints[1]}')
for i in range(len(carbpoints) - 1):
ddi.draw_line(carbpoints[i], argb, carbpoints[i + 1], argb)
if closed:
ddi.draw_line(carbpoints[-1], argb, carbpoints[0], argb)
except Exception as error: # noqa: PLW0703
import traceback
raise RuntimeError(traceback.format_exc()) from error
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
| 1,376 | Python | 33.424999 | 97 | 0.606105 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnNewFrame.py | """
This is the implementation of the OGN node defined in OgnOnNewFrame.ogn
"""
from contextlib import suppress
import omni.graph.core as og
import omni.usd
from omni.graph.ui_nodes.ogn.OgnOnNewFrameDatabase import OgnOnNewFrameDatabase
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnOnNewFrameInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
"""Instantiate the per-node state information."""
# This subscription object controls the lifetime of our callback, it will be
# cleaned up automatically when our node is destroyed
self.sub = None
# Set when the callback has triggered
self.is_set = False
# The last payload received
self.payload = None
# The node instance handle
self.node = None
# The viewport we are watching frames for
self.viewport_handle = None
def on_event(self, e):
"""The event callback"""
if e is None:
return
self.is_set = True
viewport_handle = e.payload["viewport_handle"]
if viewport_handle != self.viewport_handle:
return
self.payload = e.payload
# Tell the evaluator we need to be computed
if self.node.is_valid():
self.node.request_compute()
def first_time_subscribe(self, node: og.Node, viewport_handle: int) -> bool:
"""Checked call to set up carb subscription
Args:
node: The node instance
viewport_handle: The handle for the viewport to watch
Returns:
True if we subscribed, False if we are already subscribed
"""
if self.sub is not None and self.viewport_handle != viewport_handle:
# event name changed since we last subscribed, unsubscribe
self.sub.unsubscribe()
self.sub = None
if self.sub is None:
self.sub = (
omni.usd.get_context()
.get_rendering_event_stream()
.create_subscription_to_push_by_type(
int(omni.usd.StageRenderingEventType.NEW_FRAME),
self.on_event,
name=f"omni.graph.action.__on_new_frame.{node.node_id()}",
)
)
self.viewport_handle = viewport_handle
self.node = node
self.payload = None
return True
return False
def try_pop_event(self):
"""Pop the payload of the last event received, or None if there is no event to pop"""
if self.is_set:
self.is_set = False
payload = self.payload
self.payload = None
return payload
return None
# ======================================================================
class OgnOnNewFrame:
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnOnNewFrameInternalState()
@staticmethod
def compute(db) -> bool:
viewport_name = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport_name)
if not viewport_api:
return True
state = db.internal_state
# XXX: Note this may be incorrect, viewport_handle is not stable (and may be None)
viewport_handle = viewport_api.frame_info.get("viewport_handle")
if state.first_time_subscribe(db.node, viewport_handle):
return True
payload = state.try_pop_event()
if payload is None:
return True
# Copy the event dict contents into the output bundle
db.outputs.frameNumber = payload["frame_number"]
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
# ----------------------------------------------------------------------------
@staticmethod
def release(node):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
with suppress(og.OmniGraphError):
state = OgnOnNewFrameDatabase.per_node_internal_state(node)
if state.sub:
state.sub.unsubscribe()
state.sub = None
| 4,332 | Python | 33.388889 | 101 | 0.587719 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportMode.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from dataclasses import dataclass
from threading import Lock
from typing import Any, Callable, Dict, Optional
import omni.graph.core as og
import omni.ui as ui
from omni.graph.ui_nodes.ogn.nodes.OgnVStack import OgnVStack
from omni.graph.ui_nodes.ogn.OgnSetViewportModeDatabase import OgnSetViewportModeDatabase
from omni.kit.viewport.utility import get_active_viewport_and_window
from omni.ui import scene as sc
from omni.ui_query import OmniUIQuery
from .PickingManipulator import PickingManipulatorFactory # noqa: PLE0402
from .ViewportClickManipulator import ViewportClickManipulatorFactory # noqa: PLE0402
from .ViewportDragManipulator import ViewportDragManipulatorFactory # noqa: PLE0402
from .ViewportHoverManipulator import ViewportHoverManipulatorFactory # noqa: PLE0402
from .ViewportPressManipulator import ViewportPressManipulatorFactory # noqa: PLE0402
from .ViewportScrollManipulator import ViewportScrollManipulatorFactory # noqa: PLE0402
UI_FRAME_NAME = "omni.graph.SetViewportMode"
VIEWPORT_OVERLAY_NAME = "OG_overlay"
IS_LOCK_REQUIRED = True
class NoLock:
def __init__(self):
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
class OgnSetViewportMode:
@dataclass
class ViewportState:
viewport_click_manipulator: Optional[Any] = None
viewport_press_manipulator: Optional[Any] = None
viewport_drag_manipulator: Optional[Any] = None
viewport_hover_manipulator: Optional[Any] = None
viewport_scroll_manipulator: Optional[Any] = None
picking_manipulator: Optional[Any] = None
__viewport_states: Dict[str, ViewportState] = {}
__do_it_lock: Optional[Any] = Lock() if IS_LOCK_REQUIRED else NoLock()
@staticmethod
def compute(db) -> bool:
if db.inputs.execIn == og.ExecutionAttributeState.DISABLED:
return False
with OgnSetViewportMode.__do_it_lock:
result = OgnSetViewportMode.__do_it(
db.inputs.mode,
db.inputs.viewport,
db.abi_context,
db.outputs,
db.log_error,
db.inputs.enableViewportMouseEvents,
db.inputs.enablePicking,
db.inputs.passClicksThru,
)
if result:
if db.inputs.mode == 0:
db.outputs.defaultMode = og.ExecutionAttributeState.ENABLED
db.outputs.scriptedMode = og.ExecutionAttributeState.DISABLED
elif db.inputs.mode == 1:
db.outputs.defaultMode = og.ExecutionAttributeState.DISABLED
db.outputs.scriptedMode = og.ExecutionAttributeState.ENABLED
return True
db.outputs.defaultMode = og.ExecutionAttributeState.DISABLED
db.outputs.scriptedMode = og.ExecutionAttributeState.DISABLED
return False
@staticmethod
def __do_it(
mode: int,
viewport_window_name: str,
context: og.GraphContext,
outputs: OgnSetViewportModeDatabase.ValuesForOutputs,
log_fn: Optional[Callable],
viewport_mouse_events_enabled: bool,
picking_enabled: bool,
pass_clicks_thru: bool,
) -> bool:
# Validate the viewport window name
if not viewport_window_name:
if log_fn is not None:
log_fn(f"Viewport window '{viewport_window_name}' not found")
return False
viewport_api, viewport_window = get_active_viewport_and_window(window_name=viewport_window_name)
if viewport_window is None:
if log_fn is not None:
log_fn(f"Viewport window '{viewport_window_name}' not found")
return False
if hasattr(viewport_api, "legacy_window"):
if log_fn is not None:
log_fn(f"Legacy viewport window '{viewport_window_name}' not compatible with Set Viewport Mode")
return False
# Default mode
if mode == 0:
# Destroy the manipulators
OgnSetViewportMode.__viewport_states[viewport_window_name] = OgnSetViewportMode.__viewport_states.get(
viewport_window_name, OgnSetViewportMode.ViewportState()
)
viewport_state = OgnSetViewportMode.__viewport_states[viewport_window_name]
if viewport_state.viewport_click_manipulator is not None:
viewport_state.viewport_click_manipulator.destroy()
viewport_state.viewport_click_manipulator = None
if viewport_state.viewport_press_manipulator is not None:
viewport_state.viewport_press_manipulator.destroy()
viewport_state.viewport_press_manipulator = None
if viewport_state.viewport_drag_manipulator is not None:
viewport_state.viewport_drag_manipulator.destroy()
viewport_state.viewport_drag_manipulator = None
if viewport_state.viewport_hover_manipulator is not None:
viewport_state.viewport_hover_manipulator.destroy()
viewport_state.viewport_hover_manipulator = None
if viewport_state.viewport_scroll_manipulator is not None:
viewport_state.viewport_scroll_manipulator.destroy()
viewport_state.viewport_scroll_manipulator = None
if viewport_state.picking_manipulator is not None:
viewport_state.picking_manipulator.destroy()
viewport_state.picking_manipulator = None
# Destroy the ui.ZStack and sc.SceneView if they exist
frame = viewport_window.get_frame(UI_FRAME_NAME)
frame_children = ui.Inspector.get_children(frame)
if frame_children:
widget_container = frame_children[0]
widget_container_children = ui.Inspector.get_children(widget_container)
if widget_container_children:
scene_view = widget_container_children[0]
viewport_api.remove_scene_view(scene_view)
scene_view.scene.clear()
scene_view.destroy()
OgnVStack.deregister_widget(context, VIEWPORT_OVERLAY_NAME)
widget_container.destroy()
frame.clear()
# Clear output widget path
outputs.widgetPath = ""
# Scripted mode
elif mode == 1:
# Create the ui.ZStack and sc.SceneView if they don't exist
frame = viewport_window.get_frame(UI_FRAME_NAME)
frame_children = ui.Inspector.get_children(frame)
if frame_children:
widget_container = frame_children[0]
else:
with frame:
widget_container = ui.ZStack(identifier=VIEWPORT_OVERLAY_NAME)
# Register the container widget so that graphs can access its properties, like size.
OgnVStack.register_widget(context, VIEWPORT_OVERLAY_NAME, widget_container)
widget_container.content_clipping = not pass_clicks_thru
widget_container_children = ui.Inspector.get_children(widget_container)
if widget_container_children:
scene_view = widget_container_children[0]
else:
with widget_container:
scene_view = sc.SceneView(child_windows_input=0)
viewport_api.add_scene_view(scene_view)
# Destroy any existing manipulators and create the enabled manipulators
OgnSetViewportMode.__viewport_states[viewport_window_name] = OgnSetViewportMode.__viewport_states.get(
viewport_window_name, OgnSetViewportMode.ViewportState()
)
viewport_state = OgnSetViewportMode.__viewport_states[viewport_window_name]
if viewport_state.viewport_click_manipulator is not None:
viewport_state.viewport_click_manipulator.destroy()
viewport_state.viewport_click_manipulator = None
if viewport_state.viewport_press_manipulator is not None:
viewport_state.viewport_press_manipulator.destroy()
viewport_state.viewport_press_manipulator = None
if viewport_state.viewport_drag_manipulator is not None:
viewport_state.viewport_drag_manipulator.destroy()
viewport_state.viewport_drag_manipulator = None
if viewport_state.viewport_hover_manipulator is not None:
viewport_state.viewport_hover_manipulator.destroy()
viewport_state.viewport_hover_manipulator = None
if viewport_state.viewport_scroll_manipulator is not None:
viewport_state.viewport_scroll_manipulator.destroy()
viewport_state.viewport_scroll_manipulator = None
if viewport_state.picking_manipulator is not None:
viewport_state.picking_manipulator.destroy()
viewport_state.picking_manipulator = None
with scene_view.scene:
if viewport_mouse_events_enabled:
viewport_state.viewport_click_manipulator = ViewportClickManipulatorFactory(
{"viewport_api": viewport_api, "viewport_window_name": viewport_window_name}
)
viewport_state.viewport_press_manipulator = ViewportPressManipulatorFactory(
{"viewport_api": viewport_api, "viewport_window_name": viewport_window_name}
)
viewport_state.viewport_drag_manipulator = ViewportDragManipulatorFactory(
{"viewport_api": viewport_api, "viewport_window_name": viewport_window_name}
)
viewport_state.viewport_hover_manipulator = ViewportHoverManipulatorFactory(
{"viewport_api": viewport_api, "viewport_window_name": viewport_window_name}
)
viewport_state.viewport_scroll_manipulator = ViewportScrollManipulatorFactory(
{"viewport_api": viewport_api, "viewport_window_name": viewport_window_name}
)
if picking_enabled:
viewport_state.picking_manipulator = PickingManipulatorFactory(
{"viewport_api": viewport_api, "viewport_window_name": viewport_window_name}
)
# Set output widget path
outputs.widgetPath = OmniUIQuery.get_widget_path(viewport_window, widget_container)
return True
| 11,087 | Python | 43 | 114 | 0.638496 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportScrollManipulator.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportScrollManipulatorFactory"]
from typing import Any
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME = "omni.graph.viewport.scroll"
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
class ViewportScrollGesture(sc.ScrollGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str):
super().__init__(manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._event_type = carb.events.type_from_string(EVENT_NAME)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
def on_ended(self, *args):
mouse = self.sender.gesture_payload.mouse
resolution = self._viewport_api.resolution
# Position in normalized coords
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
if not all(0.0 <= x <= 1.0 for x in pos_norm):
return
# Position in viewport resolution pixels
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
"scroll": self.scroll[0],
}
self._message_bus.push(self._event_type, payload=payload)
class ViewportScrollManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [ViewportScrollGesture(viewport_api, viewport_window_name)]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
self._transform = sc.Transform()
with self._transform:
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def ViewportScrollManipulatorFactory(desc: dict) -> ViewportScrollManipulator: # noqa: N802
manip = ViewportScrollManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"ViewportScrollManipulator.{desc.get('viewport_window_name')}"
return manip
| 3,047 | Python | 33.636363 | 97 | 0.65146 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnWidgetClicked.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from contextlib import suppress
import omni.graph.core as og
from omni.graph.ui_nodes.ogn.OgnOnWidgetClickedDatabase import OgnOnWidgetClickedDatabase
from . import UINodeCommon
class OgnOnWidgetClicked:
@staticmethod
def internal_state():
return UINodeCommon.OgnUIEventNodeInternalState()
@staticmethod
def compute(db) -> bool:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
return True
event_name = "clicked_" + widget_identifier
if db.internal_state.first_time_subscribe(db.node, event_name):
return True
payload = db.internal_state.try_pop_event()
if payload is None:
return True
# Currently payload is an empty dictionary
db.outputs.clicked = og.ExecutionAttributeState.ENABLED
return True
# ----------------------------------------------------------------------------
@staticmethod
def release(node):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
with suppress(og.OmniGraphError):
state = OgnOnWidgetClickedDatabase.per_node_internal_state(node)
state.release()
| 1,709 | Python | 32.529411 | 101 | 0.679345 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnGetActiveViewportCamera.py | """
This is the implementation of the OGN node defined in OgnGetActiveViewportCamera.ogn
"""
from omni.kit.viewport.utility import get_viewport_window_camera_string
class OgnGetActiveViewportCamera:
"""
Gets a viewport's actively bound camera
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
viewport_name = db.inputs.viewport
active_camera = get_viewport_window_camera_string(viewport_name)
db.outputs.camera = active_camera
db.outputs.cameraPrim = [active_camera]
except Exception as error: # pylint: disable=broad-except
db.log_error(str(error))
return False
return True
| 752 | Python | 27.961537 | 84 | 0.650266 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/UINodeCommon.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 ast
from typing import Dict, List, Optional, Tuple, Type, Union
import carb.events
import omni.client
import omni.graph.core as og
import omni.kit.app
import omni.ui as ui
import omni.usd
from omni.ui_query import OmniUIQuery
# TODO: Uncomment this when Viewport 2.0 becomes the default Viewport
# import omni.kit.viewport.window as vp
class OgnUINodeInternalState:
# This class is used by old widget nodes which have not yet been converted to use
# OgWidgetNode. It will be removed once they are all converted.
def __init__(self):
self.created_widget = None
self.created_frame = None
class OgWidgetNodeCallbacks:
"""
!!!BETA: DO NOT USE!!!
A base class for callbacks used by nodes which create omni.ui widgets.
"""
@staticmethod
def get_property_names(widget: ui.Widget, writeable: bool) -> Optional[List[str]]:
"""
Returns a dictionary containing those properties which are common to all ui.Widget.
If 'writeable' is True then only those properties whose values can be set will be
returned, otherwise only those whose value can be read will be returned.
If 'widget' is not a valid widget a warning will be issued and None returned.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to retrieve property names from non-widget object '{widget}'.")
return None
# Read/write properties
props = [
"enabled", # bool
"height", # ui.Length
"name", # str
"opaque_for_mouse_events", # bool
"selected", # bool
"skip_draw_when_clipped", # bool
"style_type_name_override", # str
"tooltip", # str
"tooltip_offset_x", # float
"tooltip_offset_y", # float
"visible", # bool
"visible_max", # float
"visible_min", # float
"width", # ui.Length
]
if not writeable:
# Read-only properties
props += [
"computed_content_height", # float
"computed_content_width", # float
"computed_height", # float
"computed_width", # float
"dragging", # bool
"identifier", # str
"screen_position_x", # float
"screen_position_y", # float
]
return props
@staticmethod
def resolve_output_property(widget: ui.Widget, property_name: str, attribute: og.Attribute):
"""
Resolves the type of an output property based on a widget attribute.
This assumes the output attribute has the 'unvalidated' metadata set to true
OmniGraphError raised on failure.
"""
if not isinstance(widget, ui.Widget):
raise og.OmniGraphError(f"Attempt to resolve property on non-widget object '{widget}'.")
widget_desc = widget.identifier or repr(widget)
if not hasattr(widget, property_name):
raise og.OmniGraphError(f"Widget '{widget_desc}' has no property '{property_name}'.")
prop_value = getattr(widget, property_name)
if isinstance(prop_value, bool):
out_type = "bool"
elif isinstance(prop_value, int):
out_type = "int"
elif isinstance(prop_value, float):
out_type = "double"
elif isinstance(prop_value, (str, ui.Length, ui.Direction)):
out_type = "string"
else:
raise og.OmniGraphError(f"Cannot resolve output type: {type(prop_value)}")
attr_type = og.AttributeType.type_from_ogn_type_name(out_type)
attr_type_valid = attr_type.base_type != og.BaseDataType.UNKNOWN
if attribute.get_resolved_type().base_type != og.BaseDataType.UNKNOWN and (
not attr_type_valid or attr_type != attribute.get_resolved_type()
):
attribute.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN))
if attr_type_valid and attribute.get_resolved_type().base_type == og.BaseDataType.UNKNOWN:
attribute.set_resolved_type(attr_type)
@staticmethod
def get_property_value(widget: ui.Widget, property_name: str, attribute: og.RuntimeAttribute):
"""
Retrieves the value of a property from a widget and writes it to the given node attribute.
OmniGraphError raised on failure.
"""
if not isinstance(widget, ui.Widget):
raise og.OmniGraphError(f"Attempt to get property value from non-widget object '{widget}'.")
widget_desc = widget.identifier or repr(widget)
if not hasattr(widget, property_name):
raise og.OmniGraphError(f"Widget '{widget_desc}' has no property '{property_name}'.")
prop_value = getattr(widget, property_name)
prop_type = type(prop_value)
if prop_type in (bool, int, float, str):
try:
attribute.value = prop_value
return # Property value is retrieved
except ValueError:
pass
# XXX: To preserve the 'units' (px, fr, %) we may want to split the output of these into a (value, unit) pair
elif prop_type in (ui.Length, ui.Direction):
try:
attribute.value = str(prop_value)
return
except ValueError:
pass
else:
raise og.OmniGraphError(f"Unsupported property type: {prop_type}")
raise og.OmniGraphError(f"Attempt to get property '{property_name}' from widget '{widget_desc}' failed.")
@staticmethod
def set_property_value(widget: ui.Widget, property_name: str, attribute: og.RuntimeAttribute):
"""
Retrieves the value of a node attribute and writes it to the given widget property.
OmniGraphError raised on failure.
"""
if not isinstance(widget, ui.Widget):
raise og.OmniGraphError(f"Attempt to set property value on non-widget object '{widget}'.")
widget_desc = widget.identifier or repr(widget)
if not hasattr(widget, property_name):
raise og.OmniGraphError(f"Widget '{widget_desc}' has no property '{property_name}'.")
value = attribute.value
prop_type = type(getattr(widget, property_name))
if prop_type == str and property_name == "image_url":
try:
setattr(widget, property_name, resolve_image_url(prop_type(value)))
return
except ValueError:
pass
elif prop_type in (bool, int, float, str):
try:
setattr(widget, property_name, prop_type(value))
return
except ValueError:
pass
elif prop_type == ui.Length:
length = to_ui_length(value)
if length is not None:
try:
setattr(widget, property_name, length)
return
except ValueError:
pass
return
elif prop_type == ui.Direction:
direction = to_ui_direction(value)
if direction is not None:
try:
setattr(widget, property_name, direction)
return
except ValueError:
pass
return
else:
raise og.OmniGraphError(f"Unsupported property type: {prop_type}")
if prop_type == ui.Length:
carb.log_warn(
f"{prop_type} properties may be set from int or float values, or from string values containing "
"an int or float optionally followed by 'px' for pixels (e.g. '5px'), 'fr' for fractional amounts "
"('0.3fr') or '%' for percentages ('30%'). If no suffix is given then 'px' is assumed."
)
if isinstance(value, str) and prop_type != str:
raise og.OmniGraphError(
f"Cannot set value onto widget '{widget_desc}' property '{property_name}': "
f"string value '{value}' cannot be converted to {prop_type}."
)
raise og.OmniGraphError(
f"Cannot set value of type {type(value)} onto widget '{widget_desc}' "
f"property '{property_name}' (type {prop_type})"
)
@staticmethod
def get_style_element_names(widget: ui.Widget, writeable: bool) -> List[str]:
"""
Returns the names of those style elements which are common to all ui.Widget.
If 'writeable' is True then only those elements whose values can be set will be
returned, otherwise only those whose value can be read will be returned.
If 'widget' is not a valid widget a warning will be issued and None returned.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to retrieve style element names from non-widget object '{widget}'.")
return None
# There are currently no style elements common to all widgets.
return []
@staticmethod
def get_style_value(widget: ui.Widget, element_name: str, attribute: og.RuntimeAttribute) -> bool:
"""
Retrieves the value of a style element from a widget and writes it to the given node attribute.
Returns True on success, False on failure.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to get style element from non-widget object '{widget}'.")
return None
# TBD
return False
@staticmethod
def set_style_value(widget: ui.Widget, element_name: str, attribute: og.RuntimeAttribute) -> bool:
"""
Retrieves the value of a style element from a node attribute and sets it on the given widget.
Returns True on success, False on failure.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to set style element on non-widget object '{widget}'.")
return None
# TBD
return False
class OgWidgetNode(OgWidgetNodeCallbacks):
"""
!!!BETA: DO NOT USE!!!
A base class for nodes which create omni.ui widgets.
"""
@classmethod
def register_widget(cls, context: og.GraphContext, widget_id: str, widget: omni.ui.Widget):
"""
Register a widget by the GraphContext in which it was generated and a unique id within that context.
"""
register_widget(context, widget_id, widget, cls)
@classmethod
def deregister_widget(cls, context: og.GraphContext, widget_id: str):
"""
Deregister a previously registered widget.
"""
if context and widget_id:
remove_registered_widgets(context, widget_id)
######################################################################################################
#
# Widget Registry
#
# The widget registry provides a mapping between a widget identifier and the widget itself. Widget
# identifiers are specific to the graph context in which their widgets were created. This helps to avoid clashing
# identifiers, particularly when graphs are instanced.
#
# TODO: Internally we use the widget's full path string to identify the widget uniquely within the application.
# This is quite inefficient as it requires traversing the entire widget tree of the application each
# time we want to convert a path to a widget or vice-versa.
#
# We cannot store the widget object itself in the registry because that would increment its
# reference count and keep the widget (and its window) alive after they should have been destroyed.
#
# Using a weak reference won't work either because the widget objects we see in Python are just temporary
# wrappers around the actual C++ objects. A weak reference would be invalidated as soon as the wrapper was
# destroyed, even though the widget itself might still be alive.
#
# get_registered_widget() ensures that the widget registry for a given context does not
# grow without bound, but we still need a way to either automatically clear a widget's entry when it is
# destroyed, or completely clear the entries for a given context when that context is destroyed.
# One approach would be to have the SetViewportMode node clear the registry of all widgets in its graph
# context when it destroys its OG overlay, however since its extension doesn't depend on this one, it would
# have to monitor the loading and unloading of the omni.graph.action extension.
def register_widget(
context: og.GraphContext, widget_id: str, widget: ui.Widget, callbacks: Type[OgWidgetNodeCallbacks]
):
"""
!!!BETA: DO NOT USE!!!
Register a widget by the GraphContext in which it was generated and a unique id within that context.
'callbacks' is either a sub-class of OgWidgetNode or some other object which provides the same set of
static methods (the class methods are not necessary).
"""
if context and widget_id and widget:
path = find_widget_path(widget)
if path:
_widget_registry[(context, widget_id)] = path
_widget_callbacks[path] = callbacks
def get_registered_widget(context: og.GraphContext, widget_id: str) -> Optional[ui.Widget]:
"""
!!!BETA: DO NOT USE!!!
Returns a widget given the GraphContext in which it was created and its unique id within that context.
If there is no such widget then None is returned.
"""
path = _widget_registry.get((context, widget_id))
if path:
widget = find_widget_among_all_windows(path)
if not widget:
# This must be a deleted widget. Remove it from the registry.
remove_registered_widgets(context, widget_id)
return widget
return None
def get_registered_widgets(context: og.GraphContext = None, widget_id: str = None) -> List[ui.Widget]:
"""
!!!BETA: DO NOT USE!!!
Returns all the widgets which match the search parameters. If 'context' is None then all contexts
will be searched. If 'id' is None then all widgets within the searched context(s) will be returned.
"""
return [
find_widget_among_all_windows(path)
for (_context, _id), path in _widget_registry.items()
if (context is None or _context == context) and (widget_id is None or _id == widget_id)
]
def remove_registered_widgets(context: og.GraphContext, widget_id: str = None):
"""
!!!BETA: DO NOT USE!!!
Removes the specified widget from the registry. If 'widget_id' is not specified then all widgets
registered under the given context will be removed.
"""
if widget_id:
keys_to_remove = [(context, widget_id)]
else:
keys_to_remove = [(_ctx, _id) for (_ctx, _id) in _widget_registry if _ctx == context]
for key in keys_to_remove:
path = _widget_registry.pop(key)
_widget_callbacks.pop(path, None)
def get_widget_callbacks(widget: ui.Widget) -> Optional[Type[OgWidgetNodeCallbacks]]:
"""
!!!BETA: DO NOT USE!!!
Returns the callbacks object for a registered widget or None if no such widget is registered.
"""
return _widget_callbacks.get(find_widget_path(widget))
def get_unique_widget_identifier(db: og.Database) -> str:
"""
!!!BETA: DO NOT USE!!!
Returns a widget identifier which is unique within the current GraphContext.
The identifier is taken from the 'widgetIdentifier' input attribute, or the name
of the node if 'widgetIdentifier' is not set. If the identifier is already in
use then a suffix will be added to make it unique.
"""
base_id = db.inputs.widgetIdentifier or db.node.get_prim_path().replace("/", ":")
counter = 0
final_id = base_id
while get_registered_widget(db.abi_context, final_id) is not None:
counter += 1
final_id = base_id + "_" + str(counter)
return final_id
# Mapping between widget identifiers and widgets.
#
# Key: (graph context, widget identifier)
# Value: full path to the widget
_widget_registry: Dict[Tuple[og.GraphContext, str], str] = {}
# Callbacks to operate on per-widget data (e.g. properites)
#
# Key: full path to the widget
# Value: class object derived from OgWidgetNodeCallbacks
_widget_callbacks: Dict[str, Type[OgWidgetNodeCallbacks]] = {}
######################################################################################################
def to_ui_direction(value: str) -> ui.Direction:
"""
!!!BETA: DO NOT USE!!!
Convert the input value to a ui.Direction.
"""
if value == "LEFT_TO_RIGHT":
return ui.Direction.LEFT_TO_RIGHT
if value == "RIGHT_TO_LEFT":
return ui.Direction.RIGHT_TO_LEFT
if value == "TOP_TO_BOTTOM":
return ui.Direction.TOP_TO_BOTTOM
if value == "BOTTOM_TO_TOP":
return ui.Direction.BOTTOM_TO_TOP
if value == "BACK_TO_FRONT":
return ui.Direction.BACK_TO_FRONT
if value == "FRONT_TO_BACK":
return ui.Direction.FRONT_TO_BACK
return None
def to_ui_length(value: Union[float, int, str]) -> ui.Length:
"""
!!!BETA: DO NOT USE!!!
Convert the input value to a ui.Length.
"""
if isinstance(value, (float, int)):
return ui.Length(value)
if not isinstance(value, str):
return None
unit_type = ui.UnitType.PIXEL
if value.endswith("fr"):
unit_type = ui.UnitType.FRACTION
value = value[:-2]
elif value.endswith("%"):
unit_type = ui.UnitType.PERCENT
value = value[:-1]
elif value.endswith("px"):
value = value[:-2]
try:
return ui.Length(int(value), unit_type)
except ValueError:
try:
return ui.Length(float(value), unit_type)
except ValueError:
return None
def resolve_image_url(url: str) -> str:
if not url:
return url
edit_layer = omni.usd.get_context().get_stage().GetEditTarget().GetLayer()
if edit_layer.anonymous:
return url
return omni.client.combine_urls(edit_layer.realPath, url).replace("\\", "/")
def resolve_style_image_urls(style_dict: Optional[Dict]) -> Optional[Dict]:
if not style_dict:
return style_dict
edit_layer = omni.usd.get_context().get_stage().GetEditTarget().GetLayer()
if edit_layer.anonymous:
return style_dict
for value in style_dict.values():
if isinstance(value, dict):
url = value.get("image_url")
if url:
value["image_url"] = omni.client.combine_urls(edit_layer.realPath, url).replace("\\", "/")
return style_dict
def to_ui_style(style_string: str) -> Optional[Dict]:
"""
!!!BETA: DO NOT USE!!!
Converts a string containing a style description into a Python dictionary suitable for use with
ui.Widget.set_style().
Returns None if style_string is empty.
Raises SyntaxError if the string contains invalid style syntax.
Raises ValueError if 'style_string' is not a string.
"""
def fmt_syntax_err(err):
# Syntax errors are not very descriptive. Let's do a bit better.
msg = "Invalid style syntax"
# Don't include the message if it's just "invalid syntax".
if err.msg.lower() != "invalid syntax":
msg += " (" + err.msg + ")"
# Include the text of the line where the error was found, with an indicator at the point of the error.
# It would be nice to output this as two lines with the indicator indented beneath the error, but by the
# time the message reached the node's tooltip all such formatting would be lost. So we settle for an
# inline indicator.
text = err.text[: err.offset] + "^^^" + err.text[err.offset :]
# If the line is too long, elide the start and/or end of it.
if len(text) > 50:
right = min(err.offset + 25, len(text))
left = max(right - 50, 0)
if len(text) - right > 5:
text = text[:right] + "..."
if left > 5:
text = "..." + text[left:]
# Include the line number and offset so that the callers don't all have to do it themselves.
return msg + f": line {err.lineno} offset {err.offset}: " + text
def fmt_value_err(err):
# Value errors generally reflect some bad internal state of the parser. They only give us a message with
# no indication of where in input the error occurred.
return f"Invalid style syntax ({err.args[0]})."
if not style_string:
return None
if not isinstance(style_string, str):
raise ValueError(f"Style must be a string, not type {type(style_string)}.")
try:
return resolve_style_image_urls(ast.literal_eval(style_string))
except SyntaxError as err:
err.msg = fmt_syntax_err(err)
raise
except ValueError as err:
syn_err = SyntaxError(fmt_value_err(err))
syn_err.text = style_string
raise syn_err from err
######################################################################################################
# All code in this block deal with Viewport 1.0
# TODO: Remove this block of code when Viewport 2.0 becomes the default Viewport
def _parse_input(query, search_among_all_windows=False):
"""A variation of OmniUIQuery._parse_input that allows you to search among all windows with the same name"""
tokens = query.split("//")
window_name = tokens[0] if len(tokens) > 1 else None
widget_predicate = ""
widget_part = tokens[1] if len(tokens) > 1 else tokens[0]
widget_part_list = widget_part.split(".", maxsplit=1)
widget_path = widget_part_list[0]
if len(widget_part_list) > 1:
widget_predicate = widget_part_list[1]
window = None
if window_name:
windows = ui.Workspace.get_windows()
window_list = []
for window in windows:
if window.title == window_name:
window_list.append(window)
if not window_list:
carb.log_warn(f"Failed to find window: '{window_name}'")
return False, None, [], widget_predicate
if search_among_all_windows:
window = []
for current_window in window_list:
if isinstance(current_window, ui.Window):
window.append(current_window)
if len(window) == 0:
carb.log_warn(f"Failed to find a ui.Window named {window_name}, query only works on ui.Window")
return False, None, [], widget_predicate
else:
if len(window_list) == 1:
window = window_list[0]
else:
carb.log_warn(
f"found {len(window_list)} windows named '{window_name}'. Using first visible window found"
)
window = None
for win in window_list:
if win.visible:
window = win
break
if not window:
carb.log_warn(f"Failed to find visible window: '{window_name}'")
return False, None, [], widget_predicate
if not isinstance(window, ui.Window) and not isinstance(window, ui.ToolBar):
carb.log_warn(f"window: {window_name} is not a ui.Window, query only works on ui.Window")
return False, None, [], widget_predicate
widget_tokens = widget_path.split("/")
if window and not (widget_tokens[0] == "Frame" or widget_tokens[0] == "Frame[0]"):
carb.log_warn("Query with a window currently only supports '<WindowName>//Frame/*' type query")
return False, None, [], widget_predicate
if widget_tokens[-1] == "":
widget_tokens = widget_tokens[:-1]
return True, window, widget_tokens, widget_predicate
def __search_for_widget_in_window(window: ui.Window, widget_tokens: List[str]) -> Optional[ui.Widget]:
current_child = window.frame
for token in widget_tokens[1:]:
child = OmniUIQuery._child_widget(current_child, token, show_warnings=False) # noqa: PLW0212
if not child: # Unable to find the widget in the current window
return None
current_child = child
return current_child
def find_widget_among_all_windows(query):
"""Find a single widget given a full widget path.
If there are multiple windows with the same name, search among all of them."""
validate_status, windows, widget_tokens, _ = _parse_input(query, search_among_all_windows=True)
if not validate_status:
return None
if len(widget_tokens) == 1:
return windows[0].frame
for window in windows:
search_result = __search_for_widget_in_window(window, widget_tokens)
if search_result is not None:
return search_result
return None
def get_widget_window(widget_or_path: Union[ui.Widget, str]) -> Optional[ui.Window]:
if isinstance(widget_or_path, ui.Widget):
for window in ui.Workspace.get_windows():
if isinstance(window, ui.Window) and OmniUIQuery.get_widget_path(window, widget_or_path) is not None:
return window
elif isinstance(widget_or_path, str):
found_it, windows, widget_tokens, _ = _parse_input(widget_or_path, search_among_all_windows=True)
if not found_it:
return None
if len(widget_tokens) == 1:
return windows[0]
for window in windows:
search_result = __search_for_widget_in_window(window, widget_tokens)
if search_result is not None:
return window
return None
def get_parent_widget(db: og.Database):
"""Given the path to the parent widget db.inputs.parentWidgetPath, find the parent widget at that path.
If the path is empty, then the parent widget will be the viewport frame."""
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
# This widget is a direct child of the viewport frame
if not hasattr(db.internal_state, "window"):
db.internal_state.window = ui.Window("Viewport")
db.internal_state.window.visible = True
parent_widget = db.internal_state.window.frame
return parent_widget
# This widget is nested under some other widget
parent_widget = find_widget_among_all_windows(parent_widget_path)
if not parent_widget:
db.log_error("Cannot find the parent widget at the specified path!")
return None
return parent_widget
def find_widget_path(widget: ui.Widget):
"""Find the path to the widget. Search among all windows."""
for window in ui.Workspace.get_windows():
if isinstance(window, ui.Window):
query_result = OmniUIQuery.get_widget_path(window, widget)
if query_result is not None:
return query_result
return None
######################################################################################################
# All code in this block deal with Viewport 2.0
# TODO: Uncomment this block of code when Viewport 2.0 becomes the default Viewport
# def get_unique_frame_identifier(db):
# """Return a unique identifier for the created viewport frame"""
# unique_widget_identifier = get_unique_widget_identifier(db)
# return "omni.graph.action.ui_node." + unique_widget_identifier
#
#
# def get_default_viewport_window():
# default_viewport_name = vp.ViewportWindowExtension.WINDOW_NAME
# for window in vp.get_viewport_window_instances():
# if window.name == default_viewport_name:
# return window
# return None
#
#
# def get_parent_widget(db):
# """Given the path to the parent widget db.inputs.parentWidgetPath, find the parent widget at that path.
# If the path is empty, then the parent widget will be the viewport frame."""
# parent_widget_path = db.inputs.parentWidgetPath
#
# if not parent_widget_path:
# # This widget is a direct child of the viewport frame
# viewport_window = get_default_viewport_window()
# if not viewport_window:
# db.log_error("Cannot find the default viewport window!")
# return None
# frame_identifier = get_unique_frame_identifier(db)
# viewport_frame = viewport_window.get_frame(frame_identifier)
# return viewport_frame
#
# else:
# # This widget is nested under some other widget
# parent_widget = OmniUIQuery.find_widget(parent_widget_path)
# if not parent_widget:
# db.log_error("Cannot find the parent widget at the specified path!")
# return None
# return parent_widget
#
#
# def find_widget_path(widget: ui.Widget):
# """Given a widget in the default viewport window, find the path to the widget"""
# viewport_window = get_default_viewport_window()
# if not viewport_window:
# return None
# return OmniUIQuery.get_widget_path(viewport_window, widget)
######################################################################################################
def tear_down_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot tear down a widget that has not been created")
return False
# Since ui.Frame can only have one child, this code effectively replaces the previous child of ui.Frame
# with an empty ui.Placer, and the previous child will be automatically garbage collected.
# Due to the limitations of omni.ui, we cannot remove child widgets from the parent, so this is the best we can do.
db.internal_state.created_widget = None
with db.internal_state.created_frame:
ui.Placer()
db.internal_state.created_frame = None
db.outputs.created = og.ExecutionAttributeState.DISABLED
db.outputs.widgetPath = ""
return True
def show_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot show a widget that has not been created")
return False
db.internal_state.created_widget.visible = True
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
def hide_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot hide a widget that has not been created")
return False
db.internal_state.created_widget.visible = False
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
def enable_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot enable a widget that has not been created")
return False
db.internal_state.created_widget.enabled = True
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
def disable_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot disable a widget that has not been created")
return False
db.internal_state.created_widget.enabled = False
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
n = "omni.graph.action." + event_name
return carb.events.type_from_string(n)
class OgnUIEventNodeInternalState:
def __init__(self):
"""Instantiate the per-node state information."""
# This subscription object controls the lifetime of our callback,
# it will be cleaned up automatically when our node is destroyed
self.sub = None
# Set when the callback has triggered
self.is_set = False
# The last payload received
self.payload = None
# The event name we used to subscribe
self.sub_event_name = ""
# The node instance handle
self.node = None
def on_event(self, custom_event):
"""The event callback"""
if custom_event is None:
return
self.is_set = True
self.payload = custom_event.payload
# Tell the evaluator we need to be computed
if self.node.is_valid():
self.node.request_compute()
def first_time_subscribe(self, node: og.Node, event_name: str) -> bool:
"""Checked call to set up carb subscription
Args:
node: The node instance
event_name: The name of the carb event
Returns:
True if we subscribed, False if we are already subscribed
"""
if self.sub is not None and self.sub_event_name != event_name:
# event name changed since we last subscribed, unsubscribe
self.sub.unsubscribe()
self.sub = None
if self.sub is None:
# Add a subscription for the given event name. This is a pop subscription,
# so we expect a 1-frame lag between send and receive
reg_event_name = registered_event_name(event_name)
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self.sub = message_bus.create_subscription_to_pop_by_type(reg_event_name, self.on_event)
self.sub_event_name = event_name
self.node = node
return True
return False
def try_pop_event(self):
"""Pop the payload of the last event received, or None if there is no event to pop"""
if self.is_set:
self.is_set = False
payload = self.payload
self.payload = None
return payload
return None
def release(self):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
if self.sub:
self.sub.unsubscribe()
self.sub = None
| 34,571 | Python | 38.064407 | 119 | 0.622458 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnPlacer.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import List, Optional
import carb
import omni.graph.core as og
import omni.ui as ui
from . import UINodeCommon
class OgnPlacer(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
(position_x, position_y) = db.inputs.position
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
with parent_widget:
placer = ui.Placer(offset_x=position_x, offset_y=position_y)
if style:
placer.set_style(style)
OgnPlacer.register_widget(db.abi_context, widget_identifier, placer)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(placer)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
@staticmethod
def get_property_names(placer: ui.Placer, writeable: bool) -> Optional[List[str]]:
props = super(OgnPlacer, OgnPlacer).get_property_names(placer, writeable)
if props is not None:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to retrieve property names from non-placer object '{placer}'.")
return None
props += [
"drag_axis", # ui.Axis
"draggable", # bool
"frames_to_start_drag", # int
"offset_x", # ui.Length
"offset_y", # ui.Length
"stable_size", # bool
]
return props
@staticmethod
def get_property_value(placer: ui.Placer, property_name: str, attribute: og.RuntimeAttribute):
if not isinstance(placer, ui.Placer):
raise og.OmniGraphError(
f"Attempt to get value of property {property_name} on non-placer object '{placer}'."
)
if property_name not in OgnPlacer.get_property_names(placer, False):
raise og.OmniGraphError(f"'{property_name}' is not a readable property of placer '{placer.identifier}'")
super(OgnPlacer, OgnPlacer).get_property_value(placer, property_name, attribute)
@staticmethod
def set_property_value(placer: ui.Placer, property_name: str, attribute: og.RuntimeAttribute):
if not isinstance(placer, ui.Placer):
raise og.OmniGraphError(
f"Attempt to set value of property {property_name} on non-placer object '{placer}'."
)
if property_name not in OgnPlacer.get_property_names(placer, True):
raise og.OmniGraphError(f"'{property_name}' is not a writeable property of placer '{placer.identifier}'")
super(OgnPlacer, OgnPlacer).set_property_value(placer, property_name, attribute)
@staticmethod
def get_style_element_names(placer: ui.Placer, writeable: bool) -> List[str]:
element_names = super(OgnPlacer, OgnPlacer).get_style_element_names(placer, writeable)
if element_names is not None: # noqa: SIM102
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to retrieve style element names from non-placer widget '{placer}'.")
return None
# TBD
return element_names
@staticmethod
def get_style_value(placer: ui.Placer, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to get style element from non-placer object '{placer}'.")
return False
return super(OgnPlacer, OgnPlacer).get_style_value(placer, element_name, attribute)
@staticmethod
def set_style_value(placer: ui.Placer, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to set style element on non-placer object '{placer}'.")
return False
return super(OgnPlacer, OgnPlacer).set_style_value(placer, element_name, attribute)
| 5,171 | Python | 41.743801 | 117 | 0.637014 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnVStack.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import List, Optional
import carb
import omni.graph.core as og
import omni.ui as ui
from . import UINodeCommon
class OgnVStack(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
direction = UINodeCommon.to_ui_direction(db.inputs.direction)
if not direction:
db.log_warning("Unexpected direction input")
return False
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
with parent_widget:
stack = ui.Stack(direction, identifier=widget_identifier)
if style:
stack.set_style(style)
OgnVStack.register_widget(db.abi_context, widget_identifier, stack)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(stack)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
@staticmethod
def get_property_names(stack: ui.Stack, writeable: bool) -> Optional[List[str]]:
props = super(OgnVStack, OgnVStack).get_property_names(stack, writeable)
if props is not None:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to retrieve property names from non-stack object '{stack}'.")
return None
props += ["content_clipping", "direction", "spacing"] # bool # str # float
return props
@staticmethod
def resolve_output_property(stack: ui.Stack, property_name: str, attribute: og.Attribute):
if not isinstance(stack, ui.Stack):
raise og.OmniGraphError(f"Attempt to resolve property on non-stack object '{stack}'.")
if property_name not in OgnVStack.get_property_names(stack, False):
raise og.OmniGraphError(f"'{property_name}' is not a readable property of stack '{stack.identifier}'")
super(OgnVStack, OgnVStack).resolve_output_property(stack, property_name, attribute)
@staticmethod
def get_property_value(stack: ui.Stack, property_name: str, attribute: og.RuntimeAttribute):
if not isinstance(stack, ui.Stack):
raise og.OmniGraphError(f"Attempt to get value of property {property_name} on non-stack object '{stack}'.")
if property_name not in OgnVStack.get_property_names(stack, False):
raise og.OmniGraphError(f"'{property_name}' is not a readable property of stack '{stack.identifier}'")
super(OgnVStack, OgnVStack).get_property_value(stack, property_name, attribute)
@staticmethod
def set_property_value(stack: ui.Stack, property_name: str, attribute: og.RuntimeAttribute):
if not isinstance(stack, ui.Stack):
raise og.OmniGraphError(f"Attempt to set value of property {property_name} on non-stack object '{stack}'.")
if property_name not in OgnVStack.get_property_names(stack, True):
raise og.OmniGraphError(f"'{property_name}' is not a writeable property of stack '{stack.identifier}'")
super(OgnVStack, OgnVStack).set_property_value(stack, property_name, attribute)
@staticmethod
def get_style_element_names(stack: ui.Stack, writeable: bool) -> List[str]:
element_names = super(OgnVStack, OgnVStack).get_style_element_names(stack, writeable)
if element_names is not None: # noqa: SIM102
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to retrieve style element names from non-stack widget '{stack}'.")
return None
# TBD
return element_names
@staticmethod
def get_style_value(stack: ui.Stack, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to get style element from non-stack object '{stack}'.")
return False
return super(OgnVStack, OgnVStack).get_style_value(stack, element_name, attribute)
@staticmethod
def set_style_value(stack: ui.Stack, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to set style element on non-stack object '{stack}'.")
return False
return super(OgnVStack, OgnVStack).set_style_value(stack, element_name, attribute)
| 5,542 | Python | 44.809917 | 119 | 0.659148 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnButton.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import List, Optional
import carb
import omni.graph.core as og
import omni.kit.app
import omni.ui as ui
from . import UINodeCommon
class OgnButton(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
start_hidden = db.inputs.startHidden
text = db.inputs.text
(size_x, size_y) = db.inputs.size
if size_x < 0 or size_y < 0:
db.log_error("The size of the widget cannot be negative!")
return False
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
def on_button_clicked():
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget or not widget.enabled:
return
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
event_name = "clicked_" + widget_identifier
reg_event_name = UINodeCommon.registered_event_name(event_name)
message_bus.push(reg_event_name)
# Now create the button widget and register callbacks
with parent_widget:
button = ui.Button(
text, identifier=widget_identifier, width=size_x, height=size_y, visible=not start_hidden
)
button.set_clicked_fn(on_button_clicked)
if style:
button.set_style(style)
OgnButton.register_widget(db.abi_context, widget_identifier, button)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(button)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
@staticmethod
def get_property_names(button: ui.Button, writeable: bool) -> Optional[List[str]]:
props = super(OgnButton, OgnButton).get_property_names(button, writeable)
if props is not None:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to retrieve property names from non-button object '{button}'.")
return None
props += [
"image_height", # ui.Length
"image_url", # str
"image_width", # ui.Length
"spacing", # float
"text", # str
]
return props
@staticmethod
def resolve_output_property(button: ui.Button, property_name: str, attribute: og.Attribute):
if not isinstance(button, ui.Button):
raise og.OmniGraphError(f"Attempt to resolve property on non-button object '{button}'.")
if property_name not in OgnButton.get_property_names(button, False):
raise og.OmniGraphError(f"'{property_name}' is not a readable property of button '{button.identifier}'")
super(OgnButton, OgnButton).resolve_output_property(button, property_name, attribute)
@staticmethod
def get_property_value(button: ui.Button, property_name: str, attribute: og.RuntimeAttribute):
if not isinstance(button, ui.Button):
raise og.OmniGraphError(
f"Attempt to get value of property {property_name} on non-button object '{button}'."
)
if property_name not in OgnButton.get_property_names(button, False):
raise og.OmniGraphError(f"'{property_name}' is not a readable property of button '{button.identifier}'")
super(OgnButton, OgnButton).get_property_value(button, property_name, attribute)
@staticmethod
def set_property_value(button: ui.Button, property_name: str, attribute: og.RuntimeAttribute):
if not isinstance(button, ui.Button):
raise og.OmniGraphError(
f"Attempt to set value of property {property_name} on non-button object '{button}'."
)
if property_name not in OgnButton.get_property_names(button, True):
raise og.OmniGraphError(f"'{property_name}' is not a writeable property of button '{button.identifier}'")
super(OgnButton, OgnButton).set_property_value(button, property_name, attribute)
@staticmethod
def get_style_element_names(button: ui.Button, writeable: bool) -> List[str]:
element_names = super(OgnButton, OgnButton).get_style_element_names(button, writeable)
if element_names is not None: # noqa: SIM102
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to retrieve style element names from non-button widget '{button}'.")
return None
# TBD
return element_names
@staticmethod
def get_style_value(button: ui.Button, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to get style element from non-button object '{button}'.")
return False
return super(OgnButton, OgnButton).get_style_value(button, element_name, attribute)
@staticmethod
def set_style_value(button: ui.Button, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to set style element on non-button object '{button}'.")
return False
return super(OgnButton, OgnButton).set_style_value(button, element_name, attribute)
| 6,600 | Python | 44.212328 | 117 | 0.632576 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnGetViewportRenderer.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.
#
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnGetViewportRenderer:
"""
Gets the renderer being used by the specified viewport.
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
viewport = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport)
renderer = ""
if viewport_api is not None:
engine_name = viewport_api.hydra_engine
render_mode = viewport_api.render_mode
if engine_name == "rtx":
if render_mode == "RaytracedLighting":
renderer = "RTX: Realtime"
elif render_mode == "PathTracing":
renderer = "RTX: Path Tracing"
elif engine_name == "iray":
if render_mode == "iray":
renderer = "RTX: Iray"
elif engine_name == "pxr":
renderer = "Pixar Storm"
if renderer == "":
db.log_error(f"Unknown Hydra engine '{engine_name}' and render mode '{render_mode}'")
else:
db.log_error(f"Unknown viewport window '{viewport}'")
db.outputs.renderer = renderer
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 1,910 | Python | 33.745454 | 105 | 0.581675 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportClickManipulator.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportClickManipulatorFactory"]
from typing import Any
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME = "omni.graph.viewport.click"
GESTURE_NAMES = ["Left Mouse Click", "Right Mouse Click", "Middle Mouse Click"]
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
class ViewportClickGesture(sc.ClickGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str, mouse_button: int):
super().__init__(mouse_button=mouse_button, manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._gesture_name = GESTURE_NAMES[mouse_button]
self._event_type = carb.events.type_from_string(EVENT_NAME)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
def on_ended(self, *args):
if self.state == sc.GestureState.CANCELED:
return
mouse = self.sender.gesture_payload.mouse
resolution = self._viewport_api.resolution
# Position in normalized coords
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
if not all(0.0 <= x <= 1.0 for x in pos_norm):
return
# Position in viewport resolution pixels
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"gesture": self._gesture_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
}
self._message_bus.push(self._event_type, payload=payload)
class ViewportClickManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [
ViewportClickGesture(viewport_api, viewport_window_name, 0), # left mouse click
ViewportClickGesture(viewport_api, viewport_window_name, 1), # right mouse click
ViewportClickGesture(viewport_api, viewport_window_name, 2), # middle mouse click
]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
self._transform = sc.Transform()
with self._transform:
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def ViewportClickManipulatorFactory(desc: dict) -> ViewportClickManipulator: # noqa: N802
manip = ViewportClickManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"ViewportClickManipulator.{desc.get('viewport_window_name')}"
return manip
| 3,531 | Python | 35.412371 | 96 | 0.650241 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportHoverManipulator.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportHoverManipulatorFactory"]
from typing import Any
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME_BEGAN = "omni.graph.viewport.hover.began"
EVENT_NAME_CHANGED = "omni.graph.viewport.hover.changed"
EVENT_NAME_ENDED = "omni.graph.viewport.hover.ended"
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
class ViewportHoverGesture(sc.HoverGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str):
super().__init__(manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._event_type_began = carb.events.type_from_string(EVENT_NAME_BEGAN)
self._event_type_changed = carb.events.type_from_string(EVENT_NAME_CHANGED)
self._event_type_ended = carb.events.type_from_string(EVENT_NAME_ENDED)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self._viewport_hovered = False
def on_began(self):
self._viewport_hovered = False
def on_changed(self):
mouse = self.sender.gesture_payload.mouse
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
viewport_hovered = all(0.0 <= x <= 1.0 for x in pos_norm)
if not self._viewport_hovered and viewport_hovered:
# hover began
resolution = self._viewport_api.resolution
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
}
self._message_bus.push(self._event_type_began, payload=payload)
elif self._viewport_hovered and viewport_hovered:
# hover changed
resolution = self._viewport_api.resolution
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
mouse_moved = self.sender.gesture_payload.mouse_moved
vel_norm = self._viewport_api.map_ndc_to_texture(mouse_moved)[0]
origin_norm = self._viewport_api.map_ndc_to_texture((0, 0))[0]
vel_norm = (vel_norm[0] - origin_norm[0], origin_norm[1] - vel_norm[1])
vel_pixel = (vel_norm[0] * resolution[0], vel_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
"vel_norm_x": vel_norm[0],
"vel_norm_y": vel_norm[1],
"vel_pixel_x": vel_pixel[0],
"vel_pixel_y": vel_pixel[1],
}
self._message_bus.push(self._event_type_changed, payload=payload)
elif self._viewport_hovered and not viewport_hovered:
# hover ended
payload = {
"viewport": self._viewport_window_name,
}
self._message_bus.push(self._event_type_ended, payload=payload)
self._viewport_hovered = viewport_hovered
def on_ended(self):
if self._viewport_hovered:
# hover ended
payload = {
"viewport": self._viewport_window_name,
}
self._message_bus.push(self._event_type_ended, payload=payload)
self._viewport_hovered = False
# Custom manipulator containing a Screen that contains the gestures
class ViewportHoverManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [ViewportHoverGesture(viewport_api, viewport_window_name)]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
self._transform = sc.Transform()
with self._transform:
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def ViewportHoverManipulatorFactory(desc: dict) -> ViewportHoverManipulator: # noqa: N802
manip = ViewportHoverManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"ViewportHoverManipulator.{desc.get('viewport_window_name')}"
return manip
| 5,243 | Python | 37.277372 | 96 | 0.613008 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnReadWindowSize.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from . import UINodeCommon
class OgnReadWindowSize:
@staticmethod
def compute(db) -> bool:
db.outputs.height = 0.0
db.outputs.width = 0.0
if db.inputs.isViewport:
try:
from omni.kit.viewport.window import get_viewport_window_instances
vp_wins = [win for win in get_viewport_window_instances(None) if isinstance(win, ui.Window)]
except ImportError:
db.log_error("No non-legacy viewports found.")
return False
widget_path = db.inputs.widgetPath
if not widget_path:
window_name = db.inputs.name
if not window_name:
db.log_warning("No window name or widgetPath provided.")
return True
if db.inputs.isViewport:
for window in vp_wins:
if window.title == window_name:
db.outputs.height = window.height
db.outputs.width = window.width
return True
db.log_error(f"No viewport named '{window_name}' found.")
return False
for window in ui.Workspace.get_windows():
if isinstance(window, ui.Window) and window.title == window_name:
db.outputs.height = window.height
db.outputs.width = window.width
return True
db.log_error(f"No window named '{window_name}' found.")
return False
window = UINodeCommon.get_widget_window(widget_path)
if not window:
db.log_error(f"No widget found at path '{widget_path}'.")
return False
if db.inputs.isViewport and window not in vp_wins:
db.log_error(f"Widget '{widget_path} is not in a viewport window.")
return False
db.outputs.height = window.height
db.outputs.width = window.width
return True
| 2,426 | Python | 35.772727 | 108 | 0.597279 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnPrintText.py | """
This is the implementation of the OGN node defined in OgnPrintText.ogn
"""
import time
import carb
import omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name, post_viewport_message
class OgnOnCustomEventInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
self.display_time: float = 0
class OgnPrintText:
"""
Prints text to the log and optionally the viewport
"""
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnOnCustomEventInternalState()
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
def ok():
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
try:
toast_min_period_s = 5.0
to_screen = db.inputs.toScreen
log_level = db.inputs.logLevel.lower()
text = db.inputs.text
if not text:
return ok()
if log_level:
if log_level not in ("error", "warning", "warn", "info"):
db.log_error("Log Level must be one of error, warning or info")
return False
else:
log_level = "info"
if to_screen:
toast_time = db.internal_state.display_time
viewport_name = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport_name)
if viewport_api is None:
# Preserve legacy behavior of erroring when a name was provided
if viewport_name:
db.log_error(f"Could not get viewport window {viewport_name}")
return False
return ok()
now_s = time.time()
toast_age = now_s - toast_time
if toast_age > toast_min_period_s:
toast_time = 0
if toast_time == 0:
post_viewport_message(viewport_api, text)
db.state.displayTime = now_s
else:
# FIXME: Toast also prints to log so we only do one or the other
if log_level == "info":
carb.log_info(text)
elif log_level.startswith("warn"):
carb.log_warn(text)
else:
carb.log_error(text)
return ok()
except Exception as error: # pylint: disable=broad-except
db.log_error(str(error))
return False
| 2,717 | Python | 30.97647 | 90 | 0.536621 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportRenderer.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.graph.core as og
import omni.graph.tools.ogn as ogn
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnSetViewportRenderer:
"""
Sets renderer for the target viewport.
"""
# renderer: (hd_engine, render_mode)
RENDERER_CONFIGS = {
"RTX: Realtime": ("rtx", "RaytracedLighting"),
"RTX: Path Tracing": ("rtx", "PathTracing"),
"RTX: Iray": ("iray", "iray"),
}
@staticmethod
def initialize(context, node):
"""Assign default value and allowed tokens for the inputs:renderer attribute"""
renderers = []
# Query which engines are enabled.
setting = carb.settings.get_settings().get("/renderer/enabled")
engines = setting.split(",") if setting else ["rtx", "iray"]
# Third-party Hydra render delegates are ignored as requested by OM-75851, but they can be included if needed.
for renderer, (engine, _) in OgnSetViewportRenderer.RENDERER_CONFIGS.items():
if engine in engines:
renderers.append(renderer)
allowed_tokens = ",".join(renderers)
attr = node.get_attribute("inputs:renderer")
attr.set_metadata(ogn.MetadataKeys.ALLOWED_TOKENS, allowed_tokens)
# If the attr is not authored, its default value will be the first enabled renderer.
if attr.get() == "" and len(renderers) > 0:
attr.set(renderers[0])
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
renderer = db.inputs.renderer
if renderer != "":
viewport = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport)
if viewport_api is not None:
allowed_tokens = db.attributes.inputs.renderer.get_metadata(ogn.MetadataKeys.ALLOWED_TOKENS)
renderers = allowed_tokens.split(",")
if renderer in renderers and renderer in OgnSetViewportRenderer.RENDERER_CONFIGS:
hd_engine, render_mode = OgnSetViewportRenderer.RENDERER_CONFIGS[renderer]
# Update the legacy "/renderer/active" setting for anyone that may be watching for it
carb.settings.get_settings().set("/renderer/active", hd_engine)
viewport_api.set_hd_engine(hd_engine, render_mode)
else:
db.log_error(f"Unknown renderer '{renderer}'")
else:
db.log_error(f"Unknown viewport window '{viewport}'")
db.outputs.exec = og.ExecutionAttributeState.ENABLED
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 3,271 | Python | 37.952381 | 118 | 0.62886 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSpacer.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.graph.core as og
import omni.ui as ui
from . import UINodeCommon
class OgnSpacer(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
# Now create the spacer widget and register it.
with parent_widget:
spacer = ui.Spacer(identifier=widget_identifier, width=db.inputs.width, height=db.inputs.height)
if style:
spacer.set_style(style)
OgnSpacer.register_widget(db.abi_context, widget_identifier, spacer)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(spacer)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
# The spacer has no properties or styles of its own: height and width are base Widget properties.
| 2,116 | Python | 37.490908 | 112 | 0.657845 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportResolution.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 omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnSetViewportResolution:
"""
Sets the resolution of the target viewport.
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
viewport = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport)
if viewport_api is not None:
resolution = db.inputs.resolution
if resolution[0] > 0 and resolution[1] > 0:
viewport_api.resolution = resolution
else:
db.log_error(f"Invalid resolution {resolution[0]}x{resolution[1]}.")
else:
db.log_error(f"Unknown viewport window '{viewport}'")
db.outputs.exec = og.ExecutionAttributeState.ENABLED
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 1,461 | Python | 33.809523 | 88 | 0.651608 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnReadWidgetProperty.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.graph.core as og
from . import UINodeCommon
class OgnReadWidgetProperty:
@staticmethod
def compute(db) -> bool:
widget_path = db.inputs.widgetPath
if not widget_path:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
db.log_warning("No widgetIdentifier or widgetPath provided.")
return False
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget:
db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.")
return False
else:
widget = UINodeCommon.find_widget_among_all_windows(widget_path)
if not widget:
db.log_warning(f"No widget found at path '{widget_path}'.")
return False
# For error messages only.
widget_identifier = widget_path
property_name = db.inputs.propertyName
if not property_name:
db.log_warning("No property provided.")
return False
if not hasattr(widget, property_name):
db.log_error(f"Widget '{widget_identifier}' has no property '{property_name}'.")
return False
widget_summary = f"widget '{widget_identifier}' ({type(widget)})"
callbacks = UINodeCommon.get_widget_callbacks(widget)
if not callbacks:
db.log_error(f"{widget_summary} is not supported by the ReadWidgetProperty node.")
return False
if not hasattr(callbacks, "get_property_names") or not callable(callbacks.get_property_names):
db.log_error(f"No 'get_property_names' callback found for {widget_summary}")
return False
readable_props = callbacks.get_property_names(widget, False)
if not readable_props or property_name not in readable_props:
db.log_error(f"'{property_name}' is not a readable property of {widget_summary}")
return False
if not hasattr(callbacks, "resolve_output_property") or not callable(callbacks.resolve_output_property):
db.log_error(f"No 'resolve_output_property' callback found for {widget_summary}")
return False
try:
callbacks.resolve_output_property(widget, property_name, db.node.get_attribute("outputs:value"))
except og.OmniGraphError as og_error:
db.log_error(
f"Could resolve outputs from '{property_name}' for {widget_summary}\n{og_error}", add_context=False
)
return False
if not hasattr(callbacks, "get_property_value") or not callable(callbacks.get_property_value):
db.log_error(f"No 'get_property_value' callback found for {widget_summary}")
return False
try:
callbacks.get_property_value(widget, property_name, db.outputs.value)
except og.OmniGraphError as og_error:
db.log_error(f"Could not get value of '{property_name}' on {widget_summary}\n{og_error}", add_context=False)
return False
return True
| 3,584 | Python | 43.259259 | 120 | 0.646484 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnGetViewportResolution.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.
#
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnGetViewportResolution:
"""
Gets the resolution of the target viewport.
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
viewport = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport)
if viewport_api is not None:
db.outputs.resolution = viewport_api.resolution
else:
db.outputs.resolution = (0, 0)
db.log_error(f"Unknown viewport window '{viewport}'")
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 1,199 | Python | 32.333332 | 76 | 0.668891 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetActiveViewportCamera.py | """
This is the implementation of the OGN node defined in OgnSetActiveViewportCamera.ogn
"""
import omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name
from pxr import Sdf, UsdGeom
class OgnSetActiveViewportCamera:
"""
Sets a viewport's actively bound camera to a free camera
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
db.outputs.execOut = og.ExecutionAttributeState.DISABLED
try:
new_camera_path = db.inputs.primPath
if not Sdf.Path.IsValidPathString(new_camera_path):
return True
viewport_name = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport_name)
if not viewport_api:
return True
stage = viewport_api.stage
new_camera_prim = stage.GetPrimAtPath(new_camera_path) if stage else False
if not new_camera_prim:
return True
if not new_camera_prim.IsA(UsdGeom.Camera):
return True
new_camera_path = Sdf.Path(new_camera_path)
if viewport_api.camera_path != new_camera_path:
viewport_api.camera_path = new_camera_path
except Exception as error: # pylint: disable=broad-except
db.log_error(str(error))
return False
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
| 1,503 | Python | 32.422222 | 86 | 0.626081 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnWriteWidgetProperty.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.graph.core as og
from . import UINodeCommon
class OgnWriteWidgetProperty:
@staticmethod
def compute(db) -> bool:
if db.inputs.write != og.ExecutionAttributeState.DISABLED:
widget_path = db.inputs.widgetPath
if not widget_path:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
db.log_warning("No widgetIdentifier or widgetPath provided.")
return False
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget:
db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.")
return False
else:
widget = UINodeCommon.find_widget_among_all_windows(widget_path)
if not widget:
db.log_warning(f"No widget found at path '{widget_path}'.")
return False
# For error messages only.
widget_identifier = widget_path
property_name = db.inputs.propertyName
if not property_name:
db.log_error("No property provided.")
return False
if not hasattr(widget, property_name):
db.log_error(f"Widget '{widget_identifier}' has no property '{property_name}'.")
return False
widget_summary = f"widget '{widget_identifier}' ({type(widget)})"
callbacks = UINodeCommon.get_widget_callbacks(widget)
if not callbacks:
db.log_error(f"{widget_summary} is not supported by the WriteWidgetProperty node.")
return False
if not hasattr(callbacks, "get_property_names") or not callable(callbacks.get_property_names):
db.log_error(f"No 'get_property_names' callback found for {widget_summary}")
return False
writeable_props = callbacks.get_property_names(widget, True)
if not writeable_props or property_name not in writeable_props:
db.log_error(f"'{property_name}' is not a writeable property of {widget_summary}")
return False
if not hasattr(callbacks, "set_property_value") or not callable(callbacks.set_property_value):
db.log_error(f"No 'set_property_value' callback found for {widget_summary}")
return False
try:
callbacks.set_property_value(widget, property_name, db.inputs.value)
except og.OmniGraphError as og_error:
db.log_error(
f"Could not set value of '{property_name}' on {widget_summary}\n{og_error}", add_context=False
)
return False
db.outputs.written = og.ExecutionAttributeState.ENABLED
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
| 3,457 | Python | 44.499999 | 114 | 0.612381 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/scripts/variant_utils.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# 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 re
from typing import Any, Optional
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry
from usdrt import Sdf, Usd
def print_widget_tree(widget: ui.Widget, level: int = 0):
# Prints the widget tree to the console
for child in ui.Inspector.get_children(widget):
print_widget_tree(child, level + 1)
def get_descendants(widget: ui.Widget):
# Returns a list of all descendants of the given widget
kids = []
local_kids = ui.Inspector.get_children(widget)
kids.extend(local_kids)
for k in local_kids:
child_kids = get_descendants(k)
kids.extend(child_kids)
return kids
def get_attr_value(prim: Usd.Prim, attr_name: str) -> Any:
# Returns the value of the given attribute from usdrt
if prim:
attr = prim.GetAttribute(attr_name)
if attr:
return og.Controller().get(attribute=prim.GetAttribute(attr_name))
return False
def get_use_path(stage: Usd.Stage, node_prim_path: Sdf.Path) -> bool:
# Returns the value of the usePath input attribute
prim = stage.GetPrimAtPath(node_prim_path)
if prim:
return get_attr_value(prim, "inputs:usePath")
return False
def get_attr_has_connections(prim: Usd.Prim, attr_name: str) -> bool:
# Returns True if the attribute has authored connections
if prim:
attr = prim.GetAttribute(attr_name)
if attr:
return attr.HasAuthoredConnections()
return False
def get_target_prim(stage: Usd.Stage, node_prim_path: Sdf.Path) -> Optional[Usd.Prim]:
# Return the target prim if it exists depending on the value of the usePath input attribute.
# If usePath is True, the target prim is the prim at the path specified by the primPath input attribute.
# If usePath is False, the target prim is the first target of the prim relationship.
prim = stage.GetPrimAtPath(node_prim_path)
if prim:
if get_attr_value(prim, "inputs:usePath"):
prim_path = get_attr_value(prim, "inputs:primPath")
if prim_path is not None:
return stage.GetPrimAtPath(prim_path)
else:
rel = prim.GetRelationship("inputs:prim")
if rel.IsValid():
targets = rel.GetTargets()
if targets:
return stage.GetPrimAtPath(targets[0])
return None
def pretty_name(name: str) -> str:
# Returns a pretty name for the given property
name = name.split(":")[-1]
name = name[0].upper() + name[1:]
name = re.sub(r"([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", r"\1 ", name)
return name
def override_display_name(prop: UsdPropertyUiEntry):
# Overrides the display name of the given property with a consistent format
prop_name = pretty_name(prop.prop_name)
prop.override_display_name(prop_name)
| 3,240 | Python | 34.615384 | 108 | 0.675617 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/scripts/variants.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# 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 functools import partial
from typing import List, Optional
import omni.graph.core as og
import omni.ui as ui
from omni.graph.ui import OmniGraphAttributeModel, OmniGraphPropertiesWidgetBuilder
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH
from usdrt import Sdf, Usd
from .variant_utils import ( # noqa PLE0402
get_attr_has_connections,
get_attr_value,
get_descendants,
get_target_prim,
get_use_path,
override_display_name,
pretty_name,
)
ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP}
class VariantTokenModel(TfTokenAttributeModel):
"""Model for selecting the variant set name. We modify the list to show variant sets which are available
on the target prim."""
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item, label):
"""
Args:
item: the variant set name token to be shown
label: the label to show in the drop-down
"""
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(label)
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
node_prim_path: Sdf.Path,
):
"""
Args:
stage: The current stage
attribute_paths: The list of full attribute paths
self_refresh: ignored
metadata: pass-through metadata for model
node_prim_path: The path of the compute node
"""
self._stage = stage
self._node_prim_path = node_prim_path
self._target_prim = None
super().__init__(stage, attribute_paths, self_refresh, metadata)
def _get_allowed_tokens(self, _):
# Override of TfTokenAttributeModel to specialize what tokens are to be shown
# Returns the attributes we want to let the user select from
prim = self._stage.GetPrimAtPath(self._node_prim_path)
if not prim:
return []
self._target_prim = get_target_prim(self._stage, self._node_prim_path)
tokens = self._get_tokens(self._target_prim)
current_value = og.Controller().get(attribute=self._get_attributes()[0])
if current_value and current_value not in tokens:
tokens.append(current_value)
tokens.insert(0, "")
return tokens
@staticmethod
def _item_factory(item):
# Construct the item for the model
label = item
return VariantTokenModel.AllowedTokenItem(item, label)
def _update_allowed_token(self, **kwargs):
# Override of TfTokenAttributeModel to specialize the model items
super()._update_allowed_token(token_item=self._item_factory)
def _get_tokens(self, prim: Usd.Prim) -> List[str]:
return []
class VariantSetNamesTokenModel(VariantTokenModel):
def _get_variant_set_names(self, prim: Usd.Prim) -> List[str]:
if prim:
variant_sets = prim.GetVariantSets()
variant_sets_names = list(variant_sets.GetNames())
return variant_sets_names
return []
def _get_tokens(self, prim: Usd.Prim) -> List[str]:
return self._get_variant_set_names(prim)
class VariantNamesTokenModel(VariantTokenModel):
def _get_variant_names(self, prim: Usd.Prim) -> List[str]:
node_prim = self._stage.GetPrimAtPath(self._node_prim_path)
if node_prim and prim:
variant_sets = prim.GetVariantSets()
variant_set_name = get_attr_value(node_prim, "inputs:variantSetName")
variant_set = variant_sets.GetVariantSet(variant_set_name)
variant_sets_names = list(variant_set.GetVariantNames())
return variant_sets_names
return []
def _get_tokens(self, prim: Usd.Prim) -> List[str]:
return self._get_variant_names(prim)
# noinspection PyProtectedMember
class CustomVariantLayout:
"""Custom layout for the variant set and variant name attributes"""
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.prim_path_layout = None
self.prim_path_model = None
self.use_path_model = False
self.prim_rel_layout = None
self.prim_rel_model = None
self.variant_set_name_token_model = None
self.variant_set_name_string_model = None
self.variant_name_token_model = None
self.variant_name_string_model = None
self.variant_set_name_string_layout = None
self.variant_set_name_token_layout = None
self.variant_name_string_layout = None
self.variant_name_token_layout = None
def get_node_prim_path(self):
node_prim_path = self.compute_node_widget.payload[-1]
return node_prim_path
def get_use_path(self):
stage = self.compute_node_widget.stage
node_prim_path = self.get_node_prim_path()
use_path = get_use_path(stage, node_prim_path)
return use_path
@staticmethod
def _set_child_string_field_enabled(widget: ui.Widget, enabled: bool):
for child in get_descendants(widget):
if isinstance(child, ui.StringField):
child.enabled = enabled
def _get_target_prim(self) -> Usd.Prim:
return get_target_prim(self.compute_node_widget.stage, self.get_node_prim_path())
def _get_attr_has_connections(self, attr_name: str) -> bool:
stage = self.compute_node_widget.stage
node_prim_path = self.get_node_prim_path()
prim = stage.GetPrimAtPath(node_prim_path)
return get_attr_has_connections(prim, attr_name)
def _token_builder(self, ui_prop: UsdPropertyUiEntry):
return OmniGraphPropertiesWidgetBuilder._tftoken_builder( # noqa: PLW0212
stage=self.compute_node_widget.stage,
attr_name=ui_prop.prop_name,
type_name=ui_prop.property_type,
metadata=ui_prop.metadata,
prim_paths=[self.get_node_prim_path()],
additional_label_kwargs={"style": ATTRIB_LABEL_STYLE},
additional_widget_kwargs={"no_allowed_tokens_model_cls": OmniGraphAttributeModel},
)
def _relationship_builder(self, ui_prop: UsdPropertyUiEntry, changed_fn):
return OmniGraphPropertiesWidgetBuilder._relationship_builder( # noqa: PLW0212
stage=self.compute_node_widget.stage,
attr_name=ui_prop.prop_name,
metadata=ui_prop.metadata,
prim_paths=[self.get_node_prim_path()],
additional_label_kwargs={"style": ATTRIB_LABEL_STYLE},
additional_widget_kwargs={
"on_remove_target": changed_fn,
"target_picker_on_add_targets": changed_fn,
"targets_limit": 1,
},
)
def _bool_builder(self, ui_prop: UsdPropertyUiEntry):
return OmniGraphPropertiesWidgetBuilder._bool_builder( # noqa: PLW0212
stage=self.compute_node_widget.stage,
attr_name=ui_prop.prop_name,
type_name=ui_prop.property_type,
metadata=ui_prop.metadata,
prim_paths=[self.get_node_prim_path()],
additional_label_kwargs={"style": ATTRIB_LABEL_STYLE},
)
def _combo_box_builder(self, ui_prop: UsdPropertyUiEntry, model_cls, changed_fn=None):
stage = self.compute_node_widget.stage
node_prim_path = self.get_node_prim_path()
with ui.HStack(spacing=HORIZONTAL_SPACING):
prop_name = pretty_name(ui_prop.prop_name)
ui.Label(prop_name, name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH)
ui.Spacer(width=HORIZONTAL_SPACING)
with ui.ZStack():
attr_path = node_prim_path.AppendProperty(ui_prop.prop_name)
# Build the token-selection widget when prim is known
model = model_cls(stage, [attr_path], False, {}, node_prim_path)
ui.ComboBox(model)
if changed_fn:
model._current_index.add_value_changed_fn(changed_fn) # noqa PLW0212
return model
def _prim_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the token input prim path widget
self.prim_path_layout = ui.HStack(spacing=0)
with self.prim_path_layout:
self.prim_path_model = self._token_builder(ui_prop)
self._update_prim_path()
self.prim_path_model.add_value_changed_fn(self._on_target_prim_path_changed)
def _update_prim_path(self):
use_path = self.get_use_path()
attr_has_connections = self._get_attr_has_connections("inputs:primPath")
self.prim_path_layout.enabled = use_path
enabled = use_path and not attr_has_connections
self._set_child_string_field_enabled(self.prim_path_layout, enabled)
def _prim_rel_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the relationship input prim widget
self.prim_rel_layout = ui.HStack(spacing=0)
with self.prim_rel_layout:
self.prim_rel_model = self._relationship_builder(ui_prop, self._on_target_prim_rel_changed)
self._update_prim_rel()
def _update_prim_rel(self):
self.prim_rel_layout.enabled = not self.get_use_path()
def _use_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the boolean toggle for inputs:usePath
self.use_path_model = self._bool_builder(ui_prop)
self.use_path_model.add_value_changed_fn(self._on_use_path_changed)
def _variant_set_name_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the VariantSetName widget
# Build the simple string input for data-driven variant set name and a ComboBox for when there are
# variants and no data-driven variant set name
self.variant_set_name_string_layout = ui.HStack(spacing=0)
with self.variant_set_name_string_layout:
self.variant_set_name_string_model = self._token_builder(ui_prop)
self.variant_set_name_token_layout = ui.HStack(spacing=0)
with self.variant_set_name_token_layout:
self.variant_set_name_token_model = self._combo_box_builder(
ui_prop, VariantSetNamesTokenModel, self._on_variant_set_changed
)
self._update_variant_set_visibility()
def _update_variant_set_visibility(self):
# Show the string input if the prim is unknown or if the attribute has connections
# otherwise show the token input
if self.variant_set_name_string_layout and self.variant_set_name_token_layout:
attr_has_connections = self._get_attr_has_connections("inputs:variantSetName")
target_prim = self._get_target_prim()
use_string = not target_prim or attr_has_connections
self.variant_set_name_string_layout.visible = use_string
self.variant_set_name_token_layout.visible = not use_string
def _update_variant_set_name(self):
# Update the variant set name widget visibility when the target prim changes
self._update_variant_set_visibility()
if self.variant_set_name_token_model:
self.variant_set_name_token_model._set_dirty() # noqa: PLW0212
if self.variant_set_name_string_model:
self.variant_set_name_string_model._set_dirty() # noqa: PLW0212
def _variant_name_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the VariantName widget
# Build the simple string input for data-driven variant name and a ComboBox for when there are
# variants and no data-driven variant name
self.variant_name_string_layout = ui.HStack(spacing=0)
with self.variant_name_string_layout:
self.variant_name_string_model = self._token_builder(ui_prop)
self.variant_name_token_layout = ui.HStack(spacing=0)
with self.variant_name_token_layout:
self.variant_name_token_model = self._combo_box_builder(ui_prop, VariantNamesTokenModel)
self._update_variant_name_visibility()
def _update_variant_name_visibility(self):
# Show the string input if the prim is unknown or if the attribute has connections
# otherwise show the token input
attr_has_connections = self._get_attr_has_connections("inputs:variantName")
target_prim = self._get_target_prim()
if self.variant_name_string_layout and self.variant_name_token_layout:
use_string = not target_prim or attr_has_connections
self.variant_name_string_layout.visible = use_string
self.variant_name_token_layout.visible = not use_string
def _update_variant_name(self):
# Update the variant name widget visibility when the target prim changes
self._update_variant_name_visibility()
if self.variant_name_token_model:
self.variant_name_token_model._set_dirty() # noqa: PLW0212
if self.variant_name_string_model:
self.variant_name_string_model._set_dirty() # noqa: PLW0212
def _on_target_prim_rel_changed(self, *_):
# When the inputs:primRel token changes update the relevant widgets
self.prim_rel_model._set_dirty() # noqa: PLW0212
self._update_prim_rel()
self._update_variant_set_name()
self._update_variant_name()
def _on_target_prim_path_changed(self, *_):
# When the inputs:primPath token changes update the relevant widgets
self._update_variant_set_name()
self._update_variant_name()
def _on_use_path_changed(self, _):
# When the usePath toggle changes update the relevant widgets
self._update_prim_rel()
self._update_prim_path()
self._update_variant_set_name()
self._update_variant_name()
def _on_variant_set_changed(self, _):
# When the variantSet changes update the relevant widgets
self._update_variant_name()
def apply(self, props):
# Apply the property values to the compute node
def find_prop(name) -> Optional[UsdPropertyUiEntry]:
try:
return next((p for p in props if p.prop_name == name))
except StopIteration:
return None
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
prop_fuctions = [
("prim", self._prim_rel_build_fn),
("usePath", self._use_path_build_fn),
("primPath", self._prim_path_build_fn),
("variantSetName", self._variant_set_name_build_fn),
("variantName", self._variant_name_build_fn),
]
for prop_name, build_fn in prop_fuctions:
prop = find_prop(f"inputs:{prop_name}")
if prop:
override_display_name(prop)
CustomLayoutProperty(prop.prop_name, None, build_fn=partial(build_fn, prop))
with CustomLayoutGroup("Outputs"):
for attr in ["exists", "success", "variantSetNames", "variantName"]:
prop = find_prop(f"outputs:{attr}")
if prop:
CustomLayoutProperty(prop.prop_name, pretty_name(prop.prop_name))
return frame.apply(props)
| 16,097 | Python | 41.251968 | 113 | 0.63751 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/tests/test_ui_nodes.py | # noqa: PLC0302
import unittest
from pathlib import Path
from typing import Any, Dict, List
import carb
import carb.settings
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.kit import ui_test
from omni.kit.ui_test.input import (
emulate_mouse_drag_and_drop,
emulate_mouse_move,
emulate_mouse_move_and_click,
emulate_mouse_scroll,
)
from omni.kit.ui_test.vec2 import Vec2
from omni.ui.tests.test_base import OmniUiTest
EXT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.graph.ui_nodes}"))
class TestUINodes(OmniUiTest):
def __init__(self, tests=()):
super().__init__(tests)
self.settings = carb.settings.get_settings()
# The first value for each setting is what we want to set it to, the second is where we will store
# its original value.
self.viewport_settings: Dict[str, List[Any, Any]] = {
"/persistent/app/viewport/displayOptions": [0, None],
"/app/viewport/grid/enabled": [False, None],
"/persistent/app/viewport/{vp_id}/guide/grid/visible": [False, None],
"/persistent/app/viewport/{vp_id}/guide/axis/visible": [False, None],
# This doesn't currently work while the test is running so we set it in the test args instead.
# "/persistent/app/viewport/{vp_id}/hud/visible": [False, None],
}
self.TEST_GRAPH_PATH = "/World/TestGraph"
self.wait_frames_for_visual_update = 5
# It takes 6 frames for the nodes and connections to all draw in their proper positions.
self.wait_frames_for_graph_draw = 6
# Wait 10 frames for commands to execute and the graph to update
self.wait_frames_for_commands = 10
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
self.viewport_name, self.viewport_id = self.get_viewport_name_and_id()
self._golden_img_dir = EXT_PATH.absolute().resolve().joinpath("data/golden_images")
# Make sure the viewport looks the same as when we generated the golden images.
for setting, values in self.viewport_settings.items():
key = setting.format(vp_id=self.viewport_id)
values[1] = self.settings.get(key)
self.settings.set(key, values[0])
await omni.usd.get_context().new_stage_async()
self.stage = omni.usd.get_context().get_stage()
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
# Restore viewport settings.
for setting, (values) in self.viewport_settings.items():
key = setting.format(vp_id=self.viewport_id)
if values[1] is None:
self.settings.destroy_item(key)
else:
self.settings.set(key, values[1])
values[1] = None
omni.usd.get_context().close_stage() # Activate OnClosing node
def get_viewport_name_and_id(self):
try:
import omni.kit.viewport.window as vp
viewport = next(vp.get_viewport_window_instances())
return (viewport.name, viewport.viewport_api.id)
except StopIteration as exc:
raise og.OmniGraphError("Legacy viewport not supported for UI nodes.") from exc
def create_graph(self) -> og.Graph:
"""Create an execution graph."""
return og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
async def edit_ui_execution_graph(self, graph_path: str, graph_node_data: dict, error_thrown=False):
"""Edit graph with nodes, connections and values common to all tests."""
keys = og.Controller.Keys
data = og.Controller.edit(
graph_path,
{
keys.CREATE_NODES: [
("onLoaded", "omni.graph.action.OnLoaded"),
("viewport", "omni.graph.ui_nodes.SetViewportMode"),
("viewportClose", "omni.graph.ui_nodes.SetViewportMode"),
("onClosing", "omni.graph.action.OnClosing"),
]
+ graph_node_data.get(keys.CREATE_NODES, []),
keys.CONNECT: [
("onLoaded.outputs:execOut", "viewport.inputs:execIn"),
("onClosing.outputs:execOut", "viewportClose.inputs:execIn"),
]
+ graph_node_data.get(keys.CONNECT, []),
keys.SET_VALUES: [
("viewport.inputs:viewport", self.viewport_name),
("viewportClose.inputs:viewport", self.viewport_name),
("viewport.inputs:mode", 1),
("viewport.inputs:enablePicking", True),
]
+ graph_node_data.get(keys.SET_VALUES, []),
},
)
# There's no graph window so we're not actually waiting for it to draw, but we still need
# to give some time for all the connections to resolve.
if error_thrown:
with ogts.ExpectedError():
await ui_test.wait_n_updates(self.wait_frames_for_graph_draw)
else:
await ui_test.wait_n_updates(self.wait_frames_for_graph_draw)
return data
def get_attribute(self, attribute, node):
return og.Controller.get(og.Controller.attribute(attribute, node))
def get_attribute_and_assert_equals(self, attribute, node, expected):
attr = self.get_attribute(attribute, node)
self.assertEquals(attr, expected)
def get_attribute_and_assert_list_equals(self, attribute, node, expected):
attr = self.get_attribute(attribute, node).tolist()
self.assertListEqual(attr, expected)
def get_attribute_and_assert_list_almost_equals(self, attribute, node, expected):
attr = self.get_attribute(attribute, node).tolist()
for a, e in zip(attr, expected):
self.assertAlmostEquals(a, e)
def assert_compute_message(self, node, error_message, severity=og.Severity.ERROR):
error = node.get_compute_messages(severity)[0].split("\n")[0]
self.assertEquals(error, error_message)
async def test_button_ui(self):
"""Test UI button"""
graph = self.create_graph()
widget_identifier = "testbutton"
keys = og.Controller.Keys
(_, (_, viewport, _, _, button, click, counter), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("click", "omni.graph.ui_nodes.OnWidgetClicked"),
("counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("click.outputs:clicked", "counter.inputs:execIn"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("click.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
],
},
)
# Click the button
await emulate_mouse_move_and_click(Vec2(50, 55))
self.get_attribute_and_assert_equals(
"inputs:parentWidgetPath", button, self.get_attribute("outputs:widgetPath", viewport)
)
self.get_attribute_and_assert_equals(
"inputs:create", button, self.get_attribute("outputs:scriptedMode", viewport)
)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", button, widget_identifier)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", click, widget_identifier)
# Test button click event
self.get_attribute_and_assert_equals("outputs:count", counter, 1)
await self.finalize_test_no_image()
async def test_set_viewport_mode(self):
"""Test SetViewportMode UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, viewport, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.SET_VALUES: [("viewport.inputs:mode", 0)],
},
)
self.get_attribute_and_assert_equals("outputs:scriptedMode", viewport, 0)
self.get_attribute_and_assert_equals("outputs:defaultMode", viewport, 1)
await self.finalize_test_no_image()
async def test_on_viewport_clicked(self):
"""Test OnViewportClicked and ReadViewportClickState UI nodes"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_clicked, viewport_click_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_clicked", "omni.graph.ui_nodes.OnViewportClicked"),
("viewport_click_state", "omni.graph.ui_nodes.ReadViewportClickState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_click_state.outputs:position", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_clicked.outputs:clicked", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_clicked.inputs:viewport", self.viewport_name),
("viewport_click_state.inputs:viewport", self.viewport_name),
("on_viewport_clicked.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move_and_click(Vec2(85, 255))
position = [72.40223463687151, 158.88268156424587] # Translated (x, y) position fo the mouse click
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_clicked, "Left Mouse Click")
self.get_attribute_and_assert_equals("inputs:gesture", viewport_click_state, "Left Mouse Click")
self.get_attribute_and_assert_list_almost_equals("outputs:position", on_viewport_clicked, position)
self.get_attribute_and_assert_list_almost_equals("outputs:position", viewport_click_state, position)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_click_state, True)
await self.finalize_test_no_image()
async def test_on_viewport_pressed(self):
"""Test OnViewportPressed UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(
_,
(_, _, _, _, on_viewport_pressed, viewport_press_state, _, _, _, _),
_,
_,
) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_pressed", "omni.graph.ui_nodes.OnViewportPressed"),
("viewport_press_state", "omni.graph.ui_nodes.ReadViewportPressState"),
("to_string", "omni.graph.nodes.ToString"),
("to_string2", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
("print2", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_press_state.outputs:pressPosition", "to_string.inputs:value"),
("viewport_press_state.outputs:releasePosition", "to_string2.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("to_string2.outputs:converted", "print2.inputs:text"),
("on_viewport_pressed.outputs:pressed", "print.inputs:execIn"),
("on_viewport_pressed.outputs:released", "print2.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_pressed.inputs:viewport", self.viewport_name),
("viewport_press_state.inputs:viewport", self.viewport_name),
("on_viewport_pressed.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move_and_click(Vec2(85, 255))
position = [72.40223463687151, 158.88268156424587] # Translated (x, y) position fo the mouse click
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_pressed, "Left Mouse Press")
self.get_attribute_and_assert_equals("inputs:gesture", viewport_press_state, "Left Mouse Press")
self.get_attribute_and_assert_list_equals("outputs:pressPosition", on_viewport_pressed, position)
self.get_attribute_and_assert_list_equals("outputs:releasePosition", on_viewport_pressed, position)
self.get_attribute_and_assert_list_equals("outputs:pressPosition", viewport_press_state, position)
self.get_attribute_and_assert_list_equals("outputs:releasePosition", viewport_press_state, position)
self.get_attribute_and_assert_equals("outputs:isReleasePositionValid", viewport_press_state, True)
self.get_attribute_and_assert_equals("outputs:isPressed", viewport_press_state, False)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_press_state, True)
await self.finalize_test_no_image()
async def test_on_viewport_scrolled(self):
"""Test OnViewportScrolled UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_scrolled, viewport_scroll_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_scrolled", "omni.graph.ui_nodes.OnViewportScrolled"),
("viewport_scroll_state", "omni.graph.ui_nodes.ReadViewportScrollState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_scroll_state.outputs:position", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_scrolled.outputs:scrolled", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_scrolled.inputs:viewport", self.viewport_name),
("viewport_scroll_state.inputs:viewport", self.viewport_name),
("on_viewport_scrolled.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move(Vec2(85, 255))
await emulate_mouse_scroll(Vec2(0, 900)) # (x, y) make a variable
position = [72.40223463687151, 158.88268156424587]
self.get_attribute_and_assert_equals("outputs:scrolled", on_viewport_scrolled, 1)
self.get_attribute_and_assert_list_equals("outputs:position", on_viewport_scrolled, position)
self.get_attribute_and_assert_list_equals("outputs:position", viewport_scroll_state, position)
self.get_attribute_and_assert_equals("outputs:scrollValue", on_viewport_scrolled, 1)
self.get_attribute_and_assert_equals("outputs:scrollValue", viewport_scroll_state, 1)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_scroll_state, True)
await self.finalize_test_no_image()
async def test_on_viewport_hovered(self):
"""Test OnViewportHovered UI node"""
graph = self.create_graph()
await emulate_mouse_move(Vec2(0, 0)) # Move the cursor away from final position
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_hover, viewport_hover_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_hover", "omni.graph.ui_nodes.OnViewportHovered"),
("viewport_hover_state", "omni.graph.ui_nodes.ReadViewportHoverState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_hover_state.outputs:position", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_hover.outputs:began", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_hover.inputs:viewport", self.viewport_name),
("viewport_hover_state.inputs:viewport", self.viewport_name),
("on_viewport_hover.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move(Vec2(85, 255))
position = [72.40223463687151, 158.88268156424587]
self.get_attribute_and_assert_equals("outputs:began", on_viewport_hover, 1)
self.get_attribute_and_assert_equals("outputs:isHovered", viewport_hover_state, True)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_hover_state, True)
self.get_attribute_and_assert_list_equals("outputs:position", viewport_hover_state, position)
await self.finalize_test_no_image()
async def test_on_viewport_dragged(self):
"""Test OnViewportDrag UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_dragged, viewport_drag_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_dragged", "omni.graph.ui_nodes.OnViewportDragged"),
("viewport_drag_state", "omni.graph.ui_nodes.ReadViewportDragState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_drag_state.outputs:currentPosition", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_dragged.outputs:ended", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_dragged.inputs:viewport", self.viewport_name),
("viewport_drag_state.inputs:viewport", self.viewport_name),
("on_viewport_dragged.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_drag_and_drop(Vec2(85, 255), Vec2(100, 455))
start_position = [72.40223463687151, 158.88268156424587]
end_position = [85.81005586592177, 337.6536312849162]
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_dragged, "Left Mouse Drag")
self.get_attribute_and_assert_list_equals("outputs:initialPosition", on_viewport_dragged, start_position)
self.get_attribute_and_assert_list_equals("outputs:finalPosition", on_viewport_dragged, end_position)
self.get_attribute_and_assert_list_equals("outputs:currentPosition", viewport_drag_state, end_position)
self.get_attribute_and_assert_list_equals("outputs:initialPosition", viewport_drag_state, start_position)
self.get_attribute_and_assert_list_equals("outputs:velocity", viewport_drag_state, [0, 0])
self.get_attribute_and_assert_equals("outputs:isValid", viewport_drag_state, True)
self.get_attribute_and_assert_equals("outputs:isDragInProgress", viewport_drag_state, False)
await self.finalize_test_no_image()
async def test_on_viewport_dragged_began(self):
"""Test OnViewportDrag UI node where we begin the drag but don't complete it."""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_dragged, viewport_drag_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_dragged", "omni.graph.ui_nodes.OnViewportDragged"),
("viewport_drag_state", "omni.graph.ui_nodes.ReadViewportDragState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_drag_state.outputs:currentPosition", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_dragged.outputs:began", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_dragged.inputs:viewport", self.viewport_name),
("viewport_drag_state.inputs:viewport", self.viewport_name),
("on_viewport_dragged.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_drag_and_drop(Vec2(85, 255), Vec2(100, 455))
start_position = [72.40223463687151, 158.88268156424587]
velocity = [0.8938547486033599, 22.346368715083777]
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_dragged, "Left Mouse Drag")
self.get_attribute_and_assert_list_equals("outputs:initialPosition", on_viewport_dragged, start_position)
self.get_attribute_and_assert_list_equals("outputs:initialPosition", viewport_drag_state, start_position)
self.get_attribute_and_assert_list_equals("outputs:velocity", viewport_drag_state, velocity)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_drag_state, True)
self.get_attribute_and_assert_equals("outputs:isDragInProgress", viewport_drag_state, True)
await self.finalize_test_no_image()
async def test_read_window_size_viewport_connection(self):
"""Test ReadWindowSize UI node with the viewport/window widget path connection"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("viewport.outputs:widgetPath", "read_window_size.inputs:widgetPath"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
],
},
)
self.get_attribute_and_assert_equals("outputs:width", read_window_size, 1440)
self.get_attribute_and_assert_equals("outputs:height", read_window_size, 900)
await self.finalize_test_no_image()
async def test_read_window_size(self):
"""Test ReadWindowSize UI node with the viewport/window name"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
("read_window_size.inputs:name", self.viewport_name),
],
},
)
self.get_attribute_and_assert_equals("outputs:width", read_window_size, 1440)
self.get_attribute_and_assert_equals("outputs:height", read_window_size, 900)
await self.finalize_test_no_image()
async def test_read_window_size_no_window(self):
"""Test ReadWindowSize UI node without window (error flow)"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
],
},
error_thrown=True,
)
warning = "OmniGraph Warning: No window name or widgetPath provided."
self.assert_compute_message(read_window_size, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_read_window_size_invalid_window(self):
"""Test ReadWindowSize UI node with invalid window name (error flow)"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
("read_window_size.inputs:name", "invalid-viewport"),
],
},
error_thrown=True,
)
error = "OmniGraph Error: No viewport named 'invalid-viewport' found."
self.assert_compute_message(read_window_size, error, og.Severity.ERROR)
await self.finalize_test_no_image()
async def test_write_widget_property(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, viewport, _, _, button, click, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("click", "omni.graph.ui_nodes.OnWidgetClicked"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("click.outputs:clicked", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("click.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
("write.inputs:widgetIdentifier", widget_identifier),
("write.inputs:propertyName", "text"),
],
},
)
# Click the button to trigger property write
await emulate_mouse_move_and_click(Vec2(50, 55))
self.get_attribute_and_assert_equals(
"inputs:parentWidgetPath", button, self.get_attribute("outputs:widgetPath", viewport)
)
self.get_attribute_and_assert_equals(
"inputs:create", button, self.get_attribute("outputs:scriptedMode", viewport)
)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", button, widget_identifier)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", click, widget_identifier)
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_property.png",
)
async def test_read_widget_property(self):
"""Test ReadWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, _, _, _, button, read, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("read", "omni.graph.ui_nodes.ReadWidgetProperty"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "print.inputs:execIn"),
("read.outputs:value", "print.inputs:text"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("read.inputs:widgetIdentifier", widget_identifier),
("read.inputs:propertyName", "text"),
],
},
)
self.get_attribute_and_assert_equals("inputs:text", button, self.get_attribute("outputs:value", read))
await self.finalize_test_no_image()
async def test_write_widget_property_with_widget_path(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("click", "omni.graph.ui_nodes.OnWidgetClicked"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("click.outputs:clicked", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
("button.outputs:widgetPath", "write.inputs:widgetPath"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("click.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
("write.inputs:propertyName", "text"),
],
},
)
# Click the button to trigger property write
await emulate_mouse_move_and_click(Vec2(50, 55))
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_property_with_widget_path.png",
)
async def test_write_widget_style(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetStyle"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "A BUTTON"),
("write.inputs:widgetIdentifier", widget_identifier),
("write.inputs:style", '{"background_color": "blue"}'),
],
},
)
# Click the viewport to see it
await emulate_mouse_move_and_click(Vec2(80, 255))
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_style.png",
)
async def test_write_widget_style_with_widget_path(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetStyle"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
("button.outputs:widgetPath", "write.inputs:widgetPath"),
],
keys.SET_VALUES: [
("button.inputs:text", "A BUTTON"),
("write.inputs:style", '{"background_color": "blue"}'),
],
},
)
# Click the viewport to see it
await emulate_mouse_move_and_click(Vec2(80, 255))
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_style_with_widget_path.png",
)
async def test_placer(self):
"""Test Placer UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("placer", "omni.graph.ui_nodes.Placer"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "placer.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "placer.inputs:create"),
("placer.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("placer.outputs:created", "button.inputs:create"),
],
keys.SET_VALUES: [
("button.inputs:text", "THIS IS A PLACED BUTTON"),
("button.inputs:style", '{"background_color": "blue"}'),
("placer.inputs:position", (20.0, 250.0)),
],
},
)
# Click the viewport
await emulate_mouse_move_and_click(Vec2(50, 55))
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_placer.png"
)
async def test_vstack_and_spacer(self):
"""Test VStack and Spacer UI nodes"""
buttons = 3
colors = ["green", "blue", "orange"]
stack = [f"button{b}" for b in range(buttons)]
stack.insert(1, "spacer")
# To ensure a consistent ordering of the children within the stack, the creation of the stack triggers the
# creation of its first child widget and each child then triggers the creation of the next one.
widget_creation_connections = [("stack.outputs:created", f"{stack[0]}.inputs:create")]
for i in range(len(stack) - 1):
widget_creation_connections += [(f"{stack[i]}.outputs:created", f"{stack[i+1]}.inputs:create")]
graph = self.create_graph()
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("stack", "omni.graph.ui_nodes.VStack"),
("spacer", "omni.graph.ui_nodes.Spacer"),
]
+ [(f"button{b}", "omni.graph.ui_nodes.Button") for b in range(buttons)],
keys.CONNECT: [
("viewport.outputs:widgetPath", "stack.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "stack.inputs:create"),
]
+ widget_creation_connections
+ [("stack.outputs:widgetPath", f"{widget}.inputs:parentWidgetPath") for widget in stack],
keys.SET_VALUES: [("spacer.inputs:height", 100)]
+ [(f"button{b}.inputs:text", f"Button {b+1}") for b in range(buttons)]
+ [(f"button{b}.inputs:style", '{"background_color": "' + colors[b] + '"}') for b in range(buttons)],
},
)
# Click the viewport
await emulate_mouse_move_and_click(Vec2(50, 55))
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_vstack_and_spacer.png"
)
async def test_button_negative_size(self):
"""Test UI button error flow - negative size"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")],
keys.CONNECT: [("viewport.outputs:scriptedMode", "button.inputs:create")],
keys.SET_VALUES: [("button.inputs:size", (-1, -1))], # Negative size
},
error_thrown=True,
)
self.assert_compute_message(button, "OmniGraph Error: The size of the widget cannot be negative!")
await self.finalize_test_no_image()
async def test_button_negative_no_parent_widget(self):
"""Test UI button error flow - no parent widget"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")],
keys.CONNECT: [("viewport.outputs:scriptedMode", "button.inputs:create")],
},
error_thrown=True,
)
self.assert_compute_message(button, "OmniGraph Error: No parentWidgetPath supplied.")
await self.finalize_test_no_image()
async def test_button_negative_invalid_style(self):
"""Test UI button error flow - style not valid"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "button.inputs:create"),
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
],
keys.SET_VALUES: [("button.inputs:style", "bad style")],
},
error_thrown=True,
)
# The expected error message contains the text of a Python SyntaxError exception, which is
# different depending on the Python version. So rather than do an exact match on the entire message
# we'll just check for some identifying text that is under our control.
msg = button.get_compute_messages(og.Severity.ERROR)[0].split("\n")[0]
self.assertTrue("OmniGraph Error: 'inputs:style': Invalid style syntax" in msg, "expected syntax error")
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_widget_identifier(self):
"""Test WriteWidgetProperty UI node error flow - invalid widget identifier"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
("impulse", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("impulse.outputs:execOut", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("write.inputs:widgetIdentifier", "invalid-id"),
("string.inputs:value", "new style"),
("impulse.state:enableImpulse", True),
("impulse.inputs:onlyPlayback", False),
],
},
)
warning = "OmniGraph Warning: No widget with identifier 'invalid-id' found in this graph."
self.assert_compute_message(write, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_widget_path(self):
graph = self.create_graph()
widget_path = "Viewport//Frame/ZStack[0]/Frame[3]/OG_overlay/Placer[2]/testbutton11"
keys = og.Controller.Keys
(_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
("impulse", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("impulse.outputs:execOut", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("write.inputs:widgetPath", widget_path),
("string.inputs:value", "new style"),
("impulse.state:enableImpulse", True),
("impulse.inputs:onlyPlayback", False),
],
},
)
warning = f"OmniGraph Warning: No widget found at path '{widget_path}'."
self.assert_compute_message(write, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_widget(self):
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
("impulse", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("impulse.outputs:execOut", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("string.inputs:value", "new style"),
("impulse.state:enableImpulse", True),
("impulse.inputs:onlyPlayback", False),
],
},
)
warning = "OmniGraph Warning: No widgetIdentifier or widgetPath provided."
self.assert_compute_message(write, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_write_widget_property_no_property(self):
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, _, _, _, _, write, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
("button.outputs:widgetPath", "write.inputs:widgetPath"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
],
},
error_thrown=True,
)
error = "OmniGraph Error: No property provided."
self.assert_compute_message(write, error)
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_property(self):
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, _, _, _, _, write, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("write.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
("write.inputs:propertyName", "invalid-property"),
],
},
error_thrown=True,
)
error = f"OmniGraph Error: Widget '{widget_identifier}' has no property 'invalid-property'."
self.assert_compute_message(write, error)
await self.finalize_test_no_image()
async def test_get_set_active_viewport_camera(self):
graph = self.create_graph()
prim_path = "/OmniverseKit_Front"
keys = og.Controller.Keys
(_, (_, _, _, _, _, get_camera, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("set_camera", "omni.graph.ui_nodes.SetActiveViewportCamera"),
("get_camera", "omni.graph.ui_nodes.GetActiveViewportCamera"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "set_camera.inputs:execIn"),
("get_camera.outputs:camera", "to_string.inputs:value"),
("set_camera.outputs:execOut", "print.inputs:execIn"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("set_camera.inputs:viewport", self.viewport_name),
("set_camera.inputs:primPath", prim_path),
],
},
)
self.get_attribute_and_assert_equals("outputs:camera", get_camera, prim_path)
await self.finalize_test_no_image()
# Using emulate_mouse_move_and_click() doesn't trigger the OnPicked node, even when done through the
# Script Editor in an interactive session.
@unittest.skip("OM-77263: Not working.")
async def test_on_picked(self):
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, _, counter), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_picked", "omni.graph.ui_nodes.OnPicked"),
("counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("on_picked.outputs:picked", "counter.inputs:execIn"),
],
keys.SET_VALUES: [
("on_picked.inputs:viewport", self.viewport_name),
("on_picked.inputs:onlyPlayback", False),
],
},
)
await emulate_mouse_move_and_click(Vec2(85, 255))
cube = ogts.create_cube(self.stage, "my_cube", (1, 1, 1))
attr = cube.GetAttribute("size")
attr.Set(10.0)
await ui_test.wait_n_updates(20)
self.get_attribute_and_assert_equals("outputs:count", counter, 1)
await self.finalize_test()
async def test_pass_clicks_thru(self):
await self.create_test_area(width=1200, height=800, block_devices=False)
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
# Load some geometry so that we have something which can be selected with a mouse click.
# The pxr renderer (aka "Storm") has problems selecting implicit geometry such as that generated by
# the Cube prim, so we need to use a mesh.
(result, error) = await ogts.load_test_file("mesh-cube.usd", use_caller_subdirectory=True)
self.assertTrue(result, error)
cube_path = "/World/Cube"
cube_pos = Vec2(700, 400)
# Create an execution graph with a SetViewportMode node and a variable to control its passClicksThru.
# An OnVariableChange node triggers the SetViewportMode node whenever the variable's value changes.
graph = self.create_graph()
keys = og.Controller.Keys
controller = og.Controller()
controller.edit(
graph,
{
keys.CREATE_VARIABLES: [("passThruMode", "bool", False)],
keys.CREATE_NODES: [
("readVariable", "omni.graph.core.ReadVariable"),
("viewportMode", "omni.graph.ui_nodes.SetViewportMode"),
("variableChanged", "omni.graph.action.OnVariableChange"),
# These are needed to ensure that the viewport is set back to default mode when the test is done.
("viewportClose", "omni.graph.ui_nodes.SetViewportMode"),
("onClosing", "omni.graph.action.OnClosing"),
],
keys.SET_VALUES: [
("readVariable.inputs:variableName", "passThruMode"),
("viewportMode.inputs:viewport", self.viewport_name),
("viewportMode.inputs:mode", 1),
("variableChanged.inputs:variableName", "passThruMode"),
("variableChanged.inputs:onlyPlayback", False),
("viewportClose.inputs:viewport", self.viewport_name),
],
keys.CONNECT: [
("readVariable.outputs:value", "viewportMode.inputs:passClicksThru"),
("variableChanged.outputs:changed", "viewportMode.inputs:execIn"),
("onClosing.outputs:execOut", "viewportClose.inputs:execIn"),
],
},
)
variable = graph.find_variable("passThruMode")
# Make sure nothing is selected and give the viewport some time to settle down.
selection.clear_selected_prim_paths()
await ui_test.wait_n_updates(2)
# Enable passClicksThru and click on the cube. It should be selected.
variable.set(graph.get_context(), True)
await ui_test.wait_n_updates(2)
await emulate_mouse_move_and_click(cube_pos)
await ui_test.wait_n_updates(8)
self.assertTrue(cube_path in selection.get_selected_prim_paths(), "Selection with passClicksThru True.")
# Disable passClicksThru and click on the cube. It should not be selected.
selection.clear_selected_prim_paths()
variable.set(graph.get_context(), False)
await ui_test.wait_n_updates(2)
await emulate_mouse_move_and_click(cube_pos)
await ui_test.wait_n_updates(8)
self.assertFalse(cube_path in selection.get_selected_prim_paths(), "Selection with passClicksThru False.")
await self.finalize_test_no_image()
| 55,826 | Python | 43.307143 | 120 | 0.553846 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/tests/test_omnigraph_action.py | """
Tests that verify action UI-dependent nodes
"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.kit.viewport.utility import get_active_viewport
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf
# ======================================================================
class TestOmniGraphAction(ogts.OmniGraphTestCase):
"""Encapsulate simple sanity tests"""
# ----------------------------------------------------------------------
async def setUp(self):
await super().setUp()
viewport_api = get_active_viewport()
viewport_api.camera_path = "/OmniverseKit_Persp"
# ----------------------------------------------------------------------
async def _test_camera_nodes(self, use_prim_connections):
"""Test camera-related node basic functionality"""
keys = og.Controller.Keys
controller = og.Controller()
viewport_api = get_active_viewport()
active_cam = viewport_api.camera_path
persp_cam = "/OmniverseKit_Persp"
self.assertEqual(active_cam.pathString, persp_cam)
(graph, _, _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("SetCam", "omni.graph.ui_nodes.SetActiveViewportCamera"),
],
keys.SET_VALUES: [
("SetCam.inputs:primPath", "/OmniverseKit_Top"),
],
keys.CONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
active_cam = viewport_api.camera_path
self.assertEqual(active_cam.pathString, "/OmniverseKit_Top")
# be nice - set it back
viewport_api.camera_path = persp_cam
# Tests moving the camera and camera target
controller.edit(
graph,
{
keys.DISCONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
(graph, (_, _, get_pos, get_target), _, _) = controller.edit(
graph,
{
keys.CREATE_NODES: [
("SetPos", "omni.graph.ui_nodes.SetCameraPosition"),
("SetTarget", "omni.graph.ui_nodes.SetCameraTarget"),
("GetPos", "omni.graph.ui_nodes.GetCameraPosition"),
("GetTarget", "omni.graph.ui_nodes.GetCameraTarget"),
],
keys.SET_VALUES: [
("SetPos.inputs:position", Gf.Vec3d(1.0, 2.0, 3.0)),
# Target should be different than position
("SetTarget.inputs:target", Gf.Vec3d(-1.0, -2.0, -3.0)),
],
keys.CONNECT: [
("OnTick.outputs:tick", "SetPos.inputs:execIn"),
("SetPos.outputs:execOut", "SetTarget.inputs:execIn"),
],
},
)
if use_prim_connections:
controller.edit(
graph,
{
keys.CREATE_NODES: [
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
("GetPrimAtPath.outputs:prims", "SetPos.inputs:prim"),
("GetPrimAtPath.outputs:prims", "SetTarget.inputs:prim"),
("GetPrimAtPath.outputs:prims", "GetPos.inputs:prim"),
("GetPrimAtPath.outputs:prims", "GetTarget.inputs:prim"),
],
keys.SET_VALUES: [
("SetPos.inputs:usePath", False),
("SetTarget.inputs:usePath", False),
("GetPos.inputs:usePath", False),
("GetTarget.inputs:usePath", False),
("ConstToken.inputs:value", persp_cam),
],
},
)
else:
controller.edit(
graph,
{
keys.SET_VALUES: [
("SetPos.inputs:primPath", persp_cam),
("SetTarget.inputs:primPath", persp_cam),
("GetPos.inputs:primPath", persp_cam),
("GetTarget.inputs:primPath", persp_cam),
],
},
)
await controller.evaluate()
# XXX: May need to force these calls through legacy_viewport as C++ nodes call through to that interface.
camera_state = ViewportCameraState(persp_cam) # , viewport=viewport_api, force_legacy_api=True)
x, y, z = camera_state.position_world
for a, b in zip([x, y, z], [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
x, y, z = camera_state.target_world
for a, b in zip([x, y, z], [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# evaluate again, because push-evaluator may not have scheduled the getters after the setters
await controller.evaluate()
get_pos = og.Controller.get(controller.attribute(("outputs:position", get_pos)))
for a, b in zip(get_pos, [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
get_target = og.Controller.get(controller.attribute(("outputs:target", get_target)))
for a, b in zip(get_target, [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# ----------------------------------------------------------------------
async def test_camera_nodes(self):
await self._test_camera_nodes(use_prim_connections=False)
# ----------------------------------------------------------------------
async def test_camera_nodes_with_prim_connection(self):
await self._test_camera_nodes(use_prim_connections=True)
# ----------------------------------------------------------------------
async def test_on_new_frame(self):
"""Test OnNewFrame node"""
keys = og.Controller.Keys
controller = og.Controller()
# Check that the NewFrame node is getting updated when frames are being generated
(_, (new_frame_node,), _, _) = controller.edit(
"/TestGraph", {keys.CREATE_NODES: [("NewFrame", "omni.graph.ui_nodes.OnNewFrame")]}
)
attr = controller.attribute(("outputs:frameNumber", new_frame_node))
await og.Controller.evaluate()
frame_num = og.Controller.get(attr)
# Need to tick Kit before evaluation in order to update
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await og.Controller.evaluate()
self.assertLess(frame_num, og.Controller.get(attr))
# -------------------------------------------------------------------------
async def test_get_active_camera_viewport_prim_output(self):
"""Tests the prim output on GetActiveCameraView node returns the correct value"""
keys = og.Controller.Keys
controller = og.Controller()
(graph, (_cam_node, path_node), _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("GetCamera", "omni.graph.ui_nodes.GetActiveViewportCamera"),
("GetPrimPath", "omni.graph.nodes.GetPrimPath"),
],
keys.CONNECT: [("GetCamera.outputs:cameraPrim", "GetPrimPath.inputs:prim")],
},
)
await og.Controller.evaluate(graph)
self.assertEqual(og.Controller.get(("outputs:primPath", path_node)), "/OmniverseKit_Persp")
# -------------------------------------------------------------------------
async def test_get_active_camera_viewport_from_file(self):
"""
Test the prim output on GetActiveCameraView node exists and returns the correct value
when an older version of the node is loaded from a file.
"""
(result, error) = await ogts.load_test_file("GetActiveViewportCamera.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
# validate the node and attribute exist after loading. The attribute does not exist in the file
cam_node = og.Controller.node("/World/Graph/get_active_camera")
self.assertTrue(cam_node.is_valid())
prim_output = og.Controller.attribute("/World/Graph/get_active_camera.outputs:cameraPrim")
self.assertTrue(prim_output.is_valid())
# modify the graph and evaluate it, to verify it gets the expected results
keys = og.Controller.Keys
controller = og.Controller()
(graph, nodes, _, _) = controller.edit(
"/World/Graph",
{
keys.CREATE_NODES: [
("GetPrimPath", "omni.graph.nodes.GetPrimPath"),
],
},
)
prim_inputs = nodes[0].get_attribute("inputs:prim")
controller.connect(prim_output, prim_inputs)
await og.Controller.evaluate(graph)
self.assertEqual(og.Controller.get(("outputs:primPath", nodes[0])), "/OmniverseKit_Persp")
| 9,466 | Python | 42.828704 | 113 | 0.516586 |
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/__init__.py | """
This module contains bindings for the omni::kit::uiaudio module.
This provides functionality for playing and managing sound prims in
USD scenes.
Sound files may be in RIFF/WAV, Ogg, or FLAC format.
Data in the sound files may use 8, 16, 24, or 32 bit integer samples,
or 32 bit floating point samples. Channel counts may be from 1 to 64
If more channels of data are provided than the audio device can play,
some channels will be blended together automatically.
"""
from ._uiaudio import *
# Cached UI audio instance pointer
def get_ui_audio_interface() -> IUiAudio:
"""
helper method to retrieve a cached version of the IUiAudio interface.
Returns:
The cached :class:`omni.kit.uiaudio.IUiAudio` interface. This will only be
retrieved on the first call. All subsequent calls will return the cached interface
object.
"""
if not hasattr(get_ui_audio_interface, "ui_audio"):
get_ui_audio_interface.ui_audio = acquire_ui_audio_interface()
return get_ui_audio_interface.ui_audio
| 1,107 | Python | 34.741934 | 91 | 0.684734 |
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/tests/test_audio.py |
import omni.kit.test
import omni.kit.uiaudio
class TestAudio(omni.kit.test.AsyncTestCase): # pragma: no cover
async def test_ui_audio(self):
audio = omni.kit.uiaudio.get_ui_audio_interface()
self.assertIsNotNone(audio)
# try to load a sound to test with.
sound = audio.create_sound("${sounds}/stop.wav")
if sound == None:
# still try to play the null sound.
audio.play_sound(sound)
# verify the sound's length is zero.
length = audio.get_sound_length(sound)
self.assertEqual(length, 0.0)
# make sure querying whether the null sound is playing fails.
playing = audio.is_sound_playing(sound)
self.assertFalse(playing)
else:
# play the sound.
audio.play_sound(sound)
# verify that it is playing.
playing = audio.is_sound_playing(sound)
self.assertTrue(playing)
# verify the sound's length is non-zero.
length = audio.get_sound_length(sound)
self.assertGreater(length, 0.0)
# wait so that a user can hear that sound is playing.
time.sleep(min(length, 5.0))
# clean up the local reference to the sound.
sound = None
| 1,316 | Python | 29.627906 | 73 | 0.582067 |
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/tests/__init__.py | from .test_audio import * # pragma: no cover
| 47 | Python | 14.999995 | 45 | 0.680851 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/hd_renderer_plugins.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["HdRendererPlugins"]
from pxr import Tf, Plug
class HdRendererPlugins:
def __init__(self, callback_fn: callable = None):
self.__callback_fn = callback_fn
self.__renderers = {}
self.__listener = Tf.Notice.RegisterGlobally(
"PlugNotice::DidRegisterPlugins", lambda notice, _: self.__add_renderers(notice.GetNewPlugins())
)
self.__add_renderers(Plug.Registry().GetAllPlugins())
def __add_renderers(self, plugins):
added = False
for renderer in [d for d in Tf.Type("HdRendererPlugin").GetAllDerivedTypes() if d not in self.__renderers]:
for plugin in plugins:
declared = plugin.GetMetadataForType(renderer)
if declared:
displayName = declared.get("displayName")
self.__renderers[renderer] = {"plugin": plugin, "displayName": displayName}
added = True
if added:
self.__callback_fn(self)
@property
def renderers(self):
for k, v in self.__renderers.items():
yield k, v
def destroy(self):
if self.__listener:
self.__listener.Revoke()
self.__listener = None
def __del__(self):
self.destroy()
| 1,711 | Python | 34.666666 | 115 | 0.630625 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/style.py | import carb.tokens
from pathlib import Path
ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.render}")).joinpath("data").joinpath("icons").absolute()
ICON_CORE_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.core}")).joinpath("data").joinpath("icons").absolute()
UI_STYLE = {
"Menu.Item.Icon::Renderer": {
"image_url": f"{ICON_PATH}/viewport_renderer.svg"
},
"Menu.Item.Button": {
"background_color": 0,
"margin": 0,
"padding": 0,
},
"Menu.Item.Button.Image::OptionBox": {
"image_url": f"{ICON_CORE_PATH}/settings_submenu.svg"
},
}
| 674 | Python | 32.749998 | 148 | 0.637982 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/extension.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportRenderMenuBarExtension", "get_instance", "SingleRenderMenuItemBase", "SingleRenderMenuItem"]
from .menu_item.single_render_menu_item import SingleRenderMenuItem, SingleRenderMenuItemBase
from .renderer_menu_container import RendererMenuContainer
import omni.ext
from typing import Callable
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
class ViewportRenderMenuBarExtension(omni.ext.IExt):
"""The Entry Point for the Render Settings in Viewport Menu Bar"""
def on_startup(self, ext_id):
self._render_menu = RendererMenuContainer()
global _extension_instance
_extension_instance = self
def register_menu_item_type(self, menu_item_type: Callable[..., "SingleRenderMenuItemBase"]):
"""
Register a custom menu type for the default created renderer
Args:
menu_item_type: callable that will create the menu item
"""
if self._render_menu:
self._render_menu.set_menu_item_type(menu_item_type)
def on_shutdown(self):
if self._render_menu:
self._render_menu.destroy()
self._render_menu = None
global _extension_instance
_extension_instance = None
| 1,713 | Python | 32.607842 | 112 | 0.718039 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/hd_renderer_list.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["HdEngineRendererMenuFactory"]
from .hd_renderer_plugins import HdRendererPlugins
import carb
_log_issue = carb.log_warn
class HdRenderer:
def __init__(self, *args):
self.pluginID, self.displayName, self.usdPlugin = args
def __repr__(self):
return f'HdRenderer("{self.pluginID}", "{self.displayName}")'
class HdEngineRenderer:
def __init__(self, *args):
self.engineName, self.renderModePath = args
self.renderers = []
def __repr__(self):
return f'HdEngineRenderer("{self.engineName}", "{self.renderModePath}", {[r for r in self.renderers]})'
class HdRendererList:
RTX_RENDER_MODE_PATH = "/rtx/rendermode"
IRY_RENDER_MODE_PATH = "/rtx/iray/rendermode"
PXR_RENDER_MODE_PATH = "/pxr/rendermode"
@classmethod
def enabled_engines(cls):
engines = carb.settings.get_settings().get("/renderer/enabled")
if engines:
# Return as an ordered list based on how renderers should display
engines = engines.split(",")
for engine in ("rtx", "iray", "index", "pxr"):
if engine in engines:
engines.remove(engine)
yield engine
else:
engines = ("rtx", "iray", "pxr")
for engine in engines:
yield engine
def __init__(self, update_fn: callable = None, engines=None):
# Use an OrderedDict to preserve incoming or app-default order when added
from collections import OrderedDict
self.__renderers = OrderedDict()
self.__hd_plugins = None
self.__updated_fn = update_fn
if not engines:
engines = self.enabled_engines()
for hdEngine in engines:
if hdEngine == "rtx":
self.__add_renderer(hdEngine, self.RTX_RENDER_MODE_PATH, "RaytracedLighting", "RTX - Real-Time")
self.__add_renderer(hdEngine, self.RTX_RENDER_MODE_PATH, "PathTracing", "RTX - Interactive (Path Tracing)")
if carb.settings.get_settings().get("/rtx-transient/aperture/enabled"):
self.__add_renderer(
hdEngine, self.RTX_RENDER_MODE_PATH, "LightspeedAperture", "RTX - Aperture (Game Path Tracer)"
)
elif hdEngine == "iray":
self.__add_renderer(hdEngine, self.IRY_RENDER_MODE_PATH, "iray", "RTX - Accurate (Iray)")
# No known setting to enable this.
if False:
self.__add_renderer(hdEngine, self.IRY_RENDER_MODE_PATH, "irt", "RTX - Accurate (Iray Interactive)")
elif hdEngine == "index":
self.__add_renderer(hdEngine, None, "index", "RTX - Scientific (IndeX)")
elif hdEngine == "pxr":
self.__hd_plugins = HdRendererPlugins(self.__add_pxr_renderers)
self.__add_pxr_renderers(self.__hd_plugins)
else:
_log_issue(f"Unknown Hydra engine'{hdEngine}'.")
def destroy(self):
if self.__hd_plugins:
self.__hd_plugins.destroy()
self.__hd_plugins = None
self.__renderers = {}
self.__updated_fn = None
def __del__(self):
self.destroy()
def __add_pxr_renderers(self, plugins):
for renderer, desc in plugins.renderers:
pluginID = renderer.typeName
displayName = desc.get("displayName")
# Special case Storm's displayName which is still 'GL'
if pluginID == "HdStormRendererPlugin":
displayName = "Pixar Storm"
self.__add_renderer("pxr", self.PXR_RENDER_MODE_PATH, pluginID, displayName, desc.get("plugin"))
def __add_renderer(self, engineName: str, renderModePath: str, pluginID: str, displayName=None, usdPlugin=None):
if not displayName:
displayName = pluginID
engineRenderers = self.__renderers.get(engineName)
if not engineRenderers:
engineRenderers = HdEngineRenderer(engineName, renderModePath)
self.__renderers[engineName] = engineRenderers
elif any([True for r in engineRenderers.renderers if r.pluginID == pluginID]):
return
engineRenderers.renderers.append(HdRenderer(pluginID, displayName, usdPlugin))
if self.__updated_fn:
self.__updated_fn(self)
@property
def renderers(self):
for k, v in self.__renderers.items():
yield k, v
| 4,912 | Python | 38.943089 | 123 | 0.608917 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/renderer_menu_container.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["RendererMenuContainer"]
from .menu_item.single_render_menu_item import SingleRenderMenuItem
from .hd_renderer_list import HdRendererList
from .style import UI_STYLE
from omni.kit.viewport.menubar.core import (
IconMenuDelegate,
ViewportMenuDelegate,
SettingComboBoxModel,
ViewportMenuContainer,
RadioMenuCollection,
SelectableMenuItem,
MenuDisplayStatus,
)
from omni.kit.app import SettingChangeSubscription
import omni.ui as ui
import omni.usd
import carb
import os
import sys
import asyncio
from functools import partial
from typing import Callable, Dict, List, Sequence, TYPE_CHECKING
if TYPE_CHECKING:
from .menu_item.single_render_menu_item import SingleRenderMenuItemBase
SHADING_MODE = "/exts/omni.kit.viewport.menubar.render/shadingMode"
LIGHTING_MODE = "/exts/omni.kit.viewport.menubar.render/lightingMode"
MATERIAL_MODE = "/exts/omni.kit.viewport.menubar.render/materialMode"
class BoolStringModel(ui.SimpleBoolModel):
def __init__(self, setting_path: str, value_map: Sequence[str] = ("default", "disabled"), *args, **kwargs):
super().__init__(*args, **kwargs)
self.__setting_path = setting_path
self.__value_map = value_map
self.__settings = carb.settings.get_settings()
self.__setting_sub = SettingChangeSubscription(setting_path, self.__setting_changed)
self.__in_set = False
def __del__(self):
self.destroy()
def destroy(self):
self.__setting_sub = None
def __setting_changed(self, item: carb.dictionary._dictionary.Item, event_type: carb.settings.ChangeEventType):
if event_type == carb.settings.ChangeEventType.CHANGED:
self._value_changed()
def get_value_as_string(self) -> bool:
return self.__settings.get(self.__setting_path)
def get_value_as_bool(self) -> bool:
return self.__settings.get(self.__setting_path) == self.__value_map[1]
def get_value(self) -> bool:
return self.get_value_as_bool()
def set_value(self, value: bool) -> bool:
cur_value = self.__settings.get(self.__setting_path)
str_value = self.__value_map[bool(value)]
changed = cur_value != str_value
if changed:
self.__settings.set(self.__setting_path, str_value)
return True
return changed
class FlashLightModel(BoolStringModel):
def set_value(self, value: bool) -> bool:
changed = super().set_value(value)
if changed:
settings = carb.settings.get_settings()
settings.set("/rtx/useViewLightingMode", value)
# settings.set("/rtx/shadows/enabled", not value)
return changed
class DisableMaterialModel(BoolStringModel):
def set_value(self, value: bool) -> bool:
changed = super().set_value(value)
if changed:
dbg_type = 0 if value else -1
settings = carb.settings.get_settings()
settings.set("/rtx/debugMaterialType", dbg_type)
wire_mode = settings.get("/rtx/wireframe/mode")
if wire_mode:
wire_mode = 2 if dbg_type == 0 else 1
settings.set("/rtx/wireframe/mode", wire_mode)
return changed
class ShadingModeModel(BoolStringModel):
def set_value(self, value: bool) -> bool:
changed = super().set_value(value)
if changed:
wire_mode = 0
settings = carb.settings.get_settings()
if value:
settings.set("/rtx/debugView/target", "")
if self.get_value_as_string() == "wireframe":
flat_shade = settings.get("/rtx/debugMaterialType") == 0
wire_mode = 2 if flat_shade else 1
settings.set("/rtx/wireframe/mode", wire_mode)
return changed
class DebugShadingModel(SettingComboBoxModel):
def __init__(self, viewport_api):
debug_view_items = {}
hd_engine = viewport_api.hydra_engine
if hd_engine == "rtx":
debug_view_items.update({
"Off": "",
"3D Motion Vectors [WARNING: Flashing Colors]": "targetMotion",
"Barycentrics": "barycentrics",
"Beauty After Tonemap": "beautyPostTonemap",
"Beauty Before Tonemap": "beautyPreTonemap",
"Depth": "depth",
"Instance ID": "instanceId",
"Interpolated Normal": "normal",
"Heat Map: Any Hit": "anyHitCountHeatMap",
"Heat Map: Intersection": "intersectionCountHeatMap",
"Heat Map: Timing": "timingHeatMap",
"SDG: Cross Correspondence": "sdgCrossCorrespondence",
"SDG: Motion": "sdgMotion",
"Semantic ID": "semanticId",
"Tangent U": "tangentu",
"Tangent V": "tangentv",
"Texture Coordinates 0": "texcoord0",
"Texture Coordinates 1": "texcoord1",
"Triangle Normal": "triangleNormal",
"Triangle Normal (OctEnc)": "triangleNormalOctEnc", # ReLAX Only
"Wireframe": "wire",
})
render_mode = viewport_api.render_mode
if render_mode == "RaytracedLighting":
debug_view_items.update({
"RT Ambient Occlusion": "ao",
"RT Caustics": "caustics",
"RT Denoised Dome Light": "denoisedDomeLightingTex",
"RT Denoised Sampled Lighting": "rtDenoisedSampledLighting",
"RT Denoised Sampled Lighting Diffuse": "rtDenoiseSampledLightingDiffuse", # ReLAX Only
"RT Denoised Sampled Lighting Specular": "rtDenoiseSampledLightingSpecular", # ReLAX Only
"RT Developer Debug Texture": "developerDebug",
"RT Diffuse GI": "indirectDiffuse",
"RT Diffuse GI (Not Accumulated)": "indirectDiffuseNonAccum",
"RT Diffuse Reflectance": "diffuseReflectance",
"RT Material Normal": "materialGeometryNormal",
"RT Material Normal (OctEnc)": "materialGeometryNormalOctEnc", # ReLAX Only
"RT Matte Object Compositing Alpha": "matteObjectAlpha",
"RT Matte Object Mask": "matteObjectMask",
"RT Matte Object View Before Postprocessing": "matteBeforePostprocessing",
"RT Noisy Dome Light": "noisyDomeLightingTex",
"RT Noisy Sampled Lighting": "rtNoisySampledLighting",
"RT Noisy Sampled Lighting (Not Accumulated)": "rtNoisySampledLightingNonAccum",
"RT Noisy Sampled Lighting Diffuse": "rtNoisySampledLightingDiffuse", # ReLAX Only
"RT Noisy Sampled Lighting Diffuse (Not Accumulated)": "sampledLightingDiffuseNonAccum",
"RT Noisy Sampled Lighting Specular": "rtNoisySampledLightingSpecular", # ReLAX Only
"RT Noisy Sampled Lighting Specular (Not Accumulated)": "sampledLightingSpecularNonAccum",
"RT Radiance": "radiance",
"RT Reflections": "reflections",
"RT Reflections (Not Accumulated)": "reflectionsNonAccum",
"RT Reflections 3D Motion Vectors [WARNING: Flashing Colors]": "reflectionsMotion",
"RT Roughness": "roughness",
"RT Shadow (last light)": "shadow",
"RT Specular Reflectance": "reflectance",
"RT Translucency": "translucency",
"RT World Position": "worldPosition",
})
elif render_mode == "PathTracing":
debug_view_items.update({
"PT Adaptive Sampling Error [WARNING: Flashing Colors]": "PTAdaptiveSamplingError",
"PT Denoised Result": "pathTracerDenoised",
"PT Noisy Result": "pathTracerNoisy",
"PT AOV Background": "PTAOVBackground",
"PT AOV Diffuse Filter": "PTAOVDiffuseFilter",
"PT AOV Direct Illumation": "PTAOVDI",
"PT AOV Global Illumination": "PTAOVGI",
"PT AOV Reflections": "PTAOVReflections",
"PT AOV Reflection Filter": "PTAOVReflectionFilter",
"PT AOV Refractions": "PTAOVRefractions",
"PT AOV Refraction Filter": "PTAOVRefractionFilter",
"PT AOV Self-Illumination": "PTAOVSelfIllum",
"PT AOV Volumes": "PTAOVVolumes",
"PT AOV World Normal": "PTAOVWorldNormals",
"PT AOV World Position": "PTAOVWorldPos",
"PT AOV Z-Depth": "PTAOVZDepth",
"PT AOV Multimatte0": "PTAOVMultimatte0",
"PT AOV Multimatte1": "PTAOVMultimatte1",
"PT AOV Multimatte2": "PTAOVMultimatte2",
"PT AOV Multimatte3": "PTAOVMultimatte3",
"PT AOV Multimatte4": "PTAOVMultimatte4",
"PT AOV Multimatte5": "PTAOVMultimatte5",
"PT AOV Multimatte6": "PTAOVMultimatte6",
"PT AOV Multimatte7": "PTAOVMultimatte7",
})
# Sort the above alphabetically
names, values = [], []
if debug_view_items:
for k, v in (debug_view_items.items()):
names.append(k)
values.append(v)
else:
names = []
values = []
super().__init__("/rtx/debugView/target", names, values=values)
def _on_change(self, *args, **kwargs) -> None:
super()._on_change(*args, **kwargs)
current_value = self._settings.get(self._path)
if current_value == '':
if self._settings.get(SHADING_MODE).startswith("custom:"):
self._settings.set(SHADING_MODE, "default")
else:
self._settings.set(SHADING_MODE, f"custom:{current_value}")
self._settings.set("/rtx/wireframe/mode", 0)
def empty(self):
children = self.get_item_children(None)
return len(children) == 0 if children else True
def __del__(self):
self.destroy()
def destroy(self):
super().destroy()
class MenuContext():
def __init__(self, root_menu: ui.Menu, viewport_api, renderer_changed_fn: Callable):
super().__init__()
self.__root_menu = root_menu
self.__viewport_api = viewport_api
self.__destroyable = {}
self.__usd_context_sub = viewport_api.usd_context.get_stage_event_stream().create_subscription_to_pop(
self.__on_usd_context_event, name=f"omni.kit.viewport.menubar.render.menu_context.{id(self)}"
)
self.__renderer_changed_fn = renderer_changed_fn
self.__rs_changed_sub = viewport_api.subscribe_to_render_settings_change(self.__render_settings_changed)
def __on_usd_context_event(self, event: omni.usd.StageEventType):
if event.type == int(omni.usd.StageEventType.SETTINGS_LOADED):
self.set_default_state()
def __render_settings_changed(self, *args, **kwargs):
self.__renderer_changed_fn(self, self.__viewport_api)
def set_default_state(self):
stage = self.__viewport_api.stage
if stage:
render_settings = stage.GetMetadata('customLayerData').get('renderSettings', {})
dbg_mat_type = render_settings.get('rtx:debugMaterialType')
view_lighting = render_settings.get('rtx:useViewLightingMode')
wire_mode = render_settings.get('rtx:wireframe:mode')
dbg_target = render_settings.get('rtx:debugView:target')
settings = carb.settings.get_settings()
settings.set(MATERIAL_MODE, "disabled" if dbg_mat_type == 0 else "default")
settings.set(LIGHTING_MODE, "disabled" if view_lighting else "default")
if wire_mode:
shade_mode = "wireframe"
elif dbg_target:
shade_mode = f"custom:{dbg_target}"
else:
shade_mode = "default"
settings.set(SHADING_MODE, shade_mode)
@property
def root_menu(self) -> ui.Menu:
return self.__root_menu
@property
def delegate(self) -> ui.MenuDelegate:
return self.root_menu.delegate
@property
def viewport_api(self):
return self.__viewport_api
def add_destroyables(self, key: str, destroyables: Sequence):
self.destroy(key)
self.__destroyable[key] = destroyables
def destroy(self, key: str = None):
if key is not None:
items = self.__destroyable.get(key)
if items:
for item in items:
item.destroy()
del self.__destroyable[key]
return
if self.__usd_context_sub:
self.__usd_context_sub = None
if self.__rs_changed_sub:
self.__rs_changed_sub = None
if self.__destroyable:
for items in self.__destroyable.values():
for item in items:
item.destroy()
self.__destroyable = {}
if self.__root_menu:
self.__root_menu.destroy()
self.__root_menu = None
class RendererMenuContainer(ViewportMenuContainer):
"""The menu with the list of renderers"""
PXR_IN_USE = "/app/viewport/omni_hydra_pxr_in_use"
__enabled_engines = None
def __init__(self):
super().__init__(
name="Renderer",
delegate=None,
visible_setting_path="/exts/omni.kit.viewport.menubar.render/visible",
order_setting_path="/exts/omni.kit.viewport.menubar.render/order",
style=UI_STYLE
)
self.__render_list = None
self.__render_state_subs = None
self._folder_exist_popup = None
self.__menu_item_type = SingleRenderMenuItem
self.__pending_render_change = False
self.__menu_context: Dict[int, MenuContext] = {}
# FIXME: Grab this now (on startup) as OmniHydraEngineFactoryBase can mutate it on first activation
if not RendererMenuContainer.__enabled_engines:
RendererMenuContainer.__enabled_engines = HdRendererList.enabled_engines()
# We can possibly drop these subscriptions when Viewport-1 is retired; but for now we have to watch for some
# common events if both VP-1 and VP-2 are sharing a hydra engine instance.
settings = carb.settings.get_settings()
self.__render_state_subs = (
settings.subscribe_to_node_change_events(self.PXR_IN_USE, self.__dirty_menu),
settings.subscribe_to_node_change_events("/pxr/renderers", self.__dirty_menu),
settings.subscribe_to_node_change_events(HdRendererList.PXR_RENDER_MODE_PATH, self.__dirty_menu),
settings.subscribe_to_node_change_events(HdRendererList.RTX_RENDER_MODE_PATH, self.__dirty_menu),
settings.subscribe_to_node_change_events(HdRendererList.IRY_RENDER_MODE_PATH, self.__dirty_menu),
settings.subscribe_to_node_change_events("/renderer/enabled", self.__dirty_renderers),
)
# Watch for extension enable/disable to support backgorund renderer loading
self.__setup_extenion_watching()
def __setup_extenion_watching(self):
import omni.kit.app
app = omni.kit.app.get_app()
if not app:
return
def setup_ext_hooks(*args, **kwargs):
import omni.ext
ext_manager = omni.kit.app.get_app().get_extension_manager()
if ext_manager:
self.__ext_manager_hooks = ext_manager.subscribe_to_extension_enable(
self.__ext_enabled, self.__ext_disabled,
# ext_name="omni.hydra.*",
hook_name="omni.kit.viewport.menubar.render.extension_change",
)
if not app.is_app_ready():
self.__app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, setup_ext_hooks, name="omni.kit.viewport.menubar.render.app_ready"
)
else:
setup_ext_hooks()
def set_menu_item_type(self, menu_item_type: Callable[..., "SingleRenderMenuItemBase"]):
"""
Set the menu type for the default created renderer
Args:
menu_item_type: callable that will create the menu item
"""
if menu_item_type is None:
menu_item_type = SingleRenderMenuItem
if self.__menu_item_type != menu_item_type:
self.__menu_item_type = menu_item_type
self.__dirty_menu()
def __hide_on_click(self, viewport_context: Dict = None):
return viewport_context.get("hide_on_click", False) if viewport_context else False
def destroy(self):
self.__app_ready_sub = None
self.__ext_manager_hooks = None
if self.__render_list:
self.__render_list.destroy()
self.__render_list = None
if self.__render_state_subs:
settings = carb.settings.get_settings()
for sub in self.__render_state_subs:
settings.unsubscribe_to_change_events(sub)
self.__render_state_subs = None
for context in self.__menu_context.values():
context.destroy()
self.__menu_context = {}
super().destroy()
@property
def render_list(self):
"""Returns the list of available renderers"""
if not self.__render_list:
def set_dirty(*args):
self.__dirty_menu()
self.__render_list = HdRendererList(set_dirty, self.__enabled_engines)
return self.__render_list
def build_fn(self, viewport_context: Dict):
"""Entry point for the menu bar"""
viewport_api = viewport_context.get('viewport_api')
viewport_api_id = viewport_api.id
menu_context = self.__menu_context.get(viewport_api_id)
if menu_context:
menu_context.destroy()
root_menu = ui.Menu(self.name,
delegate=IconMenuDelegate("Renderer", text=True),
on_build_fn=partial(self._build_menu, viewport_context),
style=self._style,
hide_on_click=self.__hide_on_click(viewport_context)
)
self.__menu_context[viewport_api_id] = MenuContext(root_menu, viewport_api, self.__set_menu_label)
# It will set the renderer name
self.__dirty_menu()
def get_display_status(self, factory_args: dict) -> MenuDisplayStatus:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if context.delegate.text_visible:
return MenuDisplayStatus.LABEL
else:
return MenuDisplayStatus.MIN
def get_require_size(self, factory_args: dict, expand: bool = False) -> float:
display_status = self.get_display_status(factory_args)
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if expand:
if display_status == MenuDisplayStatus.LABEL:
return 0
else:
return context.delegate.text_size
else:
return 0
def expand(self, factory_args: dict) -> None:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if context.delegate.text_visible:
return
else:
context.delegate.text_visible = True
if context.root_menu:
context.root_menu.invalidate()
def can_contract(self, factory_args: dict) -> bool:
display_status = self.get_display_status(factory_args)
return display_status == MenuDisplayStatus.LABEL
def contract(self, factory_args: dict) -> bool:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
display_status = self.get_display_status(factory_args)
if display_status == MenuDisplayStatus.LABEL:
context.delegate.text_visible = False
if context.root_menu:
context.root_menu.invalidate()
return True
return False
def __add_destroyables(self, viewport_api, key: str, destroyables: Sequence):
menu_context = self.__menu_context.get(viewport_api.id)
assert menu_context, f"No MenuContext for {viewport_api} (id: {viewport_api.id})"
menu_context.add_destroyables(key, destroyables)
def __build_renderers(self, viewport_context):
"""Build the menu with the list of the renderers"""
viewport_api = viewport_context["viewport_api"]
viewport_api_id = viewport_api.id
hide_on_click = self.__hide_on_click(viewport_context)
settings = carb.settings.get_settings()
# See if the omni.hydra.pxr engine is available for use in this Viewport
pxr_eng_available = self.__pxr_available(settings, viewport_api)
# Example: HdStormRendererPlugin:Storm
pxr_rnd_available = settings.get("/pxr/renderers")
# Example: rtx
current_engine_name = viewport_api.hydra_engine
for engine_name, hd_engine_renderer in self.render_list.renderers:
is_pxr = engine_name == "pxr"
is_engine_current = engine_name == current_engine_name
# Only sort renderers of the engine alphabetically for pxr renderers
if is_pxr:
renderers = sorted(
hd_engine_renderer.renderers, key=lambda hd_renderer: hd_renderer.displayName.lower()
)
else:
renderers = hd_engine_renderer.renderers
# Example: /rtx/rendermode
render_mode_path = hd_engine_renderer.renderModePath
# Get current from settings
if is_engine_current:
# Example: RaytracedLighting
current_render_mode = settings.get(render_mode_path) if render_mode_path else None
else:
current_render_mode = None
for hd_renderer in renderers:
# Example: RaytracedLighting
render_mode = hd_renderer.pluginID
enabled = True
if is_pxr:
# Check the renderer hasn't actually de-registered itself
# And only enable these menu items if omni.hydra.pxr engine is available for this Viewport instance
if not pxr_eng_available or (pxr_rnd_available and pxr_rnd_available.find(render_mode) == -1):
enabled = False
checked = is_engine_current and (render_mode == current_render_mode if render_mode_path else True)
def apply(viewport_api, engine_name, render_mode_path, render_mode):
"""Switch the current renderer"""
if True:
settings = carb.settings.get_settings()
# Set the legacy /renderer/active change for anyone that may be watching for it
settings.set('/renderer/active', engine_name)
# Now set the render-mode on that engine too
if render_mode_path:
settings.set(render_mode_path, render_mode)
# Finally apply it to the backing texture
viewport_api.set_hd_engine(engine_name, render_mode)
self.__menu_item_type(
hd_renderer.displayName,
engine_name,
hd_engine_renderer,
hd_renderer,
viewport_api,
enabled=enabled,
checked=checked,
hide_on_click=hide_on_click,
triggered_fn=partial(apply, viewport_api, engine_name, render_mode_path, render_mode),
)
def __build_shading_modes(self, viewport_context):
"""Build the shading modes"""
hide_on_click = self.__hide_on_click(viewport_context)
viewport_api = viewport_context.get("viewport_api")
engine_name = viewport_api.hydra_engine
is_rtx_or_pxr = engine_name == "rtx" or engine_name == "pxr"
default_shade_mode = SelectableMenuItem(
"Default",
model=ShadingModeModel(SHADING_MODE, ("wireframe", "default")),
delegate=ViewportMenuDelegate(force_checked=True),
hide_on_click=hide_on_click,
toggle=False,
enabled=is_rtx_or_pxr,
)
wireframe_mode = SelectableMenuItem(
"Wireframe",
model=ShadingModeModel(SHADING_MODE, ("default", "wireframe")),
delegate=ViewportMenuDelegate(force_checked=True),
hide_on_click=hide_on_click,
toggle=False,
enabled=is_rtx_or_pxr,
)
debug_mode = RadioMenuCollection(
"Debug View",
DebugShadingModel(viewport_api),
hide_on_click=hide_on_click,
)
debug_mode.enabled = not debug_mode._model.empty()
self.__add_destroyables(viewport_api, 'omni.kit.viewport.menubar.render.shading_modes', [default_shade_mode, wireframe_mode, debug_mode])
if not debug_mode.enabled:
carb.settings.get_settings().set("/rtx/debugView/target", "")
async def toggle_states():
import omni.kit.app
await omni.kit.app.get_app().next_update_async()
if default_shade_mode.model:
default_shade_mode.delegate.checked = default_shade_mode.model.as_bool
if wireframe_mode.model:
wireframe_mode.delegate.checked = wireframe_mode.model.as_bool
import asyncio
asyncio.ensure_future(toggle_states())
def __build_preset_modes(self, viewport_context):
"""Build the first level menu"""
hide_on_click = self.__hide_on_click(viewport_context)
ui.MenuItem("Load from Preset", triggered_fn=None, hide_on_click=hide_on_click)
def __build_render_options(self, viewport_context):
# Get the useViewLightingMode and turn on/off shadows based on it
viewport_api = viewport_context["viewport_api"]
engine_name = viewport_api.hydra_engine
is_iray = engine_name == "iray"
is_rtx_or_pxr = engine_name == "rtx" or engine_name == "pxr"
flash_light = SelectableMenuItem("Camera Light",
model=FlashLightModel(LIGHTING_MODE),
enabled=is_rtx_or_pxr)
disable_mat = SelectableMenuItem("Disable Materials (White Mode)",
model=DisableMaterialModel(MATERIAL_MODE),
enabled=is_rtx_or_pxr or is_iray)
self.__add_destroyables(viewport_api, 'omni.kit.viewport.menubar.render.render_options', [flash_light, disable_mat])
def __build_rendering_settings(self, viewport_context):
"""Build the rendering settings presets"""
# loading settings with menu open results in weird refresh problems, so disabled
hide_on_click = True
# get presets
preset_dict = carb.settings.get_settings().get_settings_dictionary("exts/omni.kit.viewport.menubar.render/presets").get_dict()
# remove any unused presets
for preset in preset_dict.copy():
if not preset_dict[preset]:
del preset_dict[preset]
if preset_dict:
def get_title(name):
return name.replace("_", " ").title()
ui.Separator(text="Rendering Settings")
with ui.Menu("Load from Preset", hide_on_click=hide_on_click):
for preset in preset_dict:
ui.MenuItem(f"{get_title(preset)}", triggered_fn=lambda p=preset_dict[preset]: asyncio.ensure_future(self.__load_setting_file(carb.tokens.get_tokens_interface().resolve(p))), hide_on_click=hide_on_click)
ui.Separator()
ui.MenuItem("Load Preset From File", triggered_fn=lambda v=viewport_context: self.__load_settings(v), hide_on_click=hide_on_click)
ui.MenuItem("Save Current as Preset", triggered_fn=lambda v=viewport_context: self.__save_settings(v), hide_on_click=hide_on_click)
ui.MenuItem("Reset to Defaults", triggered_fn=self.__reset_settings, hide_on_click=hide_on_click)
def __reset_settings(self):
omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx")
def __save_settings(self, viewport_context):
try:
from omni.kit.window.file_exporter import get_file_exporter
def show_file_exist_popup(usd_path, save_file):
try:
from omni.kit.widget.prompt import Prompt
def on_confirm(usd_path):
on_cancel()
save_file(usd_path)
def on_cancel():
self._folder_exist_popup.hide()
self._folder_exist_popup = None
if not self._folder_exist_popup:
self._folder_exist_popup = Prompt(
title="Overwrite",
text="The file already exists, are you sure you want to overwrite it?",
ok_button_text="Overwrite",
cancel_button_text="Cancel",
ok_button_fn=lambda: on_confirm(usd_path),
cancel_button_fn=on_cancel,
)
self._folder_exist_popup.show()
except ModuleNotFoundError:
carb.log_error("omni.kit.widget.prompt not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings.show_file_exist_popup errror {exc}")
def save_handler(filename: str, dirname: str, extension: str = "", selections: List[str] = []):
try:
from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser
def save_file(usd_path):
serialiser = USDSettingsSerialiser()
serialiser.save_to_usd(usd_path)
final_path = f"{dirname}/{filename}{extension}"
if os.path.exists(final_path):
show_file_exist_popup(final_path, save_file)
else:
save_file(final_path)
except ModuleNotFoundError:
carb.log_error("omni.rtx.window.settings not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings.save_handler errror {exc}")
file_exporter = get_file_exporter()
if file_exporter:
file_exporter.show_window(
title="Save Settings File",
export_button_label="Save",
export_handler=save_handler,
filename_url=carb.tokens.get_tokens_interface().resolve("${cache}/"),
file_postfix_options=["settings"])
except ModuleNotFoundError:
carb.log_error("omni.kit.window.file_exporter not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings errror {exc}")
def __load_settings(self, viewport_context):
try:
from omni.kit.window.file_importer import get_file_importer
def load_handler(filename: str, dirname: str, selections: List[str]):
from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser
final_path = f"{dirname}/{filename}"
try:
serialiser = USDSettingsSerialiser()
serialiser.load_from_usd(final_path)
except ModuleNotFoundError:
carb.log_error("omni.rtx.window.settings not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings.save_handler errror {exc}")
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Load Settings File",
import_button_label="Load",
import_handler=load_handler,
filename_url=carb.tokens.get_tokens_interface().resolve("${cache}/"),
file_postfix_options=["settings"])
except ModuleNotFoundError:
carb.log_error("omni.kit.window.file_importer not enabled!")
except Exception as exc:
carb.log_error(f"__load_settings errror {exc}")
async def __load_setting_file(self, preset_name):
await omni.kit.app.get_app().next_update_async()
try:
from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser
serialiser = USDSettingsSerialiser()
serialiser.load_from_usd(preset_name)
except ModuleNotFoundError:
carb.log_error("omni.rtx.window.settings not enabled!")
except Exception as exc:
carb.log_error(f"__load_setting_file errror {exc}")
def _build_menu(self, viewport_context):
"""Build the first level menu"""
hide_on_click = self.__hide_on_click(viewport_context)
viewport_api = viewport_context.get("viewport_api")
if not viewport_api:
return
menu_context = self.__menu_context.get(viewport_api.id)
self.__menu_context[viewport_api.id].root_menu.clear()
ui.MenuItemCollection(on_build_fn=lambda *args: self.__build_renderers(viewport_context))
# Rendering Settings
self.__build_rendering_settings(viewport_context)
# Rendering Mode
ui.Separator(text="Rendering Mode")
ui.Menu(checkable=True, on_build_fn=lambda *args: self.__build_shading_modes(viewport_context))
ui.Separator()
ui.Menu(checkable=True, on_build_fn=lambda *args: self.__build_render_options(viewport_context))
ui.Separator()
# This opens a new Window or goes to an existing preference-pane, so close the Menu
ui.MenuItem("Preferences", triggered_fn=self.__show_render_preferences, hide_on_click=hide_on_click)
# The rest of the menu on the case someone wants to put custom stuff
children = self._children
if children:
ui.Separator()
for child in children:
child.build_fn(viewport_context)
if not menu_context:
return
self.__set_menu_label(menu_context, viewport_api)
def __dirty_menu(self, *args, **kwargs):
"""Rebuild everything"""
for context in self.__menu_context.values():
if context.root_menu:
context.root_menu.invalidate()
self.dirty = True
def __dirty_renderers(self, *args, **kwargs):
# On 105.0, changes to /renderer/enabled can/will be recursive
if self.__pending_render_change:
return
self.__pending_render_change = True
async def update_render_list():
self.__pending_render_change = False
RendererMenuContainer.__enabled_engines = HdRendererList.enabled_engines()
self.__render_list = None
self.__dirty_menu()
from omni.kit.async_engine import run_coroutine
run_coroutine(update_render_list())
def __ext_changed(self, ext_name: str, enabled: bool):
if not ext_name.startswith("omni.hydra"):
return
settings = carb.settings.get_settings()
managed_hd_exts = settings.get("/exts/omni.kit.viewport.menubar.render/autoManageEnabledList")
if not managed_hd_exts:
return
managed_hd_exts = [ext.lstrip().rstrip() for ext in managed_hd_exts.split(",")]
engine_split = ext_name.split(".")
if len(engine_split) >= 3:
engine_split = engine_split[2].split("-")[0]
# Test is this extension is "managed"
if engine_split in managed_hd_exts:
rnd_enabled = settings.get("/renderer/enabled") or ""
rnd_loc = rnd_enabled.find(engine_split)
if enabled:
if rnd_loc == -1:
settings.set("/renderer/enabled", ",".join([rnd_enabled, engine_split]))
elif rnd_loc != -1:
rnd_enabled = rnd_enabled.split(",")
rnd_enabled.remove(engine_split)
settings.set("/renderer/enabled", ",".join(rnd_enabled))
self.__dirty_renderers()
def __ext_enabled(self, ext_name: str, *args, **kwargs):
self.__ext_changed(ext_name, True)
def __ext_disabled(self, ext_name: str, *args, **kwargs):
self.__ext_changed(ext_name, False)
def __pxr_available(self, settings, viewport_api):
# See if the omni.hydra.pxr engine is available for use in this Viewport
try:
usd_context_key = f"'{viewport_api.usd_context_name}':"
setting_path = viewport_api._settings_path
pxr_eng_in_use = settings.get(self.PXR_IN_USE)
if not pxr_eng_in_use:
return True
# Iterate the list of UsdContext.name => ViewportKey
usd_context_key_len = len(usd_context_key)
for in_use in pxr_eng_in_use:
# Is a omni.hydra.pxr engine instance running for this UsdContext?
if in_use.startswith(usd_context_key):
# Yes, so the menu must can only be in the Viewport that claims the context
if in_use.find(setting_path) == usd_context_key_len:
return True
# Otherwise this Viewport cannot use omni.hydra.pxr
return False
# omni.hydra.pxr is not in use for this UsdContext, so it is available
return True
except Exception:
pass
return False
def __get_current_name(self, viewport_api):
"""Returns display name of the current renderer"""
engine_name = viewport_api.hydra_engine
engine_name, hd_engine_renderer = next(
(i for i in self.render_list.renderers if i[0] == engine_name), (None, None)
)
if not hd_engine_renderer or not hd_engine_renderer.renderers:
return self.name
# Example: /rtx/rendermode
render_mode_path = hd_engine_renderer.renderModePath
if not render_mode_path:
return hd_engine_renderer.renderers[0].displayName
# Example: RaytracedLighting
current_render_mode = carb.settings.get_settings().get(render_mode_path)
return next((i.displayName for i in hd_engine_renderer.renderers if i.pluginID == current_render_mode), None)
def __set_menu_label(self, menu_context: MenuContext, viewport_api):
if menu_context is None:
menu_context = self.__menu_context.get(viewport_api.id)
if menu_context is None:
carb.log_error("No MenuContext for this menubar-item")
return
current_renderer_name = self.__get_current_name(viewport_api)
menu_context.root_menu.text = {
"RTX - Interactive (Path Tracing)": "RTX - Interactive",
"RTX - Accurate (Iray)": "RTX - Accurate",
"RTX - Scientific (IndeX)": "RTX - Scientific",
}.get(current_renderer_name, str(current_renderer_name)) if current_renderer_name else self.name
def __show_render_preferences(self, *args, **kwargs) -> None:
try:
import omni.kit.window.preferences as preferences
async def focus_async():
pref_window = ui.Workspace.get_window("Preferences")
if pref_window:
pref_window.focus()
PAGE_TITLE = "Rendering"
inst = preferences.get_instance()
if not inst:
carb.log_error("Preferences extension is not loaded yet")
return
pages = preferences.get_page_list()
for page in pages:
if page.get_title() == PAGE_TITLE:
inst.select_page(page)
# Show the Window
inst.show_preferences_window()
# Force the tab to be the active/focused tab (this currently needs to be done in async)
asyncio.ensure_future(focus_async())
return page
else:
carb.log_error("Render Preferences page not found!")
except ImportError:
carb.log_error("omni.kit.window.preferences not enabled!")
| 41,744 | Python | 41.771516 | 223 | 0.581952 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/menu_item/single_render_menu_item.py | import abc
from typing import Callable
import omni.ui as ui
from omni.kit.viewport.menubar.core import ViewportMenuDelegate
class SingleRenderMenuItemBase(ui.MenuItem):
"""
A single menu item represent a single camera in the camera list
"""
def __init__(
self,
display_name: str,
engine_name,
hd_engine_renderer,
hd_renderer,
viewport_api,
enabled: bool,
checked: bool,
hide_on_click: bool,
triggered_fn: Callable,
):
self.__viewport_api = viewport_api
self.__engine_name = engine_name
self.__hd_engine_renderer = hd_engine_renderer
self.__hd_renderer = hd_renderer
self.__options_button = None
super().__init__(
display_name,
enabled=enabled,
checkable=True,
checked=checked,
delegate=ViewportMenuDelegate(
force_checked=False,
build_custom_widgets=lambda delegate, item: self._build_menuitem_widgets(),
),
hide_on_click=hide_on_click,
triggered_fn=triggered_fn
)
def destroy(self):
self.__options_button = None
super().destroy()
@property
def hd_renderer(self):
return self.__hd_renderer
@property
def hd_engine_renderer(self):
return self.__hd_engine_renderer
@property
def engine_name(self):
return self.__engine_name
@property
def viewport_api(self):
return self.__viewport_api
def _build_menuitem_widgets(self):
ui.Spacer(width=10)
with ui.VStack(content_clipping=1, width=0):
# Button to show renderer settings
self.__options_button = ui.Button(
style_type_name_override="Menu.Item.Button",
name="OptionBox",
width=16,
height=16,
image_width=16,
image_height=16,
visible=self.checked,
clicked_fn=self._option_clicked,
)
@abc.abstractmethod
def _option_clicked(self):
"""Function to implement when the option is clicked. Used by RTX Remix"""
pass
def set_checked(self, checked: bool) -> None:
self.checked = checked
self.delegate.checked = checked
# Only show options button when it is current camera
self.__options_button.visible = checked
class SingleRenderMenuItem(SingleRenderMenuItemBase):
"""
A single menu item represent a single camera in the camera list
"""
def _option_clicked(self):
try:
from omni.rtx.window.settings import RendererSettingsFactory
rs_instance = RendererSettingsFactory.render_settings_extension_instance
if rs_instance:
rs_instance.show_render_settings(self.engine_name, self.hd_renderer.pluginID, True)
except ImportError:
pass
| 2,988 | Python | 27.740384 | 99 | 0.587349 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/test_api.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestAPI']
import omni.kit.test
import functools
from omni.kit.test import AsyncTestCase
from unittest.mock import patch, call
from omni.kit.viewport.menubar.render import get_instance as _get_menubar_extension
from omni.kit.viewport.menubar.render import SingleRenderMenuItem as _SingleRenderMenuItem
from omni.kit.viewport.menubar.render import SingleRenderMenuItemBase as _SingleRenderMenuItemBase
from omni.kit.viewport.menubar.render.renderer_menu_container import RendererMenuContainer as _RendererMenuContainer
class TestAPI(AsyncTestCase):
async def test_get_instance(self):
extension = _get_menubar_extension()
self.assertIsNotNone(extension)
async def test_register_custom_menu_item_type(self):
def _single_render_menu_item(*args, **kwargs):
class SingleRenderMenuItem(_SingleRenderMenuItemBase):
pass
return SingleRenderMenuItem(*args, **kwargs)
extension = _get_menubar_extension()
try:
with patch.object(_RendererMenuContainer, "set_menu_item_type") as set_menu_item_type_mock:
fn = functools.partial(_single_render_menu_item)
extension.register_menu_item_type(
fn
)
self.assertEqual(1, set_menu_item_type_mock.call_count)
self.assertEqual(call(fn), set_menu_item_type_mock.call_args)
finally:
extension.register_menu_item_type(None)
async def test_register_regular_menu_item_type(self):
def _single_render_menu_item(*args, **kwargs):
return _SingleRenderMenuItem(*args, **kwargs)
extension = _get_menubar_extension()
try:
with patch.object(_RendererMenuContainer, "set_menu_item_type") as set_menu_item_type_mock:
fn = functools.partial(_single_render_menu_item)
extension.register_menu_item_type(
fn
)
self.assertEqual(1, set_menu_item_type_mock.call_count)
self.assertEqual(call(fn), set_menu_item_type_mock.call_args)
finally:
extension.register_menu_item_type(None)
| 2,635 | Python | 40.187499 | 116 | 0.677799 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/__init__.py | from .test_api import *
from .test_ui import *
| 47 | Python | 14.999995 | 23 | 0.702128 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/test_ui.py | import omni.kit.test
from re import I
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.viewport.window import ViewportWindow
import omni.kit.ui_test as ui_test
from omni.kit.ui_test import Vec2
import omni.usd
import omni.kit.app
from pathlib import Path
import carb.input
import functools
from omni.kit.viewport.menubar.render import get_instance as _get_menubar_extension
from omni.kit.viewport.menubar.render import SingleRenderMenuItemBase as _SingleRenderMenuItemBase
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
TEST_WIDTH, TEST_HEIGHT = 600, 400
class TestSettingMenuWindow(OmniUiTest):
async def setUp(self):
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
self._vw = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT)
self._viewport_api = self._vw.viewport_api
await omni.kit.app.get_app().next_update_async()
# After running each test
async def tearDown(self):
self._vw.destroy()
del self._vw
await super().tearDown()
async def __show_render_menu(self, mouse_pos: Vec2 = None):
# Enable mouse input
app_window = omni.appwindow.get_default_app_window()
for device in [carb.input.DeviceType.MOUSE]:
app_window.set_input_blocking_state(device, None)
await ui_test.emulate_mouse_move(mouse_pos if mouse_pos else Vec2(40, 40))
await ui_test.emulate_mouse_click()
await omni.kit.app.get_app().next_update_async()
async def __close_render_menu(self):
await ui_test.emulate_mouse_move(Vec2(TEST_WIDTH, TEST_HEIGHT))
await ui_test.emulate_mouse_click()
await self.wait_n_updates()
async def test_render_menu_with_custom_type(self):
"""Test custom options area item. (This likely breaks order independent testing)"""
menu_option_clicked = 0
def _single_render_menu_item(*args, **kwargs):
class SingleRenderMenuItem(_SingleRenderMenuItemBase):
def _option_clicked(self):
nonlocal menu_option_clicked
menu_option_clicked += 1
return SingleRenderMenuItem(*args, **kwargs)
extension = _get_menubar_extension()
self.assertIsNotNone(extension)
try:
await self.__show_render_menu()
self.assertEqual(0, menu_option_clicked)
# Simluate a click in options-area, but do it on Storm; not RTX
await self.__show_render_menu(Vec2(205, 135))
self.assertEqual(0, menu_option_clicked)
extension.register_menu_item_type(
functools.partial(_single_render_menu_item)
)
await self.wait_n_updates()
await ui_test.emulate_mouse_click()
await self.wait_n_updates()
self.assertEqual(1, menu_option_clicked)
finally:
extension.register_menu_item_type(None)
await self.__close_render_menu()
await self.finalize_test_no_image()
async def test_auto_manage_renderer_list(self):
"""Test auto management of the renderer menu based on extension load. (This likely breaks order independent testing)"""
settings = carb.settings.get_settings()
restore_value = settings.get("/renderer/enabled")
try:
async def change_available_renderers(golden_img_name: str, renderers: str = None):
# Close the menu to avoid issues with golden images as menu shrink is animated over time
if renderers:
settings.set("/renderer/enabled", renderers)
await self.__show_render_menu()
await self.capture_and_compare(
golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name
)
await self.__close_render_menu()
await change_available_renderers("menubar_default_list_0.png")
# Disable everything but RTX
await change_available_renderers("menubar_rtx_only.png", "rtx")
# Disable everything but Iray and Storm
await change_available_renderers("menubar_pxr_iray_only.png", "pxr,iray")
# Enable omni.hydra.index extension (Note it will enable RTX as well due to dependencies)
omni.kit.app.get_app().get_extension_manager().set_extension_enabled_immediate("omni.hydra.index", True)
await change_available_renderers("menubar_all_shipping.png")
# Disbale omni.hydra.index extension, and list should be back to menubar_default_list
omni.kit.app.get_app().get_extension_manager().set_extension_enabled_immediate("omni.hydra.index", False)
await change_available_renderers("menubar_default_list_1.png")
finally:
settings.set("/renderer/enabled", restore_value if restore_value else "")
await self.__close_render_menu()
await self.finalize_test_no_image()
| 5,203 | Python | 39.976378 | 127 | 0.647703 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageWidgetExtension"]
import omni.ext
from .stage_column_delegate_registry import StageColumnDelegateRegistry
from .visibility_column_delegate import VisibilityColumnDelegate
from .type_column_delegate import TypeColumnDelegate
from .delegates import NameColumnDelegate
from .stage_actions import register_actions, deregister_actions
from .export_utils import _get_stage_open_sub
from .stage_style import Styles as StageStyles
class StageWidgetExtension(omni.ext.IExt):
"""The entry point for Stage Window"""
def on_startup(self, ext_id):
# Register column delegates
self._name_column_sub = StageColumnDelegateRegistry().register_column_delegate("Name", NameColumnDelegate)
self._type_column_sub = StageColumnDelegateRegistry().register_column_delegate("Type", TypeColumnDelegate)
self._visibility_column_sub = StageColumnDelegateRegistry().register_column_delegate("Visibility", VisibilityColumnDelegate)
self._ext_name = omni.ext.get_extension_name(ext_id)
StageStyles.on_startup()
self._registered_hotkeys = []
register_actions(self._ext_name, self)
self._stage_open_sub = _get_stage_open_sub()
def on_shutdown(self):
self._name_column_sub = None
self._visibility_column_sub = None
self._type_column_sub = None
deregister_actions(self._ext_name, self)
self._stage_open_sub = None
| 1,860 | Python | 42.279069 | 132 | 0.746237 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/column_menu.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .event import Event
from .event import EventSubscription
from .stage_column_delegate_registry import StageColumnDelegateRegistry
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
from .stage_icons import StageIcons as Icons
import omni.ui as ui
import weakref
class ColumnMenuDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
MENU_STYLES = {
"Menu.CheckBox": {"background_color": 0x0, "margin": 0},
"Menu.CheckBox::drag": {
"image_url": Icons().get("drag"),
"color": 0xFF505050,
"alignment": ui.Alignment.CENTER,
},
"Menu.CheckBox.Image": {"image_url": Icons().get("check_off"), "color": 0xFF8A8777},
"Menu.CheckBox.Image:checked": {"image_url": Icons().get("check_on"), "color": 0x34C7FFFF},
}
def __init__(self):
super().__init__()
def destroy(self):
pass
def build_header(self, column_id):
pass
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
with ui.HStack(height=0, style=ColumnMenuDelegate.MENU_STYLES):
ui.ToolButton(
item.checked_model,
style_type_name_override="Menu.CheckBox",
width=18,
height=18,
image_width=18,
image_height=18,
)
ui.Label(item.name_model.as_string)
ui.Image(style_type_name_override="Menu.CheckBox", name="drag", width=10)
class ColumnMenuItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, model, text, checked):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.checked_model = ui.SimpleBoolModel(checked)
self.checked_model.add_value_changed_fn(self._on_checked_changed)
self.__weak_model = weakref.ref(model)
def _on_checked_changed(self, model):
model = self.__weak_model()
if model:
model._item_changed(self)
model._on_column_checked_changed([i[0] for i in model.get_columns()])
def __repr__(self):
return f'"{self.name_model.as_string}"'
class ColumnMenuModel(ui.AbstractItemModel):
"""
Represents the model for available columns.
"""
def __init__(self, enabled: Optional[List[str]] = None, accepted: Optional[List[str]] = None):
super().__init__()
self._column_delegate_sub = StageColumnDelegateRegistry().subscribe_delegate_changed(
self._on_column_delegate_changed
)
self._accepted = accepted
if enabled is None:
self._children = []
else:
self._children = [
ColumnMenuItem(self, name, True) for name in enabled if not self._accepted or name in self._accepted
]
self._on_column_delegate_changed(enabled is None)
self._on_column_checked_changed = Event()
def destroy(self):
self._column_delegate_sub = None
self._children = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return item.name_model.as_string
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
# If target_item is None, it's the drop to root. Since it's
# list model, we support reorganizetion of root only and we
# don't want to create tree.
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called when dropping something to the item."""
try:
source_id = self._children.index(source)
except ValueError:
try:
current_names = [c.name_model.as_string for c in self._children]
source_id = current_names.index(source)
source = self._children[source_id]
except ValueError:
# Not in the list. This is the source from another model.
return
if source_id == drop_location:
# Nothing to do
return
self._children.pop(source_id)
if drop_location > len(self._children):
# Drop it to the end
self._children.append(source)
else:
if source_id < drop_location:
# Becase when we removed source, the array became shorter
drop_location = drop_location - 1
self._children.insert(drop_location, source)
self._item_changed(None)
def get_columns(self) -> List[Tuple[str, bool]]:
"""
Return all the columns in the format
`[("Visibility", True), ("Type", False)]`
The first item is the column name, and the second item is a flag that
is True if the column is enabled.
"""
current_names = [c.name_model.as_string for c in self._children]
current_checked = [c.checked_model.as_bool for c in self._children]
return list(zip(current_names, current_checked))
def subscribe_delegate_changed(self, fn: Callable[[List[str]], None]) -> EventSubscription:
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return EventSubscription(self._on_column_checked_changed, fn)
def _on_column_delegate_changed(self, enabled=False):
"""Called by StageColumnDelegateRegistry"""
current_names = [c.name_model.as_string for c in self._children]
column_delegate_names = StageColumnDelegateRegistry().get_column_delegate_names()
# Exclude "Name" as it's enabled always.
if "Name" in column_delegate_names:
column_delegate_names.remove("Name")
# Filter columns. We only need the columns that is in self._accepted list.
if self._accepted:
column_delegate_names = [name for name in column_delegate_names if name in self._accepted]
# Form the new list keeping the order of the old columns
new_names = []
for name in current_names:
if name in column_delegate_names:
new_names.append(name)
# Put the new columns to the end of the list
unused_names = [name for name in column_delegate_names if name not in new_names]
new_names += unused_names
if current_names == new_names:
# Nothing changed
return
# Create item for new columns and reuse the items for old columns
new_children = []
for name in new_names:
if name in current_names:
i = current_names.index(name)
new_children.append(self._children[i])
else:
new_children.append(ColumnMenuItem(self, name, enabled))
# Replace children
self._children = new_children
self._item_changed(None)
| 8,582 | Python | 34.912134 | 116 | 0.61629 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/abstract_stage_column_delegate.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__ = ["AbstractStageColumnDelegate", "StageColumnItem"]
from pxr import Sdf, Usd
from typing import List
from .stage_item import StageItem
import abc
import omni.ui as ui
class StageColumnItem: # pragma: no cover
"""
It's not clear which data we need to pass to build_widget. It's path, but
there are potentially other information the column has. To keep API
unchanged over the time, we pass data in a struct. It also allow to pass
custom data with deriving from this class.
"""
def __init__(self, path: Sdf.Path, stage: Usd.Stage, enabled: bool, expanded: bool = True):
"""
## Arguments
`path`: Full path to the item
`stage`: USD Stage
`enabled`: When false, the widget should be grayed out
"""
self._path = path
self._stage = stage
self._enabled = enabled
self._expanded = expanded
@property
def path(self):
return self._path
@property
def stage(self):
return self._stage
@property
def enabled(self):
return self._enabled
@property
def expanded(self):
return self._expanded
class AbstractStageColumnDelegate(metaclass=abc.ABCMeta): # pragma: no cover
"""
An abstract object that is used to put the widget to the file browser
asynchronously.
"""
def destroy(self):
"""Place to release resources."""
pass
@property
def initial_width(self):
"""The initial width of the column."""
return ui.Fraction(1)
@property
def minimum_width(self):
return ui.Pixel(10)
def build_header(self, **kwargs):
"""
Build the header widget. If the column is sortable,
stage widget will help to build a background rectangle
that has hover state to tell user if the column is sortable so
all columns don't need to build that by themself. You can override
this function to build customized widgets as column header.
"""
pass
@abc.abstractmethod
async def build_widget(self, item: StageColumnItem, **kwargs):
"""
Build the widget for the given path. Works inside Frame in async
mode. Once the widget is created, it will replace the content of the
frame. It allow to await something for a while and create the widget
when the result is available.
Args:
item (StageColumnItem): DEPRECATED. It includes the non-cached simple prim
information. It's better to use keyword argument `stage_item` instead, which
provides cached rich information about the prim influened by this column.
Keyword Arguments:
stage_model (StageModel): The instance of current StageModel.
stage_item (StageItem): The current StageItem to build. It's possible that
stage_item is None when TreeView enabled display of root node.
"""
pass
def on_header_hovered(self, hovered: bool):
"""Callback when header area is hovered."""
pass
def on_stage_items_destroyed(self, items: List[StageItem]):
"""
Called when stage items are destroyed to give opportunity to delegate to release
corresponding resources.
"""
pass
@property
def sortable(self):
"""
Whether this column is sortable or not. When it's True, stage widget will build header
widget with hover and selection state to tell user it's sortable. This is only used
to instruct user that this column is sortable from UX.
"""
return False
@property
def order(self):
"""
The order to sort columns. The columns are sorted in ascending order from left to right of the stage widget.
So the smaller the order is, the closer the column is to the left of the stage widget.
"""
return 0
| 4,398 | Python | 30.647482 | 116 | 0.649613 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_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__ = ["StageDelegate"]
from .abstract_stage_column_delegate import AbstractStageColumnDelegate
from .abstract_stage_column_delegate import StageColumnItem
from .delegates import NameColumnDelegate
from .context_menu import ContextMenu
from .stage_icons import StageIcons
from .stage_model import StageItem
from typing import List
from functools import partial
import asyncio
import inspect
import weakref
import omni.ui as ui
class AwaitWithFrame:
"""
A future-like object that runs the given future and makes sure it's
always in the given frame's scope. It allows creating widgets
asynchronously.
"""
def __init__(self, frame: ui.Frame, future: asyncio.Future):
self._frame = frame
self._future = future
def __await__(self):
# create an iterator object from that iterable
iter_obj = iter(self._future.__await__())
# infinite loop
while True:
try:
with self._frame:
yield next(iter_obj)
except StopIteration:
break
self._frame = None
self._future = None
class ContextMenuEvent:
"""The object comatible with ContextMenu"""
def __init__(self, stage: "pxr.Usd.Stage", path_string, expanded=None):
self.type = 0
self.payload = {"stage": stage, "prim_path": path_string, "node_open": expanded}
class ContextMenuHandler:
"""The object that the ContextMenu calls to expand the item"""
def __init__(self):
self._expand_fn = None
self._collapse_fn = None
@property
def expand_fn(self):
return self._expand_fn
@expand_fn.setter
def expand_fn(self, value):
self._expand_fn = value
@property
def collapse_fn(self):
return self._collapse_fn
@collapse_fn.setter
def collapse_fn(self, value):
self._collapse_fn = value
def _expand(self, path):
if self._expand_fn:
self._expand_fn(path)
def _collapse(self, path):
if self._collapse_fn:
self._collapse_fn(path)
def context_menu_handler(self, cmd, prim_path):
if cmd == "opentree":
self._expand(prim_path)
elif cmd == "closetree":
self._collapse(prim_path)
class StageDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._context_menu = ContextMenu()
self._context_menu._stage_win = ContextMenuHandler()
self._column_delegates: List[AbstractStageColumnDelegate] = []
self._header_layout = None
self._header_layout_is_hovered = False
self._mouse_pressed_task = None
self._on_stage_items_destroyed_sub = None
self._name_column_delegate = None
@property
def model(self):
return self._stage_model
@model.setter
def model(self, value):
if self._on_stage_items_destroyed_sub:
self._on_stage_items_destroyed_sub.destroy()
self._on_stage_items_destroyed_sub = None
self._stage_model = value
if self._stage_model:
self._on_stage_items_destroyed_sub = self._stage_model.subscribe_stage_items_destroyed(
self.__on_stage_items_destroyed
)
def __on_stage_items_destroyed(self, items: List[StageItem]):
for delegate in self._column_delegates:
delegate.on_stage_items_destroyed(items)
@property
def expand_fn(self):
return self._context_menu._stage_win.expand_fn
@expand_fn.setter
def expand_fn(self, value):
self._context_menu._stage_win.expand_fn = value
@property
def collapse_fn(self):
return self._context_menu._stage_win.collapse_fn
@collapse_fn.setter
def collapse_fn(self, value):
self._context_menu._stage_win.collapse_fn = value
def destroy(self):
if self._on_stage_items_destroyed_sub:
self._on_stage_items_destroyed_sub.destroy()
self._on_stage_items_destroyed_sub = None
self._stage_model = None
self._context_menu.function_list.pop("rename_item", None)
self._context_menu.destroy()
self._context_menu = None
self._name_column_delegate = None
for d in self._column_delegates:
d.destroy()
self._column_delegates = []
if self._header_layout:
self._header_layout.set_mouse_hovered_fn(None)
self._header_layout = None
if self._mouse_pressed_task:
self._mouse_pressed_task.cancel()
self._mouse_pressed_task = None
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=20 * (level + 1), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.Image(
StageIcons().get(image_name), width=10, height=10, style_type_name_override="TreeView.Item"
)
ui.Spacer(width=5)
def on_mouse_pressed(self, button, stage: "pxr.Usd.Stage", item, expanded):
"""Called when the user press the mouse button on the item"""
if button != 1:
return
async def show_context_menu(stage: "pxr.Usd.Stage", item, expanded):
import omni.kit.app
await omni.kit.app.get_app().next_update_async()
# menu is for context menu only but don't check in on_mouse_pressed func as it can be out of date
# check layout_is_hovered here to make sure its updated for current mouse position
if self._header_layout_is_hovered:
return
# Form the event
path = item.path if item else None
event = ContextMenuEvent(stage, path, expanded)
# Show the menu
self._context_menu.on_mouse_event(event)
self._mouse_pressed_task = None
# this function can get called multiple times sometimes with different item values
if self._mouse_pressed_task:
self._mouse_pressed_task.cancel()
self._mouse_pressed_task = None
self._mouse_pressed_task = asyncio.ensure_future(show_context_menu(stage, item, expanded))
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if column_id >= len(self._column_delegates):
return
if item:
column_item = StageColumnItem(item.path, model.stage, not item.instance_proxy, expanded)
else:
column_item = None
stage = model.stage
frame = ui.Frame(mouse_pressed_fn=lambda x, y, b, _: self.on_mouse_pressed(b, stage, item, expanded))
# Name column needs special treatment to build frame synchronously so all items will not be built
# in the same line.
if self._name_column_delegate and self._name_column_delegate == self._column_delegates[column_id]:
with frame:
self._name_column_delegate.build_widget_sync(column_item, stage_item=item, stage_model=model)
else:
# This is for back compatibility of old interface.
build_widget_func = self._column_delegates[column_id].build_widget
argspec = inspect.getfullargspec(build_widget_func)
if not argspec.varkw:
future = build_widget_func(column_item)
else:
future = build_widget_func(column_item, stage_item=item, stage_model=model)
asyncio.ensure_future(AwaitWithFrame(frame, future))
def __on_header_hovered(self, hovered):
self._header_layout_is_hovered = hovered
def build_header(self, column_id):
if column_id >= len(self._column_delegates):
return
self._header_layout = ui.ZStack()
self._header_layout.set_mouse_hovered_fn(self.__on_header_hovered)
with self._header_layout:
column_delegate = self._column_delegates[column_id]
if column_delegate.sortable:
def on_drop_down_hovered(weakref_delegate, hovered):
if not weakref_delegate():
return
weakref_delegate().on_header_hovered(hovered)
hovered_area = ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header")
weakref_delegate = weakref.ref(column_delegate)
hovered_area.set_mouse_hovered_fn(partial(on_drop_down_hovered, weakref_delegate))
build_header_func = column_delegate.build_header
argspec = inspect.getfullargspec(build_header_func)
# This is for back compatibility of old interface.
if not argspec.varkw:
build_header_func()
else:
build_header_func(stage_model=self.model)
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 self._name_column_delegate:
self._name_column_delegate.set_highlighting(enable, text)
def set_column_delegates(self, delegates):
"""Add custom columns"""
self._name_column_delegate = None
for d in self._column_delegates:
d.destroy()
self._column_delegates = delegates
self._context_menu.function_list.pop("rename_item", None)
def rename_item(prim_path):
if not self.model:
return
item = self.model.find(prim_path)
if not item:
return
self._name_column_delegate.rename_item(item)
for delegate in delegates:
if isinstance(delegate, NameColumnDelegate):
self._name_column_delegate = delegate
self._context_menu.function_list["rename_item"] = rename_item
break
def get_name_column_delegate(self):
return self._name_column_delegate
| 10,721 | Python | 34.269737 | 119 | 0.611603 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/event.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.
#
class Event(list):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in self:
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({list.__repr__(self)})"
class EventSubscription:
"""
Event subscription.
Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.append(self._fn)
def destroy(self):
if self._fn in self._event:
self._event.remove(self._fn)
def __del__(self):
"""Called by GC."""
self.destroy()
| 1,526 | Python | 27.81132 | 76 | 0.625164 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_style.py | import omni.ui as ui
class Styles:
ITEM_DARK = None
ITEM_GRAY = None
ITEM_HOVER = None
ITEM_SEL = None
ITEM_BG_SEL = None
ICON_DARK = None
STAGE_WIDGET = None
@staticmethod
def on_startup():
from .stage_icons import StageIcons as Icons
# List Items
Styles.ITEM_DARK = 0x7723211F
Styles.ITEM_GRAY = 0xFF8A8777
Styles.ITEM_HOVER = 0xFFBBBAAA
Styles.ITEM_SEL = 0xFFDDDCCC
Styles.ITEM_BG_SEL = 0x66888777
Styles.LIVE_GREEN = 0xFF00B86B
Styles.LIVE_SEL = 0xFF00F86E
Styles.RELOAD_ORANGE = 0xFF0088CC
Styles.RELOAD_SEL = 0xFF00AAFF
Styles.STAGE_WIDGET = {
"Button.Image::filter": {"image_url": Icons().get("filter"), "color": 0xFF8A8777},
"Button.Image::options": {"image_url": Icons().get("options"), "color": 0xFF8A8777},
"Button.Image::visibility": {"image_url": Icons().get("eye_on"), "color": 0xFF8A8777},
"Button.Image::visibility:checked": {"image_url": Icons().get("eye_off"), "color": 0x88DDDCCC},
"Button.Image::visibility:disabled": {"color": 0x608A8777},
"Button.Image::visibility:selected": {"color": 0xFFCCCCCC},
"Button::filter": {"background_color": 0x0, "margin": 0},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button::visibility": {"background_color": 0x0, "margin": 0, "margin_width": 1},
"Button::visibility:checked": {"background_color": 0x0},
"Button::visibility:hovered": {"background_color": 0x0},
"Button::visibility:pressed": {"background_color": 0x0},
"Label::search": {"color": 0xFF808080, "margin_width": 4},
"Menu.CheckBox": {"background_color": 0x0, "margin": 0},
"Menu.CheckBox::drag": {
"image_url": Icons().get("drag"),
"color": 0xFF505050,
"alignment": ui.Alignment.CENTER,
},
"Menu.CheckBox.Image": {"image_url": Icons().get("check_off"), "color": 0xFF8A8777},
"Menu.CheckBox.Image:checked": {"image_url": Icons().get("check_on"), "color": 0x34C7FFFF},
"TreeView": {
"background_color": 0xFF23211F,
"background_selected_color": 0x664F4D43,
"secondary_color": 0xFF403B3B,
"border_width": 1.5,
},
"TreeView.ScrollingFrame": {"background_color": 0xFF23211F},
"TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF},
"TreeView.Image:disabled": {"color": 0x60FFFFFF},
"TreeView.Item": {"color": Styles.ITEM_GRAY},
"TreeView.Item:disabled": {"color": 0x608A8777},
"TreeView.Item::object_name_grey": {"color": 0xFF4D4B42},
"TreeView.Item::object_name_missing": {"color": 0xFF6F72FF},
"TreeView.Item::object_name_missing:hovered": {"color": 0xFF6F72FF},
"TreeView.Item::object_name_missing:selected": {"color": 0xFF6F72FF},
"TreeView.Item:hovered": {"color": Styles.ITEM_HOVER},
"TreeView.Item:selected": {"color": Styles.ITEM_SEL},
"TreeView.Item.Outdated": {"color": Styles.RELOAD_ORANGE},
"TreeView.Item.Outdated:hovered": {"color": Styles.RELOAD_SEL},
"TreeView.Item.Outdated:selected": {"color": Styles.RELOAD_SEL},
"TreeView.Item.Live": {"color": Styles.LIVE_GREEN},
"TreeView.Item.Live:hovered": {"color": Styles.LIVE_SEL},
"TreeView.Item.Live:selected": {"color": Styles.LIVE_SEL},
"TreeView:selected": {"background_color": Styles.ITEM_BG_SEL},
"TreeView:drop": {
"background_color": ui.color.shade(ui.color("#34C7FF3B")),
"background_selected_color": ui.color.shade(ui.color("#34C7FF3B")),
"border_color": ui.color.shade(ui.color("#2B87AA")),
},
# Top of the column section (that has sorting options)
"TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 12},
"TreeView.Header::visibility_header": {"image_url": Icons().get("eye_header"), "color": 0xFF888888},
"TreeView.Header::drop_down_background": {"background_color": 0xE0808080},
"TreeView.Header::drop_down_button": {"background_color": ui.color.white},
"TreeView.Header::drop_down_hovered_area": {"background_color": ui.color.transparent},
"TreeView.Header::hovering": {"background_color": 0x0, "border_radius": 1.5},
"TreeView.Header::hovering:hovered": {
"background_color": ui.color.shade(ui.color("#34C7FF3B")),
"border_width": 1.5,
"border_color": ui.color.shade(ui.color("#2B87AA"))
}
}
| 4,877 | Python | 50.347368 | 112 | 0.573098 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/selection_watch.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DefaultSelectionWatch"]
from pxr import Sdf, Trace
import omni.usd
from typing import Optional
class DefaultSelectionWatch(object):
"""
The object that update selection in TreeView when the scene selection is
changed and updated scene selection when TreeView selection is changed.
"""
def __init__(self, tree_view=None, usd_context=None):
self._usd_context = usd_context or omni.usd.get_context()
self._selection = None
self._in_selection = False
self._tree_view = None
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Stage Window Selection Update"
)
self.set_tree_view(tree_view)
self.__filter_string: Optional[str] = None
# When True, SelectionWatch should consider filtering
self.__filter_checking: bool = False
def destroy(self):
self._usd_context = None
self._selection = None
self._stage_event_sub = None
self._events = None
if self._tree_view:
self._tree_view.set_selection_changed_fn(None)
self._tree_view = None
def set_tree_view(self, tree_view):
"""Replace TreeView that should show the selection"""
if self._tree_view != tree_view:
if self._tree_view:
self._tree_view.set_selection_changed_fn(None)
self._tree_view = tree_view
self._tree_view.set_selection_changed_fn(self._on_widget_selection_changed)
self._last_selected_prim_paths = None
self._on_kit_selection_changed()
def set_filtering(self, filter_string: Optional[str]):
if filter_string:
self.__filter_string = filter_string.lower()
else:
self.__filter_string = filter_string
def enable_filtering_checking(self, enable: bool):
"""
When `enable` is True, SelectionWatch should consider filtering when
changing Kit's selection.
"""
self.__filter_checking = enable
def _on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
@Trace.TraceFunction
def _on_kit_selection_changed(self):
"""Send the selection from Kit to TreeView"""
if not self._tree_view or self._in_selection:
return
# Make sure it's a new selection. It happens that omni.usd sends the same selection twice. No sorting because
# the order of selection is important.
prim_paths = self._selection.get_selected_prim_paths()
if prim_paths == self._last_selected_prim_paths:
return
self._last_selected_prim_paths = [Sdf.Path(prim_path) for prim_path in prim_paths]
# Pump the changes to the model because to select something, TreeView should be updated.
self._tree_view.model.update_dirty()
selection = []
for path in prim_paths:
# Get the selected item and its parents. Expand all the parents of the new selection.
full_chain = self._tree_view.model.find_full_chain(path)
# When the new object is created, omni.usd sends the selection is changed before the object appears in the
# stage and it means we can't select it. In this way it's better to return because we don't have the item
# in the model yet.
# TODO: Use UsdNotice to track if the object is created.
if not full_chain or full_chain[-1].path != path:
continue
if full_chain:
for item in full_chain[:-1]:
self._tree_view.set_expanded(item, True, False)
# Save the last item in the chain. It's the selected item
selection.append(full_chain[-1])
# Send all of this to TreeView.
self._in_selection = True
self._tree_view.selection = selection
self._in_selection = False
@Trace.TraceFunction
def _on_widget_selection_changed(self, selection):
"""Send the selection from TreeView to Kit"""
if self._in_selection:
return
prim_paths = [item.path for item in selection if item]
# Filter selection
if self.__filter_string or self.__filter_checking:
# Check if the selected prims are filtered and re-select filtered items only if necessary.
filtered_paths = [item.path for item in selection if item and item.filtered]
if filtered_paths != prim_paths:
filtered_selection = [item for item in selection if item and item.path in filtered_paths]
self._tree_view.selection = filtered_selection
return
if prim_paths == self._last_selected_prim_paths:
return
# Send the selection to Kit
self._in_selection = True
old_paths = [sdf_path.pathString for sdf_path in self._last_selected_prim_paths]
new_paths = [sdf_path.pathString for sdf_path in prim_paths]
omni.kit.commands.execute("SelectPrims", old_selected_paths=old_paths, new_selected_paths=new_paths, expand_in_stage=True)
self._in_selection = False
self._last_selected_prim_paths = prim_paths
| 5,914 | Python | 40.654929 | 130 | 0.636287 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/commands.py | __all__ = ["ReorderPrimCommand"]
import carb
import omni.kit.commands
import omni.usd
from pxr import Usd, Sdf
class ReorderPrimCommand(omni.kit.commands.Command):
"""
Command to reorder prim in its parent. This command uses the support from USD to
override the reorder property, and it will always be authored into the root layer
without considering the edit target.
"""
def __init__(self, stage: Usd.Stage, prim_path: Sdf.Path, move_to_location: int):
"""
Constructor.
Args:
stage (Usd.Stage): USD stage.
prim_path (Sdf.Path): Prim to reorder.
move_to_location (int): Move to the location in its parent. If it's -1, it means to move
the prim to the bottom.
"""
self.__stage = stage
self.__prim_path = Sdf.Path(prim_path)
self.__move_to_location = move_to_location
self.__old_location = -1
self.__success = False
def __move_to(self, location):
if self.__prim_path == Sdf.Path.emptyPath or self.__prim_path == Sdf.Path.absoluteRootPath:
carb.log_warn("Failed to reorder prim as empty path or absolute root path is not supported.")
return False
prim = self.__stage.GetPrimAtPath(self.__prim_path)
if not prim:
carb.log_error(f"Failed to reorder prim {self.__prim_path} as prim is not found in the stage.")
return False
parent_path = self.__prim_path.GetParentPath()
parent_prim = self.__stage.GetPrimAtPath(parent_path)
if not parent_prim:
return
all_children = parent_prim.GetAllChildrenNames()
total_children = len(all_children)
name = self.__prim_path.name
if name in all_children:
index = all_children.index(name)
self.__old_location = index
all_children.remove(name)
else:
index = -1
if index == location:
return
if location < 0 or location > total_children:
location = -1
elif location > index and index != -1:
# If it's to move from up to down.
location -= 1
all_children.insert(location, name)
# Use Sdf API so it can be batched.
parent_prim_spec = Sdf.CreatePrimInLayer(self.__stage.GetRootLayer(), parent_path)
parent_prim_spec.nameChildrenOrder = all_children
self.__success = True
return True
def do(self):
with Usd.EditContext(self.__stage, self.__stage.GetRootLayer()):
return self.__move_to(self.__move_to_location)
def undo(self):
if self.__success:
with Usd.EditContext(self.__stage, self.__stage.GetRootLayer()):
self.__move_to(self.__old_location)
self.__success = False
| 2,855 | Python | 32.209302 | 107 | 0.592294 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_icons.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__ = ["StageIcons"]
import omni.kit.app
from .singleton import Singleton
from pathlib import Path
from typing import Union
ICON_FOLDER_PATH = Path(
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/icons"
)
@Singleton
class StageIcons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
class _Event(list):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in self:
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({list.__repr__(self)})"
class _EventSubscription:
"""
Event subscription.
_Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.append(self._fn)
def __del__(self):
"""Called by GC."""
self._event.remove(self._fn)
def __init__(self):
self._on_icons_changed = self._Event()
# Read all the svg files in the directory
self._icons = {icon.stem: str(icon) for icon in ICON_FOLDER_PATH.glob("*.svg")}
def set(self, prim_type: str, icon_path: Union[str, Path]):
"""Set the new icon path for a specific prim type"""
if icon_path is None:
# Remove the icon
if prim_type in self._icons:
del self._icons[prim_type]
else:
self._icons[prim_type] = str(icon_path)
self._on_icons_changed()
def get(self, prim_type: str, default: Union[str, Path] = None) -> str:
"""Checks the icon cache and returns the icon if exists"""
found = self._icons.get(prim_type)
if not found and default:
found = self._icons.get(default)
if found:
return found
return ""
def subscribe_icons_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self._on_icons_changed, fn)
| 3,070 | Python | 30.336734 | 100 | 0.595765 |
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.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.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.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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.