file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnDistance3DDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.Distance3D
Computes the distance between two 3D points A and B. Which is the length of the vector with start and end points A and B
If one input is an array and the other is a single point, the scaler will be broadcast to the size of the array
"""
from typing import Any
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnDistance3DDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.Distance3D
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
Outputs:
outputs.distance
"""
# 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:a', 'pointd[3],pointd[3][],pointf[3],pointf[3][],pointh[3],pointh[3][]', 1, 'A', 'Vector A', {}, True, None, False, ''),
('inputs:b', 'pointd[3],pointd[3][],pointf[3],pointf[3][],pointh[3],pointh[3][]', 1, 'B', 'Vector B', {}, True, None, False, ''),
('outputs:distance', 'double,double[],float,float[],half,half[]', 1, None, 'The distance between the input vectors', {}, 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 a(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.a"""
return og.RuntimeAttribute(self._attributes.a.get_attribute_data(), self._context, True)
@a.setter
def a(self, value_to_set: Any):
"""Assign another attribute's value to outputs.a"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.a.value = value_to_set.value
else:
self.a.value = value_to_set
@property
def b(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.b"""
return og.RuntimeAttribute(self._attributes.b.get_attribute_data(), self._context, True)
@b.setter
def b(self, value_to_set: Any):
"""Assign another attribute's value to outputs.b"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.b.value = value_to_set.value
else:
self.b.value = value_to_set
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 distance(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.distance"""
return og.RuntimeAttribute(self._attributes.distance.get_attribute_data(), self._context, False)
@distance.setter
def distance(self, value_to_set: Any):
"""Assign another attribute's value to outputs.distance"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.distance.value = value_to_set.value
else:
self.distance.value = value_to_set
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 = OgnDistance3DDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnDistance3DDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnDistance3DDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,358 | Python | 47.915384 | 152 | 0.654294 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnCurveFrameDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.CurveToFrame
Create a frame object based on a curve description
"""
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 OgnCurveFrameDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.CurveToFrame
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.curvePoints
inputs.curveVertexCounts
inputs.curveVertexStarts
Outputs:
outputs.out
outputs.tangent
outputs.up
"""
# 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:curvePoints', 'float3[]', 0, 'Curve Points', 'Points on the curve to be framed', {}, True, [], False, ''),
('inputs:curveVertexCounts', 'int[]', 0, 'Curve Vertex Counts', 'Vertex counts for the curve points', {}, True, [], False, ''),
('inputs:curveVertexStarts', 'int[]', 0, 'Curve Vertex Starts', 'Vertex starting points', {}, True, [], False, ''),
('outputs:out', 'float3[]', 0, 'Out Vectors', 'Out vector directions on the curve frame', {}, True, None, False, ''),
('outputs:tangent', 'float3[]', 0, 'Tangents', 'Tangents on the curve frame', {}, True, None, False, ''),
('outputs:up', 'float3[]', 0, 'Up Vectors', 'Up vectors on the curve frame', {}, 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 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 curveVertexCounts(self):
data_view = og.AttributeValueHelper(self._attributes.curveVertexCounts)
return data_view.get()
@curveVertexCounts.setter
def curveVertexCounts(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.curveVertexCounts)
data_view = og.AttributeValueHelper(self._attributes.curveVertexCounts)
data_view.set(value)
self.curveVertexCounts_size = data_view.get_array_size()
@property
def curveVertexStarts(self):
data_view = og.AttributeValueHelper(self._attributes.curveVertexStarts)
return data_view.get()
@curveVertexStarts.setter
def curveVertexStarts(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.curveVertexStarts)
data_view = og.AttributeValueHelper(self._attributes.curveVertexStarts)
data_view.set(value)
self.curveVertexStarts_size = data_view.get_array_size()
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.out_size = None
self.tangent_size = None
self.up_size = None
self._batchedWriteValues = { }
@property
def out(self):
data_view = og.AttributeValueHelper(self._attributes.out)
return data_view.get(reserved_element_count=self.out_size)
@out.setter
def out(self, value):
data_view = og.AttributeValueHelper(self._attributes.out)
data_view.set(value)
self.out_size = data_view.get_array_size()
@property
def tangent(self):
data_view = og.AttributeValueHelper(self._attributes.tangent)
return data_view.get(reserved_element_count=self.tangent_size)
@tangent.setter
def tangent(self, value):
data_view = og.AttributeValueHelper(self._attributes.tangent)
data_view.set(value)
self.tangent_size = data_view.get_array_size()
@property
def up(self):
data_view = og.AttributeValueHelper(self._attributes.up)
return data_view.get(reserved_element_count=self.up_size)
@up.setter
def up(self, value):
data_view = og.AttributeValueHelper(self._attributes.up)
data_view.set(value)
self.up_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 = OgnCurveFrameDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnCurveFrameDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnCurveFrameDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,832 | Python | 44.807017 | 135 | 0.648238 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnCurveTubeSTDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.CurveTubeST
Compute curve tube ST values
"""
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 OgnCurveTubeSTDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.CurveTubeST
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cols
inputs.curveVertexCounts
inputs.curveVertexStarts
inputs.scaleTLikeS
inputs.t
inputs.tubeQuadStarts
inputs.tubeSTStarts
inputs.width
Outputs:
outputs.primvars_st
outputs.primvars_st_indices
"""
# 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:cols', 'int[]', 0, 'Columns', 'Columns of the tubes', {}, True, [], False, ''),
('inputs:curveVertexCounts', 'int[]', 0, 'Curve Vertex Counts', 'Vertex counts for the curve points', {}, True, [], False, ''),
('inputs:curveVertexStarts', 'int[]', 0, 'Curve Vertex Starts', 'Vertex starting points', {}, True, [], False, ''),
('inputs:scaleTLikeS', 'bool', 0, 'Scale T Like S', 'If true then scale T the same as S', {}, True, False, False, ''),
('inputs:t', 'float[]', 0, 'T Values', 'T values of the tubes', {}, True, [], False, ''),
('inputs:tubeQuadStarts', 'int[]', 0, 'Tube Quad Starts', 'Vertex index values for the tube quad starting points', {}, True, [], False, ''),
('inputs:tubeSTStarts', 'int[]', 0, 'Tube ST Starts', 'Vertex index values for the tube ST starting points', {}, True, [], False, ''),
('inputs:width', 'float[]', 0, 'Tube Widths', 'Width of tube positions, if scaling T like S', {}, True, [], False, ''),
('outputs:primvars:st', 'float2[]', 0, 'ST Values', 'Array of computed ST values', {}, True, None, False, ''),
('outputs:primvars:st:indices', 'int[]', 0, 'ST Indices', 'Array of computed ST indices', {}, 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 cols(self):
data_view = og.AttributeValueHelper(self._attributes.cols)
return data_view.get()
@cols.setter
def cols(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.cols)
data_view = og.AttributeValueHelper(self._attributes.cols)
data_view.set(value)
self.cols_size = data_view.get_array_size()
@property
def curveVertexCounts(self):
data_view = og.AttributeValueHelper(self._attributes.curveVertexCounts)
return data_view.get()
@curveVertexCounts.setter
def curveVertexCounts(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.curveVertexCounts)
data_view = og.AttributeValueHelper(self._attributes.curveVertexCounts)
data_view.set(value)
self.curveVertexCounts_size = data_view.get_array_size()
@property
def curveVertexStarts(self):
data_view = og.AttributeValueHelper(self._attributes.curveVertexStarts)
return data_view.get()
@curveVertexStarts.setter
def curveVertexStarts(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.curveVertexStarts)
data_view = og.AttributeValueHelper(self._attributes.curveVertexStarts)
data_view.set(value)
self.curveVertexStarts_size = data_view.get_array_size()
@property
def scaleTLikeS(self):
data_view = og.AttributeValueHelper(self._attributes.scaleTLikeS)
return data_view.get()
@scaleTLikeS.setter
def scaleTLikeS(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.scaleTLikeS)
data_view = og.AttributeValueHelper(self._attributes.scaleTLikeS)
data_view.set(value)
@property
def t(self):
data_view = og.AttributeValueHelper(self._attributes.t)
return data_view.get()
@t.setter
def t(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.t)
data_view = og.AttributeValueHelper(self._attributes.t)
data_view.set(value)
self.t_size = data_view.get_array_size()
@property
def tubeQuadStarts(self):
data_view = og.AttributeValueHelper(self._attributes.tubeQuadStarts)
return data_view.get()
@tubeQuadStarts.setter
def tubeQuadStarts(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.tubeQuadStarts)
data_view = og.AttributeValueHelper(self._attributes.tubeQuadStarts)
data_view.set(value)
self.tubeQuadStarts_size = data_view.get_array_size()
@property
def tubeSTStarts(self):
data_view = og.AttributeValueHelper(self._attributes.tubeSTStarts)
return data_view.get()
@tubeSTStarts.setter
def tubeSTStarts(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.tubeSTStarts)
data_view = og.AttributeValueHelper(self._attributes.tubeSTStarts)
data_view.set(value)
self.tubeSTStarts_size = data_view.get_array_size()
@property
def width(self):
data_view = og.AttributeValueHelper(self._attributes.width)
return data_view.get()
@width.setter
def width(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.width)
data_view = og.AttributeValueHelper(self._attributes.width)
data_view.set(value)
self.width_size = data_view.get_array_size()
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.primvars_st_size = None
self.primvars_st_indices_size = None
self._batchedWriteValues = { }
@property
def primvars_st(self):
data_view = og.AttributeValueHelper(self._attributes.primvars_st)
return data_view.get(reserved_element_count=self.primvars_st_size)
@primvars_st.setter
def primvars_st(self, value):
data_view = og.AttributeValueHelper(self._attributes.primvars_st)
data_view.set(value)
self.primvars_st_size = data_view.get_array_size()
@property
def primvars_st_indices(self):
data_view = og.AttributeValueHelper(self._attributes.primvars_st_indices)
return data_view.get(reserved_element_count=self.primvars_st_indices_size)
@primvars_st_indices.setter
def primvars_st_indices(self, value):
data_view = og.AttributeValueHelper(self._attributes.primvars_st_indices)
data_view.set(value)
self.primvars_st_indices_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 = OgnCurveTubeSTDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnCurveTubeSTDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnCurveTubeSTDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,552 | Python | 44.683982 | 148 | 0.635614 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimMaterialDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrimMaterial
Given a path to a prim on the current USD stage, outputs the material of the prim. Gives an error if the given prim can
not be found.
"""
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 OgnReadPrimMaterialDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrimMaterial
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.prim
inputs.primPath
Outputs:
outputs.material
outputs.materialPrim
"""
# 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:prim', 'target', 0, None, 'The prim with the material to be read. If both this and primPath inputs are set, this input takes priority.', {}, True, [], False, ''),
('inputs:primPath', 'path', 0, 'Prim Path', 'Path of the prim with the material to be read.', {}, True, "", True, 'Use prim input instead'),
('outputs:material', 'path', 0, 'Material Path', 'The material of the input prim', {}, True, None, True, 'Use materialPrim output instead'),
('outputs:materialPrim', 'target', 0, 'Material', 'The prim containing the material of the input prim', {}, True, [], 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.prim = og.AttributeRole.TARGET
role_data.inputs.primPath = og.AttributeRole.PATH
role_data.outputs.material = og.AttributeRole.PATH
role_data.outputs.materialPrim = og.AttributeRole.TARGET
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 prim(self):
data_view = og.AttributeValueHelper(self._attributes.prim)
return data_view.get()
@prim.setter
def prim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prim)
data_view = og.AttributeValueHelper(self._attributes.prim)
data_view.set(value)
self.prim_size = data_view.get_array_size()
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primPath)
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
self.primPath_size = data_view.get_array_size()
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.material_size = None
self.materialPrim_size = None
self._batchedWriteValues = { }
@property
def material(self):
data_view = og.AttributeValueHelper(self._attributes.material)
return data_view.get(reserved_element_count=self.material_size)
@material.setter
def material(self, value):
data_view = og.AttributeValueHelper(self._attributes.material)
data_view.set(value)
self.material_size = data_view.get_array_size()
@property
def materialPrim(self):
data_view = og.AttributeValueHelper(self._attributes.materialPrim)
return data_view.get(reserved_element_count=self.materialPrim_size)
@materialPrim.setter
def materialPrim(self, value):
data_view = og.AttributeValueHelper(self._attributes.materialPrim)
data_view.set(value)
self.materialPrim_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 = OgnReadPrimMaterialDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnReadPrimMaterialDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnReadPrimMaterialDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,213 | Python | 46.150326 | 179 | 0.661722 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGetLocationAtDistanceOnCurve2Database.py | """Support for simplified access to data on nodes of type omni.graph.nodes.GetLocationAtDistanceOnCurve2
Given a set of curve points and a normalized distance between 0-1.0, return the location on a closed curve. 0 is the first
point on the curve, 1.0 is also the first point because the is an implicit segment connecting the first and last points.
Values outside the range 0-1.0 will be wrapped to that range, for example -0.4 is equivalent to 0.6 and 1.3 is equivalent
to 0.3 This is a simplistic curve-following node, intended for curves in a plane, for prototyping purposes.
"""
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 OgnGetLocationAtDistanceOnCurve2Database(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.GetLocationAtDistanceOnCurve2
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.curve
inputs.distance
inputs.forwardAxis
inputs.upAxis
Outputs:
outputs.location
outputs.orientation
outputs.rotateXYZ
Predefined Tokens:
tokens.x
tokens.y
tokens.z
tokens.X
tokens.Y
tokens.Z
"""
# 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:curve', 'point3d[]', 0, 'Curve', 'The curve to be examined', {}, True, [], False, ''),
('inputs:distance', 'double', 0, 'Distance', 'The distance along the curve, wrapped to the range 0-1.0', {}, True, 0.0, False, ''),
('inputs:forwardAxis', 'token', 0, 'Forward', 'The direction vector from which the returned rotation is relative, one of X, Y, Z', {ogn.MetadataKeys.DEFAULT: '"X"'}, True, "X", False, ''),
('inputs:upAxis', 'token', 0, 'Up', 'The world Up vector, the curve should be in a plane perpendicular with this - one of X, Y, Z', {ogn.MetadataKeys.DEFAULT: '"Y"'}, True, "Y", False, ''),
('outputs:location', 'point3d', 0, 'Location on curve at the given distance in world space', 'Location', {}, True, None, False, ''),
('outputs:orientation', 'quatf', 0, 'World space orientation of the curve at the given distance, may not be smooth for some curves', 'Orientation', {}, True, None, False, ''),
('outputs:rotateXYZ', 'vector3d', 0, 'World space rotation of the curve at the given distance, may not be smooth for some curves', 'Rotations', {}, True, None, False, ''),
])
class tokens:
x = "x"
y = "y"
z = "z"
X = "X"
Y = "Y"
Z = "Z"
@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.curve = og.AttributeRole.POSITION
role_data.outputs.location = og.AttributeRole.POSITION
role_data.outputs.orientation = og.AttributeRole.QUATERNION
role_data.outputs.rotateXYZ = og.AttributeRole.VECTOR
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 curve(self):
data_view = og.AttributeValueHelper(self._attributes.curve)
return data_view.get()
@curve.setter
def curve(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.curve)
data_view = og.AttributeValueHelper(self._attributes.curve)
data_view.set(value)
self.curve_size = data_view.get_array_size()
@property
def distance(self):
data_view = og.AttributeValueHelper(self._attributes.distance)
return data_view.get()
@distance.setter
def distance(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.distance)
data_view = og.AttributeValueHelper(self._attributes.distance)
data_view.set(value)
@property
def forwardAxis(self):
data_view = og.AttributeValueHelper(self._attributes.forwardAxis)
return data_view.get()
@forwardAxis.setter
def forwardAxis(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.forwardAxis)
data_view = og.AttributeValueHelper(self._attributes.forwardAxis)
data_view.set(value)
@property
def upAxis(self):
data_view = og.AttributeValueHelper(self._attributes.upAxis)
return data_view.get()
@upAxis.setter
def upAxis(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.upAxis)
data_view = og.AttributeValueHelper(self._attributes.upAxis)
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 location(self):
data_view = og.AttributeValueHelper(self._attributes.location)
return data_view.get()
@location.setter
def location(self, value):
data_view = og.AttributeValueHelper(self._attributes.location)
data_view.set(value)
@property
def orientation(self):
data_view = og.AttributeValueHelper(self._attributes.orientation)
return data_view.get()
@orientation.setter
def orientation(self, value):
data_view = og.AttributeValueHelper(self._attributes.orientation)
data_view.set(value)
@property
def rotateXYZ(self):
data_view = og.AttributeValueHelper(self._attributes.rotateXYZ)
return data_view.get()
@rotateXYZ.setter
def rotateXYZ(self, value):
data_view = og.AttributeValueHelper(self._attributes.rotateXYZ)
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 = OgnGetLocationAtDistanceOnCurve2Database.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnGetLocationAtDistanceOnCurve2Database.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnGetLocationAtDistanceOnCurve2Database.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 9,345 | Python | 44.368932 | 197 | 0.650187 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnRenameAttrDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.RenameAttribute
Changes the names of attributes from an input bundle for the corresponding output bundle. Attributes whose names are not
in the 'inputAttrNames' list will be copied from the input bundle to the output bundle without changing the name.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnRenameAttrDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.RenameAttribute
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.data
inputs.inputAttrNames
inputs.outputAttrNames
Outputs:
outputs.data
"""
# 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:data', 'bundle', 0, 'Original Attribute Bundle', 'Collection of attributes to be renamed', {}, True, None, False, ''),
('inputs:inputAttrNames', 'token', 0, 'Attributes To Rename', 'Comma or space separated text, listing the names of attributes in the input data to be renamed', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:outputAttrNames', 'token', 0, 'New Attribute Names', 'Comma or space separated text, listing the new names for the attributes listed in inputAttrNames', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('outputs:data', 'bundle', 0, 'Bundle Of Renamed Attributes', 'Final bundle of attributes, with attributes renamed based on inputAttrNames and outputAttrNames', {}, 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.data = og.AttributeRole.BUNDLE
role_data.outputs.data = og.AttributeRole.BUNDLE
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def data(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.data"""
return self.__bundles.data
@property
def inputAttrNames(self):
data_view = og.AttributeValueHelper(self._attributes.inputAttrNames)
return data_view.get()
@inputAttrNames.setter
def inputAttrNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.inputAttrNames)
data_view = og.AttributeValueHelper(self._attributes.inputAttrNames)
data_view.set(value)
@property
def outputAttrNames(self):
data_view = og.AttributeValueHelper(self._attributes.outputAttrNames)
return data_view.get()
@outputAttrNames.setter
def outputAttrNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.outputAttrNames)
data_view = og.AttributeValueHelper(self._attributes.outputAttrNames)
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def data(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.data"""
return self.__bundles.data
@data.setter
def data(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.data with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.data.bundle = bundle
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 = OgnRenameAttrDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnRenameAttrDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnRenameAttrDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,301 | Python | 49.708333 | 225 | 0.672374 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnDeformedPointsToHydraDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.DeformedPointsToHydra
Copy deformed points into rpresource and send to hydra
"""
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 OgnDeformedPointsToHydraDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.DeformedPointsToHydra
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.points
inputs.primPath
inputs.sendToHydra
inputs.stream
inputs.verbose
Outputs:
outputs.reload
"""
# 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:points', 'float3[]', 0, 'Prim Points', 'Points attribute input. Points and a prim path may be supplied directly as an alternative to a bundle input.', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, [], False, ''),
('inputs:primPath', 'token', 0, 'Prim path input', 'Prim path input. Points and a prim path may be supplied directly as an alternative to a bundle input.', {}, True, "", False, ''),
('inputs:sendToHydra', 'bool', 0, 'Send to hydra', 'send to hydra', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:stream', 'uint64', 0, 'stream', 'Pointer to the CUDA Stream', {}, True, 0, False, ''),
('inputs:verbose', 'bool', 0, 'Verbose', 'verbose printing', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('outputs:reload', 'bool', 0, 'Reload', 'Force RpResource reload', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, 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 points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
return data_view.get(on_gpu=True)
@points.setter
def points(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.points)
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.gpu_ptr_kind = og.PtrToPtrKind.CPU
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primPath)
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
@property
def sendToHydra(self):
data_view = og.AttributeValueHelper(self._attributes.sendToHydra)
return data_view.get()
@sendToHydra.setter
def sendToHydra(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.sendToHydra)
data_view = og.AttributeValueHelper(self._attributes.sendToHydra)
data_view.set(value)
@property
def stream(self):
data_view = og.AttributeValueHelper(self._attributes.stream)
return data_view.get()
@stream.setter
def stream(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.stream)
data_view = og.AttributeValueHelper(self._attributes.stream)
data_view.set(value)
@property
def verbose(self):
data_view = og.AttributeValueHelper(self._attributes.verbose)
return data_view.get()
@verbose.setter
def verbose(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.verbose)
data_view = og.AttributeValueHelper(self._attributes.verbose)
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 reload(self):
data_view = og.AttributeValueHelper(self._attributes.reload)
return data_view.get()
@reload.setter
def reload(self, value):
data_view = og.AttributeValueHelper(self._attributes.reload)
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 = OgnDeformedPointsToHydraDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnDeformedPointsToHydraDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnDeformedPointsToHydraDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,808 | Python | 45.2071 | 229 | 0.650102 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnTimerDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.Timer
Timer Node is a node that lets you create animation curve(s), plays back and samples the value(s) along its time to output
values.
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTimerDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.Timer
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.duration
inputs.endValue
inputs.play
inputs.startValue
Outputs:
outputs.finished
outputs.updated
outputs.value
"""
# 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:duration', 'double', 0, 'Duration', 'Number of seconds to play interpolation', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:endValue', 'double', 0, 'End Value', 'Value value of the end of the duration', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:play', 'execution', 0, 'Play', 'Play the clip from current frame', {}, True, None, False, ''),
('inputs:startValue', 'double', 0, 'Start Value', 'Value value of the start of the duration', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('outputs:finished', 'execution', 0, 'Finished', 'The Timer node has finished the playback', {}, True, None, False, ''),
('outputs:updated', 'execution', 0, 'Updated', 'The Timer node is ticked, and output value(s) resampled and updated', {}, True, None, False, ''),
('outputs:value', 'double', 0, 'Value', 'Value value of the Timer node between 0.0 and 1.0', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, 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.play = og.AttributeRole.EXECUTION
role_data.outputs.finished = og.AttributeRole.EXECUTION
role_data.outputs.updated = 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 duration(self):
data_view = og.AttributeValueHelper(self._attributes.duration)
return data_view.get()
@duration.setter
def duration(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.duration)
data_view = og.AttributeValueHelper(self._attributes.duration)
data_view.set(value)
@property
def endValue(self):
data_view = og.AttributeValueHelper(self._attributes.endValue)
return data_view.get()
@endValue.setter
def endValue(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.endValue)
data_view = og.AttributeValueHelper(self._attributes.endValue)
data_view.set(value)
@property
def play(self):
data_view = og.AttributeValueHelper(self._attributes.play)
return data_view.get()
@play.setter
def play(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.play)
data_view = og.AttributeValueHelper(self._attributes.play)
data_view.set(value)
@property
def startValue(self):
data_view = og.AttributeValueHelper(self._attributes.startValue)
return data_view.get()
@startValue.setter
def startValue(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.startValue)
data_view = og.AttributeValueHelper(self._attributes.startValue)
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 finished(self):
data_view = og.AttributeValueHelper(self._attributes.finished)
return data_view.get()
@finished.setter
def finished(self, value):
data_view = og.AttributeValueHelper(self._attributes.finished)
data_view.set(value)
@property
def updated(self):
data_view = og.AttributeValueHelper(self._attributes.updated)
return data_view.get()
@updated.setter
def updated(self, value):
data_view = og.AttributeValueHelper(self._attributes.updated)
data_view.set(value)
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
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 = OgnTimerDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTimerDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTimerDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,310 | Python | 43.924324 | 159 | 0.644404 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimsDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrims
DEPRECATED - use ReadPrimsV2!
"""
import numpy
import usdrt
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnReadPrimsDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrims
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.applySkelBinding
inputs.attrNamesToImport
inputs.computeBoundingBox
inputs.pathPattern
inputs.prims
inputs.typePattern
inputs.usdTimecode
inputs.useFindPrims
Outputs:
outputs.primsBundle
State:
state.applySkelBinding
state.attrNamesToImport
state.computeBoundingBox
state.pathPattern
state.primPaths
state.typePattern
state.usdTimecode
state.useFindPrims
"""
# 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:applySkelBinding', 'bool', 0, 'Apply Skel Binding', 'If an input USD prim is skinnable and has the SkelBindingAPI schema applied, read skeletal data and apply SkelBinding to deform the prim.\nThe output bundle will have additional child bundles created to hold data for the skeleton and skel animation prims if present. After\nevaluation, deformed points and normals will be written to the `points` and `normals` attributes, while non-deformed points and normals\nwill be copied to the `points:default` and `normals:default` attributes.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:attrNamesToImport', 'string', 0, 'Attribute Name Pattern', "A list of wildcard patterns used to match the attribute names that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']\n '*' - match any\n '* ^points' - match any, but exclude 'points'\n '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('inputs:computeBoundingBox', 'bool', 0, 'Compute Bounding Box', "For each primitive compute local bounding box and store them as 'bboxMinCorner', 'bboxMaxCorner' and 'bboxTransform' attributes.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:pathPattern', 'string', 0, 'Prim Path Pattern', "A list of wildcard patterns used to match the prim paths that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']\n '*' - match any\n '* ^/Box' - match any, but exclude '/Box'\n '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'", {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:prims', 'target', 0, None, "The prims to be read from when 'useFindPrims' is false", {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, False, [], False, ''),
('inputs:typePattern', 'string', 0, 'Prim Type Pattern', "A list of wildcard patterns used to match the prim types that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']\n '*' - match any\n '* ^Mesh' - match any, but exclude 'Mesh'\n '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('inputs:usdTimecode', 'timecode', 0, 'Time', 'The time at which to evaluate the transform of the USD prim. A value of "NaN" indicates that the default USD time stamp should be used', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''),
('inputs:useFindPrims', 'bool', 0, 'Use Find Prims', "When true, the 'pathPattern' and 'typePattern' attribute is used as the pattern to search for the prims to read\notherwise it will read the connection at the 'prim' attribute.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('outputs:primsBundle', 'bundle', 0, None, 'An output bundle containing multiple prims as children.\nEach child contains data attributes and two additional token attributes named sourcePrimPath and sourcePrimType\nwhich contains the path of the Prim being read', {}, True, None, False, ''),
('state:applySkelBinding', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('state:attrNamesToImport', 'string', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:computeBoundingBox', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('state:pathPattern', 'string', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:primPaths', 'uint64[]', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:typePattern', 'string', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:usdTimecode', 'timecode', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
('state:useFindPrims', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, 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.attrNamesToImport = og.AttributeRole.TEXT
role_data.inputs.pathPattern = og.AttributeRole.TEXT
role_data.inputs.prims = og.AttributeRole.TARGET
role_data.inputs.typePattern = og.AttributeRole.TEXT
role_data.inputs.usdTimecode = og.AttributeRole.TIMECODE
role_data.outputs.primsBundle = og.AttributeRole.BUNDLE
role_data.state.attrNamesToImport = og.AttributeRole.TEXT
role_data.state.pathPattern = og.AttributeRole.TEXT
role_data.state.typePattern = og.AttributeRole.TEXT
role_data.state.usdTimecode = og.AttributeRole.TIMECODE
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 applySkelBinding(self):
data_view = og.AttributeValueHelper(self._attributes.applySkelBinding)
return data_view.get()
@applySkelBinding.setter
def applySkelBinding(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.applySkelBinding)
data_view = og.AttributeValueHelper(self._attributes.applySkelBinding)
data_view.set(value)
@property
def attrNamesToImport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
return data_view.get()
@attrNamesToImport.setter
def attrNamesToImport(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.attrNamesToImport)
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
data_view.set(value)
self.attrNamesToImport_size = data_view.get_array_size()
@property
def computeBoundingBox(self):
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
return data_view.get()
@computeBoundingBox.setter
def computeBoundingBox(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.computeBoundingBox)
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
data_view.set(value)
@property
def pathPattern(self):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
return data_view.get()
@pathPattern.setter
def pathPattern(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.pathPattern)
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
data_view.set(value)
self.pathPattern_size = data_view.get_array_size()
@property
def prims(self):
data_view = og.AttributeValueHelper(self._attributes.prims)
return data_view.get()
@prims.setter
def prims(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prims)
data_view = og.AttributeValueHelper(self._attributes.prims)
data_view.set(value)
self.prims_size = data_view.get_array_size()
@property
def typePattern(self):
data_view = og.AttributeValueHelper(self._attributes.typePattern)
return data_view.get()
@typePattern.setter
def typePattern(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.typePattern)
data_view = og.AttributeValueHelper(self._attributes.typePattern)
data_view.set(value)
self.typePattern_size = data_view.get_array_size()
@property
def usdTimecode(self):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
return data_view.get()
@usdTimecode.setter
def usdTimecode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usdTimecode)
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
data_view.set(value)
@property
def useFindPrims(self):
data_view = og.AttributeValueHelper(self._attributes.useFindPrims)
return data_view.get()
@useFindPrims.setter
def useFindPrims(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.useFindPrims)
data_view = og.AttributeValueHelper(self._attributes.useFindPrims)
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def primsBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.primsBundle"""
return self.__bundles.primsBundle
@primsBundle.setter
def primsBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.primsBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.primsBundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.attrNamesToImport_size = None
self.pathPattern_size = None
self.primPaths_size = None
self.typePattern_size = None
@property
def applySkelBinding(self):
data_view = og.AttributeValueHelper(self._attributes.applySkelBinding)
return data_view.get()
@applySkelBinding.setter
def applySkelBinding(self, value):
data_view = og.AttributeValueHelper(self._attributes.applySkelBinding)
data_view.set(value)
@property
def attrNamesToImport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
self.attrNamesToImport_size = data_view.get_array_size()
return data_view.get()
@attrNamesToImport.setter
def attrNamesToImport(self, value):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
data_view.set(value)
self.attrNamesToImport_size = data_view.get_array_size()
@property
def computeBoundingBox(self):
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
return data_view.get()
@computeBoundingBox.setter
def computeBoundingBox(self, value):
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
data_view.set(value)
@property
def pathPattern(self):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
self.pathPattern_size = data_view.get_array_size()
return data_view.get()
@pathPattern.setter
def pathPattern(self, value):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
data_view.set(value)
self.pathPattern_size = data_view.get_array_size()
@property
def primPaths(self):
data_view = og.AttributeValueHelper(self._attributes.primPaths)
self.primPaths_size = data_view.get_array_size()
return data_view.get()
@primPaths.setter
def primPaths(self, value):
data_view = og.AttributeValueHelper(self._attributes.primPaths)
data_view.set(value)
self.primPaths_size = data_view.get_array_size()
@property
def typePattern(self):
data_view = og.AttributeValueHelper(self._attributes.typePattern)
self.typePattern_size = data_view.get_array_size()
return data_view.get()
@typePattern.setter
def typePattern(self, value):
data_view = og.AttributeValueHelper(self._attributes.typePattern)
data_view.set(value)
self.typePattern_size = data_view.get_array_size()
@property
def usdTimecode(self):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
return data_view.get()
@usdTimecode.setter
def usdTimecode(self, value):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
data_view.set(value)
@property
def useFindPrims(self):
data_view = og.AttributeValueHelper(self._attributes.useFindPrims)
return data_view.get()
@useFindPrims.setter
def useFindPrims(self, value):
data_view = og.AttributeValueHelper(self._attributes.useFindPrims)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnReadPrimsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnReadPrimsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnReadPrimsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 18,349 | Python | 52.654971 | 680 | 0.655186 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnAppendPathDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.AppendPath
Generates a path token by appending the given relative path token to the given root or prim path token
"""
from typing import Any
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnAppendPathDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.AppendPath
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.path
inputs.suffix
Outputs:
outputs.path
State:
state.path
state.suffix
"""
# 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:path', 'token,token[]', 1, None, 'The path token(s) to be appended to. Must be a base or prim path (ex. /World)', {}, True, None, False, ''),
('inputs:suffix', 'token', 0, None, 'The prim or prim-property path to append (ex. Cube or Cube.attr)', {}, True, "", False, ''),
('outputs:path', 'token,token[]', 1, None, 'The new path token(s) (ex. /World/Cube or /World/Cube.attr)', {}, True, None, False, ''),
('state:path', 'token', 0, None, 'Snapshot of previously seen path', {}, True, None, False, ''),
('state:suffix', 'token', 0, None, 'Snapshot of previously seen suffix', {}, 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 path(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.path"""
return og.RuntimeAttribute(self._attributes.path.get_attribute_data(), self._context, True)
@path.setter
def path(self, value_to_set: Any):
"""Assign another attribute's value to outputs.path"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.path.value = value_to_set.value
else:
self.path.value = value_to_set
@property
def suffix(self):
data_view = og.AttributeValueHelper(self._attributes.suffix)
return data_view.get()
@suffix.setter
def suffix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.suffix)
data_view = og.AttributeValueHelper(self._attributes.suffix)
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 path(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.path"""
return og.RuntimeAttribute(self._attributes.path.get_attribute_data(), self._context, False)
@path.setter
def path(self, value_to_set: Any):
"""Assign another attribute's value to outputs.path"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.path.value = value_to_set.value
else:
self.path.value = value_to_set
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
@property
def path(self):
data_view = og.AttributeValueHelper(self._attributes.path)
return data_view.get()
@path.setter
def path(self, value):
data_view = og.AttributeValueHelper(self._attributes.path)
data_view.set(value)
@property
def suffix(self):
data_view = og.AttributeValueHelper(self._attributes.suffix)
return data_view.get()
@suffix.setter
def suffix(self, value):
data_view = og.AttributeValueHelper(self._attributes.suffix)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnAppendPathDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnAppendPathDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnAppendPathDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,012 | Python | 44.836601 | 158 | 0.644324 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnMatrixMultiplyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.MatrixMultiply
Computes the matrix product of the inputs. Inputs must be compatible. Also accepts tuples (treated as vectors) as inputs.
Tuples in input A will be treated as row vectors. Tuples in input B will be treated as column vectors. Arrays of inputs
will be computed element-wise with broadcasting if necessary.
"""
from typing import Any
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnMatrixMultiplyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.MatrixMultiply
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
Outputs:
outputs.output
"""
# 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:a', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double[2],double[2][],double[3],double[3][],double[4],double[4][],float[2],float[2][],float[3],float[3][],float[4],float[4][],frame[4],half[2],half[2][],half[3],half[3][],half[4],half[4][],matrixd[3],matrixd[3][],matrixd[4],matrixd[4][],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],transform[4],vectord[3],vectorf[3],vectorh[3]', 1, 'A', 'First matrix or row vector to multiply', {}, True, None, False, ''),
('inputs:b', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double[2],double[2][],double[3],double[3][],double[4],double[4][],float[2],float[2][],float[3],float[3][],float[4],float[4][],frame[4],half[2],half[2][],half[3],half[3][],half[4],half[4][],matrixd[3],matrixd[3][],matrixd[4],matrixd[4][],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],transform[4],vectord[3],vectorf[3],vectorh[3]', 1, 'B', 'Second matrix or column vector to multiply', {}, True, None, False, ''),
('outputs:output', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[2][],double[3],double[3][],double[4],double[4][],double[],float,float[2],float[2][],float[3],float[3][],float[4],float[4][],float[],frame[4],half,half[2],half[2][],half[3],half[3][],half[4],half[4][],half[],matrixd[3],matrixd[3][],matrixd[4],matrixd[4][],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],transform[4],vectord[3],vectorf[3],vectorh[3]', 1, 'Product', 'Product of the two matrices', {}, 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 a(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.a"""
return og.RuntimeAttribute(self._attributes.a.get_attribute_data(), self._context, True)
@a.setter
def a(self, value_to_set: Any):
"""Assign another attribute's value to outputs.a"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.a.value = value_to_set.value
else:
self.a.value = value_to_set
@property
def b(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.b"""
return og.RuntimeAttribute(self._attributes.b.get_attribute_data(), self._context, True)
@b.setter
def b(self, value_to_set: Any):
"""Assign another attribute's value to outputs.b"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.b.value = value_to_set.value
else:
self.b.value = value_to_set
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 output(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.output"""
return og.RuntimeAttribute(self._attributes.output.get_attribute_data(), self._context, False)
@output.setter
def output(self, value_to_set: Any):
"""Assign another attribute's value to outputs.output"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.output.value = value_to_set.value
else:
self.output.value = value_to_set
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 = OgnMatrixMultiplyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnMatrixMultiplyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnMatrixMultiplyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,894 | Python | 59.267175 | 655 | 0.661895 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnFindPrimsDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.FindPrims
Finds Prims on the stage which match the given criteria
"""
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 OgnFindPrimsDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.FindPrims
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.ignoreSystemPrims
inputs.namePrefix
inputs.pathPattern
inputs.recursive
inputs.requiredAttributes
inputs.requiredRelationship
inputs.requiredRelationshipTarget
inputs.requiredTarget
inputs.rootPrim
inputs.rootPrimPath
inputs.type
Outputs:
outputs.primPaths
outputs.prims
State:
state.ignoreSystemPrims
state.inputType
state.namePrefix
state.pathPattern
state.recursive
state.requiredAttributes
state.requiredRelationship
state.requiredRelationshipTarget
state.requiredTarget
state.rootPrim
state.rootPrimPath
"""
# 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:ignoreSystemPrims', 'bool', 0, None, "Ignore system prims such as omni graph nodes that shouldn't be considered during the import.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:namePrefix', 'token', 0, 'Prim Name Prefix', 'Only prims with a name starting with the given prefix will be returned.', {}, True, "", False, ''),
('inputs:pathPattern', 'token', 0, 'Prim Path Pattern', "A list of wildcard patterns used to match the prim paths\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']\n '*' - match any\n '* ^/Box' - match any, but exclude '/Box'\n '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'", {}, True, "", False, ''),
('inputs:recursive', 'bool', 0, None, 'False means only consider children of the root prim, True means all prims in the hierarchy', {}, True, False, False, ''),
('inputs:requiredAttributes', 'string', 0, 'Attribute Names', 'A space-separated list of attribute names that are required to be present on matched prims', {}, True, "", False, ''),
('inputs:requiredRelationship', 'token', 0, 'Relationship Name', 'The name of a relationship which must have a target specified by requiredRelationshipTarget or requiredTarget', {}, True, "", False, ''),
('inputs:requiredRelationshipTarget', 'path', 0, 'Relationship Prim Path', 'The path that must be a target of the requiredRelationship', {}, True, "", True, 'Use requiredTarget instead'),
('inputs:requiredTarget', 'target', 0, 'Relationship Prim', 'The target of the requiredRelationship', {}, True, [], False, ''),
('inputs:rootPrim', 'target', 0, 'Root Prim', 'Only children of the given prim will be considered. If rootPrim is specified, rootPrimPath will be ignored.', {}, True, [], False, ''),
('inputs:rootPrimPath', 'token', 0, 'Root Prim Path', 'Only children of the given prim will be considered. Empty will search the whole stage.', {}, True, "", True, 'Use rootPrim input attribute instead'),
('inputs:type', 'token', 0, 'Prim Type Pattern', "A list of wildcard patterns used to match the prim types that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']\n '*' - match any\n '* ^Mesh' - match any, but exclude 'Mesh'\n '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('outputs:primPaths', 'token[]', 0, None, 'A list of Prim paths as tokens which match the given type', {}, True, None, False, ''),
('outputs:prims', 'target', 0, None, 'A list of Prim paths which match the given type', {}, True, [], False, ''),
('state:ignoreSystemPrims', 'bool', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:inputType', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:namePrefix', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:pathPattern', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:recursive', 'bool', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:requiredAttributes', 'string', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:requiredRelationship', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:requiredRelationshipTarget', 'string', 0, None, 'last corresponding input seen', {}, True, None, False, ''),
('state:requiredTarget', 'target', 0, None, 'last corresponding input seen', {}, True, [], False, ''),
('state:rootPrim', 'target', 0, None, 'last corresponding input seen', {}, True, [], False, ''),
('state:rootPrimPath', 'token', 0, None, 'last corresponding input seen', {}, 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.requiredAttributes = og.AttributeRole.TEXT
role_data.inputs.requiredRelationshipTarget = og.AttributeRole.PATH
role_data.inputs.requiredTarget = og.AttributeRole.TARGET
role_data.inputs.rootPrim = og.AttributeRole.TARGET
role_data.outputs.prims = og.AttributeRole.TARGET
role_data.state.requiredAttributes = og.AttributeRole.TEXT
role_data.state.requiredRelationshipTarget = og.AttributeRole.TEXT
role_data.state.requiredTarget = og.AttributeRole.TARGET
role_data.state.rootPrim = og.AttributeRole.TARGET
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 ignoreSystemPrims(self):
data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims)
return data_view.get()
@ignoreSystemPrims.setter
def ignoreSystemPrims(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.ignoreSystemPrims)
data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims)
data_view.set(value)
@property
def namePrefix(self):
data_view = og.AttributeValueHelper(self._attributes.namePrefix)
return data_view.get()
@namePrefix.setter
def namePrefix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.namePrefix)
data_view = og.AttributeValueHelper(self._attributes.namePrefix)
data_view.set(value)
@property
def pathPattern(self):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
return data_view.get()
@pathPattern.setter
def pathPattern(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.pathPattern)
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
data_view.set(value)
@property
def recursive(self):
data_view = og.AttributeValueHelper(self._attributes.recursive)
return data_view.get()
@recursive.setter
def recursive(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.recursive)
data_view = og.AttributeValueHelper(self._attributes.recursive)
data_view.set(value)
@property
def requiredAttributes(self):
data_view = og.AttributeValueHelper(self._attributes.requiredAttributes)
return data_view.get()
@requiredAttributes.setter
def requiredAttributes(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.requiredAttributes)
data_view = og.AttributeValueHelper(self._attributes.requiredAttributes)
data_view.set(value)
self.requiredAttributes_size = data_view.get_array_size()
@property
def requiredRelationship(self):
data_view = og.AttributeValueHelper(self._attributes.requiredRelationship)
return data_view.get()
@requiredRelationship.setter
def requiredRelationship(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.requiredRelationship)
data_view = og.AttributeValueHelper(self._attributes.requiredRelationship)
data_view.set(value)
@property
def requiredRelationshipTarget(self):
data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget)
return data_view.get()
@requiredRelationshipTarget.setter
def requiredRelationshipTarget(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.requiredRelationshipTarget)
data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget)
data_view.set(value)
self.requiredRelationshipTarget_size = data_view.get_array_size()
@property
def requiredTarget(self):
data_view = og.AttributeValueHelper(self._attributes.requiredTarget)
return data_view.get()
@requiredTarget.setter
def requiredTarget(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.requiredTarget)
data_view = og.AttributeValueHelper(self._attributes.requiredTarget)
data_view.set(value)
self.requiredTarget_size = data_view.get_array_size()
@property
def rootPrim(self):
data_view = og.AttributeValueHelper(self._attributes.rootPrim)
return data_view.get()
@rootPrim.setter
def rootPrim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.rootPrim)
data_view = og.AttributeValueHelper(self._attributes.rootPrim)
data_view.set(value)
self.rootPrim_size = data_view.get_array_size()
@property
def rootPrimPath(self):
data_view = og.AttributeValueHelper(self._attributes.rootPrimPath)
return data_view.get()
@rootPrimPath.setter
def rootPrimPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.rootPrimPath)
data_view = og.AttributeValueHelper(self._attributes.rootPrimPath)
data_view.set(value)
@property
def type(self):
data_view = og.AttributeValueHelper(self._attributes.type)
return data_view.get()
@type.setter
def type(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.type)
data_view = og.AttributeValueHelper(self._attributes.type)
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.primPaths_size = None
self.prims_size = None
self._batchedWriteValues = { }
@property
def primPaths(self):
data_view = og.AttributeValueHelper(self._attributes.primPaths)
return data_view.get(reserved_element_count=self.primPaths_size)
@primPaths.setter
def primPaths(self, value):
data_view = og.AttributeValueHelper(self._attributes.primPaths)
data_view.set(value)
self.primPaths_size = data_view.get_array_size()
@property
def prims(self):
data_view = og.AttributeValueHelper(self._attributes.prims)
return data_view.get(reserved_element_count=self.prims_size)
@prims.setter
def prims(self, value):
data_view = og.AttributeValueHelper(self._attributes.prims)
data_view.set(value)
self.prims_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)
self.requiredAttributes_size = None
self.requiredRelationshipTarget_size = None
self.requiredTarget_size = None
self.rootPrim_size = None
@property
def ignoreSystemPrims(self):
data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims)
return data_view.get()
@ignoreSystemPrims.setter
def ignoreSystemPrims(self, value):
data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims)
data_view.set(value)
@property
def inputType(self):
data_view = og.AttributeValueHelper(self._attributes.inputType)
return data_view.get()
@inputType.setter
def inputType(self, value):
data_view = og.AttributeValueHelper(self._attributes.inputType)
data_view.set(value)
@property
def namePrefix(self):
data_view = og.AttributeValueHelper(self._attributes.namePrefix)
return data_view.get()
@namePrefix.setter
def namePrefix(self, value):
data_view = og.AttributeValueHelper(self._attributes.namePrefix)
data_view.set(value)
@property
def pathPattern(self):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
return data_view.get()
@pathPattern.setter
def pathPattern(self, value):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
data_view.set(value)
@property
def recursive(self):
data_view = og.AttributeValueHelper(self._attributes.recursive)
return data_view.get()
@recursive.setter
def recursive(self, value):
data_view = og.AttributeValueHelper(self._attributes.recursive)
data_view.set(value)
@property
def requiredAttributes(self):
data_view = og.AttributeValueHelper(self._attributes.requiredAttributes)
self.requiredAttributes_size = data_view.get_array_size()
return data_view.get()
@requiredAttributes.setter
def requiredAttributes(self, value):
data_view = og.AttributeValueHelper(self._attributes.requiredAttributes)
data_view.set(value)
self.requiredAttributes_size = data_view.get_array_size()
@property
def requiredRelationship(self):
data_view = og.AttributeValueHelper(self._attributes.requiredRelationship)
return data_view.get()
@requiredRelationship.setter
def requiredRelationship(self, value):
data_view = og.AttributeValueHelper(self._attributes.requiredRelationship)
data_view.set(value)
@property
def requiredRelationshipTarget(self):
data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget)
self.requiredRelationshipTarget_size = data_view.get_array_size()
return data_view.get()
@requiredRelationshipTarget.setter
def requiredRelationshipTarget(self, value):
data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget)
data_view.set(value)
self.requiredRelationshipTarget_size = data_view.get_array_size()
@property
def requiredTarget(self):
data_view = og.AttributeValueHelper(self._attributes.requiredTarget)
self.requiredTarget_size = data_view.get_array_size()
return data_view.get()
@requiredTarget.setter
def requiredTarget(self, value):
data_view = og.AttributeValueHelper(self._attributes.requiredTarget)
data_view.set(value)
self.requiredTarget_size = data_view.get_array_size()
@property
def rootPrim(self):
data_view = og.AttributeValueHelper(self._attributes.rootPrim)
self.rootPrim_size = data_view.get_array_size()
return data_view.get()
@rootPrim.setter
def rootPrim(self, value):
data_view = og.AttributeValueHelper(self._attributes.rootPrim)
data_view.set(value)
self.rootPrim_size = data_view.get_array_size()
@property
def rootPrimPath(self):
data_view = og.AttributeValueHelper(self._attributes.rootPrimPath)
return data_view.get()
@rootPrimPath.setter
def rootPrimPath(self, value):
data_view = og.AttributeValueHelper(self._attributes.rootPrimPath)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnFindPrimsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnFindPrimsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnFindPrimsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 20,870 | Python | 47.424594 | 599 | 0.64322 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnWritePrimsV2Database.py | """Support for simplified access to data on nodes of type omni.graph.nodes.WritePrimsV2
Write back bundle(s) containing multiple prims to the stage.
"""
import usdrt
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnWritePrimsV2Database(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.WritePrimsV2
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.attrNamesToExport
inputs.execIn
inputs.layerIdentifier
inputs.pathPattern
inputs.prims
inputs.primsBundle
inputs.scatterUnderTargets
inputs.typePattern
inputs.usdWriteBack
Outputs:
outputs.execOut
State:
state.attrNamesToExport
state.layerIdentifier
state.pathPattern
state.primBundleDirtyId
state.scatterUnderTargets
state.typePattern
state.usdWriteBack
"""
# 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:attrNamesToExport', 'string', 0, 'Attribute Name Pattern', "A list of wildcard patterns used to match primitive attributes by name.\n\nSupported syntax of wildcard pattern:\n `*` - match an arbitrary number of any characters\n `?` - match any single character\n `^` - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['xFormOp:translate', 'xformOp:scale','radius']\n '*' - match any\n 'xformOp:*' - matches 'xFormOp:translate' and 'xformOp:scale'\n '* ^radius' - match any, but exclude 'radius'\n '* ^xformOp*' - match any, but exclude 'xFormOp:translate', 'xformOp:scale'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('inputs:execIn', 'execution', 0, None, 'The input execution (for action graphs only)', {}, True, None, False, ''),
('inputs:layerIdentifier', 'token', 0, 'Layer Identifier', 'Identifier of the layer to export to. If empty, it\'ll be exported to the current edit target at the time of usd wirte back.\'\nThis is only used when "Persist To USD" is enabled.', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:pathPattern', 'string', 0, 'Prim Path Pattern', "A list of wildcard patterns used to match primitives by path.\n\nSupported syntax of wildcard pattern:\n `*` - match an arbitrary number of any characters\n `?` - match any single character\n `^` - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']\n '*' - match any\n '* ^/Box' - match any, but exclude '/Box'\n '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('inputs:prims', 'target', 0, 'Prims', "Target(s) to which the prims in 'primsBundle' will be written to.\nThere is a 1:1 mapping between root prims paths in 'primsBundle' and the Target Prims targets\n*For advanced usage, if 'primsBundle' contains hierarchy, the unique common ancesor paths will have \n the 1:1 mapping to Target Prims targets, with the descendant paths remapped.\n*NOTE* See 'scatterUnderTargets' input for modified exporting behavior\n*WARNING* this can create new prims on the stage.\nIf attributes or prims are removed from 'primsBundle' in subsequent evaluation, they will be removed from targets as well.", {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, True, [], False, ''),
('inputs:primsBundle', 'bundle', 0, 'Prims Bundle', 'The bundle(s) of multiple prims to be written back.\nThe sourcePrimPath attribute is used to find the destination prim.', {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, True, None, False, ''),
('inputs:scatterUnderTargets', 'bool', 0, 'Scatter Under Targets', 'If true, the target prims become the parent prims that the bundled prims will be exported *UNDER*. \nIf multiple prims targets are provided, the primsBundle will be duplicated *UNDER* each \ntarget prims.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:typePattern', 'string', 0, 'Prim Type Pattern', "A list of wildcard patterns used to match primitives by type.\n\nSupported syntax of wildcard pattern:\n `*` - match an arbitrary number of any characters\n `?` - match any single character\n `^` - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']\n '*' - match any\n '* ^Mesh' - match any, but exclude 'Mesh'\n '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('inputs:usdWriteBack', 'bool', 0, 'Persist To USD', 'Whether or not the value should be written back to USD, or kept a Fabric only value', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:execOut', 'execution', 0, None, 'The output execution port (for action graphs only)', {}, True, None, False, ''),
('state:attrNamesToExport', 'string', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('state:layerIdentifier', 'token', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('state:pathPattern', 'string', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('state:primBundleDirtyId', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:scatterUnderTargets', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('state:typePattern', 'string', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('state:usdWriteBack', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, 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.attrNamesToExport = og.AttributeRole.TEXT
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.inputs.pathPattern = og.AttributeRole.TEXT
role_data.inputs.prims = og.AttributeRole.TARGET
role_data.inputs.primsBundle = og.AttributeRole.BUNDLE
role_data.inputs.typePattern = og.AttributeRole.TEXT
role_data.outputs.execOut = og.AttributeRole.EXECUTION
role_data.state.attrNamesToExport = og.AttributeRole.TEXT
role_data.state.pathPattern = og.AttributeRole.TEXT
role_data.state.typePattern = og.AttributeRole.TEXT
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def attrNamesToExport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport)
return data_view.get()
@attrNamesToExport.setter
def attrNamesToExport(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.attrNamesToExport)
data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport)
data_view.set(value)
self.attrNamesToExport_size = data_view.get_array_size()
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
@property
def layerIdentifier(self):
data_view = og.AttributeValueHelper(self._attributes.layerIdentifier)
return data_view.get()
@layerIdentifier.setter
def layerIdentifier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.layerIdentifier)
data_view = og.AttributeValueHelper(self._attributes.layerIdentifier)
data_view.set(value)
@property
def pathPattern(self):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
return data_view.get()
@pathPattern.setter
def pathPattern(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.pathPattern)
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
data_view.set(value)
self.pathPattern_size = data_view.get_array_size()
@property
def prims(self):
data_view = og.AttributeValueHelper(self._attributes.prims)
return data_view.get()
@prims.setter
def prims(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prims)
data_view = og.AttributeValueHelper(self._attributes.prims)
data_view.set(value)
self.prims_size = data_view.get_array_size()
@property
def primsBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.primsBundle"""
return self.__bundles.primsBundle
@property
def scatterUnderTargets(self):
data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets)
return data_view.get()
@scatterUnderTargets.setter
def scatterUnderTargets(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.scatterUnderTargets)
data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets)
data_view.set(value)
@property
def typePattern(self):
data_view = og.AttributeValueHelper(self._attributes.typePattern)
return data_view.get()
@typePattern.setter
def typePattern(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.typePattern)
data_view = og.AttributeValueHelper(self._attributes.typePattern)
data_view.set(value)
self.typePattern_size = data_view.get_array_size()
@property
def usdWriteBack(self):
data_view = og.AttributeValueHelper(self._attributes.usdWriteBack)
return data_view.get()
@usdWriteBack.setter
def usdWriteBack(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usdWriteBack)
data_view = og.AttributeValueHelper(self._attributes.usdWriteBack)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.attrNamesToExport_size = 1
self.pathPattern_size = 1
self.typePattern_size = 1
@property
def attrNamesToExport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport)
self.attrNamesToExport_size = data_view.get_array_size()
return data_view.get()
@attrNamesToExport.setter
def attrNamesToExport(self, value):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport)
data_view.set(value)
self.attrNamesToExport_size = data_view.get_array_size()
@property
def layerIdentifier(self):
data_view = og.AttributeValueHelper(self._attributes.layerIdentifier)
return data_view.get()
@layerIdentifier.setter
def layerIdentifier(self, value):
data_view = og.AttributeValueHelper(self._attributes.layerIdentifier)
data_view.set(value)
@property
def pathPattern(self):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
self.pathPattern_size = data_view.get_array_size()
return data_view.get()
@pathPattern.setter
def pathPattern(self, value):
data_view = og.AttributeValueHelper(self._attributes.pathPattern)
data_view.set(value)
self.pathPattern_size = data_view.get_array_size()
@property
def primBundleDirtyId(self):
data_view = og.AttributeValueHelper(self._attributes.primBundleDirtyId)
return data_view.get()
@primBundleDirtyId.setter
def primBundleDirtyId(self, value):
data_view = og.AttributeValueHelper(self._attributes.primBundleDirtyId)
data_view.set(value)
@property
def scatterUnderTargets(self):
data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets)
return data_view.get()
@scatterUnderTargets.setter
def scatterUnderTargets(self, value):
data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets)
data_view.set(value)
@property
def typePattern(self):
data_view = og.AttributeValueHelper(self._attributes.typePattern)
self.typePattern_size = data_view.get_array_size()
return data_view.get()
@typePattern.setter
def typePattern(self, value):
data_view = og.AttributeValueHelper(self._attributes.typePattern)
data_view.set(value)
self.typePattern_size = data_view.get_array_size()
@property
def usdWriteBack(self):
data_view = og.AttributeValueHelper(self._attributes.usdWriteBack)
return data_view.get()
@usdWriteBack.setter
def usdWriteBack(self, value):
data_view = og.AttributeValueHelper(self._attributes.usdWriteBack)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnWritePrimsV2Database.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnWritePrimsV2Database.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnWritePrimsV2Database.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 17,916 | Python | 53.129909 | 720 | 0.653271 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnMakeArrayDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.MakeArray
Makes an output array attribute from input values, in the order of the inputs. If 'arraySize' is less than 5, the top 'arraySize'
elements will be taken. If 'arraySize' is greater than 5 element e will be repeated to fill the remaining space
"""
from typing import Any
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 OgnMakeArrayDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.MakeArray
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.arraySize
inputs.b
inputs.c
inputs.d
inputs.e
Outputs:
outputs.array
"""
# 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:a', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 1', {}, True, None, False, ''),
('inputs:arraySize', 'int', 0, None, 'The size of the array to create', {}, True, 0, False, ''),
('inputs:b', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 2', {}, True, None, False, ''),
('inputs:c', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 3', {}, True, None, False, ''),
('inputs:d', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 4', {}, True, None, False, ''),
('inputs:e', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 5', {}, True, None, False, ''),
('outputs:array', 'colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],double[2][],double[3][],double[4][],double[],float[2][],float[3][],float[4][],float[],frame[4][],half[2][],half[3][],half[4][],half[],int64[],int[2][],int[3][],int[4][],int[],matrixd[3][],matrixd[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],quatd[4][],quatf[4][],quath[4][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],timecode[],token[],transform[4][],uchar[],uint64[],uint[],vectord[3][],vectorf[3][],vectorh[3][]', 1, None, 'The array of copied values of inputs in the given order', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"arraySize", "_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.arraySize]
self._batchedReadValues = [0]
@property
def a(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.a"""
return og.RuntimeAttribute(self._attributes.a.get_attribute_data(), self._context, True)
@a.setter
def a(self, value_to_set: Any):
"""Assign another attribute's value to outputs.a"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.a.value = value_to_set.value
else:
self.a.value = value_to_set
@property
def b(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.b"""
return og.RuntimeAttribute(self._attributes.b.get_attribute_data(), self._context, True)
@b.setter
def b(self, value_to_set: Any):
"""Assign another attribute's value to outputs.b"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.b.value = value_to_set.value
else:
self.b.value = value_to_set
@property
def c(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.c"""
return og.RuntimeAttribute(self._attributes.c.get_attribute_data(), self._context, True)
@c.setter
def c(self, value_to_set: Any):
"""Assign another attribute's value to outputs.c"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.c.value = value_to_set.value
else:
self.c.value = value_to_set
@property
def d(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.d"""
return og.RuntimeAttribute(self._attributes.d.get_attribute_data(), self._context, True)
@d.setter
def d(self, value_to_set: Any):
"""Assign another attribute's value to outputs.d"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.d.value = value_to_set.value
else:
self.d.value = value_to_set
@property
def e(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.e"""
return og.RuntimeAttribute(self._attributes.e.get_attribute_data(), self._context, True)
@e.setter
def e(self, value_to_set: Any):
"""Assign another attribute's value to outputs.e"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.e.value = value_to_set.value
else:
self.e.value = value_to_set
@property
def arraySize(self):
return self._batchedReadValues[0]
@arraySize.setter
def arraySize(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def array(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.array"""
return og.RuntimeAttribute(self._attributes.array.get_attribute_data(), self._context, False)
@array.setter
def array(self, value_to_set: Any):
"""Assign another attribute's value to outputs.array"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.array.value = value_to_set.value
else:
self.array.value = value_to_set
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 = OgnMakeArrayDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnMakeArrayDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnMakeArrayDatabase.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(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.nodes.MakeArray'
@staticmethod
def compute(context, node):
def database_valid():
if db.inputs.a.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute inputs:a is not resolved, compute skipped')
return False
if db.inputs.b.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute inputs:b is not resolved, compute skipped')
return False
if db.inputs.c.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute inputs:c is not resolved, compute skipped')
return False
if db.inputs.d.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute inputs:d is not resolved, compute skipped')
return False
if db.inputs.e.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute inputs:e is not resolved, compute skipped')
return False
if db.outputs.array.type.base_type == og.BaseDataType.UNKNOWN:
db.log_warning('Required extended attribute outputs:array is not resolved, compute skipped')
return False
return True
try:
per_node_data = OgnMakeArrayDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnMakeArrayDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnMakeArrayDatabase(node)
try:
compute_function = getattr(OgnMakeArrayDatabase.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 OgnMakeArrayDatabase.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):
OgnMakeArrayDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnMakeArrayDatabase.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(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnMakeArrayDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnMakeArrayDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnMakeArrayDatabase.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(OgnMakeArrayDatabase.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.nodes")
node_type.set_metadata(ogn.MetadataKeys.HIDDEN, "true")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Make Array")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "math:array")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Makes an output array attribute from input values, in the order of the inputs. If 'arraySize' is less than 5, the top 'arraySize' elements will be taken. If 'arraySize' is greater than 5 element e will be repeated to fill the remaining space")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnMakeArrayDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnMakeArrayDatabase.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):
OgnMakeArrayDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnMakeArrayDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.nodes.MakeArray")
| 18,278 | Python | 55.416666 | 692 | 0.629226 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnMakeTransformDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.MakeTransform
Make a transformation matrix that performs a translation, rotation (in euler angles), and scale in that order
"""
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 OgnMakeTransformDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.MakeTransform
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.rotationXYZ
inputs.scale
inputs.translation
Outputs:
outputs.transform
"""
# 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:rotationXYZ', 'vector3d', 0, None, 'The desired orientation in euler angles (XYZ)', {ogn.MetadataKeys.DEFAULT: '[0, 0, 0]'}, True, [0, 0, 0], False, ''),
('inputs:scale', 'vector3d', 0, None, 'The desired scaling factor about the X, Y, and Z axis respectively', {ogn.MetadataKeys.DEFAULT: '[1, 1, 1]'}, True, [1, 1, 1], False, ''),
('inputs:translation', 'vector3d', 0, None, 'the desired translation as a vector', {ogn.MetadataKeys.DEFAULT: '[0, 0, 0]'}, True, [0, 0, 0], False, ''),
('outputs:transform', 'matrix4d', 0, None, 'the resulting transformation matrix', {}, 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.rotationXYZ = og.AttributeRole.VECTOR
role_data.inputs.scale = og.AttributeRole.VECTOR
role_data.inputs.translation = og.AttributeRole.VECTOR
role_data.outputs.transform = og.AttributeRole.MATRIX
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 rotationXYZ(self):
data_view = og.AttributeValueHelper(self._attributes.rotationXYZ)
return data_view.get()
@rotationXYZ.setter
def rotationXYZ(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.rotationXYZ)
data_view = og.AttributeValueHelper(self._attributes.rotationXYZ)
data_view.set(value)
@property
def scale(self):
data_view = og.AttributeValueHelper(self._attributes.scale)
return data_view.get()
@scale.setter
def scale(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.scale)
data_view = og.AttributeValueHelper(self._attributes.scale)
data_view.set(value)
@property
def translation(self):
data_view = og.AttributeValueHelper(self._attributes.translation)
return data_view.get()
@translation.setter
def translation(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.translation)
data_view = og.AttributeValueHelper(self._attributes.translation)
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 transform(self):
data_view = og.AttributeValueHelper(self._attributes.transform)
return data_view.get()
@transform.setter
def transform(self, value):
data_view = og.AttributeValueHelper(self._attributes.transform)
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 = OgnMakeTransformDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnMakeTransformDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnMakeTransformDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,921 | Python | 45.77027 | 185 | 0.661321 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimBundleDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrimBundle
DEPRECATED - use ReadPrims!
"""
import carb
import usdrt
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnReadPrimBundleDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrimBundle
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.attrNamesToImport
inputs.computeBoundingBox
inputs.prim
inputs.primPath
inputs.usdTimecode
inputs.usePath
Outputs:
outputs.primBundle
State:
state.attrNamesToImport
state.computeBoundingBox
state.primPath
state.usdTimecode
state.usePath
"""
# 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:attrNamesToImport', 'token', 0, 'Attributes To Import', "A list of wildcard patterns used to match the attribute names that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']\n '*' - match any\n '* ^points' - match any, but exclude 'points'\n '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('inputs:computeBoundingBox', 'bool', 0, 'Compute Bounding Box', "For each primitive compute local bounding box and store them as 'bboxMinCorner', 'bboxMaxCorner' and 'bboxTransform' attributes.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:prim', 'target', 0, None, "The prims to be read from when 'usePath' is false", {}, False, [], False, ''),
('inputs:primPath', 'token', 0, 'Prim Path', "The paths of the prims to be read from when 'usePath' is true", {ogn.MetadataKeys.DEFAULT: '""'}, False, "", True, 'Use prim input with a GetPrimsAtPath node instead'),
('inputs:usdTimecode', 'timecode', 0, 'Time', 'The time at which to evaluate the transform of the USD prim. A value of "NaN" indicates that the default USD time stamp should be used', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''),
('inputs:usePath', 'bool', 0, 'Use Path', "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, True, 'Use prim input with a GetPrimsAtPath node instead'),
('outputs:primBundle', 'bundle', 0, None, 'A bundle containing multiple prims as children.\nEach child contains data attributes and two additional token attributes named sourcePrimPath and sourcePrimType\nwhich contain the path and the type of the Prim being read', {}, True, None, False, ''),
('state:attrNamesToImport', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:computeBoundingBox', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('state:primPath', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:usdTimecode', 'timecode', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''),
('state:usePath', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, 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.prim = og.AttributeRole.TARGET
role_data.inputs.usdTimecode = og.AttributeRole.TIMECODE
role_data.outputs.primBundle = og.AttributeRole.BUNDLE
role_data.state.usdTimecode = og.AttributeRole.TIMECODE
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 attrNamesToImport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
return data_view.get()
@attrNamesToImport.setter
def attrNamesToImport(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.attrNamesToImport)
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
data_view.set(value)
@property
def computeBoundingBox(self):
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
return data_view.get()
@computeBoundingBox.setter
def computeBoundingBox(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.computeBoundingBox)
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
data_view.set(value)
@property
def prim(self):
data_view = og.AttributeValueHelper(self._attributes.prim)
return data_view.get()
@prim.setter
def prim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prim)
data_view = og.AttributeValueHelper(self._attributes.prim)
data_view.set(value)
self.prim_size = data_view.get_array_size()
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primPath)
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
@property
def usdTimecode(self):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
return data_view.get()
@usdTimecode.setter
def usdTimecode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usdTimecode)
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
data_view.set(value)
@property
def usePath(self):
data_view = og.AttributeValueHelper(self._attributes.usePath)
return data_view.get()
@usePath.setter
def usePath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usePath)
data_view = og.AttributeValueHelper(self._attributes.usePath)
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def primBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.primBundle"""
return self.__bundles.primBundle
@primBundle.setter
def primBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.primBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.primBundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
@property
def attrNamesToImport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
return data_view.get()
@attrNamesToImport.setter
def attrNamesToImport(self, value):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
data_view.set(value)
@property
def computeBoundingBox(self):
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
return data_view.get()
@computeBoundingBox.setter
def computeBoundingBox(self, value):
data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox)
data_view.set(value)
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
@property
def usdTimecode(self):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
return data_view.get()
@usdTimecode.setter
def usdTimecode(self, value):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
data_view.set(value)
@property
def usePath(self):
data_view = og.AttributeValueHelper(self._attributes.usePath)
return data_view.get()
@usePath.setter
def usePath(self, value):
data_view = og.AttributeValueHelper(self._attributes.usePath)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnReadPrimBundleDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnReadPrimBundleDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnReadPrimBundleDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,861 | Python | 49.046692 | 677 | 0.655003 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGatherByPathDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.GatherByPath
Node to vectorize data by paths passed in via input. PROTOTYPE DO NOT USE. Requires GatherPrototype
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
import numpy
class OgnGatherByPathDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.GatherByPath
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.allAttributes
inputs.attributes
inputs.checkResyncAttributes
inputs.forceExportToHistory
inputs.hydraFastPath
inputs.primPaths
inputs.shouldWriteBack
Outputs:
outputs.gatherId
outputs.gatheredPaths
Predefined Tokens:
tokens.Disabled
tokens.World
tokens.Local
"""
# 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:allAttributes', 'bool', 0, None, "When true, all USD attributes will be gathered. Otherwise those specified by 'attributes' will be gathered.", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:attributes', 'string', 0, None, 'A space-separated list of attribute names to be gathered when allAttributes is false', {}, True, '', False, ''),
('inputs:checkResyncAttributes', 'bool', 0, None, 'When true, the data vectorization will be updated when new attributes to the Prims are added.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:forceExportToHistory', 'bool', 0, None, 'When true, all USD gathered paths will be tagged for being exported to the history.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:hydraFastPath', 'token', 0, None, "When not 'Disabled', will extract USD Geometry transforms into Hydra fast-path attributes.\n'World' will add _worldPosition, _worldOrientation. 'Local' will add _localMatrix.", {ogn.MetadataKeys.ALLOWED_TOKENS: 'Disabled,World,Local', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["Disabled", "World", "Local"]', ogn.MetadataKeys.DEFAULT: '"Disabled"'}, True, 'Disabled', False, ''),
('inputs:primPaths', 'token[]', 0, None, 'A list of Prim paths whose data should be vectorized', {}, True, [], False, ''),
('inputs:shouldWriteBack', 'bool', 0, 'Should Write Back To USD', 'Write the data back into USD if true.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('outputs:gatherId', 'uint64', 0, None, 'The GatherId corresponding to this Gather, kInvalidGatherId if the Gather failed', {}, True, None, False, ''),
('outputs:gatheredPaths', 'token[]', 0, None, 'The list of gathered prim paths in gathered-order', {}, True, None, False, ''),
])
class tokens:
Disabled = "Disabled"
World = "World"
Local = "Local"
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"allAttributes", "attributes", "checkResyncAttributes", "forceExportToHistory", "hydraFastPath", "shouldWriteBack", "_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.allAttributes, self._attributes.attributes, self._attributes.checkResyncAttributes, self._attributes.forceExportToHistory, self._attributes.hydraFastPath, self._attributes.shouldWriteBack]
self._batchedReadValues = [True, "", False, False, "Disabled", False]
@property
def primPaths(self):
data_view = og.AttributeValueHelper(self._attributes.primPaths)
return data_view.get()
@primPaths.setter
def primPaths(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primPaths)
data_view = og.AttributeValueHelper(self._attributes.primPaths)
data_view.set(value)
self.primPaths_size = data_view.get_array_size()
@property
def allAttributes(self):
return self._batchedReadValues[0]
@allAttributes.setter
def allAttributes(self, value):
self._batchedReadValues[0] = value
@property
def attributes(self):
return self._batchedReadValues[1]
@attributes.setter
def attributes(self, value):
self._batchedReadValues[1] = value
@property
def checkResyncAttributes(self):
return self._batchedReadValues[2]
@checkResyncAttributes.setter
def checkResyncAttributes(self, value):
self._batchedReadValues[2] = value
@property
def forceExportToHistory(self):
return self._batchedReadValues[3]
@forceExportToHistory.setter
def forceExportToHistory(self, value):
self._batchedReadValues[3] = value
@property
def hydraFastPath(self):
return self._batchedReadValues[4]
@hydraFastPath.setter
def hydraFastPath(self, value):
self._batchedReadValues[4] = value
@property
def shouldWriteBack(self):
return self._batchedReadValues[5]
@shouldWriteBack.setter
def shouldWriteBack(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 = {"gatherId", "_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.gatheredPaths_size = None
self._batchedWriteValues = { }
@property
def gatheredPaths(self):
data_view = og.AttributeValueHelper(self._attributes.gatheredPaths)
return data_view.get(reserved_element_count=self.gatheredPaths_size)
@gatheredPaths.setter
def gatheredPaths(self, value):
data_view = og.AttributeValueHelper(self._attributes.gatheredPaths)
data_view.set(value)
self.gatheredPaths_size = data_view.get_array_size()
@property
def gatherId(self):
value = self._batchedWriteValues.get(self._attributes.gatherId)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.gatherId)
return data_view.get()
@gatherId.setter
def gatherId(self, value):
self._batchedWriteValues[self._attributes.gatherId] = 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 = OgnGatherByPathDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnGatherByPathDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnGatherByPathDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,368 | Python | 49.091787 | 428 | 0.650656 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimAttributeDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttribute
Given a path to a prim on the current USD stage and the name of an attribute on that prim, gets the value of that attribute,
at the global timeline value.
"""
from typing import Any
import carb
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 OgnReadPrimAttributeDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttribute
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.name
inputs.prim
inputs.primPath
inputs.usdTimecode
inputs.usePath
Outputs:
outputs.value
State:
state.correctlySetup
state.importPath
state.srcAttrib
state.srcPath
state.srcPathAsToken
state.time
"""
# 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:name', 'token', 0, 'Attribute Name', 'The name of the attribute to get on the specified prim', {}, True, "", False, ''),
('inputs:prim', 'target', 0, None, "The prim to be read from when 'usePath' is false", {}, False, [], False, ''),
('inputs:primPath', 'token', 0, None, "The path of the prim to be modified when 'usePath' is true", {}, False, None, True, 'Use prim input with a GetPrimsAtPath node instead'),
('inputs:usdTimecode', 'timecode', 0, 'Time', 'The time at which to evaluate the transform of the USD prim attribute. A value of "NaN" indicates that the default USD time stamp should be used', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''),
('inputs:usePath', 'bool', 0, None, "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, True, 'Use prim input with a GetPrimsAtPath node instead'),
('outputs:value', 'any', 2, None, 'The attribute value', {}, True, None, False, ''),
('state:correctlySetup', 'bool', 0, None, 'Wheter or not the instance is properly setup', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('state:importPath', 'uint64', 0, None, 'Path at which data has been imported', {}, True, None, False, ''),
('state:srcAttrib', 'uint64', 0, None, 'A TokenC to the source attribute', {}, True, None, False, ''),
('state:srcPath', 'uint64', 0, None, 'A PathC to the source prim', {}, True, None, False, ''),
('state:srcPathAsToken', 'uint64', 0, None, 'A TokenC to the source prim', {}, True, None, False, ''),
('state:time', 'double', 0, None, 'The timecode at which we have imported the value', {}, 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.prim = og.AttributeRole.TARGET
role_data.inputs.usdTimecode = og.AttributeRole.TIMECODE
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 name(self):
data_view = og.AttributeValueHelper(self._attributes.name)
return data_view.get()
@name.setter
def name(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.name)
data_view = og.AttributeValueHelper(self._attributes.name)
data_view.set(value)
@property
def prim(self):
data_view = og.AttributeValueHelper(self._attributes.prim)
return data_view.get()
@prim.setter
def prim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prim)
data_view = og.AttributeValueHelper(self._attributes.prim)
data_view.set(value)
self.prim_size = data_view.get_array_size()
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primPath)
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
@property
def usdTimecode(self):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
return data_view.get()
@usdTimecode.setter
def usdTimecode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usdTimecode)
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
data_view.set(value)
@property
def usePath(self):
data_view = og.AttributeValueHelper(self._attributes.usePath)
return data_view.get()
@usePath.setter
def usePath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usePath)
data_view = og.AttributeValueHelper(self._attributes.usePath)
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 value(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.value"""
return og.RuntimeAttribute(self._attributes.value.get_attribute_data(), self._context, False)
@value.setter
def value(self, value_to_set: Any):
"""Assign another attribute's value to outputs.value"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.value.value = value_to_set.value
else:
self.value.value = value_to_set
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
@property
def correctlySetup(self):
data_view = og.AttributeValueHelper(self._attributes.correctlySetup)
return data_view.get()
@correctlySetup.setter
def correctlySetup(self, value):
data_view = og.AttributeValueHelper(self._attributes.correctlySetup)
data_view.set(value)
@property
def importPath(self):
data_view = og.AttributeValueHelper(self._attributes.importPath)
return data_view.get()
@importPath.setter
def importPath(self, value):
data_view = og.AttributeValueHelper(self._attributes.importPath)
data_view.set(value)
@property
def srcAttrib(self):
data_view = og.AttributeValueHelper(self._attributes.srcAttrib)
return data_view.get()
@srcAttrib.setter
def srcAttrib(self, value):
data_view = og.AttributeValueHelper(self._attributes.srcAttrib)
data_view.set(value)
@property
def srcPath(self):
data_view = og.AttributeValueHelper(self._attributes.srcPath)
return data_view.get()
@srcPath.setter
def srcPath(self, value):
data_view = og.AttributeValueHelper(self._attributes.srcPath)
data_view.set(value)
@property
def srcPathAsToken(self):
data_view = og.AttributeValueHelper(self._attributes.srcPathAsToken)
return data_view.get()
@srcPathAsToken.setter
def srcPathAsToken(self, value):
data_view = og.AttributeValueHelper(self._attributes.srcPathAsToken)
data_view.set(value)
@property
def time(self):
data_view = og.AttributeValueHelper(self._attributes.time)
return data_view.get()
@time.setter
def time(self, value):
data_view = og.AttributeValueHelper(self._attributes.time)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnReadPrimAttributeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnReadPrimAttributeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnReadPrimAttributeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 11,432 | Python | 44.011811 | 298 | 0.638121 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGetPrimDirectionVectorDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.GetPrimDirectionVector
Given a prim, find its direction vectors (up vector, forward vector, right vector, etc.)
"""
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 OgnGetPrimDirectionVectorDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.GetPrimDirectionVector
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.prim
inputs.primPath
inputs.usePath
Outputs:
outputs.backwardVector
outputs.downVector
outputs.forwardVector
outputs.leftVector
outputs.rightVector
outputs.upVector
"""
# 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:prim', 'target', 0, None, "The connection to the input prim - this attribute is used when 'usePath' is false", {}, False, [], False, ''),
('inputs:primPath', 'token', 0, None, "The path of the input prim - this attribute is used when 'usePath' is true", {}, True, "", True, 'Use prim input with a GetPrimsAtPath node instead'),
('inputs:usePath', 'bool', 0, None, "When true, it will use the 'primPath' attribute as the path to the prim, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, True, 'Use prim input with a GetPrimsAtPath node instead'),
('outputs:backwardVector', 'double3', 0, 'Backward Vector', 'The backward vector of the prim', {}, True, None, False, ''),
('outputs:downVector', 'double3', 0, 'Down Vector', 'The down vector of the prim', {}, True, None, False, ''),
('outputs:forwardVector', 'double3', 0, 'Forward Vector', 'The forward vector of the prim', {}, True, None, False, ''),
('outputs:leftVector', 'double3', 0, 'Left Vector', 'The left vector of the prim', {}, True, None, False, ''),
('outputs:rightVector', 'double3', 0, 'Right Vector', 'The right vector of the prim', {}, True, None, False, ''),
('outputs:upVector', 'double3', 0, 'Up Vector', 'The up vector of the prim', {}, 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.prim = og.AttributeRole.TARGET
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 prim(self):
data_view = og.AttributeValueHelper(self._attributes.prim)
return data_view.get()
@prim.setter
def prim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prim)
data_view = og.AttributeValueHelper(self._attributes.prim)
data_view.set(value)
self.prim_size = data_view.get_array_size()
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primPath)
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
@property
def usePath(self):
data_view = og.AttributeValueHelper(self._attributes.usePath)
return data_view.get()
@usePath.setter
def usePath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usePath)
data_view = og.AttributeValueHelper(self._attributes.usePath)
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 backwardVector(self):
data_view = og.AttributeValueHelper(self._attributes.backwardVector)
return data_view.get()
@backwardVector.setter
def backwardVector(self, value):
data_view = og.AttributeValueHelper(self._attributes.backwardVector)
data_view.set(value)
@property
def downVector(self):
data_view = og.AttributeValueHelper(self._attributes.downVector)
return data_view.get()
@downVector.setter
def downVector(self, value):
data_view = og.AttributeValueHelper(self._attributes.downVector)
data_view.set(value)
@property
def forwardVector(self):
data_view = og.AttributeValueHelper(self._attributes.forwardVector)
return data_view.get()
@forwardVector.setter
def forwardVector(self, value):
data_view = og.AttributeValueHelper(self._attributes.forwardVector)
data_view.set(value)
@property
def leftVector(self):
data_view = og.AttributeValueHelper(self._attributes.leftVector)
return data_view.get()
@leftVector.setter
def leftVector(self, value):
data_view = og.AttributeValueHelper(self._attributes.leftVector)
data_view.set(value)
@property
def rightVector(self):
data_view = og.AttributeValueHelper(self._attributes.rightVector)
return data_view.get()
@rightVector.setter
def rightVector(self, value):
data_view = og.AttributeValueHelper(self._attributes.rightVector)
data_view.set(value)
@property
def upVector(self):
data_view = og.AttributeValueHelper(self._attributes.upVector)
return data_view.get()
@upVector.setter
def upVector(self, value):
data_view = og.AttributeValueHelper(self._attributes.upVector)
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 = OgnGetPrimDirectionVectorDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnGetPrimDirectionVectorDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnGetPrimDirectionVectorDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 9,394 | Python | 44.386473 | 289 | 0.648073 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnNoiseDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.Noise
Sample values from a Perlin noise field.
The noise field for any given seed is static: the same input position will always
give the same result. This is useful in many areas, such as texturing and animation, where repeatability is essential. If
you want a result that varies then you will need to vary either the position or the seed. For example, connecting the 'frame'
output of an OnTick node to position will provide a noise result which varies from frame to frame. Perlin noise is locally
smooth, meaning that small changes in the sample position will produce small changes in the resulting noise. Varying the
seed value will produce a more chaotic result.
Another characteristic of Perlin noise is that it is zero at the corners
of each cell in the field. In practical terms this means that integral positions, such as 5.0 in a one-dimensional field
or (3.0, -1.0) in a two-dimensional field, will return a result of 0.0. Thus, if the source of your sample positions provides
only integral values then all of your results will be zero. To avoid this try offsetting your position values by a fractional
amount, such as 0.5.
"""
from typing import Any
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnNoiseDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.Noise
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.position
inputs.seed
Outputs:
outputs.result
"""
# 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:position', 'float,float[2],float[2][],float[3],float[3][],float[4],float[4][],float[]', 1, None, 'Position(s) within the noise field to be sampled. For a given seed, the same position \nwill always return the same noise value.', {}, True, None, False, ''),
('inputs:seed', 'uint', 0, None, 'Seed for generating the noise field.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:result', 'float,float[]', 1, None, 'Value at the selected position(s) in the noise field.', {}, 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 position(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.position"""
return og.RuntimeAttribute(self._attributes.position.get_attribute_data(), self._context, True)
@position.setter
def position(self, value_to_set: Any):
"""Assign another attribute's value to outputs.position"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.position.value = value_to_set.value
else:
self.position.value = value_to_set
@property
def seed(self):
data_view = og.AttributeValueHelper(self._attributes.seed)
return data_view.get()
@seed.setter
def seed(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.seed)
data_view = og.AttributeValueHelper(self._attributes.seed)
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 result(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.result"""
return og.RuntimeAttribute(self._attributes.result.get_attribute_data(), self._context, False)
@result.setter
def result(self, value_to_set: Any):
"""Assign another attribute's value to outputs.result"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.result.value = value_to_set.value
else:
self.result.value = value_to_set
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 = OgnNoiseDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnNoiseDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnNoiseDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,259 | Python | 51.230215 | 273 | 0.678744 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimAttributesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttributes
Read Prim attributes and exposes them as dynamic attributes Does not produce output bundle.
"""
import usdrt
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnReadPrimAttributesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttributes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.attrNamesToImport
inputs.prim
inputs.primPath
inputs.usdTimecode
inputs.usePath
Outputs:
outputs.primBundle
State:
state.attrNamesToImport
state.primPath
state.usdTimecode
"""
# 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:attrNamesToImport', 'string', 0, 'Attribute Name Pattern', "A list of wildcard patterns used to match the attribute names that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']\n '*' - match any\n '* ^points' - match any, but exclude 'points'\n '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''),
('inputs:prim', 'target', 0, None, "The prim to be read from when 'usePath' is false", {}, True, [], False, ''),
('inputs:primPath', 'path', 0, 'Prim Path', "The path of the prim to be read from when 'usePath' is true", {ogn.MetadataKeys.DEFAULT: '""'}, False, "", True, 'Use prim input with a GetPrimsAtPath node instead'),
('inputs:usdTimecode', 'timecode', 0, 'Time', 'The time at which to evaluate the transform of the USD prim. A value of "NaN" indicates that the default USD time stamp should be used', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''),
('inputs:usePath', 'bool', 0, 'Use Path', "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, True, 'Use prim input with a GetPrimsAtPath node instead'),
('outputs:primBundle', 'bundle', 0, None, 'A bundle of the target Prim attributes.\nIn addition to the data attributes, there are token attributes named sourcePrimPath and sourcePrimType\nwhich contains the path of the Prim being read', {ogn.MetadataKeys.HIDDEN: 'true', ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, None, False, ''),
('state:attrNamesToImport', 'string', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:primPath', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''),
('state:usdTimecode', 'timecode', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), 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.attrNamesToImport = og.AttributeRole.TEXT
role_data.inputs.prim = og.AttributeRole.TARGET
role_data.inputs.primPath = og.AttributeRole.PATH
role_data.inputs.usdTimecode = og.AttributeRole.TIMECODE
role_data.outputs.primBundle = og.AttributeRole.BUNDLE
role_data.state.attrNamesToImport = og.AttributeRole.TEXT
role_data.state.usdTimecode = og.AttributeRole.TIMECODE
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 attrNamesToImport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
return data_view.get()
@attrNamesToImport.setter
def attrNamesToImport(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.attrNamesToImport)
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
data_view.set(value)
self.attrNamesToImport_size = data_view.get_array_size()
@property
def prim(self):
data_view = og.AttributeValueHelper(self._attributes.prim)
return data_view.get()
@prim.setter
def prim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prim)
data_view = og.AttributeValueHelper(self._attributes.prim)
data_view.set(value)
self.prim_size = data_view.get_array_size()
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primPath)
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
self.primPath_size = data_view.get_array_size()
@property
def usdTimecode(self):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
return data_view.get()
@usdTimecode.setter
def usdTimecode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usdTimecode)
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
data_view.set(value)
@property
def usePath(self):
data_view = og.AttributeValueHelper(self._attributes.usePath)
return data_view.get()
@usePath.setter
def usePath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.usePath)
data_view = og.AttributeValueHelper(self._attributes.usePath)
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def primBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.primBundle"""
return self.__bundles.primBundle
@primBundle.setter
def primBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.primBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.primBundle.bundle = bundle
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.attrNamesToImport_size = None
@property
def attrNamesToImport(self):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
self.attrNamesToImport_size = data_view.get_array_size()
return data_view.get()
@attrNamesToImport.setter
def attrNamesToImport(self, value):
data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport)
data_view.set(value)
self.attrNamesToImport_size = data_view.get_array_size()
@property
def primPath(self):
data_view = og.AttributeValueHelper(self._attributes.primPath)
return data_view.get()
@primPath.setter
def primPath(self, value):
data_view = og.AttributeValueHelper(self._attributes.primPath)
data_view.set(value)
@property
def usdTimecode(self):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
return data_view.get()
@usdTimecode.setter
def usdTimecode(self, value):
data_view = og.AttributeValueHelper(self._attributes.usdTimecode)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnReadPrimAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnReadPrimAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnReadPrimAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 11,635 | Python | 50.486725 | 680 | 0.65896 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnAttrTypeDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.AttributeType
Queries information about the type of a specified attribute in an input bundle
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnAttrTypeDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.AttributeType
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.attrName
inputs.data
Outputs:
outputs.arrayDepth
outputs.baseType
outputs.componentCount
outputs.fullType
outputs.role
"""
# 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:attrName', 'token', 0, 'Attribute To Query', 'The name of the attribute to be queried', {ogn.MetadataKeys.DEFAULT: '"input"'}, True, "input", False, ''),
('inputs:data', 'bundle', 0, 'Bundle To Examine', 'Bundle of attributes to examine', {}, True, None, False, ''),
('outputs:arrayDepth', 'int', 0, 'Attribute Array Depth', 'Zero for a single value, one for an array, two for an array of arrays.\nSet to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''),
('outputs:baseType', 'int', 0, 'Attribute Base Type', 'An integer representing the type of the individual components.\nSet to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''),
('outputs:componentCount', 'int', 0, 'Attribute Component Count', 'Number of components in each tuple, e.g. one for float, three for point3f, 16 for\nmatrix4d. Set to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''),
('outputs:fullType', 'int', 0, 'Full Attribute Type', 'A single int representing the full type information.\nSet to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''),
('outputs:role', 'int', 0, 'Attribute Role', 'An integer representing semantic meaning of the type, e.g. point3f vs. normal3f vs. vector3f vs. float3.\nSet to -1 if the named attribute was not in the bundle.', {}, 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.data = og.AttributeRole.BUNDLE
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def attrName(self):
data_view = og.AttributeValueHelper(self._attributes.attrName)
return data_view.get()
@attrName.setter
def attrName(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.attrName)
data_view = og.AttributeValueHelper(self._attributes.attrName)
data_view.set(value)
@property
def data(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.data"""
return self.__bundles.data
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 arrayDepth(self):
data_view = og.AttributeValueHelper(self._attributes.arrayDepth)
return data_view.get()
@arrayDepth.setter
def arrayDepth(self, value):
data_view = og.AttributeValueHelper(self._attributes.arrayDepth)
data_view.set(value)
@property
def baseType(self):
data_view = og.AttributeValueHelper(self._attributes.baseType)
return data_view.get()
@baseType.setter
def baseType(self, value):
data_view = og.AttributeValueHelper(self._attributes.baseType)
data_view.set(value)
@property
def componentCount(self):
data_view = og.AttributeValueHelper(self._attributes.componentCount)
return data_view.get()
@componentCount.setter
def componentCount(self, value):
data_view = og.AttributeValueHelper(self._attributes.componentCount)
data_view.set(value)
@property
def fullType(self):
data_view = og.AttributeValueHelper(self._attributes.fullType)
return data_view.get()
@fullType.setter
def fullType(self, value):
data_view = og.AttributeValueHelper(self._attributes.fullType)
data_view.set(value)
@property
def role(self):
data_view = og.AttributeValueHelper(self._attributes.role)
return data_view.get()
@role.setter
def role(self, value):
data_view = og.AttributeValueHelper(self._attributes.role)
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 = OgnAttrTypeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnAttrTypeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnAttrTypeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,297 | Python | 46.965318 | 253 | 0.655538 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnBundleInspectorDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.BundleInspector
This node creates independent outputs containing information about the contents of a bundle attribute. It can be used for
testing or debugging what is inside a bundle as it flows through the graph. The bundle is inspected recursively, so any bundles
inside of the main bundle have their contents added to the output as well. The bundle contents can be printed when the node
evaluates, and it passes the input straight through unchanged so you can insert this node between two nodes to inspect the
data flowing through the graph.
"""
import carb
import numpy
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnBundleInspectorDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.BundleInspector
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.bundle
inputs.inspectDepth
inputs.print
Outputs:
outputs.arrayDepths
outputs.attributeCount
outputs.bundle
outputs.childCount
outputs.count
outputs.names
outputs.roles
outputs.tupleCounts
outputs.types
outputs.values
"""
# 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:bundle', 'bundle', 0, 'Bundle To Analyze', 'The attribute bundle to be inspected', {}, True, None, False, ''),
('inputs:inspectDepth', 'int', 0, 'Inspect Depth', 'The depth that the inspector is going to traverse and print.\n0 means just attributes on the input bundles. 1 means its immediate children. -1 means infinity.', {ogn.MetadataKeys.DEFAULT: '1'}, True, 1, False, ''),
('inputs:print', 'bool', 0, 'Print Contents', 'Setting to true prints the contents of the bundle when the node evaluates', {}, True, False, False, ''),
('outputs:arrayDepths', 'int[]', 0, 'Array Depths', 'List of the array depths of attributes present in the bundle', {}, True, None, False, ''),
('outputs:attributeCount', 'uint64', 0, 'Attribute Count', 'Number of attributes present in the bundle. Every other output is an array that\nshould have this number of elements in it.', {}, True, None, False, ''),
('outputs:bundle', 'bundle', 0, 'Bundle Passthrough', 'The attribute bundle passed through as-is from the input bundle', {}, True, None, False, ''),
('outputs:childCount', 'uint64', 0, 'Child Count', 'Number of child bundles present in the bundle.', {}, True, None, False, ''),
('outputs:count', 'uint64', 0, 'Attribute Count', 'Number of attributes present in the bundle. Every other output is an array that\nshould have this number of elements in it.', {ogn.MetadataKeys.HIDDEN: 'true'}, True, None, False, ''),
('outputs:names', 'token[]', 0, 'Attribute Names', 'List of the names of attributes present in the bundle', {}, True, None, False, ''),
('outputs:roles', 'token[]', 0, 'Attribute Roles', 'List of the names of the roles of attributes present in the bundle', {}, True, None, False, ''),
('outputs:tupleCounts', 'int[]', 0, 'Tuple Counts', 'List of the tuple counts of attributes present in the bundle', {}, True, None, False, ''),
('outputs:types', 'token[]', 0, 'Attribute Base Types', 'List of the types of attributes present in the bundle', {}, True, None, False, ''),
('outputs:values', 'token[]', 0, 'Attribute Values', 'List of the bundled attribute values, converted to token format', {}, 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.bundle = og.AttributeRole.BUNDLE
role_data.outputs.bundle = og.AttributeRole.BUNDLE
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.bundle"""
return self.__bundles.bundle
@property
def inspectDepth(self):
data_view = og.AttributeValueHelper(self._attributes.inspectDepth)
return data_view.get()
@inspectDepth.setter
def inspectDepth(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.inspectDepth)
data_view = og.AttributeValueHelper(self._attributes.inspectDepth)
data_view.set(value)
@property
def print(self):
data_view = og.AttributeValueHelper(self._attributes.print)
return data_view.get()
@print.setter
def print(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.print)
data_view = og.AttributeValueHelper(self._attributes.print)
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self.arrayDepths_size = None
self.names_size = None
self.roles_size = None
self.tupleCounts_size = None
self.types_size = None
self.values_size = None
self._batchedWriteValues = { }
@property
def arrayDepths(self):
data_view = og.AttributeValueHelper(self._attributes.arrayDepths)
return data_view.get(reserved_element_count=self.arrayDepths_size)
@arrayDepths.setter
def arrayDepths(self, value):
data_view = og.AttributeValueHelper(self._attributes.arrayDepths)
data_view.set(value)
self.arrayDepths_size = data_view.get_array_size()
@property
def attributeCount(self):
data_view = og.AttributeValueHelper(self._attributes.attributeCount)
return data_view.get()
@attributeCount.setter
def attributeCount(self, value):
data_view = og.AttributeValueHelper(self._attributes.attributeCount)
data_view.set(value)
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.bundle"""
return self.__bundles.bundle
@bundle.setter
def bundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.bundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.bundle.bundle = bundle
@property
def childCount(self):
data_view = og.AttributeValueHelper(self._attributes.childCount)
return data_view.get()
@childCount.setter
def childCount(self, value):
data_view = og.AttributeValueHelper(self._attributes.childCount)
data_view.set(value)
@property
def count(self):
data_view = og.AttributeValueHelper(self._attributes.count)
return data_view.get()
@count.setter
def count(self, value):
data_view = og.AttributeValueHelper(self._attributes.count)
data_view.set(value)
@property
def names(self):
data_view = og.AttributeValueHelper(self._attributes.names)
return data_view.get(reserved_element_count=self.names_size)
@names.setter
def names(self, value):
data_view = og.AttributeValueHelper(self._attributes.names)
data_view.set(value)
self.names_size = data_view.get_array_size()
@property
def roles(self):
data_view = og.AttributeValueHelper(self._attributes.roles)
return data_view.get(reserved_element_count=self.roles_size)
@roles.setter
def roles(self, value):
data_view = og.AttributeValueHelper(self._attributes.roles)
data_view.set(value)
self.roles_size = data_view.get_array_size()
@property
def tupleCounts(self):
data_view = og.AttributeValueHelper(self._attributes.tupleCounts)
return data_view.get(reserved_element_count=self.tupleCounts_size)
@tupleCounts.setter
def tupleCounts(self, value):
data_view = og.AttributeValueHelper(self._attributes.tupleCounts)
data_view.set(value)
self.tupleCounts_size = data_view.get_array_size()
@property
def types(self):
data_view = og.AttributeValueHelper(self._attributes.types)
return data_view.get(reserved_element_count=self.types_size)
@types.setter
def types(self, value):
data_view = og.AttributeValueHelper(self._attributes.types)
data_view.set(value)
self.types_size = data_view.get_array_size()
@property
def values(self):
data_view = og.AttributeValueHelper(self._attributes.values)
return data_view.get(reserved_element_count=self.values_size)
@values.setter
def values(self, value):
data_view = og.AttributeValueHelper(self._attributes.values)
data_view.set(value)
self.values_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 = OgnBundleInspectorDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnBundleInspectorDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnBundleInspectorDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 13,048 | Python | 47.509294 | 274 | 0.650061 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGetGatheredAttributeDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.GetGatheredAttribute
Copies gathered scaler/vector attribute values from the Gather buckets into an array attribute PROTOTYPE DO NOT USE, Requires
GatherPrototype
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
from typing import Any
class OgnGetGatheredAttributeDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.GetGatheredAttribute
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.gatherId
inputs.name
Outputs:
outputs.value
"""
# 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:gatherId', 'uint64', 0, None, 'The GatherId of the Gather containing the attribute values', {}, True, 0, False, ''),
('inputs:name', 'token', 0, None, 'The name of the gathered attribute to join', {}, True, '', False, ''),
('outputs:value', 'any', 2, None, 'The gathered attribute values as an array', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"gatherId", "name", "_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.gatherId, self._attributes.name]
self._batchedReadValues = [0, ""]
@property
def gatherId(self):
return self._batchedReadValues[0]
@gatherId.setter
def gatherId(self, value):
self._batchedReadValues[0] = value
@property
def name(self):
return self._batchedReadValues[1]
@name.setter
def name(self, value):
self._batchedReadValues[1] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""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 value(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.value"""
return og.RuntimeAttribute(self._attributes.value.get_attribute_data(), self._context, False)
@value.setter
def value(self, value_to_set: Any):
"""Assign another attribute's value to outputs.value"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.value.value = value_to_set.value
else:
self.value.value = value_to_set
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 = OgnGetGatheredAttributeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnGetGatheredAttributeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnGetGatheredAttributeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,986 | Python | 49.737288 | 133 | 0.659372 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGetPrimPathsDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.GetPrimPaths
Generates a path array from the specified relationship. This is useful when absolute prim paths may change.
"""
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 OgnGetPrimPathsDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.GetPrimPaths
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.prims
Outputs:
outputs.primPaths
"""
# 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:prims', 'target', 0, None, 'Relationship to prims on the stage', {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, True, [], False, ''),
('outputs:primPaths', 'token[]', 0, None, 'The absolute paths of the given prims as a token array', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.prims = og.AttributeRole.TARGET
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 prims(self):
data_view = og.AttributeValueHelper(self._attributes.prims)
return data_view.get()
@prims.setter
def prims(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prims)
data_view = og.AttributeValueHelper(self._attributes.prims)
data_view.set(value)
self.prims_size = data_view.get_array_size()
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.primPaths_size = None
self._batchedWriteValues = { }
@property
def primPaths(self):
data_view = og.AttributeValueHelper(self._attributes.primPaths)
return data_view.get(reserved_element_count=self.primPaths_size)
@primPaths.setter
def primPaths(self, value):
data_view = og.AttributeValueHelper(self._attributes.primPaths)
data_view.set(value)
self.primPaths_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 = OgnGetPrimPathsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnGetPrimPathsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnGetPrimPathsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,629 | Python | 45.528925 | 147 | 0.671345 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnModuloDatabase.py | """Support for simplified access to data on nodes of type omni.graph.nodes.Modulo
Computes the modulo of integer inputs (A % B), which is the remainder of A / B If B is zero, the result is zero. If A and
B are both non-negative the result is non-negative, otherwise the sign of the result is undefined.
"""
from typing import Any
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnModuloDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.nodes.Modulo
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
Outputs:
outputs.result
"""
# 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:a', 'int,int64,uchar,uint,uint64', 1, 'A', 'The dividend of (A % B)', {}, True, None, False, ''),
('inputs:b', 'int,int64,uchar,uint,uint64', 1, 'B', 'The divisor of (A % B)', {}, True, None, False, ''),
('outputs:result', 'int,int64,uchar,uint,uint64', 1, 'Result', 'Modulo (A % B), the remainder of A / B', {}, 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 a(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.a"""
return og.RuntimeAttribute(self._attributes.a.get_attribute_data(), self._context, True)
@a.setter
def a(self, value_to_set: Any):
"""Assign another attribute's value to outputs.a"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.a.value = value_to_set.value
else:
self.a.value = value_to_set
@property
def b(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.b"""
return og.RuntimeAttribute(self._attributes.b.get_attribute_data(), self._context, True)
@b.setter
def b(self, value_to_set: Any):
"""Assign another attribute's value to outputs.b"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.b.value = value_to_set.value
else:
self.b.value = value_to_set
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 result(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.result"""
return og.RuntimeAttribute(self._attributes.result.get_attribute_data(), self._context, False)
@result.setter
def result(self, value_to_set: Any):
"""Assign another attribute's value to outputs.result"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.result.value = value_to_set.value
else:
self.result.value = value_to_set
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 = OgnModuloDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnModuloDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnModuloDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,245 | Python | 47.046153 | 140 | 0.6506 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLookAtRotation.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/gf/rotation.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/math/linalg/SafeCast.h>
#include <omni/math/linalg/vec.h>
#include <OgnGetLookAtRotationDatabase.h>
namespace omni
{
namespace graph
{
namespace action
{
class OgnGetLookAtRotation
{
pxr::TfToken m_upAxisToken;
static omni::math::linalg::vec3d getSceneUp(OgnGetLookAtRotationDatabase& db)
{
// Default to the Y-axis if anything goes wrong.
omni::math::linalg::vec3d up = omni::math::linalg::vec3d::YAxis();
long stageId = db.abi_context().iContext->getStageId(db.abi_context());
auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (stage)
{
auto& state = db.internalState<OgnGetLookAtRotation>();
pxr::VtValue value;
if (stage->GetMetadata(state.m_upAxisToken, &value))
{
std::string upAxisStr = value.Cast<std::string>().Get<std::string>();
if ((upAxisStr == "X") || (upAxisStr == "x"))
{
up = omni::math::linalg::vec3d::XAxis();
}
else if ((upAxisStr == "Z") || (upAxisStr == "z"))
{
up = omni::math::linalg::vec3d::ZAxis();
}
}
}
return up;
}
public:
OgnGetLookAtRotation()
{
// Cache the token.
m_upAxisToken = pxr::TfToken("upAxis");
}
static bool compute(OgnGetLookAtRotationDatabase& db)
{
auto const start = db.inputs.start();
auto const target = db.inputs.target();
auto const forward = db.inputs.forward();
auto up = db.inputs.up();
// If 'up' is zero, use the scene's up.
if (up.GetLengthSq() == 0.0)
{
up = getSceneUp(db);
}
omni::math::linalg::vec3d const aimVec = target - start;
omni::math::linalg::vec3d const eyeU = aimVec.GetNormalized();
omni::math::linalg::vec3d eyeV = up.GetNormalized();
omni::math::linalg::vec3d const eyeW = (eyeU ^ eyeV).GetNormalized();
// eyeW and eyeU are orthogonal unit vectors so eyeV will be one as well.
eyeV = eyeW ^ eyeU;
auto localMtx = omni::math::linalg::matrix4d().SetIdentity();
omni::math::linalg::vec3d const eyeUL = forward.GetNormalized();
omni::math::linalg::vec3d eyeVL = up.GetNormalized();
omni::math::linalg::vec3d const eyeWL = (eyeUL ^ eyeVL).GetNormalized();
// eyeWL and eyeUL are orthogonal unit vectors so eyeVL will be one as well.
eyeVL = eyeWL ^ eyeUL;
localMtx.SetRow3(0, eyeUL);
localMtx.SetRow3(1, eyeVL);
localMtx.SetRow3(2, eyeWL);
// The actual aiming vectors
auto newEyeMtx = omni::math::linalg::matrix4d().SetIdentity();
newEyeMtx.SetRow3(0, eyeU);
newEyeMtx.SetRow3(1, eyeV);
newEyeMtx.SetRow3(2, eyeW);
// Output
omni::math::linalg::matrix4d aimMtx = localMtx.GetInverse() * newEyeMtx;
aimMtx.SetRow3(3, start);
omni::math::linalg::quatd orientation = aimMtx.ExtractRotation();
pxr::GfRotation rotation(omni::math::linalg::safeCastToUSD(orientation));
// extract the world space euler angles
pxr::GfVec3d decomposed = rotation.Decompose(pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis());
pxr::GfVec3d rotateXYZ(decomposed[2], decomposed[1], decomposed[0]);
db.outputs.rotateXYZ() = omni::math::linalg::safeCastToOmni(rotateXYZ);
db.outputs.orientation() = orientation;
return true;
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
| 4,307 | C++ | 32.138461 | 122 | 0.614813 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide_Tuple3.cpp | #include "OgnDivideHelper.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
bool tryComputeTuple3(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
return _tryComputeTuple<3>(db, a, b, result, count);
}
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
| 397 | C++ | 18.899999 | 118 | 0.702771 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNthRoot.cpp | // Copyright (c) 2022-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.
//
#include <OgnNthRootDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Helper functions to try doing an addition operation on two input attributes.
* We assume the runtime attributes have type T and the other one is double.
* The first input is either an array or a singular value, and the second input is a single double value
*
* @param db: database object
* @return True if we can get a result properly, false if not
*/
/**
* Used when input type is resolved as Half
*/
bool tryComputeAssumingType(OgnNthRootDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
double res;
switch (b)
{
case 3:
res = std::cbrt(a);
break;
case 2:
res = std::sqrt(a);
break;
default:
res = std::pow(static_cast<double>(static_cast<float>(a)), static_cast<double>(1.0 / static_cast<double>(b)));
break;
}
result = static_cast<pxr::GfHalf>(static_cast<float>(res));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, int, pxr::GfHalf>(db.inputs.value(), db.inputs.nthRoot(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnNthRootDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
switch (b)
{
case 3:
result = static_cast<T>(std::cbrt(a));
break;
case 2:
result = static_cast<T>(std::sqrt(a));
break;
default:
result = static_cast<T>(std::pow(a, 1.0 / static_cast<double>(b)));
break;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, int, T>(db.inputs.value(), db.inputs.nthRoot(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as int type
*/
template <typename T, typename M>
bool tryComputeAssumingType(OgnNthRootDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
switch (b)
{
case 3:
result = static_cast<M>(std::cbrt(a));
break;
case 2:
result = static_cast<M>(std::sqrt(a));
break;
default:
result = static_cast<M>(std::pow(a, 1.0 / static_cast<double>(b)));
break;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, int, M>(
db.inputs.value(), db.inputs.nthRoot(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as Half
*/
template <size_t N>
bool tryComputeAssumingType(OgnNthRootDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
double res;
switch (b)
{
case 3:
res = std::cbrt(a);
break;
case 2:
res = std::sqrt(a);
break;
default:
res = std::pow(static_cast<double>(static_cast<float>(a)), static_cast<double>(1.0 / static_cast<double>(b)));
break;
}
result = static_cast<pxr::GfHalf>(static_cast<float>(res));
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, pxr::GfHalf, int, pxr::GfHalf>(
db.inputs.value(), db.inputs.nthRoot(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as any non-int numeric type other than Half
*/
template <typename T, size_t N>
bool tryComputeAssumingType(OgnNthRootDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
switch (b)
{
case 3:
result = static_cast<T>(std::cbrt(a));
break;
case 2:
result = static_cast<T>(std::sqrt(a));
break;
default:
result = static_cast<T>(std::pow(a, 1.0 / static_cast<double>(b)));
break;
}
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int, T>(
db.inputs.value(), db.inputs.nthRoot(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as int type
*/
template <typename T, size_t N, typename M>
bool tryComputeAssumingType(OgnNthRootDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
switch (b)
{
case 3:
result = static_cast<M>(std::cbrt(a));
break;
case 2:
result = static_cast<M>(std::sqrt(a));
break;
default:
result = static_cast<M>(std::pow(a, 1.0 / static_cast<double>(b)));
break;
}
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int, M>(
db.inputs.value(), db.inputs.nthRoot(), db.outputs.result(), functor, count);
}
} // namespace
class OgnNthRoot
{
public:
static bool computeVectorized(OgnNthRootDatabase& db, size_t count)
{
try
{
const auto& vType = db.inputs.value().type();
switch (vType.componentCount)
{
case 1:
// All possible types excluding ogn::string and bool
// scalars
switch (vType.baseType)
{
case BaseDataType::eDouble:
return tryComputeAssumingType<double>(db, count);
case BaseDataType::eHalf: // Specifically for pxr::GfHalf
return tryComputeAssumingType(db, count);
case BaseDataType::eFloat:
return tryComputeAssumingType<float>(db, count);
case BaseDataType::eInt:
return tryComputeAssumingType<int32_t, double>(db, count);
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t, double>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char, double>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t, double>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t, double>(db, count);
default:
break;
}
case 2:
switch (vType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingType<int32_t, 2, double>(db, count);
case BaseDataType::eDouble:
return tryComputeAssumingType<double, 2>(db, count);
case BaseDataType::eFloat:
return tryComputeAssumingType<float, 2>(db, count);
case BaseDataType::eHalf:
return tryComputeAssumingType<2>(db, count);
default:
break;
}
case 3:
switch (vType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingType<int32_t, 3, double>(db, count);
case BaseDataType::eDouble:
return tryComputeAssumingType<double, 3>(db, count);
case BaseDataType::eFloat:
return tryComputeAssumingType<float, 3>(db, count);
case BaseDataType::eHalf:
return tryComputeAssumingType<3>(db, count);
default:
break;
}
case 4: // quaternion (IJKR), RGBA, etc
switch (vType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingType<int32_t, 4, double>(db, count);
case BaseDataType::eDouble:
return tryComputeAssumingType<double, 4>(db, count);
case BaseDataType::eFloat:
return tryComputeAssumingType<float, 4>(db, count);
case BaseDataType::eHalf:
return tryComputeAssumingType<4>(db, count);
default:
break;
}
case 9: // Matrix3f type
if (vType.baseType == BaseDataType::eDouble)
{
return tryComputeAssumingType<double, 9>(db, count);
}
case 16: // Matrix4f type
if (vType.baseType == BaseDataType::eDouble)
{
return tryComputeAssumingType<double, 16>(db, count);
}
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = value.iAttribute->getResolvedType(value);
Type newType(BaseDataType::eDouble, valueType.componentCount, valueType.arrayDepth, valueType.role);
// Require inputs to be resolved before determining sum's type
switch (valueType.baseType)
{
case BaseDataType::eUChar:
case BaseDataType::eInt:
case BaseDataType::eUInt:
case BaseDataType::eInt64:
case BaseDataType::eUInt64:
result.iAttribute->setResolvedType(result, newType);
break;
case BaseDataType::eUnknown:
break;
default:
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
break;
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 10,753 | C++ | 33.467949 | 165 | 0.562448 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAcos.cpp | // 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.
//
#include <OgnAcosDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnAcosDatabase& db)
{
auto functor = [](auto const& in, auto& out)
{
out = static_cast<T>(pxr::GfRadiansToDegrees(std::acos(in)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnAcosDatabase& db)
{
auto functor = [](auto const& in, auto& out)
{
out = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(std::acos(in))));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor);
}
} // namespace
class OgnAcos
{
public:
static bool compute(OgnAcosDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not perform Arccosine funtion : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto input = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::value.token());
auto inputType = input.iAttribute->getResolvedType(input);
// Require inputs to be resolved before determining output's type
if (inputType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { input, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,916 | C++ | 31.054945 | 118 | 0.665295 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAtan.cpp | // 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.
//
#include <OgnAtanDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnAtanDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<T>(pxr::GfRadiansToDegrees(std::atan(a)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor);
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnAtanDatabase& db)
{
auto functor = [](auto const& a, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(std::atan(a))));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor);
}
} // namespace
class OgnAtan
{
public:
static bool compute(OgnAtanDatabase& db)
{
try
{
// All possible types excluding ogn::string and bool
// scalers
if (tryComputeAssumingType<double>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf
else if (tryComputeAssumingType<float>(db)) return true;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Could not perform Arctangent funtion : %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::value.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require inputs to be resolved before determining output's type
if (valueType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,926 | C++ | 30.815217 | 118 | 0.666097 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDistance3D.cpp | // 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.
//
#include <OgnDistance3DDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnDistance3DDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]) + (b[2] - a[2]) * (b[2] - a[2]));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[3], T[3], T>(db.inputs.a(), db.inputs.b(), db.outputs.distance(), functor, count);
}
} // namespace
class OgnDistance3D
{
public:
static bool computeVectorized(OgnDistance3DDatabase& db, size_t count)
{
try
{
if (tryComputeAssumingType<double>(db, count)) return true;
else if (tryComputeAssumingType<float>(db, count)) return true;
else if (tryComputeAssumingType<pxr::GfHalf>(db, count)) return true;
else
{
db.logWarning("OgnDistance3D: Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnDistance3D: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto distance = node.iNode->getAttributeByToken(node, outputs::distance.token());
auto typeA = a.iAttribute->getResolvedType(a);
auto typeB = a.iAttribute->getResolvedType(b);
const Type invalid;
// Require a and b to be resolved before determining result's type
if (typeA != invalid && typeB != invalid)
{
uint8_t ad = std::max(typeA.arrayDepth, typeB.arrayDepth);
AttributeObj attrs[] = { a, b, distance };
uint8_t tupleCounts[] = { 3, 3, 1 };
uint8_t arrayDepths[] = { typeA.arrayDepth, typeB.arrayDepth, ad };
AttributeRole roles[] = { AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone };
node.iNode->resolvePartiallyCoupledAttributes(node, attrs, tupleCounts, arrayDepths, roles, 3);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,894 | C++ | 32.66279 | 141 | 0.638563 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSubtract.cpp | // 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.
//
#include <OgnSubtractDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnSubtractDatabase& db, size_t count)
{
auto const& dynamicInputs = db.getDynamicInputs();
if (dynamicInputs.empty())
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a - b;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.a(), db.inputs.b(), db.outputs.difference(), functor, count);
}
else
{
std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() };
inputArray.reserve(dynamicInputs.size() + 2);
for (auto const& input : dynamicInputs)
{
inputArray.emplace_back(input());
}
auto functor = [](const auto& input, auto& result)
{
result = result - input;
};
return ogn::compute::tryComputeInputsWithArrayBroadcasting<T>(inputArray, db.outputs.difference(), functor, count);
}
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnSubtractDatabase& db, size_t count)
{
auto const& dynamicInputs = db.getDynamicInputs();
if (dynamicInputs.empty())
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a - b;
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(db.inputs.a(), db.inputs.b(), db.outputs.difference(), functor, count);
}
else
{
std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() };
inputArray.reserve(dynamicInputs.size() + 2);
for (auto const& input : dynamicInputs)
{
inputArray.emplace_back(input());
}
auto functor = [](const auto& input, auto& result)
{
result = result - input;
};
return ogn::compute::tryComputeInputsWithTupleBroadcasting<N, T>(inputArray, db.outputs.difference(), functor, count);
}
}
} // namespace
class OgnSubtract
{
public:
static bool computeVectorized(OgnSubtractDatabase& db, size_t count)
{
auto& differenceType = db.outputs.difference().type();
// Compute the components, if the types are all resolved.
try
{
switch (differenceType.baseType)
{
case BaseDataType::eDouble:
switch (differenceType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (differenceType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (differenceType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (differenceType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto totalCount = node.iNode->getAttributeCount(node);
std::vector<AttributeObj> allAttributes(totalCount);
node.iNode->getAttributes(node, allAttributes.data(), totalCount);
std::vector<AttributeObj> attributes;
std::vector<uint8_t> componentCounts;
std::vector<uint8_t> arrayDepths;
std::vector<AttributeRole> roles;
attributes.reserve(totalCount - 2);
componentCounts.reserve(totalCount - 2);
arrayDepths.reserve(totalCount - 2);
roles.reserve(totalCount - 2);
uint8_t maxArrayDepth = 0;
uint8_t maxComponentCount = 0;
for (auto const& attr : allAttributes)
{
if (attr.iAttribute->getPortType(attr) == AttributePortType::kAttributePortType_Input)
{
auto resolvedType = attr.iAttribute->getResolvedType(attr);
// if some inputs are not connected stop - the output port resolution is only completed when all inputs
// are connected
if (resolvedType.baseType == BaseDataType::eUnknown)
return;
componentCounts.push_back(resolvedType.componentCount);
arrayDepths.push_back(resolvedType.arrayDepth);
roles.push_back(resolvedType.role);
maxComponentCount = std::max(maxComponentCount, resolvedType.componentCount);
maxArrayDepth = std::max(maxArrayDepth, resolvedType.arrayDepth);
attributes.push_back(attr);
}
}
auto result = node.iNode->getAttributeByToken(node, outputs::difference.token());
attributes.push_back(result);
// All inputs and the output should have the same tuple count
componentCounts.push_back(maxComponentCount);
// Allow for a mix of singular and array inputs. If any input is an array, the output must be an array
arrayDepths.push_back(maxArrayDepth);
// Copy the attribute role from the resolved type to the output type
roles.push_back(AttributeRole::eUnknown);
node.iNode->resolvePartiallyCoupledAttributes(
node, attributes.data(), componentCounts.data(), arrayDepths.data(), roles.data(), attributes.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
| 8,257 | C++ | 39.282927 | 138 | 0.603609 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnInvertMatrix.cpp | // 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.
//
#include <OgnInvertMatrixDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <exception>
using omni::math::linalg::matrix3d;
using omni::math::linalg::matrix4d;
namespace omni
{
namespace graph
{
namespace nodes
{
void computeMatrix4Inverse(const double input[16], double result[16])
{
auto& output = *reinterpret_cast<matrix4d*>(result);
output = reinterpret_cast<const matrix4d*>(input)->GetInverse();
}
void computeMatrix3Inverse(const double input[9], double result[9])
{
auto& output = *reinterpret_cast<matrix3d*>(result);
output = reinterpret_cast<const matrix3d*>(input)->GetInverse();
}
class OgnInvertMatrix
{
public:
static bool compute(OgnInvertMatrixDatabase& db)
{
auto& matrixInput = db.inputs.matrix();
auto& matrixOutput = db.outputs.invertedMatrix();
if (auto matrix = matrixInput.get<double[9]>())
{
if (auto output = matrixOutput.get<double[9]>())
{
computeMatrix3Inverse(*matrix, *output);
}
}
else if (auto matrix = matrixInput.get<double[16]>())
{
if (auto output = matrixOutput.get<double[16]>())
{
computeMatrix4Inverse(*matrix, *output);
}
}
else if (auto matrices = matrixInput.get<double[][9]>())
{
if (auto output = matrixOutput.get<double[][9]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
computeMatrix3Inverse((*matrices)[i], (*output)[i]);
}
}
}
else if (auto matrices = matrixInput.get<double[][16]>())
{
if (auto output = matrixOutput.get<double[][16]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
computeMatrix4Inverse((*matrices)[i], (*output)[i]);
}
}
}
else
{
db.logWarning("OgnInvertMatrix: Failed to resolve input types");
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node) {
std::array<AttributeObj, 2> attrs {
node.iNode->getAttributeByToken(node, inputs::matrix.token()),
node.iNode->getAttributeByToken(node, outputs::invertedMatrix.token())
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 3,090 | C++ | 29.303921 | 82 | 0.589968 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCeil.cpp | // 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.
//
#include <OgnCeilDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnCeilDatabase& db)
{
auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::ceil(a)); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, int>(db.inputs.a(), db.outputs.result(), functor);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnCeilDatabase& db)
{
auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::ceil(a)); };
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int>(db.inputs.a(), db.outputs.result(), functor);
}
} // namespace
class OgnCeil
{
public:
static bool compute(OgnCeilDatabase& db)
{
try
{
auto& aType = db.inputs.a().type();
switch (aType.baseType)
{
case BaseDataType::eDouble:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db);
case 2:
return tryComputeAssumingType<double, 2>(db);
case 3:
return tryComputeAssumingType<double, 3>(db);
case 4:
return tryComputeAssumingType<double, 4>(db);
}
break;
case BaseDataType::eFloat:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db);
case 2:
return tryComputeAssumingType<float, 2>(db);
case 3:
return tryComputeAssumingType<float, 3>(db);
case 4:
return tryComputeAssumingType<float, 4>(db);
}
break;
case BaseDataType::eHalf:
switch (aType.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db);
}
break;
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = a.iAttribute->getResolvedType(a);
if (valueType.baseType != BaseDataType::eUnknown)
{
Type resultType(BaseDataType::eInt, valueType.componentCount, valueType.arrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 4,166 | C++ | 34.922413 | 113 | 0.541527 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnFMod.py | """
Module contains the OmniGraph node implementation of omni.graph.fmod
"""
import carb
import numpy as np
import omni.graph.core as og
class OgnFMod:
"""Node to find floating point remainder"""
@staticmethod
def compute(db) -> bool:
try:
db.outputs.result.value = np.fmod(db.inputs.a.value, db.inputs.b.value)
except TypeError as error:
db.log_error(f"Remainder could not be performed: {error}")
return False
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
atype = node.get_attribute("inputs:a").get_resolved_type()
btype = node.get_attribute("inputs:b").get_resolved_type()
resultattr = node.get_attribute("outputs:result")
resulttype = resultattr.get_resolved_type()
# we can only infer the output given both inputs are resolved and they are the same.
if (
atype.base_type != og.BaseDataType.UNKNOWN
and btype.base_type != og.BaseDataType.UNKNOWN
and resulttype.base_type == og.BaseDataType.UNKNOWN
):
if atype.base_type == btype.base_type:
sum_type = og.Type(
atype.base_type,
max(atype.tuple_count, btype.tuple_count),
max(atype.array_depth, btype.array_depth),
)
resultattr.set_resolved_type(sum_type)
else:
carb.log_warn(f"Can not compute remainder of types {atype} and {btype}")
| 1,538 | Python | 33.977272 | 92 | 0.598179 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide_Scalars.cpp | #include "OgnDivideHelper.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
// AType is a scalar float or double
template <typename AType, typename BType>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<!std::is_integral<AType>::value && !std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<double>(a) / static_cast<double>(b));
};
return ogn::compute::tryComputeWithArrayBroadcasting<AType, BType, AType>(
a, b, result, functor, count);
}
// AType is a scalar half
template <typename AType, typename BType>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<float>(static_cast<double>(a) / static_cast<double>(b)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<AType, BType, AType>(
a, b, result, functor, count);
}
// AType is a scalar integral => Force result to be a scalar double
template <typename AType, typename BType>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_integral<AType>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<double>(a) / static_cast<double>(b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<AType, BType, double>(
a, b, result, functor, count);
}
bool tryComputeScalars(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (tryComputeAssumingType<double, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, double>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, float>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, pxr::GfHalf>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, int32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, int64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, unsigned char>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, uint32_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int64_t, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<unsigned char, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint32_t, uint64_t>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<uint64_t, uint64_t>(db, a, b, result, count)) return true;
return false;
}
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
| 9,201 | C++ | 58.367742 | 147 | 0.620585 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide.cpp | // 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.
//
#include <OgnDivideDatabase.h>
#include "OgnDivideHelper.h"
#include <carb/logging/Log.h>
#include <type_traits>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnDivide
{
public:
static bool computeVectorized(OgnDivideDatabase& db, size_t count)
{
auto const& a = db.inputs.a();
auto const& b = db.inputs.b();
auto& result = db.outputs.result();
try
{
if (OGNDivideHelper::tryComputeScalars(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeTuple2(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeTuple3(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeTuple4(db, a, b, result, count))
return true;
if (OGNDivideHelper::tryComputeMatrices(db, a, b, result, count))
return true;
db.logWarning("OgnDivide: Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnDivide: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto aType = a.iAttribute->getResolvedType(a);
// Require inputs to be resolved before determining result's type
if (aType.baseType != BaseDataType::eUnknown)
{
// In the case of A being an integral - then we force a double
auto newType = aType;
if (aType.baseType == BaseDataType::eUChar
|| aType.baseType == BaseDataType::eInt
|| aType.baseType == BaseDataType::eUInt
|| aType.baseType == BaseDataType::eInt64
|| aType.baseType == BaseDataType::eUInt64)
{
newType.baseType = BaseDataType::eDouble;
}
result.iAttribute->setResolvedType(result, newType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,679 | C++ | 30.529411 | 85 | 0.619261 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCrossProduct.cpp | // 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.
//
#include <OgnCrossProductDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/vec.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T, size_t N>
bool tryComputeAssumingType(OgnCrossProductDatabase& db)
{
auto functor = [](auto const& a, auto const& b, auto& product)
{
const auto& vecA = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(a);
const auto& vecB = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(b);
auto& prod = *reinterpret_cast<omni::math::linalg::base_vec<T, N>*>(product);
prod = GfCross(vecA, vecB);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor);
}
} // namespace
class OgnCrossProduct
{
public:
static bool compute(OgnCrossProductDatabase& db)
{
try
{
auto& aType = db.inputs.a().type();
switch(aType.baseType)
{
case BaseDataType::eDouble:
switch(aType.componentCount)
{
case 3: return tryComputeAssumingType<double, 3>(db);
}
case BaseDataType::eFloat:
switch(aType.componentCount)
{
case 3: return tryComputeAssumingType<float, 3>(db);
}
case BaseDataType::eHalf:
switch(aType.componentCount)
{
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db);
}
default: db.logError("Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto product = node.iNode->getAttributeByToken(node, outputs::product.token());
// Require inputs to be resolved before determining product's type
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
if ((aType.role != AttributeRole::eVector && bType.role == AttributeRole::eNone) ||
(bType.role != AttributeRole::eVector && aType.role == AttributeRole::eNone))
{
node.iNode->logComputeMessageOnInstance(node, kAuthoringGraphIndex, ogn::Severity::eWarning,
formatString("Cross product with non-vector input of types: %s, %s",
getAttributeRoleName(aType.role).c_str(), getAttributeRoleName(bType.role).c_str()).c_str()
);
}
std::array<AttributeObj, 3> attrs { a, b, product };
// a, b, product should all have the same tuple count
std::array<uint8_t, 3> tupleCounts {
aType.componentCount,
bType.componentCount,
std::max(aType.componentCount, bType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
aType.arrayDepth,
bType.arrayDepth,
// Allow for a mix of singular and array inputs. If any input is an array, the output must be an array
std::max(aType.arrayDepth, bType.arrayDepth)
};
std::array<AttributeRole, 3> rolesBuf {
aType.role,
bType.role,
// Copy the attribute role from the resolved type to the output type
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
| 4,816 | C++ | 37.846774 | 149 | 0.58887 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomUnitVector.cpp | // 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.
//
#include "random/RandomNodeBase.h"
#include <OgnRandomUnitVectorDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomUnitVector : public NodeBase<OgnRandomUnitVector, OgnRandomUnitVectorDatabase>
{
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
}
static bool onCompute(OgnRandomUnitVectorDatabase& db, size_t count)
{
// TODO: Specify output type, we should be able to generate double precision output too...
return computeRandoms(db, count, [](GeneratorState& gen) { return gen.nextUnitVec3f(); });
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 1,245 | C++ | 28.666666 | 98 | 0.751807 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNormalize.cpp | // Copyright (c) 2022-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.
//
#include <OgnNormalizeDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/vec.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T, size_t N>
bool tryComputeAssumingType(OgnNormalizeDatabase& db, size_t count)
{
auto functor = [](auto const& vector, auto& result)
{
const auto& vec = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(vector);
auto& res = *reinterpret_cast<omni::math::linalg::base_vec<T, N>*>(result);
res = vec.GetNormalized();
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N]>(db.inputs.vector(), db.outputs.result(), functor, count);
}
} // namespace
class OgnNormalize
{
public:
static bool computeVectorized(OgnNormalizeDatabase& db, size_t count)
{
try
{
auto& type = db.inputs.vector().type();
switch (type.baseType)
{
case BaseDataType::eDouble:
switch (type.componentCount)
{
case 2:
return tryComputeAssumingType<double, 2>(db, count);
case 3:
return tryComputeAssumingType<double, 3>(db, count);
case 4:
return tryComputeAssumingType<double, 4>(db, count);
}
break;
case BaseDataType::eFloat:
switch (type.componentCount)
{
case 2:
return tryComputeAssumingType<float, 2>(db, count);
case 3:
return tryComputeAssumingType<float, 3>(db, count);
case 4:
return tryComputeAssumingType<float, 4>(db, count);
}
break;
case BaseDataType::eHalf:
switch (type.componentCount)
{
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
}
break;
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input type");
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
// Require input to be resolved before determining result's type
auto vectorType = vector.iAttribute->getResolvedType(vector);
if (vectorType.baseType != BaseDataType::eUnknown)
{
Type resultType(vectorType.baseType, vectorType.componentCount, vectorType.arrayDepth);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
| 4,056 | C++ | 34.902655 | 126 | 0.558925 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAbsolute.cpp | // 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.
//
#include <carb/logging/Log.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <OgnAbsoluteDatabase.h>
#include <NumericUtils.h>
#include <cmath>
#include <type_traits>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename T>
T ogAbs(T const& input) noexcept
{
if constexpr (std::is_unsigned_v<T>)
{
return input;
}
else
{
return std::abs(input);
}
}
template <typename T, size_t N>
struct ComputeAbsoluteValueAssumingType
{
bool operator()(OgnAbsoluteDatabase& db) const
{
if constexpr (N == 1)
{
auto functor = [](T const& input, T& absolute) { absolute = ogAbs(input); };
return ogn::compute::tryComputeWithArrayBroadcasting<T, T>(db.inputs.input(), db.outputs.absolute(), functor);
}
else
{
auto functor = [](auto const& input, auto& absolute)
{
for (size_t i = 0; i < N; ++i)
{
absolute[i] = ogAbs(input[i]);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N]>(
db.inputs.input(), db.outputs.absolute(), functor);
}
}
};
}
class OgnAbsolute
{
public:
static bool compute(OgnAbsoluteDatabase& db)
{
try
{
auto const& type = db.inputs.input().type();
if (!callForNumericAttribute<ComputeAbsoluteValueAssumingType>(db, type))
{
throw ogn::compute::InputError("Failed to resolve input type");
}
}
catch (ogn::compute::InputError& error)
{
db.logError("OgnAbsolute: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto input = node.iNode->getAttributeByToken(node, inputs::input.token());
auto absolute = node.iNode->getAttributeByToken(node, outputs::absolute.token());
auto inputType = input.iAttribute->getResolvedType(input);
if (inputType.baseType != BaseDataType::eUnknown)
{
absolute.iAttribute->setResolvedType(absolute, inputType);
}
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,698 | C++ | 24.462264 | 122 | 0.607858 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/warp_noise.h | // 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.
//
#pragma once
// This file contains code taken from Warp for implementing noise functions.
// Once Warp is released this file will be deleted and the nodes which use
// it rewritten to use Warp.
#include <cmath>
#include <sys/types.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#ifndef _EPSILON
#define _EPSILON 1e-6
#endif
#define M_PIf 3.14159265358979323846f
namespace omni {
namespace graph {
namespace nodes {
typedef pxr::GfVec2f vec2;
typedef pxr::GfVec3f vec3;
typedef pxr::GfVec4f vec4;
// Adapted from warp/warp/native/rand.h
//
inline uint32_t rand_pcg(uint32_t state)
{
uint32_t b = state * 747796405u + 2891336453u;
uint32_t c = ((b >> ((b >> 28u) + 4u)) ^ b) * 277803737u;
return (c >> 22u) ^ c;
}
inline uint32_t rand_init(int seed) { return rand_pcg(uint32_t(seed)); }
inline uint32_t rand_init(int seed, int offset) { return rand_pcg(uint32_t(seed) + rand_pcg(uint32_t(offset))); }
inline int randi(uint32_t& state) { state = rand_pcg(state); return int(state); }
inline int randi(uint32_t& state, int min, int max) { state = rand_pcg(state); return state % (max - min) + min; }
inline float randf(uint32_t& state) { state = rand_pcg(state); return float(state) / 0xffffffff; }
inline float randf(uint32_t& state, float min, float max) { return (max - min) * randf(state) + min; }
// Box-Muller method
inline float randn(uint32_t& state) { return std::sqrt(-2.f * std::log(randf(state))) * std::cos(2.f * M_PIf * randf(state)); }
// Adapted from warp/warp/native/noise.h
//
inline float smootherstep(float t)
{
return t * t * t * (t * (t * 6.f - 15.f) + 10.f);
}
inline float smootherstep_gradient(float t)
{
return 30.f * t * t * (t * (t - 2.f) + 1.f);
}
inline float interpolate(float a0, float a1, float t)
{
return (a1 - a0) * smootherstep(t) + a0;
}
inline float interpolate_gradient(float a0, float a1, float t, float d_a0, float d_a1, float d_t)
{
return (d_a1 - d_a0) * smootherstep(t) + (a1 - a0) * smootherstep_gradient(t) * d_t + d_a0;
}
inline float random_gradient_1d(uint32_t seed, int ix)
{
const uint32_t p1 = 73856093;
uint32_t idx = ix*p1;
uint32_t state = seed + idx;
return randf(state, -1.f, 1.f);
}
inline vec2 random_gradient_2d(uint32_t seed, int ix, int iy)
{
const uint32_t p1 = 73856093;
const uint32_t p2 = 19349663;
uint32_t idx = ix*p1 ^ iy*p2;
uint32_t state = seed + idx;
float phi = randf(state, 0.f, 2.f*M_PIf);
float x = std::cos(phi);
float y = std::sin(phi);
return vec2(x, y);
}
inline vec3 random_gradient_3d(uint32_t seed, int ix, int iy, int iz)
{
const uint32_t p1 = 73856093;
const uint32_t p2 = 19349663;
const uint32_t p3 = 53471161;
uint32_t idx = ix*p1 ^ iy*p2 ^ iz*p3;
uint32_t state = seed + idx;
float x = randn(state);
float y = randn(state);
float z = randn(state);
return vec3(x, y, z).GetNormalized();
}
inline vec4 random_gradient_4d(uint32_t seed, int ix, int iy, int iz, int it)
{
const uint32_t p1 = 73856093;
const uint32_t p2 = 19349663;
const uint32_t p3 = 53471161;
const uint32_t p4 = 10000019;
uint32_t idx = ix*p1 ^ iy*p2 ^ iz*p3 ^ it*p4;
uint32_t state = seed + idx;
float x = randn(state);
float y = randn(state);
float z = randn(state);
float t = randn(state);
return vec4(x, y, z, t).GetNormalized();
}
inline float dot_grid_gradient_1d(uint32_t seed, int ix, float dx)
{
float gradient = random_gradient_1d(seed, ix);
return dx*gradient;
}
inline float dot_grid_gradient_1d_gradient(uint32_t seed, int ix, float d_dx)
{
float gradient = random_gradient_1d(seed, ix);
return d_dx*gradient;
}
inline float dot_grid_gradient_2d(uint32_t seed, int ix, int iy, float dx, float dy)
{
vec2 gradient = random_gradient_2d(seed, ix, iy);
return (dx*gradient[0] + dy*gradient[1]);
}
inline float dot_grid_gradient_2d_gradient(uint32_t seed, int ix, int iy, float d_dx, float d_dy)
{
vec2 gradient = random_gradient_2d(seed, ix, iy);
return (d_dx*gradient[0] + d_dy*gradient[1]);
}
inline float dot_grid_gradient_3d(uint32_t seed, int ix, int iy, int iz, float dx, float dy, float dz)
{
vec3 gradient = random_gradient_3d(seed, ix, iy, iz);
return (dx*gradient[0] + dy*gradient[1] + dz*gradient[2]);
}
inline float dot_grid_gradient_3d_gradient(uint32_t seed, int ix, int iy, int iz, float d_dx, float d_dy, float d_dz)
{
vec3 gradient = random_gradient_3d(seed, ix, iy, iz);
return (d_dx*gradient[0] + d_dy*gradient[1] + d_dz*gradient[2]);
}
inline float dot_grid_gradient_4d(uint32_t seed, int ix, int iy, int iz, int it, float dx, float dy, float dz, float dt)
{
vec4 gradient = random_gradient_4d(seed, ix, iy, iz, it);
return (dx*gradient[0] + dy*gradient[1] + dz*gradient[2] + dt*gradient[3]);
}
inline float dot_grid_gradient_4d_gradient(uint32_t seed, int ix, int iy, int iz, int it, float d_dx, float d_dy, float d_dz, float d_dt)
{
vec4 gradient = random_gradient_4d(seed, ix, iy, iz, it);
return (d_dx*gradient[0] + d_dy*gradient[1] + d_dz*gradient[2] + d_dt*gradient[3]);
}
inline float noise_1d(uint32_t seed, int x0, int x1, float dx)
{
//vX
float v0 = dot_grid_gradient_1d(seed, x0, dx);
float v1 = dot_grid_gradient_1d(seed, x1, dx-1.f);
return interpolate(v0, v1, dx);
}
inline float noise_1d_gradient(uint32_t seed, int x0, int x1, float dx, float heaviside_x)
{
float v0 = dot_grid_gradient_1d(seed, x0, dx);
float d_v0_dx = dot_grid_gradient_1d_gradient(seed, x0, heaviside_x);
float v1 = dot_grid_gradient_1d(seed, x1, dx-1.f);
float d_v1_dx = dot_grid_gradient_1d_gradient(seed, x1, heaviside_x);
return interpolate_gradient(v0, v1, dx, d_v0_dx, d_v1_dx, heaviside_x);
}
inline float noise_2d(uint32_t seed, int x0, int y0, int x1, int y1, float dx, float dy)
{
//vXY
float v00 = dot_grid_gradient_2d(seed, x0, y0, dx, dy);
float v10 = dot_grid_gradient_2d(seed, x1, y0, dx-1.f, dy);
float xi0 = interpolate(v00, v10, dx);
float v01 = dot_grid_gradient_2d(seed, x0, y1, dx, dy-1.f);
float v11 = dot_grid_gradient_2d(seed, x1, y1, dx-1.f, dy-1.f);
float xi1 = interpolate(v01, v11, dx);
return interpolate(xi0, xi1, dy);
}
inline vec2 noise_2d_gradient(uint32_t seed, int x0, int y0, int x1, int y1, float dx, float dy, float heaviside_x, float heaviside_y)
{
float v00 = dot_grid_gradient_2d(seed, x0, y0, dx, dy);
float d_v00_dx = dot_grid_gradient_2d_gradient(seed, x0, y0, heaviside_x, 0.f);
float d_v00_dy = dot_grid_gradient_2d_gradient(seed, x0, y0, 0.0, heaviside_y);
float v10 = dot_grid_gradient_2d(seed, x1, y0, dx-1.f, dy);
float d_v10_dx = dot_grid_gradient_2d_gradient(seed, x1, y0, heaviside_x, 0.f);
float d_v10_dy = dot_grid_gradient_2d_gradient(seed, x1, y0, 0.0, heaviside_y);
float v01 = dot_grid_gradient_2d(seed, x0, y1, dx, dy-1.f);
float d_v01_dx = dot_grid_gradient_2d_gradient(seed, x0, y1, heaviside_x, 0.f);
float d_v01_dy = dot_grid_gradient_2d_gradient(seed, x0, y1, 0.0, heaviside_y);
float v11 = dot_grid_gradient_2d(seed, x1, y1, dx-1.f, dy-1.f);
float d_v11_dx = dot_grid_gradient_2d_gradient(seed, x1, y1, heaviside_x, 0.f);
float d_v11_dy = dot_grid_gradient_2d_gradient(seed, x1, y1, 0.0, heaviside_y);
float xi0 = interpolate(v00, v10, dx);
float d_xi0_dx = interpolate_gradient(v00, v10, dx, d_v00_dx, d_v10_dx, heaviside_x);
float d_xi0_dy = interpolate_gradient(v00, v10, dx, d_v00_dy, d_v10_dy, 0.0);
float xi1 = interpolate(v01, v11, dx);
float d_xi1_dx = interpolate_gradient(v01, v11, dx, d_v01_dx, d_v11_dx, heaviside_x);
float d_xi1_dy = interpolate_gradient(v01, v11, dx, d_v01_dy, d_v11_dy, 0.0);
float gradient_x = interpolate_gradient(xi0, xi1, dy, d_xi0_dx, d_xi1_dx, 0.0);
float gradient_y = interpolate_gradient(xi0, xi1, dy, d_xi0_dy, d_xi1_dy, heaviside_y);
return vec2(gradient_x, gradient_y);
}
inline float noise_3d(uint32_t seed, int x0, int y0, int z0, int x1, int y1, int z1, float dx, float dy, float dz)
{
//vXYZ
float v000 = dot_grid_gradient_3d(seed, x0, y0, z0, dx, dy, dz);
float v100 = dot_grid_gradient_3d(seed, x1, y0, z0, dx-1.f, dy, dz);
float xi00 = interpolate(v000, v100, dx);
float v010 = dot_grid_gradient_3d(seed, x0, y1, z0, dx, dy-1.f, dz);
float v110 = dot_grid_gradient_3d(seed, x1, y1, z0, dx-1.f, dy-1.f, dz);
float xi10 = interpolate(v010, v110, dx);
float yi0 = interpolate(xi00, xi10, dy);
float v001 = dot_grid_gradient_3d(seed, x0, y0, z1, dx, dy, dz-1.f);
float v101 = dot_grid_gradient_3d(seed, x1, y0, z1, dx-1.f, dy, dz-1.f);
float xi01 = interpolate(v001, v101, dx);
float v011 = dot_grid_gradient_3d(seed, x0, y1, z1, dx, dy-1.f, dz-1.f);
float v111 = dot_grid_gradient_3d(seed, x1, y1, z1, dx-1.f, dy-1.f, dz-1.f);
float xi11 = interpolate(v011, v111, dx);
float yi1 = interpolate(xi01, xi11, dy);
return interpolate(yi0, yi1, dz);
}
inline vec3 noise_3d_gradient(uint32_t seed, int x0, int y0, int z0, int x1, int y1, int z1, float dx, float dy, float dz, float heaviside_x, float heaviside_y, float heaviside_z)
{
float v000 = dot_grid_gradient_3d(seed, x0, y0, z0, dx, dy, dz);
float d_v000_dx = dot_grid_gradient_3d_gradient(seed, x0, y0, z0, heaviside_x, 0.f, 0.f);
float d_v000_dy = dot_grid_gradient_3d_gradient(seed, x0, y0, z0, 0.f, heaviside_y, 0.f);
float d_v000_dz = dot_grid_gradient_3d_gradient(seed, x0, y0, z0, 0.f, 0.f, heaviside_z);
float v100 = dot_grid_gradient_3d(seed, x1, y0, z0, dx-1.f, dy, dz);
float d_v100_dx = dot_grid_gradient_3d_gradient(seed, x1, y0, z0, heaviside_x, 0.f, 0.f);
float d_v100_dy = dot_grid_gradient_3d_gradient(seed, x1, y0, z0, 0.f, heaviside_y, 0.f);
float d_v100_dz = dot_grid_gradient_3d_gradient(seed, x1, y0, z0, 0.f, 0.f, heaviside_z);
float v010 = dot_grid_gradient_3d(seed, x0, y1, z0, dx, dy-1.f, dz);
float d_v010_dx = dot_grid_gradient_3d_gradient(seed, x0, y1, z0, heaviside_x, 0.f, 0.f);
float d_v010_dy = dot_grid_gradient_3d_gradient(seed, x0, y1, z0, 0.f, heaviside_y, 0.f);
float d_v010_dz = dot_grid_gradient_3d_gradient(seed, x0, y1, z0, 0.f, 0.f, heaviside_z);
float v110 = dot_grid_gradient_3d(seed, x1, y1, z0, dx-1.f, dy-1.f, dz);
float d_v110_dx = dot_grid_gradient_3d_gradient(seed, x1, y1, z0, heaviside_x, 0.f, 0.f);
float d_v110_dy = dot_grid_gradient_3d_gradient(seed, x1, y1, z0, 0.f, heaviside_y, 0.f);
float d_v110_dz = dot_grid_gradient_3d_gradient(seed, x1, y1, z0, 0.f, 0.f, heaviside_z);
float v001 = dot_grid_gradient_3d(seed, x0, y0, z1, dx, dy, dz-1.f);
float d_v001_dx = dot_grid_gradient_3d_gradient(seed, x0, y0, z1, heaviside_x, 0.f, 0.f);
float d_v001_dy = dot_grid_gradient_3d_gradient(seed, x0, y0, z1, 0.f, heaviside_y, 0.f);
float d_v001_dz = dot_grid_gradient_3d_gradient(seed, x0, y0, z1, 0.f, 0.f, heaviside_z);
float v101 = dot_grid_gradient_3d(seed, x1, y0, z1, dx-1.f, dy, dz-1.f);
float d_v101_dx = dot_grid_gradient_3d_gradient(seed, x1, y0, z1, heaviside_x, 0.f, 0.f);
float d_v101_dy = dot_grid_gradient_3d_gradient(seed, x1, y0, z1, 0.f, heaviside_y, 0.f);
float d_v101_dz = dot_grid_gradient_3d_gradient(seed, x1, y0, z1, 0.f, 0.f, heaviside_z);
float v011 = dot_grid_gradient_3d(seed, x0, y1, z1, dx, dy-1.f, dz-1.f);
float d_v011_dx = dot_grid_gradient_3d_gradient(seed, x0, y1, z1, heaviside_x, 0.f, 0.f);
float d_v011_dy = dot_grid_gradient_3d_gradient(seed, x0, y1, z1, 0.f, heaviside_y, 0.f);
float d_v011_dz = dot_grid_gradient_3d_gradient(seed, x0, y1, z1, 0.f, 0.f, heaviside_z);
float v111 = dot_grid_gradient_3d(seed, x1, y1, z1, dx-1.f, dy-1.f, dz-1.f);
float d_v111_dx = dot_grid_gradient_3d_gradient(seed, x1, y1, z1, heaviside_x, 0.f, 0.f);
float d_v111_dy = dot_grid_gradient_3d_gradient(seed, x1, y1, z1, 0.f, heaviside_y, 0.f);
float d_v111_dz = dot_grid_gradient_3d_gradient(seed, x1, y1, z1, 0.f, 0.f, heaviside_z);
float xi00 = interpolate(v000, v100, dx);
float d_xi00_dx = interpolate_gradient(v000, v100, dx, d_v000_dx, d_v100_dx, heaviside_x);
float d_xi00_dy = interpolate_gradient(v000, v100, dx, d_v000_dy, d_v100_dy, 0.f);
float d_xi00_dz = interpolate_gradient(v000, v100, dx, d_v000_dz, d_v100_dz, 0.f);
float xi10 = interpolate(v010, v110, dx);
float d_xi10_dx = interpolate_gradient(v010, v110, dx, d_v010_dx, d_v110_dx, heaviside_x);
float d_xi10_dy = interpolate_gradient(v010, v110, dx, d_v010_dy, d_v110_dy, 0.f);
float d_xi10_dz = interpolate_gradient(v010, v110, dx, d_v010_dz, d_v110_dz, 0.f);
float xi01 = interpolate(v001, v101, dx);
float d_xi01_dx = interpolate_gradient(v001, v101, dx, d_v001_dx, d_v101_dx, heaviside_x);
float d_xi01_dy = interpolate_gradient(v001, v101, dx, d_v001_dy, d_v101_dy, 0.f);
float d_xi01_dz = interpolate_gradient(v001, v101, dx, d_v001_dz, d_v101_dz, 0.f);
float xi11 = interpolate(v011, v111, dx);
float d_xi11_dx = interpolate_gradient(v011, v111, dx, d_v011_dx, d_v111_dx, heaviside_x);
float d_xi11_dy = interpolate_gradient(v011, v111, dx, d_v011_dy, d_v111_dy, 0.f);
float d_xi11_dz = interpolate_gradient(v011, v111, dx, d_v011_dz, d_v111_dz, 0.f);
float yi0 = interpolate(xi00, xi10, dy);
float d_yi0_dx = interpolate_gradient(xi00, xi10, dy, d_xi00_dx, d_xi10_dx, 0.f);
float d_yi0_dy = interpolate_gradient(xi00, xi10, dy, d_xi00_dy, d_xi10_dy, heaviside_y);
float d_yi0_dz = interpolate_gradient(xi00, xi10, dy, d_xi00_dz, d_xi10_dz, 0.f);
float yi1 = interpolate(xi01, xi11, dy);
float d_yi1_dx = interpolate_gradient(xi01, xi11, dy, d_xi01_dx, d_xi11_dx, 0.f);
float d_yi1_dy = interpolate_gradient(xi01, xi11, dy, d_xi01_dy, d_xi11_dy, heaviside_y);
float d_yi1_dz = interpolate_gradient(xi01, xi11, dy, d_xi01_dz, d_xi11_dz, 0.f);
float gradient_x = interpolate_gradient(yi0, yi1, dz, d_yi0_dy, d_yi1_dy, 0.f);
float gradient_y = interpolate_gradient(yi0, yi1, dz, d_yi0_dx, d_yi1_dx, 0.f);
float gradient_z = interpolate_gradient(yi0, yi1, dz, d_yi0_dz, d_yi1_dz, heaviside_z);
return vec3(gradient_x, gradient_y, gradient_z);
}
inline float noise_4d(uint32_t seed, int x0, int y0, int z0, int t0, int x1, int y1, int z1, int t1, float dx, float dy, float dz, float dt)
{
//vXYZT
float v0000 = dot_grid_gradient_4d(seed, x0, y0, z0, t0, dx, dy, dz, dt);
float v1000 = dot_grid_gradient_4d(seed, x1, y0, z0, t0, dx-1.f, dy, dz, dt);
float xi000 = interpolate(v0000, v1000, dx);
float v0100 = dot_grid_gradient_4d(seed, x0, y1, z0, t0, dx, dy-1.f, dz, dt);
float v1100 = dot_grid_gradient_4d(seed, x1, y1, z0, t0, dx-1.f, dy-1.f, dz, dt);
float xi100 = interpolate(v0100, v1100, dx);
float yi00 = interpolate(xi000, xi100, dy);
float v0010 = dot_grid_gradient_4d(seed, x0, y0, z1, t0, dx, dy, dz-1.f, dt);
float v1010 = dot_grid_gradient_4d(seed, x1, y0, z1, t0, dx-1.f, dy, dz-1.f, dt);
float xi010 = interpolate(v0010, v1010, dx);
float v0110 = dot_grid_gradient_4d(seed, x0, y1, z1, t0, dx, dy-1.f, dz-1.f, dt);
float v1110 = dot_grid_gradient_4d(seed, x1, y1, z1, t0, dx-1.f, dy-1.f, dz-1.f, dt);
float xi110 = interpolate(v0110, v1110, dx);
float yi10 = interpolate(xi010, xi110, dy);
float zi0 = interpolate(yi00, yi10, dz);
float v0001 = dot_grid_gradient_4d(seed, x0, y0, z0, t1, dx, dy, dz, dt-1.f);
float v1001 = dot_grid_gradient_4d(seed, x1, y0, z0, t1, dx-1.f, dy, dz, dt-1.f);
float xi001 = interpolate(v0001, v1001, dx);
float v0101 = dot_grid_gradient_4d(seed, x0, y1, z0, t1, dx, dy-1.f, dz, dt-1.f);
float v1101 = dot_grid_gradient_4d(seed, x1, y1, z0, t1, dx-1.f, dy-1.f, dz, dt-1.f);
float xi101 = interpolate(v0101, v1101, dx);
float yi01 = interpolate(xi001, xi101, dy);
float v0011 = dot_grid_gradient_4d(seed, x0, y0, z1, t1, dx, dy, dz-1.f, dt-1.f);
float v1011 = dot_grid_gradient_4d(seed, x1, y0, z1, t1, dx-1.f, dy, dz-1.f, dt-1.f);
float xi011 = interpolate(v0011, v1011, dx);
float v0111 = dot_grid_gradient_4d(seed, x0, y1, z1, t1, dx, dy-1.f, dz-1.f, dt-1.f);
float v1111 = dot_grid_gradient_4d(seed, x1, y1, z1, t1, dx-1.f, dy-1.f, dz-1.f, dt-1.f);
float xi111 = interpolate(v0111, v1111, dx);
float yi11 = interpolate(xi011, xi111, dy);
float zi1 = interpolate(yi01, yi11, dz);
return interpolate(zi0, zi1, dt);
}
inline vec4 noise_4d_gradient(uint32_t seed, int x0, int y0, int z0, int t0, int x1, int y1, int z1, int t1, float dx, float dy, float dz, float dt, float heaviside_x, float heaviside_y, float heaviside_z, float heaviside_t)
{
float v0000 = dot_grid_gradient_4d(seed, x0, y0, z0, t0, dx, dy, dz, dt);
float d_v0000_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0000_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0000_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0000_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1000 = dot_grid_gradient_4d(seed, x1, y0, z0, t0, dx-1.f, dy, dz, dt);
float d_v1000_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1000_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1000_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1000_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0100 = dot_grid_gradient_4d(seed, x0, y1, z0, t0, dx, dy-1.f, dz, dt);
float d_v0100_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0100_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0100_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0100_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1100 = dot_grid_gradient_4d(seed, x1, y1, z0, t0, dx-1.f, dy-1.f, dz, dt);
float d_v1100_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1100_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1100_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1100_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0010 = dot_grid_gradient_4d(seed, x0, y0, z1, t0, dx, dy, dz-1.f, dt);
float d_v0010_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0010_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0010_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0010_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1010 = dot_grid_gradient_4d(seed, x1, y0, z1, t0, dx-1.f, dy, dz-1.f, dt);
float d_v1010_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1010_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1010_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1010_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0110 = dot_grid_gradient_4d(seed, x0, y1, z1, t0, dx, dy-1.f, dz-1.f, dt);
float d_v0110_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v0110_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v0110_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v0110_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v1110 = dot_grid_gradient_4d(seed, x1, y1, z1, t0, dx-1.f, dy-1.f, dz-1.f, dt);
float d_v1110_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, heaviside_x, 0.f, 0.f, 0.f);
float d_v1110_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, 0.f, heaviside_y, 0.f, 0.f);
float d_v1110_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, 0.f, 0.f, heaviside_z, 0.f);
float d_v1110_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t0, 0.f, 0.f, 0.f, heaviside_t);
float v0001 = dot_grid_gradient_4d(seed, x0, y0, z0, t1, dx, dy, dz, dt-1.f);
float d_v0001_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0001_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0001_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0001_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1001 = dot_grid_gradient_4d(seed, x1, y0, z0, t1, dx-1.f, dy, dz, dt-1.f);
float d_v1001_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1001_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1001_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1001_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v0101 = dot_grid_gradient_4d(seed, x0, y1, z0, t1, dx, dy-1.f, dz, dt-1.f);
float d_v0101_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0101_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0101_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0101_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1101 = dot_grid_gradient_4d(seed, x1, y1, z0, t1, dx-1.f, dy-1.f, dz, dt-1.f);
float d_v1101_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1101_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1101_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1101_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z0, t1, 0.f, 0.f, 0.f, heaviside_t);
float v0011 = dot_grid_gradient_4d(seed, x0, y0, z1, t1, dx, dy, dz-1.f, dt-1.f);
float d_v0011_dx = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0011_dy = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0011_dz = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0011_dt = dot_grid_gradient_4d_gradient(seed, x0, y0, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1011 = dot_grid_gradient_4d(seed, x1, y0, z1, t1, dx-1.f, dy, dz-1.f, dt-1.f);
float d_v1011_dx = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1011_dy = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1011_dz = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1011_dt = dot_grid_gradient_4d_gradient(seed, x1, y0, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float v0111 = dot_grid_gradient_4d(seed, x0, y1, z1, t1, dx, dy-1.f, dz-1.f, dt-1.f);
float d_v0111_dx = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v0111_dy = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v0111_dz = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v0111_dt = dot_grid_gradient_4d_gradient(seed, x0, y1, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float v1111 = dot_grid_gradient_4d(seed, x1, y1, z1, t1, dx-1.f, dy-1.f, dz-1.f, dt-1.f);
float d_v1111_dx = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, heaviside_x, 0.f, 0.f, 0.f);
float d_v1111_dy = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, 0.f, heaviside_y, 0.f, 0.f);
float d_v1111_dz = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, 0.f, 0.f, heaviside_z, 0.f);
float d_v1111_dt = dot_grid_gradient_4d_gradient(seed, x1, y1, z1, t1, 0.f, 0.f, 0.f, heaviside_t);
float xi000 = interpolate(v0000, v1000, dx);
float d_xi000_dx = interpolate_gradient(v0000, v1000, dx, d_v0000_dx, d_v1000_dx, heaviside_x);
float d_xi000_dy = interpolate_gradient(v0000, v1000, dx, d_v0000_dy, d_v1000_dy, 0.f);
float d_xi000_dz = interpolate_gradient(v0000, v1000, dx, d_v0000_dz, d_v1000_dz, 0.f);
float d_xi000_dt = interpolate_gradient(v0000, v1000, dx, d_v0000_dt, d_v1000_dt, 0.f);
float xi100 = interpolate(v0100, v1100, dx);
float d_xi100_dx = interpolate_gradient(v0100, v1100, dx, d_v0100_dx, d_v1100_dx, heaviside_x);
float d_xi100_dy = interpolate_gradient(v0100, v1100, dx, d_v0100_dy, d_v1100_dy, 0.f);
float d_xi100_dz = interpolate_gradient(v0100, v1100, dx, d_v0100_dz, d_v1100_dz, 0.f);
float d_xi100_dt = interpolate_gradient(v0100, v1100, dx, d_v0100_dt, d_v1100_dt, 0.f);
float xi010 = interpolate(v0010, v1010, dx);
float d_xi010_dx = interpolate_gradient(v0010, v1010, dx, d_v0010_dx, d_v1010_dx, heaviside_x);
float d_xi010_dy = interpolate_gradient(v0010, v1010, dx, d_v0010_dy, d_v1010_dy, 0.f);
float d_xi010_dz = interpolate_gradient(v0010, v1010, dx, d_v0010_dz, d_v1010_dz, 0.f);
float d_xi010_dt = interpolate_gradient(v0010, v1010, dx, d_v0010_dt, d_v1010_dt, 0.f);
float xi110 = interpolate(v0110, v1110, dx);
float d_xi110_dx = interpolate_gradient(v0110, v1110, dx, d_v0110_dx, d_v1110_dx, heaviside_x);
float d_xi110_dy = interpolate_gradient(v0110, v1110, dx, d_v0110_dy, d_v1110_dy, 0.f);
float d_xi110_dz = interpolate_gradient(v0110, v1110, dx, d_v0110_dz, d_v1110_dz, 0.f);
float d_xi110_dt = interpolate_gradient(v0110, v1110, dx, d_v0110_dt, d_v1110_dt, 0.f);
float xi001 = interpolate(v0001, v1001, dx);
float d_xi001_dx = interpolate_gradient(v0001, v1001, dx, d_v0001_dx, d_v1001_dx, heaviside_x);
float d_xi001_dy = interpolate_gradient(v0001, v1001, dx, d_v0001_dy, d_v1001_dy, 0.f);
float d_xi001_dz = interpolate_gradient(v0001, v1001, dx, d_v0001_dz, d_v1001_dz, 0.f);
float d_xi001_dt = interpolate_gradient(v0001, v1001, dx, d_v0001_dt, d_v1001_dt, 0.f);
float xi101 = interpolate(v0101, v1101, dx);
float d_xi101_dx = interpolate_gradient(v0101, v1101, dx, d_v0101_dx, d_v1101_dx, heaviside_x);
float d_xi101_dy = interpolate_gradient(v0101, v1101, dx, d_v0101_dy, d_v1101_dy, 0.f);
float d_xi101_dz = interpolate_gradient(v0101, v1101, dx, d_v0101_dz, d_v1101_dz, 0.f);
float d_xi101_dt = interpolate_gradient(v0101, v1101, dx, d_v0101_dt, d_v1101_dt, 0.f);
float xi011 = interpolate(v0011, v1011, dx);
float d_xi011_dx = interpolate_gradient(v0011, v1011, dx, d_v0011_dx, d_v1011_dx, heaviside_x);
float d_xi011_dy = interpolate_gradient(v0011, v1011, dx, d_v0011_dy, d_v1011_dy, 0.f);
float d_xi011_dz = interpolate_gradient(v0011, v1011, dx, d_v0011_dz, d_v1011_dz, 0.f);
float d_xi011_dt = interpolate_gradient(v0011, v1011, dx, d_v0011_dt, d_v1011_dt, 0.f);
float xi111 = interpolate(v0111, v1111, dx);
float d_xi111_dx = interpolate_gradient(v0111, v1111, dx, d_v0111_dx, d_v1111_dx, heaviside_x);
float d_xi111_dy = interpolate_gradient(v0111, v1111, dx, d_v0111_dy, d_v1111_dy, 0.f);
float d_xi111_dz = interpolate_gradient(v0111, v1111, dx, d_v0111_dz, d_v1111_dz, 0.f);
float d_xi111_dt = interpolate_gradient(v0111, v1111, dx, d_v0111_dt, d_v1111_dt, 0.f);
float yi00 = interpolate(xi000, xi100, dy);
float d_yi00_dx = interpolate_gradient(xi000, xi100, dy, d_xi000_dx, d_xi100_dx, 0.f);
float d_yi00_dy = interpolate_gradient(xi000, xi100, dy, d_xi000_dy, d_xi100_dy, heaviside_y);
float d_yi00_dz = interpolate_gradient(xi000, xi100, dy, d_xi000_dz, d_xi100_dz, 0.f);
float d_yi00_dt = interpolate_gradient(xi000, xi100, dy, d_xi000_dt, d_xi100_dt, 0.f);
float yi10 = interpolate(xi010, xi110, dy);
float d_yi10_dx = interpolate_gradient(xi010, xi110, dy, d_xi010_dx, d_xi110_dx, 0.f);
float d_yi10_dy = interpolate_gradient(xi010, xi110, dy, d_xi010_dy, d_xi110_dy, heaviside_y);
float d_yi10_dz = interpolate_gradient(xi010, xi110, dy, d_xi010_dz, d_xi110_dz, 0.f);
float d_yi10_dt = interpolate_gradient(xi010, xi110, dy, d_xi010_dt, d_xi110_dt, 0.f);
float yi01 = interpolate(xi001, xi101, dy);
float d_yi01_dx = interpolate_gradient(xi001, xi101, dy, d_xi001_dx, d_xi101_dx, 0.f);
float d_yi01_dy = interpolate_gradient(xi001, xi101, dy, d_xi001_dy, d_xi101_dy, heaviside_y);
float d_yi01_dz = interpolate_gradient(xi001, xi101, dy, d_xi001_dz, d_xi101_dz, 0.f);
float d_yi01_dt = interpolate_gradient(xi001, xi101, dy, d_xi001_dt, d_xi101_dt, 0.f);
float yi11 = interpolate(xi011, xi111, dy);
float d_yi11_dx = interpolate_gradient(xi011, xi111, dy, d_xi011_dx, d_xi111_dx, 0.f);
float d_yi11_dy = interpolate_gradient(xi011, xi111, dy, d_xi011_dy, d_xi111_dy, heaviside_y);
float d_yi11_dz = interpolate_gradient(xi011, xi111, dy, d_xi011_dz, d_xi111_dz, 0.f);
float d_yi11_dt = interpolate_gradient(xi011, xi111, dy, d_xi011_dt, d_xi111_dt, 0.f);
float zi0 = interpolate(yi00, yi10, dz);
float d_zi0_dx = interpolate_gradient(yi00, yi10, dz, d_yi00_dx, d_yi10_dx, 0.f);
float d_zi0_dy = interpolate_gradient(yi00, yi10, dz, d_yi00_dy, d_yi10_dy, 0.f);
float d_zi0_dz = interpolate_gradient(yi00, yi10, dz, d_yi00_dz, d_yi10_dz, heaviside_z);
float d_zi0_dt = interpolate_gradient(yi00, yi10, dz, d_yi00_dt, d_yi10_dt, 0.f);
float zi1 = interpolate(yi01, yi11, dz);
float d_zi1_dx = interpolate_gradient(yi01, yi11, dz, d_yi01_dx, d_yi11_dx, 0.f);
float d_zi1_dy = interpolate_gradient(yi01, yi11, dz, d_yi01_dy, d_yi11_dy, 0.f);
float d_zi1_dz = interpolate_gradient(yi01, yi11, dz, d_yi01_dz, d_yi11_dz, heaviside_z);
float d_zi1_dt = interpolate_gradient(yi01, yi11, dz, d_yi01_dt, d_yi11_dt, 0.f);
float gradient_x = interpolate_gradient(zi0, zi1, dt, d_zi0_dx, d_zi1_dx, 0.f);
float gradient_y = interpolate_gradient(zi0, zi1, dt, d_zi0_dy, d_zi1_dy, 0.f);
float gradient_z = interpolate_gradient(zi0, zi1, dt, d_zi0_dz, d_zi1_dz, 0.f);
float gradient_t = interpolate_gradient(zi0, zi1, dt, d_zi0_dt, d_zi1_dt, heaviside_t);
return vec4(gradient_x, gradient_y, gradient_z, gradient_t);
}
// non-periodic Perlin noise
inline float noise(uint32_t seed, float x)
{
float dx = x - floor(x);
int x0 = (int)floor(x);
int x1 = x0 + 1;
return noise_1d(seed, x0, x1, dx);
}
inline float noise(uint32_t seed, const vec2& xy)
{
float dx = xy[0] - floor(xy[0]);
float dy = xy[1] - floor(xy[1]);
int x0 = (int)floor(xy[0]);
int y0 = (int)floor(xy[1]);
int x1 = x0 + 1;
int y1 = y0 + 1;
return noise_2d(seed, x0, y0, x1, y1, dx, dy);
}
inline float noise(uint32_t seed, const vec3& xyz)
{
float dx = xyz[0] - floor(xyz[0]);
float dy = xyz[1] - floor(xyz[1]);
float dz = xyz[2] - floor(xyz[2]);
int x0 = (int)floor(xyz[0]);
int y0 = (int)floor(xyz[1]);
int z0 = (int)floor(xyz[2]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
return noise_3d(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz);
}
inline float noise(uint32_t seed, const vec4& xyzt)
{
float dx = xyzt[0] - floor(xyzt[0]);
float dy = xyzt[1] - floor(xyzt[1]);
float dz = xyzt[2] - floor(xyzt[2]);
float dt = xyzt[3] - floor(xyzt[3]);
int x0 = (int)floor(xyzt[0]);
int y0 = (int)floor(xyzt[1]);
int z0 = (int)floor(xyzt[2]);
int t0 = (int)floor(xyzt[3]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
int t1 = t0 + 1;
return noise_4d(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt);
}
// periodic Perlin noise
inline float pnoise(uint32_t seed, float x, int px)
{
float dx = x - floor(x);
int x0 = ((int)floor(x)) % px;
int x1 = (x0 + 1) % px;
return noise_1d(seed, x0, x1, dx);
}
inline float pnoise(uint32_t seed, const vec2& xy, int px, int py)
{
float dx = xy[0] - floor(xy[0]);
float dy = xy[1] - floor(xy[1]);
int x0 = ((int)floor(xy[0])) % px;
int y0 = ((int)floor(xy[1])) % py;
int x1 = (x0 + 1) % px;
int y1 = (y0 + 1) % py;
return noise_2d(seed, x0, y0, x1, y1, dx, dy);
}
inline float pnoise(uint32_t seed, const vec3& xyz, int px, int py, int pz)
{
float dx = xyz[0] - floor(xyz[0]);
float dy = xyz[1] - floor(xyz[1]);
float dz = xyz[2] - floor(xyz[2]);
int x0 = ((int)floor(xyz[0])) % px;
int y0 = ((int)floor(xyz[1])) % py;
int z0 = ((int)floor(xyz[2])) % pz;
int x1 = (x0 + 1) % px;
int y1 = (y0 + 1) % py;
int z1 = (z0 + 1) % pz;
return noise_3d(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz);
}
inline float pnoise(uint32_t seed, const vec4& xyzt, int px, int py, int pz, int pt)
{
float dx = xyzt[0] - floor(xyzt[0]);
float dy = xyzt[1] - floor(xyzt[1]);
float dz = xyzt[2] - floor(xyzt[2]);
float dt = xyzt[3] - floor(xyzt[3]);
int x0 = ((int)floor(xyzt[0])) % px;
int y0 = ((int)floor(xyzt[1])) % py;
int z0 = ((int)floor(xyzt[2])) % pz;
int t0 = ((int)floor(xyzt[3])) % pt;
int x1 = (x0 + 1) % px;
int y1 = (y0 + 1) % py;
int z1 = (z0 + 1) % pz;
int t1 = (t0 + 1) % pt;
return noise_4d(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt);
}
// curl noise
inline vec2 curlnoise(uint32_t seed, const vec2& xy)
{
float dx = xy[0] - floor(xy[0]);
float dy = xy[1] - floor(xy[1]);
float heaviside_x = 1.f;
float heaviside_y = 1.f;
if (dx < _EPSILON) heaviside_x = 0.f;
if (dy < _EPSILON) heaviside_y = 0.f;
int x0 = (int)floor(xy[0]);
int y0 = (int)floor(xy[1]);
int x1 = x0 + 1;
int y1 = y0 + 1;
vec2 grad_field = noise_2d_gradient(seed, x0, y0, x1, y1, dx, dy, heaviside_x, heaviside_y);
return vec2(-grad_field[1], grad_field[0]);
}
inline vec3 curlnoise(uint32_t seed, const vec3& xyz)
{
float dx = xyz[0] - floor(xyz[0]);
float dy = xyz[1] - floor(xyz[1]);
float dz = xyz[2] - floor(xyz[2]);
float heaviside_x = 1.f;
float heaviside_y = 1.f;
float heaviside_z = 1.f;
if (dx < _EPSILON) heaviside_x = 0.f;
if (dy < _EPSILON) heaviside_y = 0.f;
if (dz < _EPSILON) heaviside_z = 0.f;
int x0 = (int)floor(xyz[0]);
int y0 = (int)floor(xyz[1]);
int z0 = (int)floor(xyz[2]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
vec3 grad_field_1 = noise_3d_gradient(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz, heaviside_x, heaviside_y, heaviside_z);
seed = rand_init(seed, 10019689);
vec3 grad_field_2 = noise_3d_gradient(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz, heaviside_x, heaviside_y, heaviside_z);
seed = rand_init(seed, 13112221);
vec3 grad_field_3 = noise_3d_gradient(seed, x0, y0, z0, x1, y1, z1, dx, dy, dz, heaviside_x, heaviside_y, heaviside_z);
return vec3(
grad_field_3[1] - grad_field_2[2],
grad_field_1[2] - grad_field_3[0],
grad_field_2[0] - grad_field_1[1]);
}
inline vec3 curlnoise(uint32_t seed, const vec4& xyzt)
{
float dx = xyzt[0] - floor(xyzt[0]);
float dy = xyzt[1] - floor(xyzt[1]);
float dz = xyzt[2] - floor(xyzt[2]);
float dt = xyzt[3] - floor(xyzt[3]);
float heaviside_x = 1.f;
float heaviside_y = 1.f;
float heaviside_z = 1.f;
float heaviside_t = 1.f;
if (dx < _EPSILON) heaviside_x = 0.f;
if (dy < _EPSILON) heaviside_y = 0.f;
if (dz < _EPSILON) heaviside_z = 0.f;
if (dt < _EPSILON) heaviside_t = 0.f;
int x0 = (int)floor(xyzt[0]);
int y0 = (int)floor(xyzt[1]);
int z0 = (int)floor(xyzt[2]);
int t0 = (int)floor(xyzt[3]);
int x1 = x0 + 1;
int y1 = y0 + 1;
int z1 = z0 + 1;
int t1 = t0 + 1;
vec4 grad_field_1 = noise_4d_gradient(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt, heaviside_x, heaviside_y, heaviside_z, heaviside_t);
seed = rand_init(seed, 10019689);
vec4 grad_field_2 = noise_4d_gradient(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt, heaviside_x, heaviside_y, heaviside_z, heaviside_t);
seed = rand_init(seed, 13112221);
vec4 grad_field_3 = noise_4d_gradient(seed, x0, y0, z0, t0, x1, y1, z1, t1, dx, dy, dz, dt, heaviside_x, heaviside_y, heaviside_z, heaviside_t);
return vec3(
grad_field_3[1] - grad_field_2[2],
grad_field_1[2] - grad_field_3[0],
grad_field_2[0] - grad_field_1[1]);
}
} // namespace nodes
} // namespace graph
} // namespace omni
| 37,782 | C | 45.530788 | 224 | 0.631147 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnEase.cpp | // Copyright (c) 2021-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.
//
#define _USE_MATH_DEFINES
#include <OgnEaseDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
#include <functional>
#include "XformUtils.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
std::function<T(const T&, const T&, const float&)> getOperation(OgnEaseDatabase& db)
{
const auto& easeFunc = db.inputs.easeFunc();
auto exponent = std::max(std::min(db.inputs.blendExponent(), 10), 0);
// Find the desired comparison
std::function<T(const T&, const T&, const float&)> fn;
if (easeFunc == db.tokens.EaseIn)
fn = [=](const T& start, const T& end, const float& alpha) { return easeIn(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.EaseOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeOut(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.EaseInOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeInOut(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.Linear)
fn = [=](const T& start, const T& end, const float& alpha) { return lerp(start, end, alpha); };
else if (easeFunc == db.tokens.SinIn)
fn = [=](const T& start, const T& end, const float& alpha) { return easeSinIn(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.SinOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeSinOut(start, end, alpha, exponent); };
else if (easeFunc == db.tokens.SinInOut)
fn = [=](const T& start, const T& end, const float& alpha) { return easeSinInOut(start, end, alpha, exponent); };
else
{
throw ogn::compute::InputError("Failed to resolve token " + std::string(db.tokenToString(easeFunc)) +
", expected one of EaseIn, EaseOut, EaseInOut, Linear, SinIn, SinOut, SinInOut");
}
return fn;
}
template<typename T>
bool tryComputeAssumingType(OgnEaseDatabase& db, size_t count)
{
auto op = getOperation<T>(db);
auto functor = [&](auto& start, auto& end, auto& alpha, auto& result)
{
auto a = std::min(std::max(alpha, (float) 0.0), (float) 1.0);
result = op(start, end, a);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T, float, T>(
db.inputs.start(), db.inputs.end(), db.inputs.alpha(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnEaseDatabase& db, size_t count)
{
auto op = getOperation<T>(db);
auto functor = [&](auto& start, auto& end, auto& alpha, auto& result)
{
auto a = std::min(std::max(alpha, (float) 0.0), (float) 1.0);
for (size_t i = 0; i < N; i++)
{
result[i] = op(start[i], end[i], a);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], float, T[N]>(
db.inputs.start(), db.inputs.end(), db.inputs.alpha(), db.outputs.result(), functor, count);
}
} // namespace
class OgnEase
{
public:
static bool computeVectorized(OgnEaseDatabase& db, size_t count)
{
auto& inputType = db.inputs.start().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnEase: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto start = node.iNode->getAttributeByToken(node, inputs::start.token());
auto end = node.iNode->getAttributeByToken(node, inputs::end.token());
auto alpha = node.iNode->getAttributeByToken(node, inputs::alpha.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto startType = start.iAttribute->getResolvedType(start);
auto endType = end.iAttribute->getResolvedType(end);
auto alphaType = alpha.iAttribute->getResolvedType(alpha);
// Require start, end, and alpha to be resolved before determining result's type
if (startType.baseType != BaseDataType::eUnknown && endType.baseType != BaseDataType::eUnknown
&& alphaType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { start, end, result };
std::array<uint8_t, 3> tupleCounts {
startType.componentCount,
endType.componentCount,
std::max(startType.componentCount, endType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
startType.arrayDepth,
endType.arrayDepth,
std::max(alphaType.arrayDepth, std::max(startType.arrayDepth, endType.arrayDepth))
};
std::array<AttributeRole, 3> rolesBuf {
startType.role,
endType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion)
{
if (oldVersion < newVersion)
{
const INode* const iNode = nodeObj.iNode;
if (oldVersion < 2)
{
auto const instanceIdx = kAccordingToContextIndex;
auto oldAttrObj = iNode->getAttribute(nodeObj, "inputs:exponent");
auto oldAttrDataHandle = oldAttrObj.iAttribute->getAttributeDataHandle(oldAttrObj, instanceIdx);
ConstRawPtr srcDataPtr{ nullptr };
size_t srcDataSize{ 0 };
context.iAttributeData->getDataReferenceR(oldAttrDataHandle, context, srcDataPtr, srcDataSize);
if (srcDataPtr)
{
float exponentFloat = *(const float*)srcDataPtr;
auto newAttrObj = iNode->getAttribute(nodeObj, "inputs:blendExponent");
auto newAttrDataHandle = newAttrObj.iAttribute->getAttributeDataHandle(newAttrObj, instanceIdx);
RawPtr dstDataPtr{ nullptr };
size_t srcDataSize{ 0 };
context.iAttributeData->getDataReferenceW(newAttrDataHandle, context, dstDataPtr, srcDataSize);
if (dstDataPtr)
{
*dstDataPtr = (int)exponentFloat;
}
}
iNode->removeAttribute(nodeObj, "inputs:exponent");
}
return true;
}
return false;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 9,125 | C++ | 41.84507 | 121 | 0.593205 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRound.cpp | // Copyright (c) 2022-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.
//
#include <OgnRoundDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnRoundDatabase& db, size_t count)
{
int decimals = db.inputs.decimals();
float k = powf(10.0f, static_cast<float>(decimals));
auto functor = [&](auto const& input, auto& output)
{
output = static_cast<T>(round(input * k) / k);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.input(), db.outputs.output(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnRoundDatabase& db, size_t count)
{
int decimals = db.inputs.decimals();
float k = powf(10.0f, static_cast<float>(decimals));
auto functor = [&](auto const& input, auto& output)
{
for (size_t i = 0; i < N; ++i)
{
output[i] = static_cast<T>(round(input[i] * k) / k);
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N]>(db.inputs.input(), db.outputs.output(), functor, count);
}
} // namespace
class OgnRound
{
public:
static bool computeVectorized(OgnRoundDatabase& db, size_t count)
{
auto& inputType = db.inputs.input().type();
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnRound: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto input = node.iNode->getAttributeByToken(node, inputs::input.token());
auto output = node.iNode->getAttributeByToken(node, outputs::output.token());
auto inputType = input.iAttribute->getResolvedType(input);
// Require input to be resolved before determining output's type
if (inputType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { input, output };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
| 4,496 | C++ | 37.110169 | 119 | 0.606762 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnConcatenateFloat3Arrays.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnConcatenateFloat3ArraysDatabase.h>
#include <carb/Framework.h>
#include <carb/Types.h>
#include <omni/graph/core/Accessors.h>
#include <omni/graph/core/IGatherPrototype.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::vec3f;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnConcatenateFloat3Arrays
{
public:
static bool compute(OgnConcatenateFloat3ArraysDatabase& db)
{
auto iGatherPrototype = carb::getCachedInterface<IGatherPrototype>();
if (!iGatherPrototype)
{
db.logError("Could not acquire IGatherPrototype and therefore could not compute");
return false;
}
auto& outputArray = db.outputs.outputArray();
auto& outputSizesArray = db.outputs.arraySizes();
// TODO: This uses the legacy approach instead of the database until gather arrays are supported
AttributeObj inputArrayObj = db.abi_node().iNode->getAttribute(db.abi_node(), "inputs:inputArrays");
AttributeObj inputArraySrcObj = getNthUpstreamAttributeOrSelf<0>(inputArrayObj);
auto inputArrayValues = reinterpret_cast<const vec3f* const* const>(
iGatherPrototype->getGatherArray(db.abi_context(), inputArraySrcObj, kReadOnly)
);
if (!inputArrayValues)
{
return false;
}
auto inputArraySizes = iGatherPrototype->getGatherArrayAttributeSizes(db.abi_context(), inputArraySrcObj, kReadOnly);
const size_t inputArrayCount = iGatherPrototype->getElementCount(db.abi_context(), inputArraySrcObj);
// Find the total output size.
size_t outputCount = 0;
for (size_t arrayi = 0; arrayi < inputArrayCount; ++arrayi)
{
outputCount += inputArraySizes[arrayi];
}
outputArray.resize(outputCount);
outputSizesArray.resize(inputArrayCount);
for (size_t arrayi = 0, outputi = 0; arrayi < inputArrayCount; ++arrayi)
{
const vec3f* const currentInputArray = inputArrayValues[arrayi];
size_t currentSize = inputArraySizes[arrayi];
outputSizesArray[arrayi] = int(currentSize);
for (size_t inputi = 0; inputi < currentSize; ++inputi, ++outputi)
{
outputArray[outputi] = currentInputArray[inputi];
}
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,853 | C++ | 32.57647 | 125 | 0.677532 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomGaussian.cpp | // 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.
//
#include "OgnRandomGaussianDatabase.h"
#include "random/RandomNodeBase.h"
#include <omni/graph/core/ogn/ComputeHelpers.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomGaussian : public NodeBase<OgnRandomGaussian, OgnRandomGaussianDatabase>
{
template <typename T>
static bool tryComputeAssumingType(OgnRandomGaussianDatabase& db, size_t count)
{
if (db.inputs.useLog())
{
return ogn::compute::tryComputeWithArrayBroadcasting<T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextLogNormal(mean, stdev);
},
count);
}
return ogn::compute::tryComputeWithArrayBroadcasting<T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextNormal(mean, stdev);
},
count);
}
template <typename T, size_t N>
static bool tryComputeAssumingType(OgnRandomGaussianDatabase& db, size_t count)
{
if (db.inputs.useLog())
{
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextLogNormal(mean, stdev);
},
count);
}
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(
db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextNormal(mean, stdev);
},
count);
}
static bool defaultCompute(OgnRandomGaussianDatabase& db, size_t count)
{
auto const genBuffers = db.state.gen.vectorized(count);
if (genBuffers.size() != count)
{
db.logWarning("Failed to write to output standard normal distribution (wrong genBuffers size)");
return false;
}
for (size_t i = 0; i < count; ++i)
{
auto outPtr = db.outputs.random(i).get<double>();
if (!outPtr)
{
db.logWarning("Failed to write to output standard normal distribution (null output pointer)");
return false;
}
*outPtr = asGenerator(genBuffers[i]).nextNormal<double>(0.0, 1.0);
}
return true;
}
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
// HACK: onConnectionTypeResolve is not called the first time,
// but by setting the output type, we force it to be called.
//
// TODO: OGN should really support default inputs for union types!
// See https://nvidia-omniverse.atlassian.net/browse/OM-67739
setDefaultOutputType(nodeObj, outputs::random.token());
}
static bool onCompute(OgnRandomGaussianDatabase& db, size_t count)
{
auto const& meanAttr{ db.inputs.mean() };
auto const& stdevAttr{ db.inputs.stdev() };
auto const& outAttr{ db.outputs.random() };
if (!outAttr.resolved())
{
// Output type not yet resolved, can't compute
db.logWarning("Unsupported input types");
return false;
}
if (!meanAttr.resolved() && !stdevAttr.resolved())
{
// Output using default mean and stdev
return defaultCompute(db, count);
}
// Inputs and outputs are resolved, try all real types
auto const outType = outAttr.type();
switch (outType.baseType) // NOLINT(clang-diagnostic-switch-enum)
{
case BaseDataType::eDouble:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db, count);
case 2:
return tryComputeAssumingType<double, 2>(db, count);
case 3:
return tryComputeAssumingType<double, 3>(db, count);
case 4:
return tryComputeAssumingType<double, 4>(db, count);
case 9:
return tryComputeAssumingType<double, 9>(db, count);
case 16:
return tryComputeAssumingType<double, 16>(db, count);
default:
break;
}
case BaseDataType::eFloat:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db, count);
case 2:
return tryComputeAssumingType<float, 2>(db, count);
case 3:
return tryComputeAssumingType<float, 3>(db, count);
case 4:
return tryComputeAssumingType<float, 4>(db, count);
default:
break;
}
case BaseDataType::eHalf:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default:
break;
}
default:
break;
}
db.logWarning("Unsupported input types");
return false;
}
static void onConnectionTypeResolve(NodeObj const& node)
{
resolveOutputType(node, inputs::mean.token(), inputs::stdev.token(), outputs::random.token());
}
};
#undef TRY_CASE
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 6,994 | C++ | 33.289216 | 110 | 0.573778 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnPartialSum.cpp | // 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.
//
#include <OgnPartialSumDatabase.h>
#include <numeric>
class OgnPartialSum
{
public:
static bool compute(OgnPartialSumDatabase& db)
{
auto inputs = db.inputs.array();
auto outputs = db.outputs.partialSum();
outputs.resize(inputs.size() + 1);
outputs[0] = 0;
std::partial_sum(inputs.begin(), inputs.end(), outputs.begin() + 1);
return true;
}
};
REGISTER_OGN_NODE()
| 861 | C++ | 30.925925 | 77 | 0.708479 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSourceIndices.cpp | // 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.
//
#include <OgnSourceIndicesDatabase.h>
class OgnSourceIndices
{
public:
static bool compute(OgnSourceIndicesDatabase& db)
{
auto inputValues = db.inputs.sourceStartsInTarget();
auto sourceCount = inputValues.size();
auto sourceIndices = db.outputs.sourceIndices();
if (sourceCount <= 1)
{
sourceIndices.resize(0);
return true;
}
--sourceCount;
int32_t targetCount = inputValues[sourceCount];
if (targetCount < 0)
{
sourceIndices.resize(0);
return true;
}
sourceIndices.resize(targetCount);
int32_t i = 0;
for (size_t sourcei = 0; sourcei < sourceCount; ++sourcei)
{
const int32_t sourceEnd = inputValues[sourcei + 1];
while (i < sourceEnd)
{
sourceIndices[i] = (int32_t)sourcei;
++i;
}
}
return true;
}
};
REGISTER_OGN_NODE()
| 1,443 | C++ | 26.76923 | 77 | 0.612613 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMagnitude.cpp | // 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.
//
#include <OgnMagnitudeDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <cmath>
#include <type_traits>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
template<typename T>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
magnitude = static_cast<T>(std::abs(static_cast<double>(input)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, T>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<>
bool tryComputeAssumingType<pxr::GfHalf>(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
magnitude = static_cast<pxr::GfHalf>(std::abs(static_cast<float>(input)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, pxr::GfHalf>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<typename T, size_t N,
std::enable_if_t<!std::is_same<T, int>::value && !std::is_same<T, pxr::GfHalf>::value, bool> = true>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
double acc = 0.0;
for (size_t i = 0; i < N; ++i)
{
acc += static_cast<double>(input[i]) * static_cast<double>(input[i]);
}
acc = std::sqrt(acc);
magnitude = static_cast<T>(acc);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<typename T, size_t N,
std::enable_if_t<std::is_same<T, int>::value, bool> = true>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
double acc = 0.0;
for (size_t i = 0; i < N; ++i)
{
acc += static_cast<double>(input[i]) * static_cast<double>(input[i]);
}
acc = std::sqrt(acc);
magnitude = acc;
};
return ogn::compute::tryComputeWithArrayBroadcasting<int[N], double>(db.inputs.input(), db.outputs.magnitude(), functor);
}
template<typename T, size_t N,
std::enable_if_t<std::is_same<T, pxr::GfHalf>::value, bool> = true>
bool tryComputeAssumingType(OgnMagnitudeDatabase& db)
{
auto functor = [](auto const& input, auto& magnitude)
{
float acc = 0.0f;
for (size_t i = 0; i < N; ++i)
{
acc += static_cast<float>(input[i]) * static_cast<float>(input[i]);
}
acc = std::sqrt(acc);
magnitude = static_cast<pxr::GfHalf>(acc);
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[N], pxr::GfHalf>(db.inputs.input(), db.outputs.magnitude(), functor);
}
} // namespace
class OgnMagnitude
{
public:
static bool compute(OgnMagnitudeDatabase& db)
{
try
{
auto& type = db.inputs.input().type();
// All possible types excluding ogn::string and bool
switch (type.baseType)
{
case BaseDataType::eDouble:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db);
case 2:
return tryComputeAssumingType<double, 2>(db);
case 3:
return tryComputeAssumingType<double, 3>(db);
case 4:
return tryComputeAssumingType<double, 4>(db); // quaternion (XYZW), RGBA, etc
case 9:
return tryComputeAssumingType<double, 9>(db); // Matrix3f type
case 16:
return tryComputeAssumingType<double, 16>(db); // Matrix4f type
}
break;
case BaseDataType::eFloat:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db);
case 2:
return tryComputeAssumingType<float, 2>(db);
case 3:
return tryComputeAssumingType<float, 3>(db);
case 4:
return tryComputeAssumingType<float, 4>(db); // quaternion (XYZW), RGBA, etc
}
break;
case BaseDataType::eHalf:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db); // quaternion (XYZW), RGBA, etc
}
break;
case BaseDataType::eInt:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<int32_t>(db);
case 2:
return tryComputeAssumingType<int32_t, 2>(db);
case 3:
return tryComputeAssumingType<int32_t, 3>(db);
case 4:
return tryComputeAssumingType<int32_t, 4>(db);
}
break;
case BaseDataType::eUInt:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<uint32_t>(db);
}
break;
case BaseDataType::eInt64:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<int64_t>(db);
}
break;
case BaseDataType::eUInt64:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<uint64_t>(db);
}
break;
case BaseDataType::eUChar:
switch (type.componentCount)
{
case 1:
return tryComputeAssumingType<unsigned char>(db);
}
break;
default:
break;
}
throw ogn::compute::InputError("Failed to resolve input type");
}
catch (ogn::compute::InputError &error)
{
db.logError("OgnMagnitude: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto input = node.iNode->getAttributeByToken(node, inputs::input.token());
auto magnitude = node.iNode->getAttributeByToken(node, outputs::magnitude.token());
auto inputType = input.iAttribute->getResolvedType(input);
// Require input to be resolved before determining magnitude's type
if (inputType.baseType != BaseDataType::eUnknown)
{
if (inputType.baseType == BaseDataType::eInt && inputType.componentCount > 1)
{
// int[N] => double
auto newType = inputType;
newType.baseType = BaseDataType::eDouble;
newType.componentCount = 1;
magnitude.iAttribute->setResolvedType(magnitude, newType);
}
else
{
// T => T
// T[N] => T
std::array<AttributeObj, 2> attrs { input, magnitude };
std::array<uint8_t, 2> tupleCounts {
inputType.componentCount,
1
};
std::array<uint8_t, 2> arrayDepths {
inputType.arrayDepth,
inputType.arrayDepth
};
std::array<AttributeRole, 2> rolesBuf {
inputType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
| 9,416 | C++ | 37.125506 | 138 | 0.506691 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMatrixMultiply.cpp | // 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.
//
#include <OgnMatrixMultiplyDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/vec.h>
#include <type_traits>
using omni::math::linalg::base_matrix;
using omni::math::linalg::base_vec;
using ogn::compute::tryComputeWithArrayBroadcasting;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
// Base type T, dimension N (eg: 2,3,4)
template<typename T, size_t N>
bool tryComputeAssumingType(OgnMatrixMultiplyDatabase& db)
{
auto matrixMatrixFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aMatrix = *reinterpret_cast<const base_matrix<T, N>*>(a);
const auto& bMatrix = *reinterpret_cast<const base_matrix<T, N>*>(b);
auto& resultMatrix = *reinterpret_cast<base_matrix<T, N>*>(result);
resultMatrix = aMatrix * bMatrix;
};
auto matrixVectorFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aMatrix = *reinterpret_cast<const base_matrix<T, N>*>(a);
const auto& bVec = *reinterpret_cast<const base_vec<T, N>*>(b);
auto& resultVec = *reinterpret_cast<base_vec<T, N>*>(result);
resultVec = aMatrix * bVec;
};
auto vectorMatrixFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aVec = *reinterpret_cast<const base_vec<T, N>*>(a);
const auto& bMatrix = *reinterpret_cast<const base_matrix<T, N>*>(b);
auto& resultVec = *reinterpret_cast<base_vec<T, N>*>(result);
resultVec = aVec * bMatrix;
};
auto vectorVectorFn = [](auto const& a, auto const& b, auto& result)
{
const auto& aVec = *reinterpret_cast<const base_vec<T, N>*>(a);
const auto& bVec = *reinterpret_cast<const base_vec<T, N>*>(b);
result = aVec * bVec;
};
if (N >= 3 && tryComputeWithArrayBroadcasting<T[N*N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), matrixMatrixFn))
return true;
else if (N >= 3 && tryComputeWithArrayBroadcasting<T[N*N], T[N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), matrixVectorFn))
return true;
else if (N >= 3 && tryComputeWithArrayBroadcasting<T[N], T[N*N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), vectorMatrixFn))
return true;
else if (tryComputeWithArrayBroadcasting<T[N], T[N], T>(db.inputs.a(), db.inputs.b(), db.outputs.output(), vectorVectorFn))
return true;
return false;
}
} // namespace
class OgnMatrixMultiply
{
public:
static bool compute(OgnMatrixMultiplyDatabase& db)
{
try
{
if (tryComputeAssumingType<double, 2>(db)) return true;
else if (tryComputeAssumingType<double, 3>(db)) return true;
else if (tryComputeAssumingType<double, 4>(db)) return true;
else if (tryComputeAssumingType<float, 2>(db)) return true;
else if (tryComputeAssumingType<float, 3>(db)) return true;
else if (tryComputeAssumingType<float, 4>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf, 2>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf, 3>(db)) return true;
else if (tryComputeAssumingType<pxr::GfHalf, 4>(db)) return true;
else
{
db.logWarning("OgnMatrixMultiply: Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnMatrixMultiply: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto b = node.iNode->getAttributeByToken(node, inputs::b.token());
auto output = node.iNode->getAttributeByToken(node, outputs::output.token());
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
// Require inputs to be resolved before determining output's type
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
auto biggerDim = std::max(aType.componentCount, bType.componentCount);
auto smallerDim = std::min(aType.componentCount, bType.componentCount);
if (biggerDim != smallerDim && biggerDim != smallerDim * smallerDim)
{
CARB_LOG_WARN_ONCE("OgnMatrixMultiply: Inputs are not compatible with tuple counts %d and %d", aType.componentCount, bType.componentCount);
return;
}
// Vector4 * Matrix4 = Vector4, Matrix4 * Vector4 = Vector4 and etc.
auto tupleCount = smallerDim;
auto role = aType.componentCount < bType.componentCount ? aType.role : bType.role;
if (smallerDim == biggerDim && smallerDim <= 4)
{
// equivalent to dot product of two vectors
tupleCount = 1;
role = AttributeRole::eNone;
}
std::array<AttributeObj, 3> attrs { a, b, output };
std::array<uint8_t, 3> tupleCounts {
aType.componentCount,
bType.componentCount,
tupleCount
};
std::array<uint8_t, 3> arrayDepths {
aType.arrayDepth,
bType.arrayDepth,
std::max(aType.arrayDepth, bType.arrayDepth)
};
std::array<AttributeRole, 3> rolesBuf {
aType.role,
bType.role,
role
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 6,428 | C++ | 39.949044 | 155 | 0.61061 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomBoolean.cpp | // 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.
//
#include "random/RandomNodeBase.h"
#include <OgnRandomBooleanDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomBoolean : public NodeBase<OgnRandomBoolean, OgnRandomBooleanDatabase>
{
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
}
static bool onCompute(OgnRandomBooleanDatabase& db, size_t count)
{
return computeRandoms(db, count, [](GeneratorState& gen) { return gen.nextUniformBool(); });
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 1,133 | C++ | 26.658536 | 100 | 0.753751 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve.cpp | // 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.
//
#include <OgnGetLocationAtDistanceOnCurveDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/gf/rotation.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/math/linalg/SafeCast.h>
#include <cmath>
#include "XformUtils.h"
using omni::math::linalg::quatf;
using omni::math::linalg::quatd;
using omni::math::linalg::vec3d;
using omni::math::linalg::matrix4d;
// return the named unit vector X,Y or Z
static vec3d axisToVec(NameToken axisToken, OgnGetLocationAtDistanceOnCurveDatabase::TokenManager& tokens)
{
if (axisToken == tokens.y || axisToken == tokens.Y)
return vec3d::YAxis();
if (axisToken == tokens.z || axisToken == tokens.Z)
return vec3d::ZAxis();
return vec3d::XAxis();
}
class OgnGetLocationAtDistanceOnCurve
{
public:
static bool compute(OgnGetLocationAtDistanceOnCurveDatabase& db)
{
/* This is a simple closed poly-line interpolation to find p, the point on the curve
1. find the total length of the curve
2. find the start and end cvs of the line segment which contains p
3. calculate the position on that line segment, and the rotation
*/
bool ok = false;
const auto& curve_cvs_in = db.inputs.curve();
auto& locations = db.outputs.location();
auto& rotations = db.outputs.rotateXYZ();
auto& orientations = db.outputs.orientation();
const auto& distances = db.inputs.distance();
double curve_length = 0; // The total curve length
std::vector<double> accumulated_lengths; // the length of the curve at each the end of each segment
std::vector<double> segment_lengths; // the length of each segment
size_t num_cvs = curve_cvs_in.size();
if (num_cvs == 0)
return false;
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "resize");
locations.resize(distances.size());
rotations.resize(distances.size());
orientations.resize(distances.size());
}
if (num_cvs == 1)
{
std::fill(locations.begin(), locations.end(), curve_cvs_in[0]);
std::fill(rotations.begin(), rotations.end(), vec3d(0, 0, 0));
return true;
}
std::vector<vec3d> curve_cvs;
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "PreprocessCurve");
curve_cvs.resize(curve_cvs_in.size() + 1);
std::copy(curve_cvs_in.begin(), curve_cvs_in.end(), curve_cvs.begin());
// add a cv to make a closed curve
curve_cvs[curve_cvs_in.size()] = curve_cvs_in[0];
// calculate the total curve length and the length at the end of each segment
const vec3d* p_a = curve_cvs.data();
for (size_t i = 1; i < curve_cvs.size(); ++i)
{
const vec3d& p_b = curve_cvs[i];
double segment_length = (p_b - *p_a).GetLength();
segment_lengths.push_back(segment_length);
curve_length += segment_length;
accumulated_lengths.push_back(curve_length);
p_a = &p_b;
}
}
const vec3d forwardAxis = axisToVec(db.inputs.forwardAxis(), db.tokens);
const vec3d upAxis = axisToVec(db.inputs.upAxis(), db.tokens);
// Calculate eye frame
auto eyeUL = forwardAxis;
auto eyeVL = upAxis;
auto eyeWL = (eyeUL ^ eyeVL).GetNormalized();
eyeVL = eyeWL ^ eyeUL;
// local transform from forward axis
matrix4d localMat, localMatInv;
localMat.SetIdentity();
localMat.SetRow3(0, eyeUL);
localMat.SetRow3(1, eyeVL);
localMat.SetRow3(2, eyeWL);
localMatInv = localMat.GetInverse();
auto distanceIter = distances.begin();
auto locationIter = locations.begin();
auto rotationIter = rotations.begin();
auto orientationIter = orientations.begin();
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "ScanCurve");
for (; distanceIter != distances.end(); ++distanceIter, ++locationIter, ++rotationIter, ++orientationIter)
{
// wrap distance to range [0, 1.0]
double normalized_distance = std::fmod(*distanceIter, 1.0);
// the distance along the curve in world space
double distance = curve_length * normalized_distance;
// Find the location and direction
double remaining_dist = 0;
for (size_t i = 0; i < accumulated_lengths.size(); ++i)
{
double segment_length = accumulated_lengths[i];
if (segment_length >= distance)
{
if (i > 0)
remaining_dist = distance - accumulated_lengths[i - 1];
else
remaining_dist = distance;
const auto& start_cv = curve_cvs[i];
const auto& end_cv = curve_cvs[i + 1];
const auto aimVec = end_cv - start_cv;
const auto segment_unit_vec = aimVec / segment_lengths[i];
const auto point_on_segment = start_cv + segment_unit_vec * remaining_dist;
*locationIter = point_on_segment;
// calculate the rotation
vec3d eyeU = segment_unit_vec;
vec3d eyeV = upAxis;
auto eyeW = (eyeU ^ eyeV).GetNormalized();
eyeV = eyeW ^ eyeU;
matrix4d eyeMtx;
eyeMtx.SetIdentity();
eyeMtx.SetTranslateOnly(point_on_segment);
// eye aiming
eyeMtx.SetRow3(0, eyeU);
eyeMtx.SetRow3(1, eyeV);
eyeMtx.SetRow3(2, eyeW);
matrix4d orientMtx = localMatInv * eyeMtx;
const quatd q = omni::graph::nodes::extractRotationQuatd(orientMtx);
const pxr::GfRotation rotation(omni::math::linalg::safeCastToUSD(q));
const auto eulerRotations =
rotation.Decompose(pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis());
pxr::GfVec3d eulerRotationsXYZ(eulerRotations[2], eulerRotations[1], eulerRotations[0]);
*rotationIter = omni::math::linalg::safeCastToOmni(eulerRotationsXYZ);
*orientationIter = quatf(q);
ok = true;
break;
}
}
}
}
return ok;
}
};
REGISTER_OGN_NODE()
| 7,280 | C++ | 37.523809 | 114 | 0.576786 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnATan2.py | """
This is the implementation of the OGN node defined in OgnATan2.ogn
"""
import math
import omni.graph.core as og
class OgnATan2:
"""
Calculates the arc tangent of A,B. This is the angle in radians between the ray ending at the origin and
passing through the point (B, A).
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
db.outputs.result.value = math.degrees(math.atan2(db.inputs.a.value, db.inputs.b.value))
except TypeError as error:
db.log_error(f"atan2 could not be performed: {error}")
return False
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
aattr = node.get_attribute("inputs:a")
battr = node.get_attribute("inputs:b")
resultattr = node.get_attribute("outputs:result")
og.resolve_fully_coupled([aattr, battr, resultattr])
| 949 | Python | 27.787878 | 109 | 0.640674 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnModulo.cpp | // 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.
//
#include <OgnModuloDatabase.h>
#include <cmath>
#include <algorithm>
#include <array>
template <typename T, typename AttrInType, typename AttrOutType>
void modulo(AttrInType& a, AttrInType& b, AttrOutType& result)
{
T bval = *b.template get<T>();
if (bval == 0)
{
*result.template get<T>() = 0;
return;
}
*result.template get<T>() = *a.template get<T>() % bval;
}
class OgnModulo
{
public:
static bool compute(OgnModuloDatabase& db)
{
const auto& a = db.inputs.a();
const auto& b = db.inputs.b();
auto& result = db.outputs.result();
if (!a.resolved())
return true;
switch(a.type().baseType)
{
case BaseDataType::eInt:
modulo<int>(a, b, result);
break;
case BaseDataType::eUInt:
modulo<uint32_t>(a, b, result);
break;
case BaseDataType::eInt64:
modulo<int64_t>(a, b, result);
break;
case BaseDataType::eUInt64:
modulo<uint64_t>(a, b, result);
break;
default:
break;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node){
// Resolve fully-coupled types for the 3 attributes
std::array<AttributeObj, 3> attrs {
node.iNode->getAttribute(node, OgnModuloAttributes::inputs::a.m_name),
node.iNode->getAttribute(node, OgnModuloAttributes::inputs::b.m_name),
node.iNode->getAttribute(node, OgnModuloAttributes::outputs::result.m_name)
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
| 2,148 | C++ | 29.267605 | 87 | 0.616853 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide_Matrices.cpp | #include "OgnDivideHelper.h"
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
template<size_t N>
bool _tryCompute(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (tryComputeAssumingType<double, double, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, float, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, pxr::GfHalf, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int32_t, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, int64_t, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, unsigned char, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint32_t, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<double, uint64_t, N>(db, a, b, result, count)) return true;
return false;
}
bool tryComputeMatrices(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
// Matrix3f type
if (_tryCompute<9>(db, a, b, result, count)) return true;
// Matrix4f type
if (_tryCompute<16>(db, a, b, result, count)) return true;
return false;
}
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
| 1,470 | C++ | 35.774999 | 117 | 0.659864 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnExponent.cpp | // 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.
//
#include <OgnExponentDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
//
bool tryComputeAssumingScalarHalf(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(std::pow(static_cast<double>(static_cast<float>(base)), exp)));
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, int, pxr::GfHalf>(db.inputs.base(),
db.inputs.exponent(),
db.outputs.result(),
functor);
}
template <typename T, typename M>
bool tryComputeAssumingScalarType(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<M>(std::pow(base, exp));
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, int, M>(db.inputs.base(), db.inputs.exponent(),
db.outputs.result(), functor);
}
template <size_t N>
bool tryComputeAssumingTupleHalf(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<pxr::GfHalf>(static_cast<float>(std::pow(static_cast<double>(static_cast<float>(base)), exp)));
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, pxr::GfHalf, int, pxr::GfHalf>(db.inputs.base(),
db.inputs.exponent(),
db.outputs.result(),
functor);
}
template <typename T, size_t N, typename M>
bool tryComputeAssumingTupleType(OgnExponentDatabase& db)
{
auto functor = [](auto const& base, auto const& exp, auto& result)
{
result = static_cast<M>(std::pow(base, exp));
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int, M>(db.inputs.base(), db.inputs.exponent(),
db.outputs.result(), functor);
}
} // unnamed namespace
class OgnExponent
{
public:
static bool compute(OgnExponentDatabase& db)
{
try
{
const auto& bType = db.inputs.base().type();
switch (bType.componentCount)
{
case 1:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingScalarType<int32_t, double>(db);
case BaseDataType::eInt64:
return tryComputeAssumingScalarType<int64_t, double>(db);
case BaseDataType::eUInt:
return tryComputeAssumingScalarType<uint32_t, double>(db);
case BaseDataType::eUInt64:
return tryComputeAssumingScalarType<uint64_t, double>(db);
case BaseDataType::eUChar:
return tryComputeAssumingScalarType<unsigned char, double>(db);
case BaseDataType::eHalf:
return tryComputeAssumingScalarHalf(db);
case BaseDataType::eDouble:
return tryComputeAssumingScalarType<double, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingScalarType<float, float>(db);
default:
break;
}
case 2:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingTupleType<int32_t, 2, double>(db);
case BaseDataType::eDouble:
return tryComputeAssumingTupleType<double, 2, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingTupleType<float, 2, float>(db);
case BaseDataType::eHalf:
return tryComputeAssumingTupleHalf<2>(db);
default:
break;
}
case 3:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingTupleType<int32_t, 3, double>(db);
case BaseDataType::eDouble:
return tryComputeAssumingTupleType<double, 3, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingTupleType<float, 3, float>(db);
case BaseDataType::eHalf:
return tryComputeAssumingTupleHalf<3>(db);
default:
break;
}
case 4:
switch (bType.baseType)
{
case BaseDataType::eInt:
return tryComputeAssumingTupleType<int32_t, 4, double>(db);
case BaseDataType::eDouble:
return tryComputeAssumingTupleType<double, 4, double>(db);
case BaseDataType::eFloat:
return tryComputeAssumingTupleType<float, 4, float>(db);
case BaseDataType::eHalf:
return tryComputeAssumingTupleHalf<4>(db);
default:
break;
}
case 9:
if (bType.baseType == BaseDataType::eDouble )
{
return tryComputeAssumingTupleType<double, 9, double>(db);
}
case 16:
if (bType.baseType == BaseDataType::eDouble )
{
return tryComputeAssumingTupleType<double, 16, double>(db);
}
}
throw ogn::compute::InputError("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto base = node.iNode->getAttributeByToken(node, inputs::base.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto bType = base.iAttribute->getResolvedType(base);
Type newType(BaseDataType::eDouble, bType.componentCount, bType.arrayDepth, bType.role);
if (bType.baseType != BaseDataType::eUnknown)
{
switch (bType.baseType)
{
case BaseDataType::eUChar:
case BaseDataType::eInt:
case BaseDataType::eUInt:
case BaseDataType::eInt64:
case BaseDataType::eUInt64:
result.iAttribute->setResolvedType(result, newType);
break;
default:
std::array<AttributeObj, 2> attrs { base, result};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
break;
}
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 8,078 | C++ | 40.010152 | 124 | 0.525006 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnInterpolateTo.cpp | // Copyright (c) 2021-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.
//
#include <algorithm>
#include <OgnInterpolateToDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/quat.h>
#include "XformUtils.h"
using omni::math::linalg::quatd;
using omni::math::linalg::GfSlerp;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeAssumingType(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
result = a + (b - a) * (float) alpha;
};
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
template<typename T, size_t N>
bool tryComputeAssumingType(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < N; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float) alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<T[N]>(db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
template<>
bool tryComputeAssumingType<double, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto currentAttribute =
db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name);
auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role;
if (currentRole == AttributeRole::eQuaternion)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ
auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha);
result[0] = q.GetImaginary()[0];
result[1] = q.GetImaginary()[1];
result[2] = q.GetImaginary()[2];
result[3] = q.GetReal();
};
return ogn::compute::tryComputeWithArrayBroadcasting<double[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
else
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < 4; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float)alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<double[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
}
template<>
bool tryComputeAssumingType<float, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto currentAttribute =
db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name);
auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role;
if (currentRole == AttributeRole::eQuaternion)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ
auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha);
result[0] = (float)q.GetImaginary()[0];
result[1] = (float)q.GetImaginary()[1];
result[2] = (float)q.GetImaginary()[2];
result[3] = (float)q.GetReal();
};
return ogn::compute::tryComputeWithArrayBroadcasting<float[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
else
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < 4; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float)alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<float[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
};
}
template<>
bool tryComputeAssumingType<pxr::GfHalf, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count)
{
auto currentAttribute =
db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name);
auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role;
if (currentRole == AttributeRole::eQuaternion)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ
auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha);
result[0] = (float)q.GetImaginary()[0];
result[1] = (float)q.GetImaginary()[1];
result[2] = (float)q.GetImaginary()[2];
result[3] = (float)q.GetReal();
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
}
else
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
// Linear interpolation between a and b, alpha in [0, 1]
for (size_t i = 0; i < 4; i++)
{
result[i] = a[i] + (b[i] - a[i]) * (float)alpha;
}
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[4]>(
db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count);
};
}
} // namespace
class OgnInterpolateTo
{
public:
static bool computeVectorized(OgnInterpolateToDatabase& db, size_t count)
{
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
float deltaSeconds = std::max(0.f, float(db.inputs.deltaSeconds()));
// delta step
float alpha = std::min(std::max(speed * deltaSeconds, 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
double alpha2 = 1.f - exponent(1.f - alpha, exp);
auto& inputType = db.inputs.current().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, alpha2, count);
case 2: return tryComputeAssumingType<double, 2>(db, alpha2, count);
case 3: return tryComputeAssumingType<double, 3>(db, alpha2, count);
case 4: return tryComputeAssumingType<double, 4>(db, alpha2, count);
case 9: return tryComputeAssumingType<double, 9>(db, alpha2, count);
case 16: return tryComputeAssumingType<double, 16>(db, alpha2, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, alpha2, count);
case 2: return tryComputeAssumingType<float, 2>(db, alpha2, count);
case 3: return tryComputeAssumingType<float, 3>(db, alpha2, count);
case 4: return tryComputeAssumingType<float, 4>(db, alpha2, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, alpha2, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, alpha2, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, alpha2, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, alpha2, count);
default: break;
}
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnInterpolateTo: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto current = node.iNode->getAttributeByToken(node, inputs::current.token());
auto target = node.iNode->getAttributeByToken(node, inputs::target.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto currentType = current.iAttribute->getResolvedType(current);
auto targetType = target.iAttribute->getResolvedType(target);
// Require current, target, and alpha to be resolved before determining result's type
if (currentType.baseType != BaseDataType::eUnknown && targetType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { current, target, result };
std::array<uint8_t, 3> tupleCounts {
currentType.componentCount,
targetType.componentCount,
std::max(currentType.componentCount, targetType.componentCount)
};
std::array<uint8_t, 3> arrayDepths {
currentType.arrayDepth,
targetType.arrayDepth,
std::max(currentType.arrayDepth, targetType.arrayDepth)
};
std::array<AttributeRole, 3> rolesBuf {
currentType.role,
targetType.role,
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 10,834 | C++ | 41.159533 | 141 | 0.592856 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnEachZero.cpp | // Copyright (c) 2022-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.
//
#include <OgnEachZeroDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input";
// Check whether a scalar attribute contains a value which lies within 'tolerance' of 0.
//
// 'tolerance' must be non-negative. It is ignored for bool values.
// 'isZero' will be set true if 'value' contains a zero value, false otherwise.
//
// The return value is true if 'value' is a supported scalar type, false otherwise.
//
bool checkScalarForZero(OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break;
case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break;
case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break;
case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break;
case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break;
case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break;
case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break;
case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break;
case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break;
default:
return false;
}
return true;
}
// Determine which components of a decimal tuple attribute are within a given tolerance of zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each component of the tuple. On return the elements
// will be set true where the corresponding components lie within 'tolerance' of zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T, uint8_t N>
bool getTupleZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
if (auto const tuple = value.get<T[N]>())
{
for (uint8_t i = 0; i < N; ++i)
{
isZero[i] = (std::abs(tuple[i]) <= tolerance);
}
return true;
}
return false;
}
// Determine which components of a tuple attribute are zero
// (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each component of the tuple. On return the elements
// will be set true where the corresponding components are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool getTupleZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<double, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<double, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<double, 4>(value, tolerance, isZero);
case 9: return getTupleZeroes<double, 9>(value, tolerance, isZero);
case 16: return getTupleZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<float, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<float, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return getTupleZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return getTupleZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return getTupleZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
// Determine which elements of an unsigned array attribute are zero (i.e. they lie
// within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be an unsigned type, other than bool.
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each element of the unsigned array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the unsigned array are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T>
bool getUnsignedArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = (array->at(i) <= (T)tolerance);
return true;
}
return false;
}
// Determine which elements of a bool array attribute are zero/false. No tolerance
// value is applied since tolerance is meaningless for bool.
//
// 'isZero' is an array of bool with one element for each element of the 'value' array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the 'value' array are zero, false otherwise.
//
// The return value is true if 'value' is a bool array type, false otherwise.
//
bool getBoolArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, ogn::array<bool>& isZero)
{
if (auto const array = value.get<bool[]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = !array->at(i);
return true;
}
return false;
}
// Determine which elements of a signed array attribute are within a given tolerance of zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be a signed type.
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each element of the signed array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the unsigned array are within 'tolerance'
// of 0.0, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T>
bool getSignedArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = (std::abs(array->at(i)) <= tolerance);
return true;
}
return false;
}
// Determine which elements of a scalar array attribute are zero (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each element of the scalar array. On return the elements
// of 'isZero' will be set true where the corresponding elements in the scalar array are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool getScalarArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: return getBoolArrayZeroes(value, isZero);
case BaseDataType::eDouble: return getSignedArrayZeroes<double>(value, tolerance, isZero);
case BaseDataType::eFloat: return getSignedArrayZeroes<float>(value, tolerance, isZero);
case BaseDataType::eHalf: return getSignedArrayZeroes<pxr::GfHalf>(value, tolerance, isZero);
case BaseDataType::eInt: return getSignedArrayZeroes<int32_t>(value, tolerance, isZero);
case BaseDataType::eInt64: return getSignedArrayZeroes<int64_t>(value, tolerance, isZero);
case BaseDataType::eUChar: return getUnsignedArrayZeroes<unsigned char>(value, tolerance, isZero);
case BaseDataType::eUInt: return getUnsignedArrayZeroes<uint32_t>(value, tolerance, isZero);
case BaseDataType::eUInt64: return getUnsignedArrayZeroes<uint64_t>(value, tolerance, isZero);
default: break;
}
return false;
}
// Returns true if all components of the tuple are zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - base type of the tuple (e.g. float if tuple is float[2]).
// N - number of components in the tuple (e.g. '2' in the example above).
//
// 'tolerance' must be non-negative
//
template <typename T, uint8_t N>
bool isTupleZero(const T tuple[N], double tolerance)
{
CARB_ASSERT(tolerance >= 0.0);
for (uint8_t i = 0; i < N; ++i)
{
if (std::abs(tuple[i]) > tolerance) return false;
}
return true;
}
// Determine which elements of a tuple array attribute are zero (i.e. all of the tuple's
// components lie within a 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each tuple in the tuple array. On return the elements
// of 'isZero' will be set true where the corresponding tuples are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T, uint8_t N>
bool getTupleArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, double tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[][N]>())
{
for (size_t i = 0; i < array.size(); ++i)
isZero[i] = isTupleZero<T, N>(array->at(i), tolerance);
return true;
}
return false;
}
// Determine which elements of a tuple array attribute are zero (i.e. all of the tuple's components
// lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is an array of bool with one element for each tuple in the tuple array. On return the elements
// of 'isZero' will be set true where the corresponding tuples are zero, false otherwise.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool getTupleArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<double, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<double, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<double, 4>(value, tolerance, isZero);
case 9: return getTupleArrayZeroes<double, 9>(value, tolerance, isZero);
case 16: return getTupleArrayZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<float, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<float, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return getTupleArrayZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return getTupleArrayZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return getTupleArrayZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
} // namespace
class OgnEachZero
{
public:
static bool compute(OgnEachZeroDatabase& db)
{
const auto& value = db.inputs.value();
if (!value.resolved())
return true;
const auto& tolerance = db.inputs.tolerance();
auto& result = db.outputs.result();
try
{
bool foundType{ false };
// Arrays
if (value.type().arrayDepth > 0)
{
if (auto resultArray = result.get<bool[]>())
{
resultArray.resize(value.size());
// Arrays of tuples.
if (value.type().componentCount > 1)
{
foundType = getTupleArrayZeroes(value, tolerance, *resultArray);
}
// Arrays of scalars.
else
{
foundType = getScalarArrayZeroes(value, tolerance, *resultArray);
}
}
else
{
throw ogn::compute::InputError("input value is an array but result is not bool[]");
}
}
// Tuples
else if (value.type().componentCount > 1)
{
if (auto resultArray = result.get<bool[]>())
{
resultArray.resize(value.type().componentCount);
foundType = getTupleZeroes(value, tolerance, *resultArray);
}
else
{
throw ogn::compute::InputError("input value is a tuple but result is not bool[]");
}
}
// Scalars
else
{
if (auto resultScalar = result.get<bool>())
{
*resultScalar = false;
foundType = checkScalarForZero(value, tolerance, *resultScalar);
}
else
{
throw ogn::compute::InputError("input value is a scalar but result is not bool");
}
}
if (! foundType)
{
throw ogn::compute::InputError(kValueTypeUnresolved);
}
}
catch (ogn::compute::InputError &error)
{
db.logError("%s", error.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require value to be resolved before determining result's type
if (valueType.baseType != BaseDataType::eUnknown)
{
// The result is bool for scalar values, and bool array for arrays and tuples.
bool resultIsArray = ((valueType.arrayDepth > 0) || (valueType.componentCount > 1));
Type resultType(BaseDataType::eBool, 1, (resultIsArray ? 1 : 0));
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 17,818 | C++ | 37.238197 | 131 | 0.616399 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnClamp.cpp | // Copyright (c) 2022-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.
//
#include <OgnClampDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/graph/core/ogn/UsdTypes.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template <typename T>
void clamp(T const& input, T const& lower, T const& upper, T& result)
{
if (lower > upper)
{
throw ogn::compute::InputError("Lower is greater than upper!");
}
if (input <= lower)
{
result = lower;
}
else if (input < upper)
{
result = input;
}
else
{
result = upper;
}
}
template <typename T>
bool tryComputeAssumingType(OgnClampDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.input(), db.inputs.lower(), db.inputs.upper(), db.outputs.result(), &clamp<T>, count);
}
template<typename T, size_t tupleSize>
bool tryComputeAssumingType(OgnClampDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T>(
db.inputs.input(), db.inputs.lower(), db.inputs.upper(), db.outputs.result(), &clamp<T>, count);
}
} // namespace
// Node to clamp an input value or array of values to some range [lower, upper],
class OgnClamp
{
public:
// Clamp a number or array of numbers to a specified range
// If an array of numbers is provided as the input and lower/upper are scalers
// Then each input numeric will be clamped to the range [lower, upper]
// If all inputs are arrays, clamping will be done element-wise. lower & upper are broadcast against input
static bool computeVectorized(OgnClampDatabase& db, size_t count)
{
auto& inputType = db.inputs.input().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (const std::exception& e)
{
db.logError("Clamping could not be performed: %s", e.what());
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
auto inputAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::input.token());
auto lowerAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::lower.token());
auto upperAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::upper.token());
auto resultAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::result.token());
auto inputType = inputAttr.iAttribute->getResolvedType(inputAttr);
auto lowerType = lowerAttr.iAttribute->getResolvedType(lowerAttr);
auto upperType = upperAttr.iAttribute->getResolvedType(upperAttr);
// If one of the upper or lower is resolved we can resolve the other because they should match
if ((lowerType == BaseDataType::eUnknown) != (upperType == BaseDataType::eUnknown))
{
std::array<AttributeObj, 2> attrs { lowerAttr, upperAttr };
nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size());
lowerType = lowerAttr.iAttribute->getResolvedType(lowerAttr);
upperType = upperAttr.iAttribute->getResolvedType(upperAttr);
}
// The output shape must match the input shape and visa-versa, however we can't say anything
// about the input base type until it's connected
if (inputType.baseType != BaseDataType::eUnknown && lowerType != BaseDataType::eUnknown && upperType != BaseDataType::eUnknown)
{
if (inputType.baseType != lowerType.baseType || inputType.baseType != upperType.baseType)
{
nodeObj.iNode->logComputeMessageOnInstance(
nodeObj, kAuthoringGraphIndex, ogn::Severity::eError, "Unable to connect inputs to clamp with different base types");
return;
}
std::array<AttributeObj, 2> attrs { inputAttr, resultAttr };
nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE();
}
}
}
| 7,192 | C++ | 39.410112 | 156 | 0.615823 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivideHelper.h | #include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/ogn/UsdTypes.h>
#include <omni/graph/core/ogn/Database.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace OGNDivideHelper
{
using InType = ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>;
using ResType = ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>;
// Allow (AType[N] / BType) and (AType[N] / BType[N]) but not (AType / BType[N])
template<typename AType, typename BType, typename CType, size_t N, typename Functor>
bool tryComputeWithLimitedTupleBroadcasting(
InType const& a, InType const& b, ResType& result, Functor functor, size_t count)
{
if (ogn::compute::tryComputeWithArrayBroadcasting<AType[N], BType[N], CType[N]>(a, b, result,
[&](auto const& a, auto const& b, auto& result) { for (size_t i = 0; i < N; i++) functor(a[i], b[i], result[i]); }, count))
return true;
else if (ogn::compute::tryComputeWithArrayBroadcasting<AType[N], BType, CType[N]>(a, b, result,
[&](auto const& a, auto const& b, auto& result) { for (size_t i = 0; i < N; i++) functor(a[i], b, result[i]); }, count))
return true;
return false;
}
// AType is a vector of float's or double's
template<typename AType, typename BType, size_t N>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<!std::is_integral<AType>::value && !std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<double>(a) / static_cast<double>(b));
};
return tryComputeWithLimitedTupleBroadcasting<AType, BType, AType, N>(a, b, result, functor, count);
}
// AType is a vector of half's
template<typename AType, typename BType, size_t N>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_same<AType, pxr::GfHalf>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<AType>(static_cast<float>(static_cast<double>(a) / static_cast<double>(b)));
};
return tryComputeWithLimitedTupleBroadcasting<AType, BType, AType, N>(a, b, result, functor, count);
}
// AType is a vector of integrals => Force result to be a vector of doubles
template<typename AType, typename BType, size_t N>
bool tryComputeAssumingType(ogn::OmniGraphDatabase& db,
InType const& a,
InType const& b,
ResType& result,
size_t count,
typename std::enable_if_t<std::is_integral<AType>::value, AType>* = 0)
{
auto functor = [&](auto const& a, auto const& b, auto& result)
{
if (static_cast<double>(b) == 0.0)
{
db.logWarning("OgnDivide: Divide by zero encountered");
}
result = static_cast<double>(a) / static_cast<double>(b);
};
return tryComputeWithLimitedTupleBroadcasting<AType, BType, double, N>(a, b, result, functor, count);
}
template<typename T, size_t N>
bool _tryComputeAssuming(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (tryComputeAssumingType<double, T, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<float, T, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<pxr::GfHalf, T, N>(db, a, b, result, count)) return true;
if (tryComputeAssumingType<int32_t, T, N>(db, a, b, result, count)) return true;
return false;
}
template<size_t N>
bool _tryComputeTuple(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count)
{
if (_tryComputeAssuming<double, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<float, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<pxr::GfHalf, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<int32_t, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<int64_t, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<unsigned char, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<uint32_t, N>(db, a, b, result, count)) return true;
if (_tryComputeAssuming<uint64_t, N>(db, a, b, result, count)) return true;
return false;
}
bool tryComputeScalars(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeTuple2(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeTuple3(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeTuple4(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
bool tryComputeMatrices(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count);
} // namespace OGNDivideHelper
} // namespace nodes
} // namespace graph
} // namespace omni
| 5,806 | C | 44.724409 | 143 | 0.628143 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomNumeric.cpp | // 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.
//
#include "OgnRandomNumericDatabase.h"
#include "random/RandomNodeBase.h"
#include <omni/graph/core/ogn/ComputeHelpers.h>
namespace omni
{
namespace graph
{
namespace nodes
{
using namespace random;
class OgnRandomNumeric : public NodeBase<OgnRandomNumeric, OgnRandomNumericDatabase>
{
template <typename T>
static bool tryComputeAssumingType(OgnRandomNumericDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithArrayBroadcasting<T>(
db.state.gen(), db.inputs.min(), db.inputs.max(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& min, T const& max, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextUniform(min, max);
},
count);
}
template <typename T, size_t N>
static bool tryComputeAssumingType(OgnRandomNumericDatabase& db, size_t count)
{
return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(
db.state.gen(), db.inputs.min(), db.inputs.max(), db.outputs.random(),
[](GenBuffer_t const& genBuffer, T const& min, T const& max, T& result)
{
// Generate next random
result = asGenerator(genBuffer).nextUniform(min, max);
},
count);
}
static bool defaultCompute(OgnRandomNumericDatabase& db, size_t count)
{
auto const genBuffers = db.state.gen.vectorized(count);
if (genBuffers.size() != count)
{
db.logWarning("Failed to write to output using default range [0..1) (wrong genBuffers size)");
return false;
}
for (size_t i = 0; i < count; ++i)
{
auto outPtr = db.outputs.random(i).get<double>();
if (!outPtr)
{
db.logWarning("Failed to write to output using default range [0..1) (null output pointer)");
return false;
}
*outPtr = asGenerator(genBuffers[i]).nextUniform<double>(0.0, 1.0);
}
return true;
}
public:
static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed);
// HACK: onConnectionTypeResolve is not called the first time,
// but by setting the output type, we force it to be called.
//
// TODO: OGN should really support default inputs for union types!
// See https://nvidia-omniverse.atlassian.net/browse/OM-67739
setDefaultOutputType(nodeObj, outputs::random.token());
}
static bool onCompute(OgnRandomNumericDatabase& db, size_t count)
{
auto const& minAttr{ db.inputs.min() };
auto const& maxAttr{ db.inputs.max() };
auto const& outAttr{ db.outputs.random() };
if (!outAttr.resolved())
{
// Output type not yet resolved, can't compute
db.logWarning("Unsupported input types");
return false;
}
if (!minAttr.resolved() && !maxAttr.resolved())
{
// Output using default min and max
return defaultCompute(db, count);
}
// Inputs and outputs are resolved, try all possible types, excluding bool and ogn::string
auto const outType = outAttr.type();
switch (outType.baseType) // NOLINT(clang-diagnostic-switch-enum)
{
case BaseDataType::eDouble:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<double>(db, count);
case 2:
return tryComputeAssumingType<double, 2>(db, count);
case 3:
return tryComputeAssumingType<double, 3>(db, count);
case 4:
return tryComputeAssumingType<double, 4>(db, count);
case 9:
return tryComputeAssumingType<double, 9>(db, count);
case 16:
return tryComputeAssumingType<double, 16>(db, count);
default:
break;
}
case BaseDataType::eFloat:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<float>(db, count);
case 2:
return tryComputeAssumingType<float, 2>(db, count);
case 3:
return tryComputeAssumingType<float, 3>(db, count);
case 4:
return tryComputeAssumingType<float, 4>(db, count);
default:
break;
}
case BaseDataType::eHalf:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<pxr::GfHalf>(db, count);
case 2:
return tryComputeAssumingType<pxr::GfHalf, 2>(db, count);
case 3:
return tryComputeAssumingType<pxr::GfHalf, 3>(db, count);
case 4:
return tryComputeAssumingType<pxr::GfHalf, 4>(db, count);
default:
break;
}
case BaseDataType::eInt:
switch (outType.componentCount)
{
case 1:
return tryComputeAssumingType<int32_t>(db, count);
case 2:
return tryComputeAssumingType<int32_t, 2>(db, count);
case 3:
return tryComputeAssumingType<int32_t, 3>(db, count);
case 4:
return tryComputeAssumingType<int32_t, 4>(db, count);
default:
break;
}
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default:
break;
}
db.logWarning("Unsupported input types");
return false;
}
static void onConnectionTypeResolve(NodeObj const& node)
{
resolveOutputType(node, inputs::min.token(), inputs::max.token(), outputs::random.token());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 6,903 | C++ | 32.678049 | 108 | 0.580762 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIncrement.cpp | // Copyright (c) 2021-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.
//
#include <OgnIncrementDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Helper functions to try doing an addition operation on two input attributes.
* We assume the runtime attributes have type T and the other one is double.
* The first input is either an array or a singular value, and the second input is a single double value
*
* @param db: database object
* @return True if we can get a result properly, false if not
*/
/**
* Used when input type is resolved as Half
*/
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<float>(b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, double, pxr::GfHalf>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as any numeric type other than Half
*/
template<typename T>
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<T>(b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<T, double, T>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as Half
*/
template <size_t N>
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<float>(b);
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, pxr::GfHalf, double, pxr::GfHalf>(
db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
/**
* Used when input type is resolved as any numeric type other than Half
*/
template<typename T, size_t N>
bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count)
{
auto functor = [](auto const& a, auto const& b, auto& result)
{
result = a + static_cast<T>(b);
};
return ogn::compute::tryComputeWithTupleBroadcasting<N, T, double, T>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count);
}
} // namespace
class OgnIncrement
{
public:
static size_t computeVectorized(OgnIncrementDatabase& db, size_t count)
{
auto& inputType = db.inputs.value().type();
// Compute the components, if the types are all resolved.
try
{
switch (inputType.baseType)
{
case BaseDataType::eDouble:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<double>(db, count);
case 2: return tryComputeAssumingType<double, 2>(db, count);
case 3: return tryComputeAssumingType<double, 3>(db, count);
case 4: return tryComputeAssumingType<double, 4>(db, count);
case 9: return tryComputeAssumingType<double, 9>(db, count);
case 16: return tryComputeAssumingType<double, 16>(db, count);
default: break;
}
case BaseDataType::eFloat:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<float>(db, count);
case 2: return tryComputeAssumingType<float, 2>(db, count);
case 3: return tryComputeAssumingType<float, 3>(db, count);
case 4: return tryComputeAssumingType<float, 4>(db, count);
default: break;
}
case BaseDataType::eHalf:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType(db, count);
case 2: return tryComputeAssumingType<2>(db, count);
case 3: return tryComputeAssumingType<3>(db, count);
case 4: return tryComputeAssumingType<4>(db, count);
default: break;
}
case BaseDataType::eInt:
switch (inputType.componentCount)
{
case 1: return tryComputeAssumingType<int32_t>(db, count);
case 2: return tryComputeAssumingType<int32_t, 2>(db, count);
case 3: return tryComputeAssumingType<int32_t, 3>(db, count);
case 4: return tryComputeAssumingType<int32_t, 4>(db, count);
default: break;
}
;
case BaseDataType::eInt64:
return tryComputeAssumingType<int64_t>(db, count);
case BaseDataType::eUChar:
return tryComputeAssumingType<unsigned char>(db, count);
case BaseDataType::eUInt:
return tryComputeAssumingType<uint32_t>(db, count);
case BaseDataType::eUInt64:
return tryComputeAssumingType<uint64_t>(db, count);
default: break;
}
db.logWarning("Failed to resolve input types");
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return 0;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto value = node.iNode->getAttributeByToken(node, inputs::value.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto valueType = value.iAttribute->getResolvedType(value);
// Require inputs to be resolved before determining sum's type
if (valueType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { value, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 6,591 | C++ | 38.005917 | 170 | 0.618874 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTrig.cpp | // Copyright (c) 2022-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.
//
#include <OgnTrigDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include <omni/math/linalg/math.h>
#include <math.h>
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
_____ ____ _ _ ____ _______ _____ ____ _______ __
| __ \ / __ \ | \ | |/ __ \__ __| / ____/ __ \| __ \ \ / /
| | | | | | | | \| | | | | | | | | | | | | |__) \ \_/ /
| | | | | | | | . ` | | | | | | | | | | | | ___/ \ /
| |__| | |__| | | |\ | |__| | | | | |___| |__| | | | |
|_____/ \____/ |_| \_|\____/ |_| \_____\____/|_| |_|
This node uses a large cascading "if" to select operation type, which is not efficient. It will be eventually be
refactored but until then do not propagate this anti-pattern. Thanks for keeping things fast!
*/
/**
* Used when input type is resolved as non-int numeric type other than Half
*/
template <typename T>
bool tryComputeAssumingType(OgnTrigDatabase& db, NameToken operation, size_t count)
{
if (operation == db.tokens.SIN) // Sine
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::sin(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.COS) // Cosine
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::cos(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.TAN) // Tangent
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::tan(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.ARCSIN) // Arcsine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<T>(pxr::GfRadiansToDegrees(std::asin(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.ARCCOS) // Arccosine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<T>(pxr::GfRadiansToDegrees(std::acos(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.ARCTAN) // Arctangent
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<T>(pxr::GfRadiansToDegrees(std::atan(a))); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.DEGREES) // Degrees
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfRadiansToDegrees(a)); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
else if (operation == db.tokens.RADIANS) // Radians
{
auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfDegreesToRadians(a)); };
return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count);
}
throw ogn::compute::InputError("Operation not one of sin, cos, tan, asin, acos, degrees, radians");
}
template <>
bool tryComputeAssumingType<pxr::GfHalf>(OgnTrigDatabase& db, NameToken operation, size_t count)
{
if (operation == db.tokens.SIN) // Sine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::sin(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.COS) // Cosine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::cos(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.TAN) // Tangent
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::tan(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.ARCSIN) // Arcsine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::asin(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.ARCCOS) // Arccosine
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::acos(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.ARCTAN) // Arctangent
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(std::atan(pxr::GfDegreesToRadians(a)))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.DEGREES) // Degrees
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(a))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
else if (operation == db.tokens.RADIANS) // Radians
{
auto functor = [](auto const& a, auto& result)
{ result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfDegreesToRadians(a))); };
return ogn::compute::tryCompute(
db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count);
}
throw ogn::compute::InputError("Operation not one of sin, cos, tan, asin, acos, degrees, radians");
}
} // namespace
class OgnTrig
{
public:
static size_t computeVectorized(OgnTrigDatabase& db, size_t count)
{
NameToken const& operation = db.inputs.operation();
try
{
if (tryComputeAssumingType<double>(db, operation, count)) return count;
else if (tryComputeAssumingType<pxr::GfHalf>(db, operation, count)) return count;
else if (tryComputeAssumingType<float>(db, operation, count)) return count;
else
{
db.logWarning("Failed to resolve input types");
}
}
catch (std::exception &error)
{
db.logError("Operation %s could not be performed : %s", db.tokenToString(operation), error.what());
}
return 0;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto a = node.iNode->getAttributeByToken(node, inputs::a.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto aType = a.iAttribute->getResolvedType(a);
// Require inputs to be resolved before determining output's type
if (aType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { a, result };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 8,956 | C++ | 43.785 | 128 | 0.607191 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIsZero.cpp | // Copyright (c) 2022-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.
//
#include <OgnIsZeroDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input";
// Check whether a scalar attribute contains a value which lies within 'tolerance' of 0.
//
// 'tolerance' must be non-negative. It is ignored for bool values.
// 'isZero' will be set true if 'value' contains a zero value, false otherwise.
//
// The return value is true if 'value' is a supported scalar type, false otherwise.
//
bool checkScalarForZero(OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break;
case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break;
case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break;
case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break;
case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break;
case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break;
case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break;
case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break;
case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break;
default:
return false;
}
return true;
}
// Check whether a tuple attribute contains a tuple whose components are all zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' is assumed to be true on entry and will be set false if any component of the tuple is not zero.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
template <typename T, int N>
bool checkTupleForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
CARB_ASSERT(isZero);
if (auto const tuple = value.get<T[N]>())
{
for (int i = 0; isZero && (i < N); ++i)
{
isZero = (std::abs(tuple[i]) <= tolerance);
}
return true;
}
return false;
}
// Check whether a tuple attribute contains a tuple whose components are all zero
// (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' is assumed to be true on entry and will be set false if any component of the tuple is not zero.
//
// The return value is true if 'value' is a supported tuple type, false otherwise.
//
bool checkTupleForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
CARB_ASSERT(isZero);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<double, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<double, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<double, 4>(value, tolerance, isZero);
case 9: return checkTupleForZeroes<double, 9>(value, tolerance, isZero);
case 16: return checkTupleForZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<float, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<float, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return checkTupleForZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return checkTupleForZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return checkTupleForZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
// Check whether an unsigned array attribute's elements are all zero (i.e. they lie
// within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be an unsigned type, other than bool.
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a supported unsigned integer array type, false otherwise.
//
template <typename T>
bool checkUnsignedArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const int& tolerance, bool& isZero)
{
static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return element <= (T)tolerance; });
return true;
}
return false;
}
// Check whether a bool array attribute's elements are all zero/false. No tolerance
// value is applied since tolerance is meaningless for bool.
//
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a bool array type, false otherwise.
//
bool checkBoolArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, bool& isZero)
{
if (auto const array = value.get<bool[]>())
{
isZero = std::all_of(array->begin(), array->end(), [](auto element){ return !element; });
return true;
}
return false;
}
// Check whether a signed array attribute's elements are all zero (i.e. they lie
// within 'tolerance' of 0).
//
// T - type of the elements of the array. Must be a signed type.
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a supported signed array type, false otherwise.
//
template <typename T>
bool checkSignedArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required.");
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[]>())
{
isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return (std::abs(element) <= tolerance); });
return true;
}
return false;
}
// Check whether a scalar array attribute's elements are all zero (i.e. they lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all elements of the array are zero, false otherwise.
//
// The return value is true if 'value' is a supported scalar array type, false otherwise.
//
bool checkScalarArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eBool: return checkBoolArrayForZeroes(value, isZero);
case BaseDataType::eDouble: return checkSignedArrayForZeroes<double>(value, tolerance, isZero);
case BaseDataType::eFloat: return checkSignedArrayForZeroes<float>(value, tolerance, isZero);
case BaseDataType::eHalf: return checkSignedArrayForZeroes<pxr::GfHalf>(value, tolerance, isZero);
case BaseDataType::eInt: return checkSignedArrayForZeroes<int32_t>(value, tolerance, isZero);
case BaseDataType::eInt64: return checkSignedArrayForZeroes<int64_t>(value, tolerance, isZero);
case BaseDataType::eUChar: return checkUnsignedArrayForZeroes<unsigned char>(value, (int)tolerance, isZero);
case BaseDataType::eUInt: return checkUnsignedArrayForZeroes<uint32_t>(value, (int)tolerance, isZero);
case BaseDataType::eUInt64: return checkUnsignedArrayForZeroes<uint64_t>(value, (int)tolerance, isZero);
default: break;
}
return false;
}
// Returns true if all components of the tuple are zero.
// (i.e. they lie within 'tolerance' of 0).
//
// T - base type of the tuple (e.g. float if tuple is float[2]).
// N - number of components in the tuple (e.g. '2' in the example above).
//
// 'tolerance' must be non-negative
//
template <typename T, int N>
bool isTupleZero(const T tuple[N], double tolerance)
{
CARB_ASSERT(tolerance >= 0.0);
for (int i = 0; i < N; ++i)
{
if (std::abs(tuple[i]) > tolerance) return false;
}
return true;
}
// Check whether a tuple array attribute's elements are all zero tuples
// (i.e. all of their components are within 'tolerance' of 0).
//
// T - type of the components of the tuple.
// N - number of components in the tuple
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all tuples in the array is are zero, false otherwise.
//
// The return value is true if 'value' is a supported decimal tuple array type, false otherwise.
//
template <typename T, int N>
bool checkTupleArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, double tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
if (auto const array = value.get<T[][N]>())
{
isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return isTupleZero<T, N>(element, tolerance); });
return true;
}
return false;
}
// Check whether a tuple array attribute's elements are all zero tuples (i.e. all of their components
// lie within 'tolerance' of 0).
//
// 'tolerance' must be non-negative
// 'isZero' will be set true if all tuples in the array is are zero, false otherwise.
//
// The return value is true if 'value' is a supported decimal tuple array type, false otherwise.
//
bool checkTupleArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero)
{
CARB_ASSERT(tolerance >= 0.0);
switch (value.type().baseType)
{
case BaseDataType::eDouble:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<double, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<double, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<double, 4>(value, tolerance, isZero);
case 9: return checkTupleArrayForZeroes<double, 9>(value, tolerance, isZero);
case 16: return checkTupleArrayForZeroes<double, 16>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eFloat:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<float, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<float, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<float, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eHalf:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<pxr::GfHalf, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<pxr::GfHalf, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<pxr::GfHalf, 4>(value, tolerance, isZero);
default: break;
}
break;
case BaseDataType::eInt:
switch (value.type().componentCount)
{
case 2: return checkTupleArrayForZeroes<int32_t, 2>(value, tolerance, isZero);
case 3: return checkTupleArrayForZeroes<int32_t, 3>(value, tolerance, isZero);
case 4: return checkTupleArrayForZeroes<int32_t, 4>(value, tolerance, isZero);
default: break;
}
break;
default: break;
}
return false;
}
} // namespace
class OgnIsZero
{
public:
static bool compute(OgnIsZeroDatabase& db)
{
const auto& value = db.inputs.value();
if (!value.resolved())
return true;
const auto& tolerance = std::abs(db.inputs.tolerance());
auto& result = db.outputs.result();
try
{
// Some of the functions below return as soon as they find a non-zero value, so
// we start out assuming all values are zero and let them change that to false.
//
result = true;
bool foundType{ false };
// Arrays
if (value.type().arrayDepth > 0)
{
// Arrays of tuples.
if (value.type().componentCount > 1)
{
foundType = checkTupleArrayForZeroes(value, tolerance, result);
}
// Arrays of scalars.
else
{
foundType = checkScalarArrayForZeroes(value, tolerance, result);
}
}
// Tuples
else if (value.type().componentCount > 1)
{
foundType = checkTupleForZeroes(value, tolerance, result);
}
// Scalars
else
{
foundType = checkScalarForZero(value, tolerance, result);
}
if (! foundType)
{
throw ogn::compute::InputError(kValueTypeUnresolved);
}
}
catch (ogn::compute::InputError &error)
{
db.logError("OgnIsZero: %s", error.what());
return false;
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 15,541 | C++ | 37 | 135 | 0.628595 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNoise.cpp | // 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.
//
// This node implements the noise() function from Warp. Once Warp has been released
// it will be reimplemented using Warp.
//
// If you're interested in how to use the output from this node to drive a procedural
// noise texture, take a look at the core_definitions::perlin_noise_texture from the material library,
// documented here:
//
// https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_material-graph/nodes/Texturing_High_Level/perlin-noise.html
//
// Its MDL implementation can be found in the omni-core-materials repo, in mdl/nvidia/core_definitions.mdl
// That in turn calls base::perlin_noise_texture() which is implemented in the MDL-SDK repo, in src/shaders/mdl/base/base.mdl
//
#include <OgnNoiseDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include "warp_noise.h"
namespace omni {
namespace graph {
namespace nodes {
namespace {
template <typename T, typename PXRTYPE>
bool getNoiseValues(uint32_t &rng_state, const OgnNoiseAttributes::inputs::position_t& position, ogn::array<float> &resultArray)
{
if (auto positionArray = position.get<T>())
{
resultArray.resize(positionArray.size());
size_t i = 0;
for (auto pos : *positionArray)
{
resultArray[i++] = noise(rng_state, *(const PXRTYPE*)pos);
}
return true;
}
return false;
}
// Specialization for non-tuple type.
template <>
bool getNoiseValues<float[],float>(uint32_t &rng_state, const OgnNoiseAttributes::inputs::position_t& position, ogn::array<float> &resultArray)
{
if (auto positionArray = position.get<float[]>())
{
resultArray.resize(positionArray.size());
size_t i = 0;
for (auto pos : *positionArray)
{
resultArray[i++] = noise(rng_state, pos);
}
return true;
}
return false;
}
}
class OgnNoise
{
public:
static bool compute(OgnNoiseDatabase& db)
{
const auto& position = db.inputs.position();
// If we don't have any positions to sample then there's nothing to do.
if (!position.resolved())
return true;
auto& result = db.outputs.result();
const auto& seed = db.inputs.seed();
uint32_t rng_state = rand_init(seed);
try
{
if (position.type().arrayDepth == 0)
{
if (auto resultScalar = result.get<float>())
{
switch (position.type().componentCount)
{
case 1:
{
*resultScalar = noise(rng_state, *position.get<float>());
return true;
}
case 2:
{
*resultScalar = noise(rng_state, *(GfVec2f*)(*position.get<float[2]>()));
return true;
}
case 3:
{
*resultScalar = noise(rng_state, *(GfVec3f*)(*position.get<float[3]>()));
return true;
}
case 4:
{
*resultScalar = noise(rng_state, *(GfVec4f*)(*position.get<float[4]>()));
return true;
}
default:
db.logError("'position' has invalid tuple size of %i.", position.type().componentCount);
}
}
else
{
throw ogn::compute::InputError("'result' is an array but 'position' is not");
}
}
else if (auto resultArray = result.get<float[]>())
{
switch (position.type().componentCount)
{
case 1:
{
if (getNoiseValues<float[], float>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[]");
}
case 2:
{
if (getNoiseValues<float[][2], GfVec2f>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[2][]");
}
case 3:
{
if (getNoiseValues<float[][3], GfVec3f>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[3][]");
}
case 4:
{
if (getNoiseValues<float[][4], GfVec4f>(rng_state, position, *resultArray)) return true;
throw ogn::compute::InputError("could not resolve 'position' to float[4][]");
}
default:
db.logError("'position' has invalid tuple size of %i.", position.type().componentCount);
}
}
else
{
throw ogn::compute::InputError("'position' is an array but 'result' is not");
}
}
catch (ogn::compute::InputError &error)
{
db.logError(error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto position = node.iNode->getAttributeByToken(node, inputs::position.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto positionType = position.iAttribute->getResolvedType(position);
if (positionType.baseType != BaseDataType::eUnknown)
{
// 'result' is always float but has the same array depth as 'position'.
Type type(BaseDataType::eFloat, 1, positionType.arrayDepth, AttributeRole::eNone);
result.iAttribute->setResolvedType(result, type);
}
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
// end-compute-helpers
| 6,563 | C++ | 33.010363 | 143 | 0.551272 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadKeyboardState.cpp | // Copyright (c) 2021-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.
//
#include <OgnReadKeyboardStateDatabase.h>
#include <carb/input/IInput.h>
#include <carb/input/InputTypes.h>
#include <omni/kit/IAppWindow.h>
using namespace carb::input;
namespace omni {
namespace graph {
namespace action {
// This list matches carb::input::KeyboardInput
constexpr size_t s_numNames = size_t(carb::input::KeyboardInput::eCount);
static constexpr std::array<const char*, s_numNames> s_keyNames = {
"Unknown",
"Space",
"Apostrophe",
"Comma",
"Minus",
"Period",
"Slash",
"Key0",
"Key1",
"Key2",
"Key3",
"Key4",
"Key5",
"Key6",
"Key7",
"Key8",
"Key9",
"Semicolon",
"Equal",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"LeftBracket",
"Backslash",
"RightBracket",
"GraveAccent",
"Escape",
"Tab",
"Enter",
"Backspace",
"Insert",
"Del",
"Right",
"Left",
"Down",
"Up",
"PageUp",
"PageDown",
"Home",
"End",
"CapsLock",
"ScrollLock",
"NumLock",
"PrintScreen",
"Pause",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"Numpad0",
"Numpad1",
"Numpad2",
"Numpad3",
"Numpad4",
"Numpad5",
"Numpad6",
"Numpad7",
"Numpad8",
"Numpad9",
"NumpadDel",
"NumpadDivide",
"NumpadMultiply",
"NumpadSubtract",
"NumpadAdd",
"NumpadEnter",
"NumpadEqual",
"LeftShift",
"LeftControl",
"LeftAlt",
"LeftSuper",
"RightShift",
"RightControl",
"RightAlt",
"RightSuper",
"Menu"
};
static_assert(s_keyNames.size() == size_t(carb::input::KeyboardInput::eCount), "enum must match this table");
static std::array<NameToken, s_numNames> s_keyTokens;
class OgnReadKeyboardState
{
public:
static bool compute(OgnReadKeyboardStateDatabase& db)
{
static NameToken const emptyToken = db.stringToToken("");
NameToken const& keyIn = db.inputs.key();
auto contextObj = db.abi_context();
// First time look up all the token string values
static bool callOnce = ([&contextObj] {
std::transform(s_keyNames.begin(), s_keyNames.end(), s_keyTokens.begin(),
[&contextObj](auto const& s) { return contextObj.iToken->getHandle(s); });
} (), true);
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
if (!appWindow)
{
return false;
}
Keyboard* keyboard = appWindow->getKeyboard();
if (!keyboard)
{
CARB_LOG_ERROR_ONCE("No Keyboard!");
return false;
}
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
{
CARB_LOG_ERROR_ONCE("No Input!");
return false;
}
bool isPressed = false;
// Get the index of the token of the key of interest
auto iter = std::find(s_keyTokens.begin(), s_keyTokens.end(), keyIn);
if (iter != s_keyTokens.end())
{
size_t index = iter - s_keyTokens.begin();
KeyboardInput key = KeyboardInput(index);
isPressed = (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, key));
}
db.outputs.shiftOut() =
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftShift)) ||
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightShift));
db.outputs.ctrlOut() =
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftControl)) ||
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightControl));
db.outputs.altOut() =
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftAlt)) ||
(carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightAlt));
db.outputs.isPressed() = isPressed;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 4,887 | C++ | 23.19802 | 121 | 0.581747 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadGamepadState.cpp | // 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.
//
#include <OgnReadGamepadStateDatabase.h>
#include <carb/input/IInput.h>
#include <carb/input/InputTypes.h>
#include <omni/kit/IAppWindow.h>
using namespace carb::input;
namespace omni {
namespace graph {
namespace nodes {
// This is different from carb::input::GamepadInput::eCount by 4 because we combine the joystick inputs by axis (x/y)
constexpr size_t s_numNames = size_t(carb::input::GamepadInput::eCount) - 4;
static std::array<NameToken, s_numNames> s_elementTokens;
class OgnReadGamepadState
{
public:
static bool compute(OgnReadGamepadStateDatabase& db)
{
NameToken const& elementIn = db.inputs.gamepadElement();
const unsigned int gamepadId = db.inputs.gamepadId();
const float deadzone = db.inputs.deadzone();
// First time initialization of all the token values
static bool callOnce = ([&db] {
s_elementTokens = {
db.tokens.LeftStickXAxis,
db.tokens.LeftStickYAxis,
db.tokens.RightStickXAxis,
db.tokens.RightStickYAxis,
db.tokens.LeftTrigger,
db.tokens.RightTrigger,
db.tokens.FaceButtonBottom,
db.tokens.FaceButtonRight,
db.tokens.FaceButtonLeft,
db.tokens.FaceButtonTop,
db.tokens.LeftShoulder,
db.tokens.RightShoulder,
db.tokens.SpecialLeft,
db.tokens.SpecialRight,
db.tokens.LeftStickButton,
db.tokens.RightStickButton,
db.tokens.DpadUp,
db.tokens.DpadRight,
db.tokens.DpadDown,
db.tokens.DpadLeft
};
} (), true);
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
if (!appWindow)
{
return false;
}
Gamepad* gamepad = appWindow->getGamepad(gamepadId);
if (!gamepad)
{
db.logWarning("No Gamepad!");
return false;
}
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
{
db.logWarning("No Input!");
return false;
}
bool isPressed = false;
float value = 0.0;
// Get the index of the token of the element of interest
auto iter = std::find(s_elementTokens.begin(), s_elementTokens.end(), elementIn);
if (iter != s_elementTokens.end())
{
size_t index = iter - s_elementTokens.begin();
if (index < 4)
{
// We want to combine the joystick inputs by its axis (x/y instead of right/left/up/down)
GamepadInput positiveElement = GamepadInput(2*index);
GamepadInput negativeElement = GamepadInput(2*index+1);
value = input->getGamepadValue(gamepad, positiveElement) - input->getGamepadValue(gamepad, negativeElement);
}
else
{
// index is offset by 4 because we combine the joystick x/y axis
GamepadInput element = GamepadInput(index + 4);
value = input->getGamepadValue(gamepad, element);
}
// Check for deadzone threshold
if (std::abs(value) < deadzone)
{
value = 0.0;
isPressed = false;
}
else
{
isPressed = true;
}
}
db.outputs.isPressed() = isPressed;
db.outputs.value() = value;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 4,137 | C++ | 31.84127 | 124 | 0.580131 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Quaternion.cpp | // Copyright (c) 2021-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.
//
#include <OgnSetMatrix4QuaternionDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/quat.h>
using omni::math::linalg::matrix4d;
using omni::math::linalg::quatd;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
void updateMatrix(const double input[16], double result[16], const double quaternion[4])
{
matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result);
memcpy(resultMat.data(), input, sizeof(double) * 16);
resultMat.SetRotateOnly(quatd(quaternion[3], quaternion[0], quaternion[1], quaternion[2]));
}
}
class OgnSetMatrix4Quaternion
{
public:
static bool compute(OgnSetMatrix4QuaternionDatabase& db)
{
const auto& matrixInput = db.inputs.matrix();
const auto& quaternionInput = db.inputs.quaternion();
auto matrixOutput = db.outputs.matrix();
bool failed = true;
// Singular case
if (auto matrix = matrixInput.get<double[16]>())
{
if (auto quaternion = quaternionInput.get<double[4]>())
{
if (auto output = matrixOutput.get<double[16]>())
{
updateMatrix(*matrix, *output, *quaternion);
failed = false;
}
}
}
// Array case
else if (auto matrices = matrixInput.get<double[][16]>())
{
if (auto quaternions = quaternionInput.get<double[][4]>())
{
if (auto output = matrixOutput.get<double[][16]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
updateMatrix((*matrices)[i], (*output)[i], (*quaternions)[i]);
}
failed = false;
}
}
}
else
{
db.logError("Input type for matrix input not supported");
return false;
}
if (failed)
{
db.logError("Input and output depths need to align: Matrix input with depth %s, quaternion input with depth %s, and output with depth %s",
matrixInput.type().arrayDepth, quaternionInput.type().arrayDepth, matrixOutput.type().arrayDepth);
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node){
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs {
node.iNode->getAttribute(node, OgnSetMatrix4QuaternionAttributes::inputs::matrix.m_name),
node.iNode->getAttribute(node, OgnSetMatrix4QuaternionAttributes::outputs::matrix.m_name)
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,340 | C++ | 31.754902 | 151 | 0.592216 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToTarget.cpp | // Copyright (c) 2021-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.
//
#include <OgnRotateToTargetDatabase.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/math.h>
#include <omni/math/linalg/SafeCast.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usdGeom/xformCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include "PrimCommon.h"
#include "XformUtils.h"
using namespace omni::math::linalg;
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
class OgnRotateToTarget
{
XformUtils::MoveState m_moveState;
public:
static bool compute(OgnRotateToTargetDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnRotateToTarget>();
double& startTime = state.m_moveState.startTime;
pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName;
quatd& startOrientation = state.m_moveState.startOrientation;
vec3d& startEuler = state.m_moveState.startEuler;
XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
try
{
auto sourcePrimPath = getPrimOrPath(contextObj, nodeObj, inputs::sourcePrim.token(), inputs::sourcePrimPath.token(), inputs::useSourcePath.token(), db.getInstanceIndex());
auto destPrimPath =
getPrimOrPath(contextObj, nodeObj, inputs::targetPrim.token(), inputs::targetPrimPath.token(),
inputs::useTargetPath.token(), db.getInstanceIndex());
if (sourcePrimPath.IsEmpty() || destPrimPath.IsEmpty())
return true;
pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath);
pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath);
pxr::UsdGeomXformCache xformCache;
matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim));
matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim));
quatd destWorldOrient = extractRotationQuatd(destWorldTransform).GetNormalized();
quatd sourceParentWorldOrient = extractRotationQuatd(sourceParentTransform).GetNormalized();
bool hasRotations =
(destWorldOrient != quatd::GetIdentity()) or (sourceParentWorldOrient != quatd::GetIdentity());
if (startTime <= kUninitializedStartTime || now < startTime)
{
std::tie(startOrientation, targetAttribName) =
XformUtils::extractPrimOrientOp(contextObj, sourcePrimPath);
if (targetAttribName.IsEmpty())
{
if (hasRotations)
throw std::runtime_error(
"RotateToTarget requires the source Prim to have xformOp:orient"
" when the destination Prim or source Prim parent has rotation, please Add");
std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, sourcePrimPath);
if (not targetAttribName.IsEmpty())
rotationMode = XformUtils::RotationMode::eEuler;
}
else
rotationMode = XformUtils::RotationMode::eQuat;
if (targetAttribName.IsEmpty())
throw std::runtime_error(
formatString("Could not find suitable XformOp on %s, please add", sourcePrimPath.GetText()));
startTime = now;
// Start sleeping
db.outputs.finished() = kExecutionAttributeStateLatentPush;
return true;
}
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
// delta step
float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp);
// Convert dest prim transform to the source's parent frame
matrix4d destLocalTransform = destWorldTransform / sourceParentTransform;
if (rotationMode == XformUtils::RotationMode::eQuat)
{
const quatd& targetOrientation = extractRotationQuatd(destLocalTransform).GetNormalized();
quatd quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized();
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), quat);
}
else if (rotationMode == XformUtils::RotationMode::eEuler)
{
// FIXME: We previously checked that there is no rotation on the target, so we just have to interpolate
// to identity.
vec3d const targetRot{};
auto rot = GfLerp(alpha2, startEuler, targetRot);
// Write back to the prim
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), rot);
}
if (alpha2 < 1)
{
// still waiting, output is disabled
db.outputs.finished() = kExecutionAttributeStateDisabled;
return true;
}
else
{
// Completed the maneuver
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
}
catch(const std::exception& e)
{
db.logError(e.what());
return false;
}
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
| 6,759 | C++ | 37.850574 | 183 | 0.62169 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTransformVector.cpp | // Copyright (c) 2021-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.
//
#include <OgnTransformVectorDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/vec.h>
using omni::math::linalg::matrix4d;
using omni::math::linalg::matrix3d;
using omni::math::linalg::vec3;
using ogn::compute::tryComputeWithArrayBroadcasting;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeWithMatrix3(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix3d*>(matrix);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<T>*>(result);
// left multiplication by row vector
resultVec = vec3<T>(sourceVec * transformMat);
};
return tryComputeWithArrayBroadcasting<double[9], T[3], T[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor);
}
template<typename T>
bool tryComputeWithMatrix4(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix4d*>(matrix);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<T>*>(result);
resultVec = vec3<T>(transformMat.Transform(sourceVec));
};
return tryComputeWithArrayBroadcasting<double[16], T[3], T[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor);
}
/* FIXME: GfHalf has no explicit conversion from double to half, so we need to convert to a float first */
template<>
bool tryComputeWithMatrix3<pxr::GfHalf>(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix3d*>(matrix);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result);
// left multiplication by row vector
resultVec = vec3<pxr::GfHalf>(vec3<float>(sourceVec * transformMat));
};
return tryComputeWithArrayBroadcasting<double[9], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor);
}
template<>
bool tryComputeWithMatrix4<pxr::GfHalf>(OgnTransformVectorDatabase& db)
{
auto functor = [&](auto& matrix, auto& vector, auto& result)
{
auto& transformMat = *reinterpret_cast<const matrix4d*>(matrix);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result);
resultVec = vec3<pxr::GfHalf>(vec3<float>(transformMat.Transform(sourceVec)));
};
return tryComputeWithArrayBroadcasting<double[16], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor);
}
} // namespace
class OgnTransformVector
{
public:
static bool compute(OgnTransformVectorDatabase& db)
{
try
{
// matrix3
if (tryComputeWithMatrix3<double>(db)) return true;
else if (tryComputeWithMatrix3<float>(db)) return true;
else if (tryComputeWithMatrix3<pxr::GfHalf>(db)) return true;
// matrix4
else if (tryComputeWithMatrix4<double>(db)) return true;
else if (tryComputeWithMatrix4<float>(db)) return true;
else if (tryComputeWithMatrix4<pxr::GfHalf>(db)) return true;
else
{
db.logWarning("OgnTransformVector: Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnTransformVector: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node){
auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token());
auto matrix = node.iNode->getAttributeByToken(node, inputs::matrix.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
auto matrixType = matrix.iAttribute->getResolvedType(matrix);
// Require vector, matrix to be resolved before determining result's type
if (vectorType.baseType != BaseDataType::eUnknown && matrixType.baseType != BaseDataType::eUnknown)
{
Type resultType(vectorType.baseType, vectorType.componentCount, std::max(vectorType.arrayDepth, matrixType.arrayDepth), vectorType.role);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
}
}
}
| 5,308 | C++ | 38.325926 | 157 | 0.679352 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToLocation.cpp | // Copyright (c) 2021-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.
//
#include <OgnTranslateToLocationDatabase.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/math.h>
#include "PrimCommon.h"
#include "XformUtils.h"
using omni::math::linalg::vec3d;
using omni::math::linalg::GfLerp;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
struct TranslateMoveState : public XformUtils::MoveState
{
vec3d targetTranslate;
};
class OgnTranslateToLocation
{
TranslateMoveState m_moveState;
public:
static bool compute(OgnTranslateToLocationDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnTranslateToLocation>();
double& startTime = state.m_moveState.startTime;
vec3d& startTranslation = state.m_moveState.startTranslation;
vec3d& targetTranslation = state.m_moveState.targetTranslate;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
try
{
auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(),
inputs::usePath.token(), db.getInstanceIndex());
if (primPath.IsEmpty())
return true;
if (startTime <= kUninitializedStartTime || now < startTime)
{
// Set state variables
try
{
startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
startTime = now;
targetTranslation = db.inputs.target();
// This is the first entry, start sleeping
db.outputs.finished() = kExecutionAttributeStateLatentPush;
return true;
}
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
// delta step
float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp);
vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation);
// Write back to the prim
try
{
trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr, translation);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
if (alpha2 < 1)
{
// still waiting
db.outputs.finished() = kExecutionAttributeStateDisabled;
return true;
}
else
{
// Completed the maneuver
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
}
catch(const std::exception& e)
{
db.logError(e.what());
return true;
}
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
| 4,230 | C++ | 29.65942 | 127 | 0.582033 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToTarget.cpp | // Copyright (c) 2021-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.
//
#include <OgnTranslateToTargetDatabase.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/math.h>
#include <omni/math/linalg/SafeCast.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usdGeom/xformCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include "PrimCommon.h"
#include "XformUtils.h"
using namespace omni::math::linalg;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
class OgnTranslateToTarget
{
XformUtils::MoveState m_moveState;
public:
static bool compute(OgnTranslateToTargetDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnTranslateToTarget>();
double& startTime = state.m_moveState.startTime;
vec3d& startTranslation = state.m_moveState.startTranslation;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
try
{
auto sourcePrimPath =
getPrimOrPath(contextObj, nodeObj, inputs::sourcePrim.token(), inputs::sourcePrimPath.token(),
inputs::useSourcePath.token(), db.getInstanceIndex());
auto destPrimPath =
getPrimOrPath(contextObj, nodeObj, inputs::targetPrim.token(), inputs::targetPrimPath.token(),
inputs::useTargetPath.token(), db.getInstanceIndex());
if (sourcePrimPath.IsEmpty() || destPrimPath.IsEmpty())
return true;
// First frame of the maneuver.
if (startTime <= kUninitializedStartTime || now < startTime)
{
try
{
startTranslation =
tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
startTime = now;
// Start sleeping
db.outputs.finished() = kExecutionAttributeStateLatentPush;
return true;
}
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath);
pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath);
pxr::UsdGeomXformCache xformCache;
// Convert dest prim transform to the source's parent frame
matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim));
matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim));
matrix4d destLocalTransform = destWorldTransform / sourceParentTransform;
const vec3d& targetTranslation = destLocalTransform.ExtractTranslation();
// delta step
float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp);
vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation);
// Write back to the prim
try
{
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr, translation);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
if (alpha2 < 1)
{
// still waiting, output is disabled
db.outputs.finished() = kExecutionAttributeStateDisabled;
return true;
}
else
{
// Completed the maneuver
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
}
catch(const std::exception& e)
{
db.logError(e.what());
return true;
}
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
| 5,199 | C++ | 33.437086 | 118 | 0.604155 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToOrientation.cpp | // Copyright (c) 2021-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.
//
#include <OgnRotateToOrientationDatabase.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/matrix.h>
#include "PrimCommon.h"
#include "XformUtils.h"
using namespace omni::math::linalg;
namespace omni
{
namespace graph
{
namespace nodes
{
struct RotateMoveState: public XformUtils::MoveState
{
vec3d targetEuler;
};
class OgnRotateToOrientation
{
public:
RotateMoveState m_moveState;
static bool compute(OgnRotateToOrientationDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnRotateToOrientation>();
double& startTime = state.m_moveState.startTime;
pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName;
quatd& startOrientation = state.m_moveState.startOrientation;
vec3d& startEuler = state.m_moveState.startEuler;
vec3d& targetEuler = state.m_moveState.targetEuler;
XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = XformUtils::kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
try
{
auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(),
inputs::usePath.token(), db.getInstanceIndex());
if (primPath.IsEmpty())
return true;
// First frame of the maneuver.
if (startTime <= XformUtils::kUninitializedStartTime || now < startTime)
{
try
{
std::tie(startOrientation, targetAttribName) =
XformUtils::extractPrimOrientOp(contextObj, primPath);
if (not targetAttribName.IsEmpty())
rotationMode = XformUtils::RotationMode::eQuat;
else
{
std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, primPath);
if (not targetAttribName.IsEmpty())
rotationMode = XformUtils::RotationMode::eEuler;
}
if (targetAttribName.IsEmpty())
throw std::runtime_error(
formatString("Could not find suitable XformOp on %s, please add", primPath.GetText()));
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
// Copy the target in case it changes during the movement
targetEuler = db.inputs.target();
startTime = now;
// Start sleeping
db.outputs.finished() = kExecutionAttributeStateLatentPush;
return true;
}
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
// delta step
float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp);
try
{
if (rotationMode == XformUtils::RotationMode::eQuat)
{
quatd const& targetOrientation =
eulerAnglesToQuaternion(GfDegreesToRadians(targetEuler), EulerRotationOrder::XYZ);
auto const quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized();
// Write back to the prim
trySetPrimAttribute(
contextObj, nodeObj, primPath, targetAttribName.GetText(), quat);
}
else if (rotationMode == XformUtils::RotationMode::eEuler)
{
vec3d rot = lerp(startEuler, targetEuler, alpha2);
// Write back to the prim
trySetPrimAttribute(
contextObj, nodeObj, primPath, targetAttribName.GetText(), rot);
}
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
if (alpha2 < 1)
{
// still waiting, output is disabled
db.outputs.finished() = kExecutionAttributeStateDisabled;
return true;
}
else
{
// Completed the maneuver
startTime = XformUtils::kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
}
catch(const std::exception& e)
{
db.logError(e.what());
return true;
}
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
| 5,830 | C++ | 34.773006 | 118 | 0.559863 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTransform.cpp | // Copyright (c) 2021-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.
//
#include <OgnMoveToTransformDatabase.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/math.h>
#include <omni/math/linalg/SafeCast.h>
#include <cmath>
#include "PrimCommon.h"
#include "XformUtils.h"
using namespace omni::math::linalg;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
constexpr double kUninitializedStartTime = -1.;
}
struct MoveMoveState : public XformUtils::MoveState
{
matrix4d targetTransform;
};
class OgnMoveToTransform
{
public:
MoveMoveState m_moveState;
static bool compute(OgnMoveToTransformDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnMoveToTransform>();
double& startTime = state.m_moveState.startTime;
pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName;
quatd& startOrientation = state.m_moveState.startOrientation;
vec3d& startTranslation = state.m_moveState.startTranslation;
matrix4d& targetTransform = state.m_moveState.targetTransform;
vec3d& startScale = state.m_moveState.startScale;
XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
try
{
auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(),
inputs::usePath.token(), db.getInstanceIndex());
if (primPath.IsEmpty())
return true;
// First frame of the maneuver.
if (startTime <= kUninitializedStartTime || now < startTime)
{
try
{
std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, primPath);
if (targetAttribName.IsEmpty())
throw std::runtime_error("MoveToTransform requires the source Prim to have xformOp:orient, please add");
rotationMode = XformUtils::RotationMode::eQuat;
startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr);
startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
startTime = now;
targetTransform = db.inputs.target();
// Start sleeping
db.outputs.finished() = kExecutionAttributeStateLatentPush;
return true;
}
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
// delta step
float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp);
try
{
if (rotationMode == XformUtils::RotationMode::eQuat)
{
quatd targetOrientation = extractRotationQuatd(targetTransform).GetNormalized();
quatd quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized();
// Write back to the prim
trySetPrimAttribute(contextObj, nodeObj, primPath, targetAttribName.GetText(), quat);
}
vec3d targetTranslation = targetTransform.ExtractTranslation();
vec3d targetScale{ targetTransform.GetRow(0).GetLength(),
targetTransform.GetRow(1).GetLength(),
targetTransform.GetRow(2).GetLength() };
vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation);
vec3d scale = GfLerp(alpha2, startScale, targetScale);
// Write back to the prim
trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr, translation);
trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr, scale);
}
catch (std::runtime_error const& error)
{
db.logError(error.what());
return false;
}
if (alpha2 < 1)
{
// still waiting, output is disabled
db.outputs.finished() = kExecutionAttributeStateDisabled;
return true;
}
else
{
// Completed the maneuver
startTime = kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
}
catch(const std::exception& e)
{
db.logError(e.what());
return false;
}
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
| 6,047 | C++ | 35 | 128 | 0.593187 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Rotation.cpp | // Copyright (c) 2021-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.
//
#include <OgnSetMatrix4RotationDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <cmath>
using omni::math::linalg::matrix4d;
using omni::math::linalg::quatd;
using omni::math::linalg::vec3d;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
void updateMatrix(const double input[16], double result[16], vec3d axis, double angle)
{
matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result);
memcpy(resultMat.data(), input, sizeof(double) * 16);
axis.Normalize();
// 0.5 is because quaternions cover the space of rotations twice
angle = 0.5f * omni::math::linalg::GfDegreesToRadians(angle);
double c = std::cos(angle);
double s = std::sin(angle);
resultMat.SetRotateOnly(quatd(c, s * axis));
}
}
class OgnSetMatrix4Rotation
{
public:
static bool compute(OgnSetMatrix4RotationDatabase& db)
{
vec3d axis(0);
const auto& fixedRotationAxis = db.inputs.fixedRotationAxis();
if (fixedRotationAxis == db.tokens.X) { axis[0] = 1; }
else if (fixedRotationAxis == db.tokens.Z) { axis[2] = 1; }
else if (fixedRotationAxis == db.tokens.Y || fixedRotationAxis == omni::fabric::kUninitializedToken) { axis[1] = 1; }
else
{
db.logError("fixedRotationAxis must be one of X,Y,Z");
return false;
}
const auto& matrixInput = db.inputs.matrix();
const auto& rotationAngleInput = db.inputs.rotationAngle();
auto matrixOutput = db.outputs.matrix();
bool failed = true;
// Singular case
if (auto matrix = matrixInput.get<double[16]>())
{
if (auto rotationAngle = rotationAngleInput.get<double>())
{
if (auto output = matrixOutput.get<double[16]>())
{
updateMatrix(*matrix, *output, axis, *rotationAngle);
failed = false;
}
}
}
// Array case
else if (auto matrices = matrixInput.get<double[][16]>())
{
if (auto rotationAngles = rotationAngleInput.get<double[]>())
{
if (auto output = matrixOutput.get<double[][16]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
updateMatrix((*matrices)[i], (*output)[i], axis, (*rotationAngles)[i]);
}
failed = false;
}
}
}
else
{
db.logError("Input type for matrix input not supported");
return false;
}
if (failed)
{
db.logError("Input and output depths need to align: Matrix input with depth %s, rotation angles input with depth %s, and output with depth %s",
matrixInput.type().arrayDepth, rotationAngleInput.type().arrayDepth, matrixOutput.type().arrayDepth);
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node){
// Resolve fully-coupled types for the 2 attributes
std::array<AttributeObj, 2> attrs {
node.iNode->getAttribute(node, OgnSetMatrix4RotationAttributes::inputs::matrix.m_name),
node.iNode->getAttribute(node, OgnSetMatrix4RotationAttributes::outputs::matrix.m_name)
};
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
}
}
}
| 4,103 | C++ | 32.639344 | 156 | 0.595662 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimDirectionVector.cpp | // 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.
//
#include <OgnGetPrimDirectionVectorDatabase.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/SafeCast.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usdGeom/xformCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include "PrimCommon.h"
#include "XformUtils.h"
using namespace omni::math::linalg;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimDirectionVector
{
public:
static bool compute(OgnGetPrimDirectionVectorDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
try
{
// Retrieve the prim path string in one of two ways
bool usePath = db.inputs.usePath();
std::string primPathStr;
if (usePath)
{
// Use the absolute path
NameToken primPath = db.inputs.primPath();
primPathStr = db.tokenToString(primPath);
if (primPathStr.empty())
{
db.logWarning("No prim path specified");
return false;
}
}
else
{
// Read the path from the relationship input on this compute node
auto primPath = getRelationshipPrimPath(
contextObj, nodeObj, OgnGetPrimDirectionVectorAttributes::inputs::prim.m_token, db.getInstanceIndex());
primPathStr = primPath.GetText();
}
// Retrieve a reference to the prim
pxr::UsdPrim prim = getPrim(contextObj, pxr::SdfPath(primPathStr));
// Extract the rotation from the local to world transformation matrix
pxr::UsdGeomXformCache xformCache;
matrix4d localWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(prim));
quatd rotation = extractRotationQuatd(localWorldTransform).GetNormalized();
// Apply the rotation to (0,1,0) to get the up vector
vec3<double> upVector = rotation.Transform(vec3<double>::YAxis());
db.outputs.upVector() = upVector;
db.outputs.downVector() = -upVector;
// Apply the rotation to (0,0,-1) to get the forward vector
vec3<double> forwardVector = rotation.Transform(-vec3<double>::ZAxis());
db.outputs.forwardVector() = forwardVector;
db.outputs.backwardVector() = -forwardVector;
// Apply the rotation to (1,0,0) to get the right vector
vec3<double> rightVector = rotation.Transform(vec3<double>::XAxis());
db.outputs.rightVector() = rightVector;
db.outputs.leftVector() = -rightVector;
return true;
}
catch(const std::exception& e)
{
db.logError(e.what());
return false;
}
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 3,520 | C++ | 32.216981 | 123 | 0.617614 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Translation.cpp | // Copyright (c) 2021-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.
//
#include <OgnGetMatrix4TranslationDatabase.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/matrix.h>
using omni::math::linalg::matrix4d;
using omni::math::linalg::vec3d;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
void getTranslation(const double input[16], double result[4])
{
vec3d translation = reinterpret_cast<const matrix4d*>(input)->ExtractTranslation();
memcpy(result, translation.data(), sizeof(double) * 3);
}
}
class OgnGetMatrix4Translation
{
public:
static bool computeVectorized(OgnGetMatrix4TranslationDatabase& db, size_t count)
{
const auto& matrixInput = db.inputs.matrix();
bool inOk = false;
bool failed = true;
// Singular case
if (matrixInput.type().arrayDepth == 0)
{
if (auto matrix = matrixInput.get<double[16]>())
{
inOk = true;
auto translationOutput = db.outputs.translation();
if (auto output = translationOutput.get<double[3]>())
{
auto matrices = matrix.vectorized(count);
auto outputs = output.vectorized(count);
for (size_t i = 0; i < count; ++i)
getTranslation(matrices[i], outputs[i]);
failed = false;
}
}
}
// Array case
else
{
for (size_t inst = 0; inst < count; ++inst)
{
if (auto matrices = db.inputs.matrix(inst).get<double[][16]>())
{
inOk = true;
if (auto output = db.outputs.translation(inst).get<double[][3]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
getTranslation((*matrices)[i], (*output)[i]);
}
failed = false;
}
}
}
}
if (!inOk)
{
db.logError("Input type for matrix input not supported");
return false;
}
if (failed)
{
db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s",
matrixInput.type().arrayDepth, db.outputs.translation().type().arrayDepth);
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node) {
auto start = node.iNode->getAttribute(node, OgnGetMatrix4TranslationAttributes::inputs::matrix.m_name);
auto result = node.iNode->getAttribute(node, OgnGetMatrix4TranslationAttributes::outputs::translation.m_name);
auto startType = start.iAttribute->getResolvedType(start);
std::array<AttributeObj, 2> attrs { start, result };
std::array<uint8_t, 2> tupleCounts { 16, 3 };
std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth };
std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eVector };
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,907 | C++ | 32.689655 | 118 | 0.562836 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Rotation.cpp | // Copyright (c) 2021-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.
//
#include <OgnGetMatrix4RotationDatabase.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/base/gf/rotation.h>
#include <omni/graph/core/PostUsdInclude.h>
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
void getRotation(const double input[16], double result[3])
{
pxr::GfVec3d rotation = reinterpret_cast<const pxr::GfMatrix4d*>(input)->DecomposeRotation(pxr::GfVec3d::XAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::ZAxis());
memcpy(result, rotation.data(), sizeof(double) * 3);
}
}
class OgnGetMatrix4Rotation
{
public:
static bool compute(OgnGetMatrix4RotationDatabase& db)
{
const auto& matrixInput = db.inputs.matrix();
auto rotationOutput = db.outputs.rotation();
bool failed = true;
// Singular case
if (auto matrix = matrixInput.get<double[16]>())
{
if (auto output = rotationOutput.get<double[3]>())
{
getRotation(*matrix, *output);
failed = false;
}
}
// Array case
else if (auto matrices = matrixInput.get<double[][16]>())
{
if (auto output = rotationOutput.get<double[][3]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
getRotation((*matrices)[i], (*output)[i]);
}
failed = false;
}
}
else
{
db.logError("Input type for matrix input not supported");
return false;
}
if (failed)
{
db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s",
matrixInput.type().arrayDepth, rotationOutput.type().arrayDepth);
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node) {
auto start = node.iNode->getAttribute(node, OgnGetMatrix4RotationAttributes::inputs::matrix.m_name);
auto result = node.iNode->getAttribute(node, OgnGetMatrix4RotationAttributes::outputs::rotation.m_name);
auto startType = start.iAttribute->getResolvedType(start);
std::array<AttributeObj, 2> attrs { start, result };
std::array<uint8_t, 2> tupleCounts { 16, 3 };
std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth };
std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eVector };
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,276 | C++ | 32.438775 | 168 | 0.606227 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransform.cpp | // Copyright (c) 2021-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.
//
#include <OgnMakeTransformDatabase.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/matrix.h>
using omni::math::linalg::quatd;
using omni::math::linalg::matrix4d;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnMakeTransform
{
public:
static bool compute(OgnMakeTransformDatabase& db)
{
auto& translation = db.inputs.translation();
auto& orientation = db.inputs.rotationXYZ();
auto& scale = db.inputs.scale();
const quatd q = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(orientation), omni::math::linalg::EulerRotationOrder::XYZ).GetNormalized();
db.outputs.transform() = matrix4d().SetScale(scale) * matrix4d().SetRotate(q) * matrix4d().SetTranslate(translation);
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,264 | C++ | 27.749999 | 162 | 0.732595 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Quaternion.cpp | // Copyright (c) 2021-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.
//
#include <OgnGetMatrix4QuaternionDatabase.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/quat.h>
#include "XformUtils.h"
using omni::math::linalg::matrix4d;
using omni::math::linalg::quatd;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
void getQuaternion(const double input[16], double result[4])
{
quatd quat = extractRotationQuatd(*reinterpret_cast<const matrix4d*>(input));
// In fabric, quaternions are stored as (XYZW). Note the quatd constructor uses (WXYZ)s
memcpy(&result[0], quat.GetImaginary().data(), sizeof(double) * 3);
result[3] = quat.GetReal();
}
}
class OgnGetMatrix4Quaternion
{
public:
static bool compute(OgnGetMatrix4QuaternionDatabase& db)
{
const auto& matrixInput = db.inputs.matrix();
auto quaternionOutput = db.outputs.quaternion();
bool failed = true;
// Singular case
if (auto matrix = matrixInput.get<double[16]>())
{
if (auto output = quaternionOutput.get<double[4]>())
{
getQuaternion(*matrix, *output);
failed = false;
}
}
// Array case
else if (auto matrices = matrixInput.get<double[][16]>())
{
if (auto output = quaternionOutput.get<double[][4]>())
{
output->resize(matrices->size());
for (size_t i = 0; i < matrices.size(); i++)
{
getQuaternion((*matrices)[i], (*output)[i]);
}
failed = false;
}
}
else
{
db.logError("Input type for matrix input not supported");
return false;
}
if (failed)
{
db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s",
matrixInput.type().arrayDepth, quaternionOutput.type().arrayDepth);
return false;
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& node) {
auto start = node.iNode->getAttribute(node, OgnGetMatrix4QuaternionAttributes::inputs::matrix.m_name);
auto result = node.iNode->getAttribute(node, OgnGetMatrix4QuaternionAttributes::outputs::quaternion.m_name);
auto startType = start.iAttribute->getResolvedType(start);
std::array<AttributeObj, 2> attrs { start, result };
std::array<uint8_t, 2> tupleCounts { 16, 4 };
std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth };
std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eQuaternion };
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(),
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
};
REGISTER_OGN_NODE()
}
}
}
| 3,416 | C++ | 32.5 | 116 | 0.61007 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateVector.cpp | // Copyright (c) 2021-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.
//
#include <OgnRotateVectorDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/quat.h>
using omni::math::linalg::matrix4d;
using omni::math::linalg::matrix3d;
using omni::math::linalg::vec3;
using omni::math::linalg::quat;
using ogn::compute::tryComputeWithArrayBroadcasting;
namespace omni
{
namespace graph
{
namespace nodes
{
namespace
{
template<typename T>
bool tryComputeWithMatrix3(OgnRotateVectorDatabase& db)
{
auto functor = [&](auto& rotation, auto& vector, auto& result)
{
auto& matrix = *reinterpret_cast<const matrix3d*>(rotation);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<T>*>(result);
// left multiplication by row vector
resultVec = vec3<T>(sourceVec * matrix);
};
return tryComputeWithArrayBroadcasting<double[9], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor);
}
template<typename T>
bool tryComputeWithMatrix4(OgnRotateVectorDatabase& db)
{
auto functor = [&](auto& rotation, auto& vector, auto& result)
{
auto& matrix = *reinterpret_cast<const matrix4d*>(rotation);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<T>*>(result);
resultVec = vec3<T>(matrix.TransformDir(sourceVec));
};
return tryComputeWithArrayBroadcasting<double[16], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor);
}
template<typename T>
bool tryComputeWithQuat(OgnRotateVectorDatabase& db)
{
auto functor = [&](auto& rotation, auto& vector, auto& result)
{
auto& quaternion = *reinterpret_cast<const quat<T>*>(rotation);
auto& sourceVec = *reinterpret_cast<const vec3<T>*>(vector);
auto& resultVec = *reinterpret_cast<vec3<T>*>(result);
resultVec = quaternion.Transform(sourceVec);
};
return tryComputeWithArrayBroadcasting<T[4], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor);
}
template<typename T>
bool tryComputeWithEulerAngles(OgnRotateVectorDatabase& db)
{
auto functor = [&](auto& rotation, auto& vector, auto& result)
{
auto eulerAngles = vec3<double>(*reinterpret_cast<const vec3<T>*>(rotation));
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<T>*>(result);
auto quaternion = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(eulerAngles), omni::math::linalg::EulerRotationOrder::XYZ);
resultVec = vec3<T>(quaternion.Transform(sourceVec));
};
return tryComputeWithArrayBroadcasting<T[3], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor);
}
/* FIXME: GfHalf has no explicit conversion from double to half, so we need to convert to a float first */
template<>
bool tryComputeWithMatrix3<pxr::GfHalf>(OgnRotateVectorDatabase& db)
{
auto functor = [&](auto& rotation, auto& vector, auto& result)
{
auto& matrix = *reinterpret_cast<const matrix3d*>(rotation);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result);
// left multiplication by row vector
resultVec = vec3<pxr::GfHalf>(vec3<float>(sourceVec * matrix));
};
return tryComputeWithArrayBroadcasting<double[9], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor);
}
template<>
bool tryComputeWithMatrix4<pxr::GfHalf>(OgnRotateVectorDatabase& db)
{
auto functor = [&](auto& rotation, auto& vector, auto& result)
{
auto& matrix = *reinterpret_cast<const matrix4d*>(rotation);
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result);
resultVec = vec3<pxr::GfHalf>(vec3<float>(matrix.TransformDir(sourceVec)));
};
return tryComputeWithArrayBroadcasting<double[16], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor);
}
template<>
bool tryComputeWithEulerAngles<pxr::GfHalf>(OgnRotateVectorDatabase& db)
{
auto functor = [&](auto& rotation, auto& vector, auto& result)
{
auto eulerAngles = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(rotation));
auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector));
auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result);
auto quaternion = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(eulerAngles), omni::math::linalg::EulerRotationOrder::XYZ);
resultVec = vec3<pxr::GfHalf>(vec3<float>(quaternion.Transform(sourceVec)));
};
return tryComputeWithArrayBroadcasting<pxr::GfHalf[3], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor);
}
} // namespace
class OgnRotateVector
{
public:
static bool compute(OgnRotateVectorDatabase& db)
{
try
{
// matrix3
if (tryComputeWithMatrix3<double>(db)) return true;
else if (tryComputeWithMatrix3<float>(db)) return true;
else if (tryComputeWithMatrix3<pxr::GfHalf>(db)) return true;
// matrix4
else if (tryComputeWithMatrix4<double>(db)) return true;
else if (tryComputeWithMatrix4<float>(db)) return true;
else if (tryComputeWithMatrix4<pxr::GfHalf>(db)) return true;
// quat
else if (tryComputeWithQuat<double>(db)) return true;
else if (tryComputeWithQuat<float>(db)) return true;
else if (tryComputeWithQuat<pxr::GfHalf>(db)) return true;
// euler angles
else if (tryComputeWithEulerAngles<double>(db)) return true;
else if (tryComputeWithEulerAngles<float>(db)) return true;
else if (tryComputeWithEulerAngles<pxr::GfHalf>(db)) return true;
else
{
db.logWarning("OgnRotateVector: Failed to resolve input types");
}
}
catch (ogn::compute::InputError &error)
{
db.logWarning("OgnRotateVector: %s", error.what());
}
return false;
}
static void onConnectionTypeResolve(const NodeObj& node) {
auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token());
auto rotation = node.iNode->getAttributeByToken(node, inputs::rotation.token());
auto result = node.iNode->getAttributeByToken(node, outputs::result.token());
auto vectorType = vector.iAttribute->getResolvedType(vector);
auto rotationType = rotation.iAttribute->getResolvedType(rotation);
// Require vector, rotation to be resolved before determining result's type
if (vectorType.baseType != BaseDataType::eUnknown && rotationType.baseType != BaseDataType::eUnknown)
{
Type resultType(vectorType.baseType, vectorType.componentCount, std::max(vectorType.arrayDepth, rotationType.arrayDepth), vectorType.role);
result.iAttribute->setResolvedType(result, resultType);
}
}
};
REGISTER_OGN_NODE()
}
}
}
| 7,929 | C++ | 43.301676 | 163 | 0.679279 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTarget.cpp | // Copyright (c) 2021-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.
//
#include <OgnMoveToTargetDatabase.h>
#include <omni/math/linalg/quat.h>
#include <omni/math/linalg/vec.h>
#include <omni/math/linalg/matrix.h>
#include <omni/math/linalg/math.h>
#include <omni/math/linalg/SafeCast.h>
#include <cmath>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/usdGeom/xformCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include "PrimCommon.h"
#include "XformUtils.h"
using namespace omni::math::linalg;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnMoveToTarget
{
XformUtils::MoveState m_moveState;
public:
static bool compute(OgnMoveToTargetDatabase& db)
{
auto& nodeObj = db.abi_node();
const auto& contextObj = db.abi_context();
auto iContext = contextObj.iContext;
double now = iContext->getTimeSinceStart(contextObj);
auto& state = db.internalState<OgnMoveToTarget>();
double& startTime = state.m_moveState.startTime;
pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName;
vec3d& startTranslation = state.m_moveState.startTranslation;
quatd& startOrientation = state.m_moveState.startOrientation;
vec3d& startEuler = state.m_moveState.startEuler;
vec3d& startScale = state.m_moveState.startScale;
XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode;
if (db.inputs.stop() != kExecutionAttributeStateDisabled)
{
startTime = XformUtils::kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
try
{
auto sourcePrimPath =
getPrimOrPath(contextObj, nodeObj, inputs::sourcePrim.token(), inputs::sourcePrimPath.token(),
inputs::useSourcePath.token(), db.getInstanceIndex());
auto destPrimPath =
getPrimOrPath(contextObj, nodeObj, inputs::targetPrim.token(), inputs::targetPrimPath.token(),
inputs::useTargetPath.token(), db.getInstanceIndex());
if (sourcePrimPath.IsEmpty() || destPrimPath.IsEmpty())
return true;
pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath);
pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath);
pxr::UsdGeomXformCache xformCache;
if (not sourcePrim or not targetPrim)
{
throw std::runtime_error("Could not find source or target prim");
}
matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim));
matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim));
quatd destWorldOrient = extractRotationQuatd(destWorldTransform).GetNormalized();
quatd sourceParentWorldOrient = extractRotationQuatd(sourceParentTransform).GetNormalized();
bool hasRotations =
(destWorldOrient != quatd::GetIdentity()) or (sourceParentWorldOrient != quatd::GetIdentity());
// First frame of the maneuver.
if (startTime <= XformUtils::kUninitializedStartTime || now < startTime)
{
std::tie(startOrientation, targetAttribName) =
XformUtils::extractPrimOrientOp(contextObj, sourcePrimPath);
if (targetAttribName.IsEmpty())
{
if (hasRotations)
throw std::runtime_error("MoveToTarget requires the source Prim to have xformOp:orient"
" when the destination Prim or source Prim parent has rotation, please Add");
std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, sourcePrimPath);
if (not targetAttribName.IsEmpty())
rotationMode = XformUtils::RotationMode::eEuler;
}
else
rotationMode = XformUtils::RotationMode::eQuat;
if (targetAttribName.IsEmpty())
throw std::runtime_error(
formatString("Could not find suitable XformOp on %s, please add", sourcePrimPath.GetText()));
startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr);
startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::ScaleAttrStr);
startTime = now;
// Start sleeping
db.outputs.finished() = kExecutionAttributeStateLatentPush;
return true;
}
int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10);
float speed = std::max(0.f, float(db.inputs.speed()));
// delta step
float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f);
// Ease out by applying a shifted exponential to the alpha
float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp);
// Convert dest prim transform to the source's parent frame
matrix4d destLocalTransform = destWorldTransform / sourceParentTransform;
if (rotationMode == XformUtils::RotationMode::eQuat)
{
quatd targetOrientation = extractRotationQuatd(destLocalTransform).GetNormalized();
auto quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized();
// Write back to the prim
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), quat);
}
else if (rotationMode == XformUtils::RotationMode::eEuler)
{
// FIXME: We previously checked that there is no rotation on the target, so we just have to interpolate
// to identity.
vec3d const targetRot{};
auto rot = GfLerp(alpha2, startEuler, targetRot);
// Write back to the prim
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), rot);
}
vec3d targetTranslation = destLocalTransform.ExtractTranslation();
vec3d targetScale{destLocalTransform.GetRow(0).GetLength(),
destLocalTransform.GetRow(1).GetLength(),
destLocalTransform.GetRow(2).GetLength()};
vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation);
vec3d scale = GfLerp(alpha2, startScale, targetScale);
// Write back to the prim
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr, translation);
trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::ScaleAttrStr, scale);
if (alpha2 < 1)
{
// still waiting, output is disabled
db.outputs.finished() = kExecutionAttributeStateDisabled;
return true;
}
else
{
// Completed the maneuver
startTime = XformUtils::kUninitializedStartTime;
db.outputs.finished() = kExecutionAttributeStateLatentFinish;
return true;
}
}
catch(const std::exception& e)
{
db.logError(e.what());
return false;
}
}
};
REGISTER_OGN_NODE()
} // action
} // graph
} // omni
| 8,051 | C++ | 40.081632 | 129 | 0.623401 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimLocalToWorldTransform.cpp | // Copyright (c) 2021-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.
//
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usdGeom/xformCache.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/fabric/FabricUSD.h>
#include <OgnGetPrimLocalToWorldTransformDatabase.h>
#include <omni/math/linalg/SafeCast.h>
#include "PrimCommon.h"
using namespace omni::fabric;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrimLocalToWorldTransform
{
public:
static bool compute(OgnGetPrimLocalToWorldTransformDatabase& db)
{
// Get interfaces
auto& nodeObj = db.abi_node();
const IPath& iPath = *db.abi_context().iPath;
const IToken& iToken = *db.abi_context().iToken;
const INode& iNode = *nodeObj.iNode;
bool usePath = db.inputs.usePath();
long stageId = db.abi_context().iContext->getStageId(db.abi_context());
auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logWarning("Could not find USD stage %ld", stageId);
return true;
}
// Find the target prim path one of 2 ways
std::string destPrimPathStr;
if (usePath)
{
// Use the absolute path
NameToken primPath = db.inputs.primPath();
destPrimPathStr = db.tokenToString(primPath);
if (destPrimPathStr.empty())
{
db.logWarning("No target prim path specified");
return true;
}
}
else
{
// Read the path from the relationship input on this compute node
const char* thisPrimPathStr = iNode.getPrimPath(nodeObj);
// Find our stage
long stageId = db.abi_context().iContext->getStageId(db.abi_context());
auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logWarning("Could not find USD stage %ld", stageId);
return true;
}
// Find this prim
const pxr::UsdPrim thisPrim = stage->GetPrimAtPath(pxr::SdfPath(thisPrimPathStr));
if (!thisPrim.IsValid())
{
db.logError("GetPrimAttribute requires USD backing when 'usePath' is false.");
return false;
}
try
{
// Find the relationship
const pxr::SdfPath primPath = getRelationshipPrimPath(
db.abi_context(), nodeObj, OgnGetPrimLocalToWorldTransformAttributes::inputs::prim.m_token,
db.getInstanceIndex());
destPrimPathStr = primPath.GetString();
}
catch (const std::exception& e)
{
db.logError(e.what());
return false;
}
}
// Retrieve a reference to the prim
PathC destPath = iPath.getHandle(destPrimPathStr.c_str());
pxr::UsdPrim prim = stage->GetPrimAtPath(pxr::SdfPath(toSdfPath(destPath)));
if (!prim.IsValid())
{
return true;
}
pxr::UsdGeomXformCache xformCache;
pxr::GfMatrix4d usdTransform = xformCache.GetLocalToWorldTransform(prim);
db.outputs.localToWorldTransform() = omni::math::linalg::safeCastToOmni(usdTransform);
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 4,069 | C++ | 31.301587 | 111 | 0.608258 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransformLookAt.cpp | // Copyright (c) 2022-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.
//
#include <OgnMakeTransformLookAtDatabase.h>
#include <omni/math/linalg/matrix.h>
using omni::math::linalg::matrix4d;
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnMakeTransformLookAt
{
public:
static bool compute(OgnMakeTransformLookAtDatabase& db)
{
const auto& eyeInput = db.inputs.eye();
const auto& centerInput = db.inputs.center();
const auto& upInput = db.inputs.up();
matrix4d matrix;
matrix.SetLookAt(centerInput,eyeInput,upInput);
db.outputs.transform() = matrix;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,050 | C++ | 22.886363 | 77 | 0.721905 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnAnd.cpp | // 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.
//
#include <OgnAndDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include "OperatorComputeWrapper.h"
#include "ResolveBooleanOpAttributes.h"
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Boolean AND on two inputs.
* If a and b are arrays, AND operations will be performed pair-wise. Sizes of a and b must match.
* If only one input is an array, the other input will be broadcast to the size of the array.
* Returns an array of booleans if either input is an array, otherwise returning a boolean.
*
* @param db: database object
* @return True if we can get a result properly, false if not
*/
bool tryCompute(OgnAndDatabase& db)
{
auto const& dynamicInputs = db.getDynamicInputs();
if (dynamicInputs.empty())
{
auto functor = [](bool const& a, bool const& b, bool& result)
{
result = static_cast<bool>(a && b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor);
}
else
{
std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() };
inputs.reserve(dynamicInputs.size() + 2);
for (auto const& input : dynamicInputs)
inputs.emplace_back(input());
auto functor = [](bool const& a, bool& result)
{
result = static_cast<bool>(result && a);
};
return ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), functor);
}
}
} // namespace
class OgnAnd
{
public:
static bool compute(OgnAndDatabase& db)
{
return tryComputeOperator<OgnAndDatabase>(tryCompute, db);
}
static void onConnectionTypeResolve(const NodeObj& node)
{
resolveBooleanOpDynamicAttributes(node, outputs::result.token());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,438 | C++ | 30.675324 | 137 | 0.687449 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNot.cpp | // Copyright (c) 2019-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.
//
#include <OgnNotDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnNot
{
public:
static bool compute(OgnNotDatabase& db)
{
auto functor = [](bool const& valueIn, bool& valueOut)
{
valueOut = static_cast<bool>(!valueIn);
};
return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool>(db.inputs.valueIn(), db.outputs.valueOut(), functor);
}
static void onConnectionTypeResolve(const NodeObj& node)
{
auto valueIn = node.iNode->getAttributeByToken(node, inputs::valueIn.token());
auto valueOut = node.iNode->getAttributeByToken(node, outputs::valueOut.token());
auto valueInType = valueIn.iAttribute->getResolvedType(valueIn);
// Require inputs to be resolved before determining result type
if (valueInType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 2> attrs { valueIn, valueOut };
node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size());
}
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,580 | C++ | 28.277777 | 125 | 0.693038 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnXor.cpp | // 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.
//
#include <OgnXorDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include "ResolveBooleanOpAttributes.h"
#include "OperatorComputeWrapper.h"
namespace omni {
namespace graph {
namespace nodes {
// unnamed namespace to avoid multiple declaration when linking
namespace {
/**
* Boolean XOR on two inputs.
* If a and b are arrays, XOR operations will be performed pair-wise. Sizes of a and b must match.
* If only one input is an array, the other input will be broadcast to the size of the array.
* Returns an array of booleans if either input is an array, otherwise returning a boolean.
*
* @param db: database object
* @return True if we can get a result properly, false if not
*/
bool tryCompute(OgnXorDatabase& db)
{
auto functor = [](bool const& a, bool const& b, bool& result)
{
result = static_cast<bool>(a != b);
};
return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor);
}
} // namespace
class OgnXor
{
public:
static bool compute(OgnXorDatabase& db)
{
return tryComputeOperator<OgnXorDatabase>(tryCompute, db);
}
static void onConnectionTypeResolve(const NodeObj& node)
{
resolveBooleanOpAttributes(node,
inputs::a.token(),
inputs::b.token(),
outputs::result.token());
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,002 | C++ | 30.296875 | 133 | 0.686813 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/ResolveBooleanOpAttributes.cpp | // 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.
//
#include "ResolveBooleanOpAttributes.h"
#include <omni/graph/core/iComputeGraph.h>
#include <algorithm>
#include <array>
namespace omni
{
namespace graph
{
namespace nodes
{
void resolveBooleanOpAttributes(const core::NodeObj& node,
const core::NameToken aToken,
const core::NameToken bToken,
const core::NameToken resultToken)
{
auto a = node.iNode->getAttributeByToken(node, aToken);
auto b = node.iNode->getAttributeByToken(node, bToken);
auto result = node.iNode->getAttributeByToken(node, resultToken);
auto aType = a.iAttribute->getResolvedType(a);
auto bType = b.iAttribute->getResolvedType(b);
// Require inputs to be resolved before determining result type
if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown)
{
std::array<AttributeObj, 3> attrs { a, b, result };
std::array<uint8_t, 3> arrayDepths {
aType.arrayDepth,
bType.arrayDepth,
// Allow for a mix of singular and array inputs. If any input is an array, the output must be an array
std::max(aType.arrayDepth, bType.arrayDepth)
};
std::array<AttributeRole, 3> rolesBuf {
aType.role,
bType.role,
// Copy the attribute role from the resolved type to the output type
AttributeRole::eUnknown
};
node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), nullptr, // tupleCounts default to scalar
arrayDepths.data(), rolesBuf.data(), attrs.size());
}
}
void resolveBooleanOpDynamicAttributes(const core::NodeObj& node, const core::NameToken resultToken)
{
auto totalCount = node.iNode->getAttributeCount(node);
std::vector<AttributeObj> allAttributes(totalCount);
node.iNode->getAttributes(node, allAttributes.data(), totalCount);
std::vector<AttributeObj> attributes;
std::vector<uint8_t> arrayDepths;
std::vector<AttributeRole> roles;
attributes.reserve(totalCount - 2);
arrayDepths.reserve(totalCount - 2);
roles.reserve(totalCount - 2);
uint8_t maxArrayDepth = 0;
uint8_t maxComponentCount = 0;
for (auto const& attr : allAttributes)
{
if (attr.iAttribute->getPortType(attr) == AttributePortType::kAttributePortType_Input)
{
auto resolvedType = attr.iAttribute->getResolvedType(attr);
// all inputs must be connected and resolved to complete the output port type resolution
if (resolvedType.baseType == BaseDataType::eUnknown)
return;
arrayDepths.push_back(resolvedType.arrayDepth);
roles.push_back(resolvedType.role);
maxComponentCount = std::max(maxComponentCount, resolvedType.componentCount);
maxArrayDepth = std::max(maxArrayDepth, resolvedType.arrayDepth);
attributes.push_back(attr);
}
}
attributes.push_back(node.iNode->getAttributeByToken(node, resultToken));
// Allow for a mix of singular and array inputs. If any input is an array, the output must be an array
arrayDepths.push_back(maxArrayDepth);
// Copy the attribute role from the resolved type to the output type
roles.push_back(AttributeRole::eUnknown);
node.iNode->resolvePartiallyCoupledAttributes(
node, attributes.data(), nullptr, // tupleCounts default to scalar
arrayDepths.data(), roles.data(), attributes.size());
}
}
}
}
| 4,020 | C++ | 37.295238 | 115 | 0.670647 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OperatorComputeWrapper.h | // 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.
//
#pragma once
#include <carb/logging/Log.h>
namespace omni
{
namespace graph
{
namespace nodes
{
template <typename T, typename F>
static bool tryComputeOperator(F&& f, T t)
{
try
{
return f(t);
}
catch (std::exception &error)
{
t.logError("Could not perform function: %s", error.what());
}
return false;
}
}
}
}
| 794 | C | 21.083333 | 77 | 0.709068 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/ResolveBooleanOpAttributes.h | // 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.
//
#pragma once
#include "omni/graph/core/Handle.h"
namespace omni {
namespace graph {
namespace core {
struct NodeObj;
}
namespace nodes {
extern void resolveBooleanOpAttributes(const core::NodeObj&,
const core::NameToken aToken,
const core::NameToken bToken,
const core::NameToken resultToken);
extern void resolveBooleanOpDynamicAttributes(const core::NodeObj& node, const core::NameToken resultToken);
} // namespace nodes
} // namespace graph
} // namespace omni
| 1,024 | C | 31.031249 | 108 | 0.695312 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnBooleanExpr.py | """
NOTE: DEPRECATED AS OF 1.26.0 IN FAVOUR OF INDIVIDAL BOOLEAN OP NODES
This is the implementation of the OGN node defined in OgnBooleanExpr.ogn
"""
class OgnBooleanExpr:
"""
Boolean AND of two inputs
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
# convert to numpy bool arrays
a = db.inputs.a
b = db.inputs.b
op = db.inputs.operator.lower()
if not op:
return False
if op == "and":
result = a and b
elif op == "or":
result = a or b
elif op == "nand":
result = not (a and b)
elif op == "nor":
result = not (a or b)
elif op in ["xor", "!="]:
result = a != b
elif op in ["xnor", "=="]:
result = a == b
else:
return False
db.outputs.result = result
return True
| 947 | Python | 22.699999 | 72 | 0.498416 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnAttrType.cpp | // 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.
//
#include "OgnAttrTypeDatabase.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnAttrType
{
public:
// Queries information about the type of a specified attribute in an input prim
static bool compute(OgnAttrTypeDatabase& db)
{
auto bundledAttribute = db.inputs.data().attributeByName(db.inputs.attrName());
if (!bundledAttribute.isValid())
{
db.outputs.baseType() = -1;
db.outputs.componentCount() = -1;
db.outputs.arrayDepth() = -1;
db.outputs.role() = -1;
db.outputs.fullType() = -1;
}
else
{
auto& attributeType = bundledAttribute.type();
db.outputs.baseType() = int(attributeType.baseType);
db.outputs.componentCount() = attributeType.componentCount;
db.outputs.arrayDepth() = attributeType.arrayDepth;
db.outputs.role() = int(attributeType.role);
db.outputs.fullType() = int(omni::fabric::TypeC(attributeType).type);
}
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 1,532 | C++ | 29.058823 | 87 | 0.6547 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractAttr.cpp | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "OgnExtractAttrDatabase.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnExtractAttr
{
public:
// Copies a single attribute from an input prim to an output attribute directly on the node,
// if it exists in the input prim and matches the type of the output attribute.
static bool compute(OgnExtractAttrDatabase& db)
{
const auto& inputToken = db.inputs.attrName();
auto extractedBundledAttribute = db.inputs.data().attributeByName(inputToken);
if (!extractedBundledAttribute.isValid())
{
db.logWarning("No attribute matching '%s' was found in the input bundle", db.tokenToString(inputToken));
return false;
}
const Type& inputType = extractedBundledAttribute.type();
auto& outputAttribute = db.outputs.output();
// This compute is not creating the attribute data, that should have been done externally.
// The attribute type should match the one extracted though, otherwise connections can go astray.
if (!outputAttribute.resolved())
{
// Not resolved, so we have to resolve it now. This node is unusual in that the resolved output type
// depends on run-time state of the bundle.
AttributeObj out = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::output.m_token);
out.iAttribute->setResolvedType(out, inputType);
outputAttribute.reset(
db.abi_context(), out.iAttribute->getAttributeDataHandle(out, db.getInstanceIndex()), out);
}
else
{
Type outType = outputAttribute.type();
if (!inputType.compatibleRawData(outType))
{
db.logWarning("Attribute '%s' of type %s in the input bundle is not compatible with type %s",
db.tokenToString(inputToken), getOgnTypeName(inputType).c_str(),
getOgnTypeName(outType).c_str());
return false;
}
}
outputAttribute.copyData( extractedBundledAttribute );
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 2,613 | C++ | 38.60606 | 116 | 0.657865 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnIsPrimActive.cpp | // 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.
#include "OgnIsPrimActiveDatabase.h"
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
#include <omni/fabric/FabricUSD.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnIsPrimActive
{
public:
// ----------------------------------------------------------------------------
static bool compute(OgnIsPrimActiveDatabase& db)
{
// At some point, only target input types will be supported, so at the time that the path input is deprecated,
// also rename "primTarget" to "prim"
auto const& primPath = db.inputs.prim();
auto const& prim = db.inputs.primTarget();
if(prim.size() > 0 || pxr::SdfPath::IsValidPathString(primPath))
{
// Find our stage
const GraphContextObj& context = db.abi_context();
long stageId = context.iContext->getStageId(context);
auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
if (!stage)
{
db.logError("Could not find USD stage %ld", stageId);
return false;
}
pxr::UsdPrim targetPrim = stage->GetPrimAtPath(prim.size() == 0 ? pxr::SdfPath(primPath)
: omni::fabric::toSdfPath(prim[0]));
if (!targetPrim)
{
// Should this really be an error?? When prim path input is removed, might be worth changing this to
// just a warning instead
db.logError("Could not find prim \"%s\" in USD stage", prim.size() == 0 ? primPath.data() : db.pathToString(prim[0]));
db.outputs.active() = false;
return false;
}
db.outputs.active() = targetPrim.IsActive();
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 2,546 | C++ | 34.873239 | 134 | 0.598193 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWriteSetting.cpp | // Copyright (c) 2022-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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "PrimCommon.h"
#include <OgnWriteSettingDatabase.h>
#include <carb/settings/ISettings.h>
#include <carb/settings/SettingsUtils.h>
#include <carb/dictionary/IDictionary.h>
using carb::dictionary::ItemType;
namespace omni
{
namespace graph
{
namespace nodes
{
// unnamed namespace to avoid multiple declaration when linking
namespace
{
bool isValidInput(OgnWriteSettingDatabase& db) {
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = db.inputs.settingPath();
char const* settingPath = strSettingPath.c_str();
Type valueType = db.inputs.value().type();
ItemType pathType;
if (settings->isAccessibleAsArray(settingPath))
pathType = settings->getPreferredArrayType(settingPath);
else
pathType = settings->getItemType(settingPath);
if (pathType == ItemType::eCount)
return true;
if (pathType == ItemType::eDictionary)
return false;
if (pathType == ItemType::eBool && valueType.baseType != BaseDataType::eBool)
return false;
if (pathType == ItemType::eInt && valueType.baseType != BaseDataType::eInt && valueType.baseType != BaseDataType::eInt64)
return false;
if (pathType == ItemType::eFloat && valueType.baseType != BaseDataType::eFloat && valueType.baseType != BaseDataType::eDouble)
return false;
if (pathType == ItemType::eString && valueType.baseType != BaseDataType::eToken)
return false;
size_t arrayLen = settings->getArrayLength(settingPath);
if (valueType.componentCount > 1 && valueType.arrayDepth == 0)
return arrayLen == valueType.componentCount;
else if (valueType.componentCount == 1 && valueType.arrayDepth == 0)
return arrayLen == 0;
else if (valueType.componentCount == 1 && valueType.arrayDepth == 1)
return true;
else
return false;
}
template<typename T>
void setSetting(OgnWriteSettingDatabase& db)
{
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = db.inputs.settingPath();
char const* settingPath = strSettingPath.c_str();
auto const inputValue = db.inputs.value().template get<T>();
settings->set(settingPath, *inputValue);
}
template<typename T>
void setSettingArray(OgnWriteSettingDatabase& db)
{
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = db.inputs.settingPath();
char const* settingPath = strSettingPath.c_str();
auto const inputValue = db.inputs.value().template get<T[]>();
size_t arrayLen = (size_t)settings->getArrayLength(settingPath);
settings->setArray(settingPath, inputValue->data(), arrayLen);
}
template<typename T, size_t N>
void setSettingArray(OgnWriteSettingDatabase& db)
{
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = db.inputs.settingPath();
char const* settingPath = strSettingPath.c_str();
auto const inputValue = db.inputs.value().template get<T[N]>();
settings->setArray(settingPath, *inputValue, N);
}
} // namespace
class OgnWriteSetting
{
public:
static bool compute(OgnWriteSettingDatabase& db)
{
auto const valueType = db.inputs.value().type();
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
std::string strSettingPath = db.inputs.settingPath();
char const* settingPath = strSettingPath.c_str();
if (!isValidInput(db)) {
std::stringstream ss;
ss << valueType;
db.logError("Setting Path '%s' is not compatible with type '%s'", settingPath, ss.str());
return false;
}
switch (valueType.baseType)
{
case BaseDataType::eBool:
switch (valueType.arrayDepth)
{
case 0:
setSetting<bool>(db);
break;
case 1:
setSettingArray<bool>(db);
break;
}
break;
case BaseDataType::eInt:
switch (valueType.componentCount)
{
case 1:
switch (valueType.arrayDepth)
{
case 0:
setSetting<int32_t>(db);
break;
case 1:
setSettingArray<int32_t>(db);
break;
}
break;
case 2:
setSettingArray<int32_t, 2>(db);
break;
case 3:
setSettingArray<int32_t, 3>(db);
break;
case 4:
setSettingArray<int32_t, 4>(db);
break;
}
break;
case BaseDataType::eInt64:
switch (valueType.arrayDepth)
{
case 0:
setSetting<int64_t>(db);
break;
case 1:
setSettingArray<int64_t>(db);
break;
}
break;
case BaseDataType::eFloat:
switch (valueType.componentCount)
{
case 1:
switch (valueType.arrayDepth)
{
case 0:
setSetting<float>(db);
break;
case 1:
setSettingArray<float>(db);
break;
}
break;
case 2:
setSettingArray<float, 2>(db);
break;
case 3:
setSettingArray<float, 3>(db);
break;
case 4:
setSettingArray<float, 4>(db);
break;
}
break;
case BaseDataType::eDouble:
switch (valueType.componentCount)
{
case 1:
switch (valueType.arrayDepth)
{
case 0:
setSetting<double>(db);
break;
case 1:
setSettingArray<double>(db);
break;
}
break;
case 2:
setSettingArray<double, 2>(db);
break;
case 3:
setSettingArray<double, 3>(db);
break;
case 4:
setSettingArray<double, 4>(db);
break;
}
break;
case BaseDataType::eToken:
switch (valueType.arrayDepth)
{
case 0:
{
auto const inputValue = db.inputs.value().template get<OgnToken>();
char const* inputString = db.tokenToString(*inputValue);
settings->set(settingPath, inputString);
break;
}
case 1:
{
auto const inputValue = db.inputs.value().template get<OgnToken[]>();
std::vector<char const*> inputString(inputValue.size());
for (size_t i = 0; i < inputValue.size(); i++)
inputString[i] = db.tokenToString((*inputValue)[i]);
size_t arrayLen = settings->getArrayLength(settingPath);
settings->setArray(settingPath, inputString.data(), arrayLen);
break;
}
}
break;
default:
{
db.logError("Type %s not supported", getOgnTypeName(valueType).c_str());
return false;
}
}
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace nodes
} // namespace graph
} // namespace omni
| 8,397 | C++ | 30.931559 | 130 | 0.558176 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadTime.cpp | // Copyright (c) 2021-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.
//
#include <OgnReadTimeDatabase.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnReadTime
{
public:
static bool compute(OgnReadTimeDatabase& db)
{
const auto& contextObj = db.abi_context();
const IGraphContext* const iContext = contextObj.iContext;
db.outputs.deltaSeconds() = iContext->getElapsedTime(contextObj);
db.outputs.isPlaying() = iContext->getIsPlaying(contextObj);
db.outputs.time() = iContext->getTime(contextObj);
db.outputs.frame() = iContext->getFrame(contextObj);
db.outputs.timeSinceStart() = iContext->getTimeSinceStart(contextObj);
db.outputs.absoluteSimTime() = iContext->getAbsoluteSimTime(contextObj);
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 1,239 | C++ | 27.837209 | 80 | 0.72155 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnHasAttr.cpp | // 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.
//
#include "OgnHasAttrDatabase.h"
namespace omni
{
namespace graph
{
namespace core
{
class OgnHasAttr
{
public:
// Checks whether an input prim contains the specified attribute
static bool compute(OgnHasAttrDatabase& db)
{
db.outputs.output() = db.inputs.data().attributeByName(db.inputs.attrName()).isValid();
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
| 825 | C++ | 23.294117 | 95 | 0.74303 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractBundle.cpp | // Copyright (c) 2020-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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "OgnExtractBundleDatabase.h"
#include "ReadPrimCommon.h"
#include <omni/fabric/FabricUSD.h>
#include <omni/kit/commands/ICommandBridge.h>
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnExtractBundle
{
private:
std::unordered_set<NameToken> m_added;
public:
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
// When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected.
AttributeObj inputBundleAttribObj =
nodeObj.iNode->getAttributeByToken(nodeObj, OgnExtractBundleAttributes::inputs::bundle.m_token);
inputBundleAttribObj.iAttribute->registerValueChangedCallback(
inputBundleAttribObj, onInputBundleValueChanged, true);
}
static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData)
{
NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj);
GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj);
// If the graph is currently disabled then delay the update until the next compute.
// Arguably this should be done at the message propagation layer, then this wouldn't be necessary.
if (graphObj.iGraph->isDisabled(graphObj))
{
return;
}
GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj);
cleanOutput(context, nodeObj, kAccordingToContextIndex);
}
static void cleanOutput(GraphContextObj const& contextObj, NodeObj const& nodeObj, InstanceIndex instanceIdx)
{
// clear the output bundles
auto outputTokens = { OgnExtractBundleAttributes::outputs::passThrough.m_token };
for (auto& outputToken : outputTokens)
{
BundleHandle outBundle =
contextObj.iContext->getOutputBundle(contextObj, nodeObj.nodeContextHandle, outputToken, instanceIdx);
contextObj.iContext->clearBundleContents(contextObj, outBundle);
}
// remove dynamic attributes
BundleType empty;
updateAttributes(contextObj, nodeObj, empty, instanceIdx);
}
static void updateAttributes(GraphContextObj const& contextObj,
NodeObj const& nodeObj,
BundleType const& bundle,
InstanceIndex instIdx)
{
OgnExtractBundle& state = OgnExtractBundleDatabase::sInternalState<OgnExtractBundle>(nodeObj);
omni::kit::commands::ICommandBridge::ScopedUndoGroup scopedUndoGroup;
extractBundle_reflectBundleDynamicAttributes(nodeObj, contextObj, bundle, state.m_added, instIdx);
}
// Copies attributes from an input bundle to attributes directly on the node
static bool compute(OgnExtractBundleDatabase& db)
{
auto& contextObj = db.abi_context();
auto& nodeObj = db.abi_node();
auto const& inputBundle = db.inputs.bundle();
if (!inputBundle.isValid())
{
cleanOutput(contextObj, nodeObj, db.getInstanceIndex());
return false;
}
// extract attributes directly from input bundle
updateAttributes(contextObj, nodeObj, inputBundle, db.getInstanceIndex());
db.outputs.passThrough() = inputBundle;
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 3,936 | C++ | 34.790909 | 118 | 0.692581 |
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetPrims.cpp | // 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.
//
#include "OgnGetPrimsDatabase.h"
#include "PrimCommon.h"
namespace omni
{
namespace graph
{
namespace nodes
{
class OgnGetPrims
{
public:
static bool compute(OgnGetPrimsDatabase& db)
{
IBundle2* outputBundle = db.outputs.bundle().abi_bundleInterface();
outputBundle->clearContents(true);
IConstBundle2* inputBundle = db.inputs.bundle().abi_bundleInterface();
size_t const childBundleCount = inputBundle->getChildBundleCount();
// nothing to do
if (childBundleCount == 0)
{
return true;
}
std::vector<ConstBundleHandle> childBundleHandles(childBundleCount);
inputBundle->getConstChildBundles(childBundleHandles.data(), childBundleHandles.size());
std::vector<ConstBundleHandle> bundles;
bundles.reserve(childBundleCount);
GraphContextObj const& context = db.abi_context();
if (db.inputs.prims().size() != 0)
{
// We want to have same order of `prims` input in the output.
// Unfortunately, the order of child bundles is not preserved, OM-
// Construct children lookup map
std::unordered_map<fabric::TokenC, ConstBundleHandle> pathToChildMap;
for (ConstBundleHandle const& childBundleHandle : childBundleHandles)
{
ConstAttributeDataHandle const attr =
getAttributeR(context, childBundleHandle, PrimAdditionalAttrs::kSourcePrimPathToken);
if (fabric::Token const* data = getDataR<fabric::Token>(context, attr))
{
pathToChildMap.emplace(data->asTokenC(), childBundleHandle);
}
}
// Search for inputTargets
auto const& inputPrims = db.inputs.prims();
for (auto const& inputTarget : inputPrims)
{
auto const asToken = fabric::asInt(fabric::toSdfPath(inputTarget).GetToken());
if(auto it = pathToChildMap.find(asToken); it != pathToChildMap.end())
{
bundles.push_back(it->second);
}
}
}
else
{
// By default all primitives matching the path/type patterns are added to the output bundle;
// when the "inverse" option is on, all mismatching primitives will be added instead.
bool const inverse = db.inputs.inverse();
// Use wildcard pattern matching for prim type.
std::string const typePattern(db.inputs.typePattern());
PatternMatcher const typeMatcher(typePattern);
// Use wildcard pattern matching for prim path.
std::string const pathPattern(db.inputs.pathPattern());
PatternMatcher const pathMatcher(pathPattern);
auto matchesPattern =
[&context](ConstBundleHandle& bundle, NameToken attrName, PatternMatcher const& patternMatcher)
{
ConstAttributeDataHandle attr = getAttributeR(context, bundle, attrName);
return attr.isValid() && patternMatcher.matches(*getDataR<NameToken>(context, attr));
};
for (ConstBundleHandle& childBundleHandle : childBundleHandles)
{
bool const matched =
matchesPattern(childBundleHandle, PrimAdditionalAttrs::kSourcePrimTypeToken, typeMatcher) &&
matchesPattern(childBundleHandle, PrimAdditionalAttrs::kSourcePrimPathToken, pathMatcher);
if (matched != inverse)
{
bundles.push_back(childBundleHandle);
}
}
}
if (!bundles.empty())
{
outputBundle->copyChildBundles(bundles.data(), bundles.size());
}
return true;
}
};
REGISTER_OGN_NODE()
} // nodes
} // graph
} // omni
| 4,352 | C++ | 35.579832 | 112 | 0.616728 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.