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.tutorials/ogn/docs/OgnTutorialComplexDataPy.rst | .. _omni_graph_tutorials_ComplexDataPy_1:
.. _omni_graph_tutorials_ComplexDataPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: Attributes With Arrays of Tuples
:keywords: lang-en omnigraph node tutorials tutorials complex-data-py
Tutorial Python Node: Attributes With Arrays of Tuples
======================================================
.. <description>
This is a tutorial node written in Python. It will compute the point3f array by multiplying each element of the float array by the three element vector in the multiplier.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a_inputArray", "``float[]``", "Input array", "[]"
"inputs:a_vectorMultiplier", "``float[3]``", "Vector multiplier", "[1.0, 2.0, 3.0]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:a_productArray", "``pointf[3][]``", "Output array", "[]"
"outputs:a_tokenArray", "``token[]``", "String representations of the input array", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.ComplexDataPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.ComplexDataPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: Attributes With Arrays of Tuples"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialComplexDataPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,073 | reStructuredText | 28.211267 | 170 | 0.591413 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialBundles.rst | .. _omni_graph_tutorials_BundleManipulation_1:
.. _omni_graph_tutorials_BundleManipulation:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Bundle Manipulation
:keywords: lang-en omnigraph node tutorials tutorials bundle-manipulation
Tutorial Node: Bundle Manipulation
==================================
.. <description>
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Filtered Bundle (*inputs:filteredBundle*)", "``bundle``", "Bundle whose contents are filtered before being added to the output", "None"
"inputs:filters", "``token[]``", "List of filter names to be applied to the filteredBundle. Any filter name appearing in this list will be applied to members of that bundle and only those passing all filters will be added to the output bundle. Legal filter values are 'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), and 'int' (attributes whose base type is integer).", "[]"
"Full Bundle (*inputs:fullBundle*)", "``bundle``", "Bundle whose contents are passed to the output in their entirety", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:combinedBundle", "``bundle``", "This is the union of fullBundle and filtered members of the filteredBundle.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.BundleManipulation"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.BundleManipulation.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Bundle Manipulation"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialBundlesDatabase"
"Python Module", "omni.graph.tutorials"
| 2,437 | reStructuredText | 33.338028 | 410 | 0.632335 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialTupleArrays.rst | .. _omni_graph_tutorials_TupleArrays_1:
.. _omni_graph_tutorials_TupleArrays:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Attributes With Arrays of Tuples
:keywords: lang-en omnigraph node tutorials threadsafe tutorials tuple-arrays
Tutorial Node: Attributes With Arrays of Tuples
===============================================
.. <description>
This is a tutorial node. It will compute the float array 'result' as the elementwise dot product of the input arrays 'a' and 'b'.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a", "``float[3][]``", "First array", "[]"
"inputs:b", "``float[3][]``", "Second array", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:result", "``float[]``", "Dot-product array", "[]"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.TupleArrays"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.TupleArrays.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Attributes With Arrays of Tuples"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialTupleArraysDatabase"
"Python Module", "omni.graph.tutorials"
| 1,857 | reStructuredText | 25.542857 | 130 | 0.568659 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialArrayData.rst | .. _omni_graph_tutorials_ArrayData_1:
.. _omni_graph_tutorials_ArrayData:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: Array Attributes
:keywords: lang-en omnigraph node tutorials threadsafe tutorials array-data
Tutorial Node: Array Attributes
===============================
.. <description>
This is a tutorial node. It will compute the array 'result' as the input array 'original' with every element multiplied by the constant 'multiplier'.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:gates", "``bool[]``", "Boolean mask telling which elements of the array should be multiplied", "[]"
"inputs:info", "``token[]``", "List of strings providing commentary", "['There', 'is', 'no', 'data']"
"inputs:multiplier", "``float``", "Multiplier of the array elements", "1.0"
"inputs:original", "``float[]``", "Array to be multiplied", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:infoSize", "``int``", "Number of letters in all strings in the info input", "None"
"outputs:negativeValues", "``bool[]``", "Array of booleans set to true if the corresponding 'result' is negative", "None"
"outputs:result", "``float[]``", "Multiplied array", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.ArrayData"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.ArrayData.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: Array Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialArrayDataDatabase"
"Python Module", "omni.graph.tutorials"
| 2,282 | reStructuredText | 29.851351 | 150 | 0.593777 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialCpuGpuBundles.rst | .. _omni_graph_tutorials_CpuGpuBundles_1:
.. _omni_graph_tutorials_CpuGpuBundles:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: CPU/GPU Bundles
:keywords: lang-en omnigraph node tutorials tutorials cpu-gpu-bundles
Tutorial Node: CPU/GPU Bundles
==============================
.. <description>
This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found, computes their dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This node is identical to OgnTutorialCpuGpuBundlesPy.ogn, except it is implemented in C++.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"CPU Input Bundle (*inputs:cpuBundle*)", "``bundle``", "Input bundle whose data always lives on the CPU", "None"
"Results To GPU (*inputs:gpu*)", "``bool``", "If true then copy gpuBundle onto the output, otherwise copy cpuBundle", "False"
"GPU Input Bundle (*inputs:gpuBundle*)", "``bundle``", "Input bundle whose data always lives on the GPU", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Constructed Bundle (*outputs:cpuGpuBundle*)", "``bundle``", "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this bundle's contents will be entirely on the GPU, otherwise they will be on the CPU.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.CpuGpuBundles"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.CpuGpuBundles.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"tags", "tutorial,bundle,gpu"
"uiName", "Tutorial Node: CPU/GPU Bundles"
"__tokens", "[""points"", ""dotProducts""]"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialCpuGpuBundlesDatabase"
"Python Module", "omni.graph.tutorials"
| 2,762 | reStructuredText | 36.849315 | 581 | 0.64084 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialABI.rst | .. _omni_graph_tutorials_Abi_1:
.. _omni_graph_tutorials_Abi:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: ABI Overrides
:keywords: lang-en omnigraph node tutorials,tutorial:abi tutorials abi
Tutorial Node: ABI Overrides
============================
.. <description>
This tutorial node shows how to override ABI methods on your node.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:namespace:a_bool", "``bool``", "The input is any boolean value", "True"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:namespace:a_bool", "``bool``", "The output is computed as the negation of the input", "True"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.Abi"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.Abi.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "python"
"uiName", "Tutorial Node: ABI Overrides"
"Categories", "tutorials,tutorial:abi"
"__categoryDescriptions", "tutorial:abi,Tutorial nodes that override the ABI functions"
"Generated Class Name", "OgnTutorialABIDatabase"
"Python Module", "omni.graph.tutorials"
| 1,795 | reStructuredText | 24.657143 | 105 | 0.582173 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialEmpty.rst | .. _omni_graph_tutorials_Empty_1:
.. _omni_graph_tutorials_Empty:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Node: No Attributes
:keywords: lang-en omnigraph node tutorials threadsafe tutorials empty
Tutorial Node: No Attributes
============================
.. <description>
This is a tutorial node. It does absolutely nothing and is only meant to serve as an example to use for setting up your build.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.Empty"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.Empty.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Node: No Attributes"
"Categories", "tutorials"
"Generated Class Name", "OgnTutorialEmptyDatabase"
"Python Module", "omni.graph.tutorials"
| 1,341 | reStructuredText | 25.313725 | 127 | 0.577927 |
omniverse-code/kit/exts/omni.graph.tutorials/ogn/docs/OgnTutorialABIPy.rst | .. _omni_graph_tutorials_AbiPy_1:
.. _omni_graph_tutorials_AbiPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Tutorial Python Node: ABI Overrides
:keywords: lang-en omnigraph node tutorials,tutorial:abiPy tutorials abi-py
Tutorial Python Node: ABI Overrides
===================================
.. <description>
This tutorial node shows how to override ABI methods on your Python node. The algorithm of the node converts an RGB color into HSV components.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.tutorials<ext_omni_graph_tutorials>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Color To Convert (*inputs:color*)", "``colord[3]``", "The color to be converted", "[0.0, 0.0, 0.0]"
"", "*multipleValues*", "value1,value2,value3", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:h", "``double``", "The hue component of the input color", "None"
"outputs:s", "``double``", "The saturation component of the input color", "None"
"outputs:v", "``double``", "The value component of the input color", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.tutorials.AbiPy"
"Version", "1"
"Extension", "omni.graph.tutorials"
"Icon", "ogn/icons/omni.graph.tutorials.AbiPy.svg"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Tutorial Python Node: ABI Overrides"
"Categories", "tutorials,tutorial:abiPy"
"__categoryDescriptions", "tutorial:abiPy,Tutorial nodes that override the Python ABI functions"
"Generated Class Name", "OgnTutorialABIPyDatabase"
"Python Module", "omni.graph.tutorials"
| 2,139 | reStructuredText | 28.315068 | 142 | 0.59467 |
omniverse-code/kit/exts/omni.graph.tutorials/config/extension.toml | [package]
title = "OmniGraph Tutorials"
version = "1.3.3"
category = "Graph"
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
description = "Contains a collection of tutorials on constructing OmniGraph nodes."
repository = ""
keywords = ["kit", "omnigraph", "core", "tutorials"]
# Main Python module, available as "import omni.graph.tutorials"
[[python.module]]
name = "omni.graph.tutorials"
# Watch the .ogn files for hot reloading (only works for Python files)
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Other extensions on which this one relies
[dependencies]
"omni.graph" = {}
"omni.graph.nodes" = {}
"omni.graph.tools" = {}
"omni.kit.test" = {}
"omni.kit.stage_templates" = {}
"omni.usd" = {}
"omni.kit.pipapi" = {}
[python.pipapi]
requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
[[test]]
timeout = 300
stdoutFailPatterns.exclude = [
# Exclude carb.events leak that only shows up locally
"*[Error] [carb.events.plugin]*PooledAllocator*",
]
pythonTests.unreliable = [
"*test_bundle_gpu_py", # OM-50554
"*test_setting_in_ogn_python_api", # OM-55532
]
[documentation]
deps = [
["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph refs until that workflow is moved
]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 1,400 | TOML | 24.017857 | 108 | 0.68 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundlesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleManipulation
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents.
"""
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 OgnTutorialBundlesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleManipulation
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.filteredBundle
inputs.filters
inputs.fullBundle
Outputs:
outputs.combinedBundle
"""
# 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:filteredBundle', 'bundle', 0, 'Filtered Bundle', 'Bundle whose contents are filtered before being added to the output', {}, True, None, False, ''),
('inputs:filters', 'token[]', 0, None, "List of filter names to be applied to the filteredBundle. Any filter name\nappearing in this list will be applied to members of that bundle and only those\npassing all filters will be added to the output bundle. Legal filter values are\n'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), \nand 'int' (attributes whose base type is integer).", {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:fullBundle', 'bundle', 0, 'Full Bundle', 'Bundle whose contents are passed to the output in their entirety', {}, True, None, False, ''),
('outputs:combinedBundle', 'bundle', 0, None, 'This is the union of fullBundle and filtered members of the filteredBundle.', {}, 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.filteredBundle = og.AttributeRole.BUNDLE
role_data.inputs.fullBundle = og.AttributeRole.BUNDLE
role_data.outputs.combinedBundle = 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 filteredBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.filteredBundle"""
return self.__bundles.filteredBundle
@property
def filters(self):
data_view = og.AttributeValueHelper(self._attributes.filters)
return data_view.get()
@filters.setter
def filters(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.filters)
data_view = og.AttributeValueHelper(self._attributes.filters)
data_view.set(value)
self.filters_size = data_view.get_array_size()
@property
def fullBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.fullBundle"""
return self.__bundles.fullBundle
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 combinedBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.combinedBundle"""
return self.__bundles.combinedBundle
@combinedBundle.setter
def combinedBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.combinedBundle 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.combinedBundle.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 = OgnTutorialBundlesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundlesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundlesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,335 | Python | 51.4 | 475 | 0.678391 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCudaDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CudaData
This is a tutorial node. It performs different functions on the GPU to illustrate different types of data access. The first
adds inputs 'a' and 'b' to yield output 'sum', all of which are on the GPU. The second is a sample expansion deformation
that multiplies every point on a set of input points, stored on the GPU, by a constant value, stored on the CPU, to yield
a set of output points, also on the GPU. The third is an assortment of different data types illustrating how different data
is passed to the GPU. This particular node uses CUDA for its GPU computations, as indicated in the memory type value. Normal
use case for GPU compute is large amounts of data. For testing purposes this node only handles a very small amount but the
principle is the same.
"""
import carb
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 OgnTutorialCudaDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CudaData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
inputs.color
inputs.half
inputs.matrix
inputs.multiplier
inputs.points
Outputs:
outputs.color
outputs.half
outputs.matrix
outputs.points
outputs.sum
"""
# 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', 'float', 0, None, 'First value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:b', 'float', 0, None, 'Second value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:color', 'color3d', 0, None, 'Input with three doubles as a color for algorithm 3', {ogn.MetadataKeys.DEFAULT: '[1.0, 0.5, 1.0]'}, True, [1.0, 0.5, 1.0], False, ''),
('inputs:half', 'half', 0, None, 'Input of type half for algorithm 3', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:matrix', 'matrix4d', 0, None, 'Input with 16 doubles interpreted as a double-precision 4d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]'}, True, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], False, ''),
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points in algorithm 2', {ogn.MetadataKeys.MEMORY_TYPE: 'cpu', ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Points to be moved by algorithm 2', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:color', 'color3d', 0, None, 'Output with three doubles as a color for algorithm 3', {}, True, None, False, ''),
('outputs:half', 'half', 0, None, 'Output of type half for algorithm 3', {}, True, None, False, ''),
('outputs:matrix', 'matrix4d', 0, None, 'Output with 16 doubles interpreted as a double-precision 4d matrix', {}, True, None, False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points from algorithm 2', {}, True, None, False, ''),
('outputs:sum', 'float', 0, None, 'Sum of the two inputs from algorithm 1', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.color = og.AttributeRole.COLOR
role_data.inputs.matrix = og.AttributeRole.MATRIX
role_data.outputs.color = og.AttributeRole.COLOR
role_data.outputs.matrix = 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 a(self):
data_view = og.AttributeValueHelper(self._attributes.a)
return data_view.get(on_gpu=True)
@a.setter
def a(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a)
data_view = og.AttributeValueHelper(self._attributes.a)
data_view.set(value, on_gpu=True)
@property
def b(self):
data_view = og.AttributeValueHelper(self._attributes.b)
return data_view.get(on_gpu=True)
@b.setter
def b(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.b)
data_view = og.AttributeValueHelper(self._attributes.b)
data_view.set(value, on_gpu=True)
@property
def color(self):
data_view = og.AttributeValueHelper(self._attributes.color)
return data_view.get(on_gpu=True)
@color.setter
def color(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.color)
data_view = og.AttributeValueHelper(self._attributes.color)
data_view.set(value, on_gpu=True)
@property
def half(self):
data_view = og.AttributeValueHelper(self._attributes.half)
return data_view.get(on_gpu=True)
@half.setter
def half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.half)
data_view = og.AttributeValueHelper(self._attributes.half)
data_view.set(value, on_gpu=True)
@property
def matrix(self):
data_view = og.AttributeValueHelper(self._attributes.matrix)
return data_view.get(on_gpu=True)
@matrix.setter
def matrix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.matrix)
data_view = og.AttributeValueHelper(self._attributes.matrix)
data_view.set(value, on_gpu=True)
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
return data_view.get()
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.set(value)
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
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.set(value, on_gpu=True)
self.points_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.points_size = None
self._batchedWriteValues = { }
@property
def color(self):
data_view = og.AttributeValueHelper(self._attributes.color)
return data_view.get(on_gpu=True)
@color.setter
def color(self, value):
data_view = og.AttributeValueHelper(self._attributes.color)
data_view.set(value, on_gpu=True)
@property
def half(self):
data_view = og.AttributeValueHelper(self._attributes.half)
return data_view.get(on_gpu=True)
@half.setter
def half(self, value):
data_view = og.AttributeValueHelper(self._attributes.half)
data_view.set(value, on_gpu=True)
@property
def matrix(self):
data_view = og.AttributeValueHelper(self._attributes.matrix)
return data_view.get(on_gpu=True)
@matrix.setter
def matrix(self, value):
data_view = og.AttributeValueHelper(self._attributes.matrix)
data_view.set(value, on_gpu=True)
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
return data_view.get(reserved_element_count=self.points_size, on_gpu=True)
@points.setter
def points(self, value):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
@property
def sum(self):
data_view = og.AttributeValueHelper(self._attributes.sum)
return data_view.get(on_gpu=True)
@sum.setter
def sum(self, value):
data_view = og.AttributeValueHelper(self._attributes.sum)
data_view.set(value, on_gpu=True)
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 = OgnTutorialCudaDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCudaDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCudaDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,300 | Python | 45.950382 | 343 | 0.633252 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuData
This is a tutorial node. It illustrates how to access data whose memory location, CPU or GPU, is determined at runtime in
the compute method. The data types are the same as for the purely CPU and purely GPU tutorials, it is only the access method
that changes. The input 'is_gpu' determines where the data of the other attributes can be accessed.
"""
import carb
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 OgnTutorialCpuGpuDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
inputs.is_gpu
inputs.multiplier
inputs.points
Outputs:
outputs.points
outputs.sum
"""
# 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', 'float', 0, None, 'First value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:b', 'float', 0, None, 'Second value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:is_gpu', 'bool', 0, None, 'Runtime switch determining where the data for the other attributes lives.', {ogn.MetadataKeys.MEMORY_TYPE: 'cpu', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points in algorithm 2', {ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Points to be moved by algorithm 2', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points from algorithm 2', {}, True, None, False, ''),
('outputs:sum', 'float', 0, None, 'Sum of the two inputs from algorithm 1', {}, 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 = []
class __a:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.a)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.a)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def a(self):
return self.__class__.__a(self)
class __b:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.b)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.b)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def b(self):
return self.__class__.__b(self)
@property
def is_gpu(self):
data_view = og.AttributeValueHelper(self._attributes.is_gpu)
return data_view.get()
@is_gpu.setter
def is_gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.is_gpu)
data_view = og.AttributeValueHelper(self._attributes.is_gpu)
data_view.set(value)
class __multiplier:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.multiplier)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.multiplier)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def multiplier(self):
return self.__class__.__multiplier(self)
class __points:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
self._parent.cpu_size = data_view.get_array_size()
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
self._parent.gpu_size = data_view.get_array_size()
@property
def points(self):
return self.__class__.__points(self)
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.points_size = None
self._batchedWriteValues = { }
class __points:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(reserved_element_count=self._parent.points_size)
@cpu.setter
def cpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
self._parent.cpu_size = data_view.get_array_size()
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(reserved_element_count=self._parent.points_size, on_gpu=True)
@gpu.setter
def gpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
self._parent.gpu_size = data_view.get_array_size()
@property
def points(self):
return self.__class__.__points(self)
class __sum:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.sum)
return data_view.get()
@cpu.setter
def cpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.sum)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def sum(self):
return self.__class__.__sum(self)
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 = OgnTutorialCpuGpuDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,813 | Python | 41.430463 | 218 | 0.590806 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStateAttributesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.StateAttributesPy
This is a tutorial node. It exercises state attributes to remember data from on evaluation to the next.
"""
import carb
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 OgnTutorialStateAttributesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.StateAttributesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.ignored
State:
state.monotonic
state.reset
"""
# 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:ignored', 'bool', 0, None, 'Ignore me', {}, True, False, False, ''),
('state:monotonic', 'int', 0, None, 'The monotonically increasing output value, reset to 0 when the reset value is true', {}, True, None, False, ''),
('state:reset', 'bool', 0, None, 'If true then the inputs are ignored and outputs are set to default values, then this\nflag is set to false for subsequent evaluations.', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"ignored", "_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.ignored]
self._batchedReadValues = [False]
@property
def ignored(self):
return self._batchedReadValues[0]
@ignored.setter
def ignored(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 = { }
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 monotonic(self):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
data_view.set(value)
@property
def reset(self):
data_view = og.AttributeValueHelper(self._attributes.reset)
return data_view.get()
@reset.setter
def reset(self, value):
data_view = og.AttributeValueHelper(self._attributes.reset)
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 = OgnTutorialStateAttributesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStateAttributesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStateAttributesPyDatabase.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(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.StateAttributesPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialStateAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialStateAttributesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialStateAttributesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialStateAttributesPyDatabase.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 OgnTutorialStateAttributesPyDatabase.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):
OgnTutorialStateAttributesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialStateAttributesPyDatabase.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(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialStateAttributesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialStateAttributesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialStateAttributesPyDatabase.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(OgnTutorialStateAttributesPyDatabase.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.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: State Attributes")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises state attributes to remember data from on evaluation to the next.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.StateAttributesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialStateAttributesPyDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialStateAttributesPyDatabase.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):
OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialStateAttributesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.StateAttributesPy")
| 11,647 | Python | 47.132231 | 238 | 0.649008 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundlesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleManipulationPy
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents. The configuration
is the same as omni.graph.tutorials.BundleManipulation except that the implementation language is Python
"""
import carb
import numpy
import sys
import traceback
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 OgnTutorialBundlesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleManipulationPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.filteredBundle
inputs.filters
inputs.fullBundle
Outputs:
outputs.combinedBundle
"""
# 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:filteredBundle', 'bundle', 0, 'Filtered Bundle', 'Bundle whose contents are filtered before being added to the output', {}, True, None, False, ''),
('inputs:filters', 'token[]', 0, None, "List of filter names to be applied to the filteredBundle. Any filter name\nappearing in this list will be applied to members of that bundle and only those\npassing all filters will be added to the output bundle. Legal filter values are\n'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), \nand 'int' (attributes whose base type is integer).", {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:fullBundle', 'bundle', 0, 'Full Bundle', 'Bundle whose contents are passed to the output in their entirety', {}, True, None, False, ''),
('outputs:combinedBundle', 'bundle', 0, None, 'This is the union of fullBundle and filtered members of the filteredBundle.', {}, 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.filteredBundle = og.AttributeRole.BUNDLE
role_data.inputs.fullBundle = og.AttributeRole.BUNDLE
role_data.outputs.combinedBundle = 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 filteredBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.filteredBundle"""
return self.__bundles.filteredBundle
@property
def filters(self):
data_view = og.AttributeValueHelper(self._attributes.filters)
return data_view.get()
@filters.setter
def filters(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.filters)
data_view = og.AttributeValueHelper(self._attributes.filters)
data_view.set(value)
self.filters_size = data_view.get_array_size()
@property
def fullBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.fullBundle"""
return self.__bundles.fullBundle
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 combinedBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.combinedBundle"""
return self.__bundles.combinedBundle
@combinedBundle.setter
def combinedBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.combinedBundle 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.combinedBundle.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 = OgnTutorialBundlesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundlesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundlesPyDatabase.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(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.BundleManipulationPy'
@staticmethod
def compute(context, node):
def database_valid():
if not db.inputs.filteredBundle.valid:
db.log_warning('Required bundle inputs.filteredBundle is invalid or not connected, compute skipped')
return False
if not db.inputs.fullBundle.valid:
db.log_warning('Required bundle inputs.fullBundle is invalid or not connected, compute skipped')
return False
if not db.outputs.combinedBundle.valid:
db.log_error('Required bundle outputs.combinedBundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialBundlesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialBundlesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialBundlesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialBundlesPyDatabase.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 OgnTutorialBundlesPyDatabase.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):
OgnTutorialBundlesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialBundlesPyDatabase.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(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialBundlesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialBundlesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialBundlesPyDatabase.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(OgnTutorialBundlesPyDatabase.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.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Bundle Manipulation")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents. The configuration is the same as omni.graph.tutorials.BundleManipulation except that the implementation language is Python")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.BundleManipulationPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialBundlesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialBundlesPyDatabase.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):
OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialBundlesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.BundleManipulationPy")
| 13,575 | Python | 51.015325 | 475 | 0.657459 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialRoleDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.RoleData
This is a tutorial node. It creates both an input and output attribute of every supported role-based data type. The values
are modified in a simple way so that the compute modifies values.
"""
import carb
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 OgnTutorialRoleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.RoleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_color3d
inputs.a_color3f
inputs.a_color3h
inputs.a_color4d
inputs.a_color4f
inputs.a_color4h
inputs.a_frame
inputs.a_matrix2d
inputs.a_matrix3d
inputs.a_matrix4d
inputs.a_normal3d
inputs.a_normal3f
inputs.a_normal3h
inputs.a_point3d
inputs.a_point3f
inputs.a_point3h
inputs.a_quatd
inputs.a_quatf
inputs.a_quath
inputs.a_texcoord2d
inputs.a_texcoord2f
inputs.a_texcoord2h
inputs.a_texcoord3d
inputs.a_texcoord3f
inputs.a_texcoord3h
inputs.a_timecode
inputs.a_vector3d
inputs.a_vector3f
inputs.a_vector3h
Outputs:
outputs.a_color3d
outputs.a_color3f
outputs.a_color3h
outputs.a_color4d
outputs.a_color4f
outputs.a_color4h
outputs.a_frame
outputs.a_matrix2d
outputs.a_matrix3d
outputs.a_matrix4d
outputs.a_normal3d
outputs.a_normal3f
outputs.a_normal3h
outputs.a_point3d
outputs.a_point3f
outputs.a_point3h
outputs.a_quatd
outputs.a_quatf
outputs.a_quath
outputs.a_texcoord2d
outputs.a_texcoord2f
outputs.a_texcoord2h
outputs.a_texcoord3d
outputs.a_texcoord3f
outputs.a_texcoord3h
outputs.a_timecode
outputs.a_vector3d
outputs.a_vector3f
outputs.a_vector3h
"""
# 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_color3d', 'color3d', 0, None, 'This is an attribute interpreted as a double-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color3f', 'color3f', 0, None, 'This is an attribute interpreted as a single-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color3h', 'color3h', 0, None, 'This is an attribute interpreted as a half-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color4d', 'color4d', 0, None, 'This is an attribute interpreted as a double-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_color4f', 'color4f', 0, None, 'This is an attribute interpreted as a single-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_color4h', 'color4h', 0, None, 'This is an attribute interpreted as a half-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_frame', 'frame4d', 0, None, 'This is an attribute interpreted as a coordinate frame', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]'}, True, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], False, ''),
('inputs:a_matrix2d', 'matrix2d', 0, None, 'This is an attribute interpreted as a double-precision 2d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0], [0.0, 1.0]]'}, True, [[1.0, 0.0], [0.0, 1.0]], False, ''),
('inputs:a_matrix3d', 'matrix3d', 0, None, 'This is an attribute interpreted as a double-precision 3d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]'}, True, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], False, ''),
('inputs:a_matrix4d', 'matrix4d', 0, None, 'This is an attribute interpreted as a double-precision 4d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]'}, True, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], False, ''),
('inputs:a_normal3d', 'normal3d', 0, None, 'This is an attribute interpreted as a double-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_normal3f', 'normal3f', 0, None, 'This is an attribute interpreted as a single-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_normal3h', 'normal3h', 0, None, 'This is an attribute interpreted as a half-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3d', 'point3d', 0, None, 'This is an attribute interpreted as a double-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3f', 'point3f', 0, None, 'This is an attribute interpreted as a single-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3h', 'point3h', 0, None, 'This is an attribute interpreted as a half-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_quatd', 'quatd', 0, None, 'This is an attribute interpreted as a double-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_quatf', 'quatf', 0, None, 'This is an attribute interpreted as a single-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_quath', 'quath', 0, None, 'This is an attribute interpreted as a half-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord2d', 'texCoord2d', 0, None, 'This is an attribute interpreted as a double-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord2f', 'texCoord2f', 0, None, 'This is an attribute interpreted as a single-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord2h', 'texCoord2h', 0, None, 'This is an attribute interpreted as a half-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord3d', 'texCoord3d', 0, None, 'This is an attribute interpreted as a double-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord3f', 'texCoord3f', 0, None, 'This is an attribute interpreted as a single-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord3h', 'texCoord3h', 0, None, 'This is an attribute interpreted as a half-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_timecode', 'timecode', 0, None, 'This is a computed attribute interpreted as a timecode', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:a_vector3d', 'vector3d', 0, None, 'This is an attribute interpreted as a double-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_vector3f', 'vector3f', 0, None, 'This is an attribute interpreted as a single-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_vector3h', 'vector3h', 0, None, 'This is an attribute interpreted as a half-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('outputs:a_color3d', 'color3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d color', {}, True, None, False, ''),
('outputs:a_color3f', 'color3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d color', {}, True, None, False, ''),
('outputs:a_color3h', 'color3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d color', {}, True, None, False, ''),
('outputs:a_color4d', 'color4d', 0, None, 'This is a computed attribute interpreted as a double-precision 4d color', {}, True, None, False, ''),
('outputs:a_color4f', 'color4f', 0, None, 'This is a computed attribute interpreted as a single-precision 4d color', {}, True, None, False, ''),
('outputs:a_color4h', 'color4h', 0, None, 'This is a computed attribute interpreted as a half-precision 4d color', {}, True, None, False, ''),
('outputs:a_frame', 'frame4d', 0, None, 'This is a computed attribute interpreted as a coordinate frame', {}, True, None, False, ''),
('outputs:a_matrix2d', 'matrix2d', 0, None, 'This is a computed attribute interpreted as a double-precision 2d matrix', {}, True, None, False, ''),
('outputs:a_matrix3d', 'matrix3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d matrix', {}, True, None, False, ''),
('outputs:a_matrix4d', 'matrix4d', 0, None, 'This is a computed attribute interpreted as a double-precision 4d matrix', {}, True, None, False, ''),
('outputs:a_normal3d', 'normal3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d normal', {}, True, None, False, ''),
('outputs:a_normal3f', 'normal3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d normal', {}, True, None, False, ''),
('outputs:a_normal3h', 'normal3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d normal', {}, True, None, False, ''),
('outputs:a_point3d', 'point3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d point', {}, True, None, False, ''),
('outputs:a_point3f', 'point3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d point', {}, True, None, False, ''),
('outputs:a_point3h', 'point3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d point', {}, True, None, False, ''),
('outputs:a_quatd', 'quatd', 0, None, 'This is a computed attribute interpreted as a double-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_quatf', 'quatf', 0, None, 'This is a computed attribute interpreted as a single-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_quath', 'quath', 0, None, 'This is a computed attribute interpreted as a half-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_texcoord2d', 'texCoord2d', 0, None, 'This is a computed attribute interpreted as a double-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord2f', 'texCoord2f', 0, None, 'This is a computed attribute interpreted as a single-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord2h', 'texCoord2h', 0, None, 'This is a computed attribute interpreted as a half-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3d', 'texCoord3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3f', 'texCoord3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3h', 'texCoord3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_timecode', 'timecode', 0, None, 'This is a computed attribute interpreted as a timecode', {}, True, None, False, ''),
('outputs:a_vector3d', 'vector3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d vector', {}, True, None, False, ''),
('outputs:a_vector3f', 'vector3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d vector', {}, True, None, False, ''),
('outputs:a_vector3h', 'vector3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d vector', {}, 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.a_color3d = og.AttributeRole.COLOR
role_data.inputs.a_color3f = og.AttributeRole.COLOR
role_data.inputs.a_color3h = og.AttributeRole.COLOR
role_data.inputs.a_color4d = og.AttributeRole.COLOR
role_data.inputs.a_color4f = og.AttributeRole.COLOR
role_data.inputs.a_color4h = og.AttributeRole.COLOR
role_data.inputs.a_frame = og.AttributeRole.FRAME
role_data.inputs.a_matrix2d = og.AttributeRole.MATRIX
role_data.inputs.a_matrix3d = og.AttributeRole.MATRIX
role_data.inputs.a_matrix4d = og.AttributeRole.MATRIX
role_data.inputs.a_normal3d = og.AttributeRole.NORMAL
role_data.inputs.a_normal3f = og.AttributeRole.NORMAL
role_data.inputs.a_normal3h = og.AttributeRole.NORMAL
role_data.inputs.a_point3d = og.AttributeRole.POSITION
role_data.inputs.a_point3f = og.AttributeRole.POSITION
role_data.inputs.a_point3h = og.AttributeRole.POSITION
role_data.inputs.a_quatd = og.AttributeRole.QUATERNION
role_data.inputs.a_quatf = og.AttributeRole.QUATERNION
role_data.inputs.a_quath = og.AttributeRole.QUATERNION
role_data.inputs.a_texcoord2d = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord2f = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord2h = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3d = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3f = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3h = og.AttributeRole.TEXCOORD
role_data.inputs.a_timecode = og.AttributeRole.TIMECODE
role_data.inputs.a_vector3d = og.AttributeRole.VECTOR
role_data.inputs.a_vector3f = og.AttributeRole.VECTOR
role_data.inputs.a_vector3h = og.AttributeRole.VECTOR
role_data.outputs.a_color3d = og.AttributeRole.COLOR
role_data.outputs.a_color3f = og.AttributeRole.COLOR
role_data.outputs.a_color3h = og.AttributeRole.COLOR
role_data.outputs.a_color4d = og.AttributeRole.COLOR
role_data.outputs.a_color4f = og.AttributeRole.COLOR
role_data.outputs.a_color4h = og.AttributeRole.COLOR
role_data.outputs.a_frame = og.AttributeRole.FRAME
role_data.outputs.a_matrix2d = og.AttributeRole.MATRIX
role_data.outputs.a_matrix3d = og.AttributeRole.MATRIX
role_data.outputs.a_matrix4d = og.AttributeRole.MATRIX
role_data.outputs.a_normal3d = og.AttributeRole.NORMAL
role_data.outputs.a_normal3f = og.AttributeRole.NORMAL
role_data.outputs.a_normal3h = og.AttributeRole.NORMAL
role_data.outputs.a_point3d = og.AttributeRole.POSITION
role_data.outputs.a_point3f = og.AttributeRole.POSITION
role_data.outputs.a_point3h = og.AttributeRole.POSITION
role_data.outputs.a_quatd = og.AttributeRole.QUATERNION
role_data.outputs.a_quatf = og.AttributeRole.QUATERNION
role_data.outputs.a_quath = og.AttributeRole.QUATERNION
role_data.outputs.a_texcoord2d = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord2f = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord2h = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3d = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3f = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3h = og.AttributeRole.TEXCOORD
role_data.outputs.a_timecode = og.AttributeRole.TIMECODE
role_data.outputs.a_vector3d = og.AttributeRole.VECTOR
role_data.outputs.a_vector3f = og.AttributeRole.VECTOR
role_data.outputs.a_vector3h = 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 a_color3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
return data_view.get()
@a_color3d.setter
def a_color3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3d)
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
data_view.set(value)
@property
def a_color3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
return data_view.get()
@a_color3f.setter
def a_color3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3f)
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
data_view.set(value)
@property
def a_color3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
return data_view.get()
@a_color3h.setter
def a_color3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3h)
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
data_view.set(value)
@property
def a_color4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
return data_view.get()
@a_color4d.setter
def a_color4d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4d)
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
data_view.set(value)
@property
def a_color4f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
return data_view.get()
@a_color4f.setter
def a_color4f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4f)
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
data_view.set(value)
@property
def a_color4h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
return data_view.get()
@a_color4h.setter
def a_color4h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4h)
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
data_view.set(value)
@property
def a_frame(self):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
return data_view.get()
@a_frame.setter
def a_frame(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_frame)
data_view = og.AttributeValueHelper(self._attributes.a_frame)
data_view.set(value)
@property
def a_matrix2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
return data_view.get()
@a_matrix2d.setter
def a_matrix2d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix2d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
data_view.set(value)
@property
def a_matrix3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
return data_view.get()
@a_matrix3d.setter
def a_matrix3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix3d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
data_view.set(value)
@property
def a_matrix4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
return data_view.get()
@a_matrix4d.setter
def a_matrix4d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix4d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
data_view.set(value)
@property
def a_normal3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
return data_view.get()
@a_normal3d.setter
def a_normal3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3d)
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
data_view.set(value)
@property
def a_normal3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
return data_view.get()
@a_normal3f.setter
def a_normal3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3f)
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
data_view.set(value)
@property
def a_normal3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
return data_view.get()
@a_normal3h.setter
def a_normal3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3h)
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
data_view.set(value)
@property
def a_point3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
return data_view.get()
@a_point3d.setter
def a_point3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3d)
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
data_view.set(value)
@property
def a_point3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
return data_view.get()
@a_point3f.setter
def a_point3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3f)
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
data_view.set(value)
@property
def a_point3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
return data_view.get()
@a_point3h.setter
def a_point3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3h)
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
data_view.set(value)
@property
def a_quatd(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
return data_view.get()
@a_quatd.setter
def a_quatd(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quatd)
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
data_view.set(value)
@property
def a_quatf(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
return data_view.get()
@a_quatf.setter
def a_quatf(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quatf)
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
data_view.set(value)
@property
def a_quath(self):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
return data_view.get()
@a_quath.setter
def a_quath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quath)
data_view = og.AttributeValueHelper(self._attributes.a_quath)
data_view.set(value)
@property
def a_texcoord2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
return data_view.get()
@a_texcoord2d.setter
def a_texcoord2d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2d)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
data_view.set(value)
@property
def a_texcoord2f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
return data_view.get()
@a_texcoord2f.setter
def a_texcoord2f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2f)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
data_view.set(value)
@property
def a_texcoord2h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
return data_view.get()
@a_texcoord2h.setter
def a_texcoord2h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2h)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
data_view.set(value)
@property
def a_texcoord3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
return data_view.get()
@a_texcoord3d.setter
def a_texcoord3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3d)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
data_view.set(value)
@property
def a_texcoord3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
return data_view.get()
@a_texcoord3f.setter
def a_texcoord3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3f)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
data_view.set(value)
@property
def a_texcoord3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
return data_view.get()
@a_texcoord3h.setter
def a_texcoord3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3h)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
data_view.set(value)
@property
def a_timecode(self):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
return data_view.get()
@a_timecode.setter
def a_timecode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_timecode)
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
data_view.set(value)
@property
def a_vector3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
return data_view.get()
@a_vector3d.setter
def a_vector3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3d)
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
data_view.set(value)
@property
def a_vector3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
return data_view.get()
@a_vector3f.setter
def a_vector3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3f)
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
data_view.set(value)
@property
def a_vector3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
return data_view.get()
@a_vector3h.setter
def a_vector3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3h)
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
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 a_color3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
return data_view.get()
@a_color3d.setter
def a_color3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
data_view.set(value)
@property
def a_color3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
return data_view.get()
@a_color3f.setter
def a_color3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
data_view.set(value)
@property
def a_color3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
return data_view.get()
@a_color3h.setter
def a_color3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
data_view.set(value)
@property
def a_color4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
return data_view.get()
@a_color4d.setter
def a_color4d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
data_view.set(value)
@property
def a_color4f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
return data_view.get()
@a_color4f.setter
def a_color4f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
data_view.set(value)
@property
def a_color4h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
return data_view.get()
@a_color4h.setter
def a_color4h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
data_view.set(value)
@property
def a_frame(self):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
return data_view.get()
@a_frame.setter
def a_frame(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
data_view.set(value)
@property
def a_matrix2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
return data_view.get()
@a_matrix2d.setter
def a_matrix2d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
data_view.set(value)
@property
def a_matrix3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
return data_view.get()
@a_matrix3d.setter
def a_matrix3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
data_view.set(value)
@property
def a_matrix4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
return data_view.get()
@a_matrix4d.setter
def a_matrix4d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
data_view.set(value)
@property
def a_normal3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
return data_view.get()
@a_normal3d.setter
def a_normal3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
data_view.set(value)
@property
def a_normal3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
return data_view.get()
@a_normal3f.setter
def a_normal3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
data_view.set(value)
@property
def a_normal3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
return data_view.get()
@a_normal3h.setter
def a_normal3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
data_view.set(value)
@property
def a_point3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
return data_view.get()
@a_point3d.setter
def a_point3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
data_view.set(value)
@property
def a_point3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
return data_view.get()
@a_point3f.setter
def a_point3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
data_view.set(value)
@property
def a_point3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
return data_view.get()
@a_point3h.setter
def a_point3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
data_view.set(value)
@property
def a_quatd(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
return data_view.get()
@a_quatd.setter
def a_quatd(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
data_view.set(value)
@property
def a_quatf(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
return data_view.get()
@a_quatf.setter
def a_quatf(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
data_view.set(value)
@property
def a_quath(self):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
return data_view.get()
@a_quath.setter
def a_quath(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
data_view.set(value)
@property
def a_texcoord2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
return data_view.get()
@a_texcoord2d.setter
def a_texcoord2d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
data_view.set(value)
@property
def a_texcoord2f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
return data_view.get()
@a_texcoord2f.setter
def a_texcoord2f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
data_view.set(value)
@property
def a_texcoord2h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
return data_view.get()
@a_texcoord2h.setter
def a_texcoord2h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
data_view.set(value)
@property
def a_texcoord3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
return data_view.get()
@a_texcoord3d.setter
def a_texcoord3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
data_view.set(value)
@property
def a_texcoord3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
return data_view.get()
@a_texcoord3f.setter
def a_texcoord3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
data_view.set(value)
@property
def a_texcoord3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
return data_view.get()
@a_texcoord3h.setter
def a_texcoord3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
data_view.set(value)
@property
def a_timecode(self):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
return data_view.get()
@a_timecode.setter
def a_timecode(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
data_view.set(value)
@property
def a_vector3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
return data_view.get()
@a_vector3d.setter
def a_vector3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
data_view.set(value)
@property
def a_vector3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
return data_view.get()
@a_vector3f.setter
def a_vector3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
data_view.set(value)
@property
def a_vector3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
return data_view.get()
@a_vector3h.setter
def a_vector3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
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 = OgnTutorialRoleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialRoleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialRoleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 42,891 | Python | 46.446903 | 346 | 0.616936 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTokensPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.TokensPy
This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has
been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token
list.
"""
import carb
import numpy
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialTokensPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.TokensPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.valuesToCheck
Outputs:
outputs.isColor
Predefined Tokens:
tokens.red
tokens.green
tokens.blue
"""
# 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:valuesToCheck', 'token[]', 0, None, 'Array of tokens that are to be checked', {}, True, [], False, ''),
('outputs:isColor', 'bool[]', 0, None, 'True values if the corresponding input value appears in the token list', {}, True, None, False, ''),
])
class tokens:
red = "red"
green = "green"
blue = "blue"
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 valuesToCheck(self):
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
return data_view.get()
@valuesToCheck.setter
def valuesToCheck(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.valuesToCheck)
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
data_view.set(value)
self.valuesToCheck_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.isColor_size = None
self._batchedWriteValues = { }
@property
def isColor(self):
data_view = og.AttributeValueHelper(self._attributes.isColor)
return data_view.get(reserved_element_count=self.isColor_size)
@isColor.setter
def isColor(self, value):
data_view = og.AttributeValueHelper(self._attributes.isColor)
data_view.set(value)
self.isColor_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 = OgnTutorialTokensPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTokensPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTokensPyDatabase.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(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.TokensPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialTokensPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialTokensPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialTokensPyDatabase(node)
try:
compute_function = getattr(OgnTutorialTokensPyDatabase.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 OgnTutorialTokensPyDatabase.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):
OgnTutorialTokensPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialTokensPyDatabase.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(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialTokensPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialTokensPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialTokensPyDatabase.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(OgnTutorialTokensPyDatabase.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.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Tokens")
node_type.set_metadata(ogn.MetadataKeys.TOKENS, "[\"red\", \"green\", \"blue\"]")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token list.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.TokensPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialTokensPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialTokensPyDatabase.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):
OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialTokensPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.TokensPy")
| 11,282 | Python | 46.407563 | 324 | 0.649885 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.State
This is a tutorial node. It makes use of internal state information to continuously increment an output.
"""
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 OgnTutorialStateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.State
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.override
inputs.overrideValue
Outputs:
outputs.monotonic
"""
# 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:override', 'bool', 0, 'Enable Override', 'When true get the output from the overrideValue, otherwise use the internal value', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:overrideValue', 'int64', 0, 'Override Value', "Value to use instead of the monotonically increasing internal one when 'override' is true", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:monotonic', 'int64', 0, 'State-Based Output', 'Monotonically increasing output, set by internal state information', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, 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 override(self):
data_view = og.AttributeValueHelper(self._attributes.override)
return data_view.get()
@override.setter
def override(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.override)
data_view = og.AttributeValueHelper(self._attributes.override)
data_view.set(value)
@property
def overrideValue(self):
data_view = og.AttributeValueHelper(self._attributes.overrideValue)
return data_view.get()
@overrideValue.setter
def overrideValue(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.overrideValue)
data_view = og.AttributeValueHelper(self._attributes.overrideValue)
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 monotonic(self):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
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 = OgnTutorialStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,974 | Python | 47.185483 | 209 | 0.67392 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialDynamicAttributesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributes
This is a C++ node that exercises the ability to add and remove database attribute accessors for dynamic attributes. When
the dynamic attribute is added the property will exist and be able to get/set the attribute values. When it does not the
property will not exist. The dynamic attribute names are found in the tokens below. If neither exist then the input value
is copied to the output directly. If 'firstBit' exists then the 'firstBit'th bit of the input is x-ored for the copy. If
'secondBit' exists then the 'secondBit'th bit of the input is x-ored for the copy. (Recall bitwise match xor(0,0)=0, xor(0,1)=1,
xor(1,0)=1, and xor(1,1)=0.) For example, if 'firstBit' is present and set to 1 then the bitmask will be b0010, where bit
1 is set. If the input is 7, or b0111, then the xor operation will flip bit 1, yielding b0101, or 5 as the result. If on
the next run 'secondBit' is also present and set to 2 then its bitmask will be b0100, where bit 2 is set. The input of 7
(b0111) flips bit 1 because firstBit=1 and flips bit 2 because secondBit=2, yielding a final result of 1 (b0001).
"""
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 OgnTutorialDynamicAttributesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.value
Outputs:
outputs.result
Predefined Tokens:
tokens.firstBit
tokens.secondBit
tokens.invert
"""
# 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:value', 'uint', 0, None, 'Original value to be modified.', {}, True, 0, False, ''),
('outputs:result', 'uint', 0, None, 'Modified value', {}, True, None, False, ''),
])
class tokens:
firstBit = "inputs:firstBit"
secondBit = "inputs:secondBit"
invert = "inputs:invert"
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 value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.value)
data_view = og.AttributeValueHelper(self._attributes.value)
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):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get()
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
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 = OgnTutorialDynamicAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialDynamicAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialDynamicAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,314 | Python | 48.335937 | 128 | 0.684194 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialDefaultsDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.Defaults
This is a tutorial node. It will move the values of inputs to corresponding outputs. Inputs all have unspecified, and therefore
empty, default values.
"""
import carb
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 OgnTutorialDefaultsDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.Defaults
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_array
inputs.a_bool
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int2
inputs.a_int64
inputs.a_matrix
inputs.a_string
inputs.a_token
inputs.a_uchar
inputs.a_uint
inputs.a_uint64
Outputs:
outputs.a_array
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int2
outputs.a_int64
outputs.a_matrix
outputs.a_string
outputs.a_token
outputs.a_uchar
outputs.a_uint
outputs.a_uint64
"""
# 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_array', 'float[]', 0, None, 'This is an attribute of type array of floats', {}, True, [], False, ''),
('inputs:a_bool', 'bool', 0, None, 'This is an attribute of type boolean', {}, True, False, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_half', 'half', 0, None, 'This is an attribute of type 16 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {}, True, 0, False, ''),
('inputs:a_int2', 'int2', 0, None, 'This is an attribute of type 2-tuple of integers', {}, True, [0, 0], False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {}, True, 0, False, ''),
('inputs:a_matrix', 'matrix2d', 0, None, 'This is an attribute of type 2x2 matrix', {}, True, [[1.0, 0.0], [0.0, 1.0]], False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {}, True, "", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {}, True, "", False, ''),
('inputs:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {}, True, 0, False, ''),
('inputs:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {}, True, 0, False, ''),
('inputs:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {}, True, 0, False, ''),
('outputs:a_array', 'float[]', 0, None, 'This is a computed attribute of type array of floats', {}, True, None, False, ''),
('outputs:a_bool', 'bool', 0, None, 'This is a computed attribute of type boolean', {}, True, None, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {}, True, None, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {}, True, None, False, ''),
('outputs:a_half', 'half', 0, None, 'This is a computed attribute of type 16 bit floating point', {}, True, None, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {}, True, None, False, ''),
('outputs:a_int2', 'int2', 0, None, 'This is a computed attribute of type 2-tuple of integers', {}, True, None, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {}, True, None, False, ''),
('outputs:a_matrix', 'matrix2d', 0, None, 'This is a computed attribute of type 2x2 matrix', {}, True, None, False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {}, True, None, False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {}, True, None, False, ''),
('outputs:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {}, True, None, False, ''),
('outputs:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {}, True, None, False, ''),
('outputs:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {}, 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.a_matrix = og.AttributeRole.MATRIX
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_matrix = og.AttributeRole.MATRIX
role_data.outputs.a_string = 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._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a_array(self):
data_view = og.AttributeValueHelper(self._attributes.a_array)
return data_view.get()
@a_array.setter
def a_array(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_array)
data_view = og.AttributeValueHelper(self._attributes.a_array)
data_view.set(value)
self.a_array_size = data_view.get_array_size()
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_bool)
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double)
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float)
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half)
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int)
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int2)
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int64)
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_matrix(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
return data_view.get()
@a_matrix.setter
def a_matrix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix)
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
data_view.set(value)
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_string)
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_token)
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uchar)
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
data_view.set(value)
@property
def a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uint)
data_view = og.AttributeValueHelper(self._attributes.a_uint)
data_view.set(value)
@property
def a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uint64)
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
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.a_array_size = None
self.a_string_size = None
self._batchedWriteValues = { }
@property
def a_array(self):
data_view = og.AttributeValueHelper(self._attributes.a_array)
return data_view.get(reserved_element_count=self.a_array_size)
@a_array.setter
def a_array(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_array)
data_view.set(value)
self.a_array_size = data_view.get_array_size()
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_matrix(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
return data_view.get()
@a_matrix.setter
def a_matrix(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
data_view.set(value)
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get(reserved_element_count=self.a_string_size)
@a_string.setter
def a_string(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
data_view.set(value)
@property
def a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
data_view.set(value)
@property
def a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
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 = OgnTutorialDefaultsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialDefaultsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialDefaultsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 19,763 | Python | 41.412017 | 162 | 0.601882 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTupleDataDatabase.py | """Support for simplified access to data on nodes of type omni.tutorials.TupleData
This is a tutorial node. It creates both an input and output attribute of some of the supported tuple types. The values
are modified in a simple way so that the compute can be tested.
"""
import carb
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 OgnTutorialTupleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.tutorials.TupleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_double2
inputs.a_double3
inputs.a_float2
inputs.a_float3
inputs.a_half2
inputs.a_int2
Outputs:
outputs.a_double2
outputs.a_double3
outputs.a_float2
outputs.a_float3
outputs.a_half2
outputs.a_int2
"""
# 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_double2', 'double2', 0, None, 'This is an attribute with two double values', {ogn.MetadataKeys.DEFAULT: '[1.1, 2.2]'}, True, [1.1, 2.2], False, ''),
('inputs:a_double3', 'double3', 0, None, 'This is an attribute with three double values', {ogn.MetadataKeys.DEFAULT: '[1.1, 2.2, 3.3]'}, True, [1.1, 2.2, 3.3], False, ''),
('inputs:a_float2', 'float2', 0, None, 'This is an attribute with two float values', {ogn.MetadataKeys.DEFAULT: '[4.4, 5.5]'}, True, [4.4, 5.5], False, ''),
('inputs:a_float3', 'float3', 0, None, 'This is an attribute with three float values', {ogn.MetadataKeys.DEFAULT: '[6.6, 7.7, 8.8]'}, True, [6.6, 7.7, 8.8], False, ''),
('inputs:a_half2', 'half2', 0, None, 'This is an attribute with two 16-bit float values', {ogn.MetadataKeys.DEFAULT: '[7.0, 8.0]'}, True, [7.0, 8.0], False, ''),
('inputs:a_int2', 'int2', 0, None, 'This is an attribute with two 32-bit integer values', {ogn.MetadataKeys.DEFAULT: '[10, 11]'}, True, [10, 11], False, ''),
('outputs:a_double2', 'double2', 0, None, 'This is a computed attribute with two double values', {}, True, None, False, ''),
('outputs:a_double3', 'double3', 0, None, 'This is a computed attribute with three double values', {}, True, None, False, ''),
('outputs:a_float2', 'float2', 0, None, 'This is a computed attribute with two float values', {}, True, None, False, ''),
('outputs:a_float3', 'float3', 0, None, 'This is a computed attribute with three float values', {}, True, None, False, ''),
('outputs:a_half2', 'half2', 0, None, 'This is a computed attribute with two 16-bit float values', {}, True, None, False, ''),
('outputs:a_int2', 'int2', 0, None, 'This is a computed attribute with two 32-bit integer values', {}, 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_double2(self):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
return data_view.get()
@a_double2.setter
def a_double2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double2)
data_view = og.AttributeValueHelper(self._attributes.a_double2)
data_view.set(value)
@property
def a_double3(self):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
return data_view.get()
@a_double3.setter
def a_double3(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double3)
data_view = og.AttributeValueHelper(self._attributes.a_double3)
data_view.set(value)
@property
def a_float2(self):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
return data_view.get()
@a_float2.setter
def a_float2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float2)
data_view = og.AttributeValueHelper(self._attributes.a_float2)
data_view.set(value)
@property
def a_float3(self):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
return data_view.get()
@a_float3.setter
def a_float3(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float3)
data_view = og.AttributeValueHelper(self._attributes.a_float3)
data_view.set(value)
@property
def a_half2(self):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
return data_view.get()
@a_half2.setter
def a_half2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half2)
data_view = og.AttributeValueHelper(self._attributes.a_half2)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int2)
data_view = og.AttributeValueHelper(self._attributes.a_int2)
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 a_double2(self):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
return data_view.get()
@a_double2.setter
def a_double2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
data_view.set(value)
@property
def a_double3(self):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
return data_view.get()
@a_double3.setter
def a_double3(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
data_view.set(value)
@property
def a_float2(self):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
return data_view.get()
@a_float2.setter
def a_float2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
data_view.set(value)
@property
def a_float3(self):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
return data_view.get()
@a_float3.setter
def a_float3(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
data_view.set(value)
@property
def a_half2(self):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
return data_view.get()
@a_half2.setter
def a_half2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
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 = OgnTutorialTupleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTupleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTupleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,851 | Python | 43.842975 | 179 | 0.625933 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialExtendedTypesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypesPy
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types. It is identical
to OgnTutorialExtendedTypes.ogn, except the language of implementation is selected to be python.
"""
from typing import Any
import carb
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 OgnTutorialExtendedTypesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.flexible
inputs.floatOrToken
inputs.toNegate
inputs.tuple
Outputs:
outputs.doubledResult
outputs.flexible
outputs.negatedResult
outputs.tuple
"""
# 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:flexible', 'float[3][],token', 1, 'Flexible Values', 'Flexible data type input', {}, True, None, False, ''),
('inputs:floatOrToken', 'float,token', 1, 'Float Or Token', 'Attribute that can either be a float value or a token value', {}, True, None, False, ''),
('inputs:toNegate', 'bool[],float[]', 1, 'To Negate', 'Attribute that can either be an array of booleans or an array of floats', {}, True, None, False, ''),
('inputs:tuple', 'any', 2, 'Tuple Values', 'Variable size/type tuple values', {}, True, None, False, ''),
('outputs:doubledResult', 'any', 2, 'Doubled Input Value', "If the input 'floatOrToken' is a float this is 2x the value.\nIf it is a token this contains the input token repeated twice.", {}, True, None, False, ''),
('outputs:flexible', 'float[3][],token', 1, 'Inverted Flexible Values', 'Flexible data type output', {}, True, None, False, ''),
('outputs:negatedResult', 'bool[],float[]', 1, 'Negated Array Values', "Result of negating the data from the 'toNegate' input", {}, True, None, False, ''),
('outputs:tuple', 'any', 2, 'Negative Tuple Values', 'Negated values of the tuple input', {}, 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 flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, True)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def floatOrToken(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.floatOrToken"""
return og.RuntimeAttribute(self._attributes.floatOrToken.get_attribute_data(), self._context, True)
@floatOrToken.setter
def floatOrToken(self, value_to_set: Any):
"""Assign another attribute's value to outputs.floatOrToken"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.floatOrToken.value = value_to_set.value
else:
self.floatOrToken.value = value_to_set
@property
def toNegate(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.toNegate"""
return og.RuntimeAttribute(self._attributes.toNegate.get_attribute_data(), self._context, True)
@toNegate.setter
def toNegate(self, value_to_set: Any):
"""Assign another attribute's value to outputs.toNegate"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.toNegate.value = value_to_set.value
else:
self.toNegate.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, True)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.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 doubledResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.doubledResult"""
return og.RuntimeAttribute(self._attributes.doubledResult.get_attribute_data(), self._context, False)
@doubledResult.setter
def doubledResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.doubledResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.doubledResult.value = value_to_set.value
else:
self.doubledResult.value = value_to_set
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, False)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def negatedResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.negatedResult"""
return og.RuntimeAttribute(self._attributes.negatedResult.get_attribute_data(), self._context, False)
@negatedResult.setter
def negatedResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.negatedResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.negatedResult.value = value_to_set.value
else:
self.negatedResult.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, False)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.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 = OgnTutorialExtendedTypesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialExtendedTypesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialExtendedTypesPyDatabase.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(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.ExtendedTypesPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialExtendedTypesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialExtendedTypesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialExtendedTypesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialExtendedTypesPyDatabase.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 OgnTutorialExtendedTypesPyDatabase.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):
OgnTutorialExtendedTypesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialExtendedTypesPyDatabase.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(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialExtendedTypesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialExtendedTypesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialExtendedTypesPyDatabase.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(OgnTutorialExtendedTypesPyDatabase.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.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Extended Attribute Types")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types. It is identical to OgnTutorialExtendedTypes.ogn, except the language of implementation is selected to be python.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.ExtendedTypesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialExtendedTypesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialExtendedTypesPyDatabase.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):
OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialExtendedTypesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.ExtendedTypesPy")
| 16,110 | Python | 49.823344 | 290 | 0.646369 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuExtendedDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtended
This is a tutorial node. It exercises functionality for accessing data in extended attributes that are on the GPU as well
as those whose CPU/GPU location is decided at runtime. The compute adds the two inputs 'gpuData' and 'cpuData' together,
placing the result in `cpuGpuSum`, whose memory location is determined by the 'gpu' flag. This node is identical to OgnTutorialCpuGpuExtendedPy.ogn,
except is is implemented in C++.
"""
from typing import Any
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 OgnTutorialCpuGpuExtendedDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtended
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuData
inputs.gpu
inputs.gpuData
Outputs:
outputs.cpuGpuSum
"""
# 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:cpuData', 'any', 2, 'CPU Input Attribute', 'Input attribute whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then put the sum on the GPU, otherwise put it on the CPU', {}, True, False, False, ''),
('inputs:gpuData', 'any', 2, 'GPU Input Attribute', 'Input attribute whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuSum', 'any', 2, 'Sum', "This is the attribute with the selected data. If the 'gpu' attribute is set to true then this\nattribute's contents will be entirely on the GPU, otherwise it will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, 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 cpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.cpuData"""
return og.RuntimeAttribute(self._attributes.cpuData.get_attribute_data(), self._context, True)
@cpuData.setter
def cpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuData.value = value_to_set.value
else:
self.cpuData.value = value_to_set
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def gpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.gpuData"""
return og.RuntimeAttribute(self._attributes.gpuData.get_attribute_data(), self._context, True)
@gpuData.setter
def gpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.gpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.gpuData.value = value_to_set.value
else:
self.gpuData.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 cpuGpuSum(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.cpuGpuSum"""
return og.RuntimeAttribute(self._attributes.cpuGpuSum.get_attribute_data(), self._context, False)
@cpuGpuSum.setter
def cpuGpuSum(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuGpuSum"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuGpuSum.value = value_to_set.value
else:
self.cpuGpuSum.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 = OgnTutorialCpuGpuExtendedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuExtendedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuExtendedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,494 | Python | 49.986394 | 290 | 0.667734 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialSimpleDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.SimpleData
This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are
modified in a simple way so that the compute modifies values.
"""
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 OgnTutorialSimpleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.SimpleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_bool
inputs.a_constant_input
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int64
inputs.a_objectId
inputs.a_path
inputs.a_string
inputs.a_token
inputs.unsigned_a_uchar
inputs.unsigned_a_uint
inputs.unsigned_a_uint64
Outputs:
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int64
outputs.a_objectId
outputs.a_path
outputs.a_string
outputs.a_token
outputs.unsigned_a_uchar
outputs.unsigned_a_uint
outputs.unsigned_a_uint64
"""
# 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_bool', 'bool', 0, 'Sample Boolean Input', 'This is an attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:a_constant_input', 'int', 0, None, 'This is an input attribute whose value can be set but can only be connected as a source.', {ogn.MetadataKeys.OUTPUT_ONLY: '1'}, True, 0, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_half', 'half', 0, 'Sample Half Precision Input', 'This is an attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_objectId', 'objectId', 0, None, 'This is an attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_path', 'path', 0, None, 'This is an attribute of type path', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {ogn.MetadataKeys.DEFAULT: '"helloString"'}, True, "helloString", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"helloToken"'}, True, "helloToken", False, ''),
('inputs:unsigned:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:unsigned:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:unsigned:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:a_bool', 'bool', 0, 'Sample Boolean Output', 'This is a computed attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '5.0'}, True, 5.0, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '4.0'}, True, 4.0, False, ''),
('outputs:a_half', 'half', 0, 'Sample Half Precision Output', 'This is a computed attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '2'}, True, 2, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '3'}, True, 3, False, ''),
('outputs:a_objectId', 'objectId', 0, None, 'This is a computed attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '8'}, True, 8, False, ''),
('outputs:a_path', 'path', 0, None, 'This is a computed attribute of type path', {ogn.MetadataKeys.DEFAULT: '"/"'}, True, "/", False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {ogn.MetadataKeys.DEFAULT: '"seven"'}, True, "seven", False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"six"'}, True, "six", False, ''),
('outputs:unsigned:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '9'}, True, 9, False, ''),
('outputs:unsigned:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''),
('outputs:unsigned:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '11'}, True, 11, 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.a_objectId = og.AttributeRole.OBJECT_ID
role_data.inputs.a_path = og.AttributeRole.PATH
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.outputs.a_path = og.AttributeRole.PATH
role_data.outputs.a_string = 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._batchedReadAttributes = []
self._batchedReadValues = []
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_bool)
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_constant_input(self):
data_view = og.AttributeValueHelper(self._attributes.a_constant_input)
return data_view.get()
@a_constant_input.setter
def a_constant_input(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_constant_input)
data_view = og.AttributeValueHelper(self._attributes.a_constant_input)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double)
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float)
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half)
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int)
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int64)
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_objectId(self):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_objectId)
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
data_view.set(value)
@property
def a_path(self):
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get()
@a_path.setter
def a_path(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_path)
data_view = og.AttributeValueHelper(self._attributes.a_path)
data_view.set(value)
self.a_path_size = data_view.get_array_size()
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_string)
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_token)
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def unsigned_a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
return data_view.get()
@unsigned_a_uchar.setter
def unsigned_a_uchar(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uchar)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
data_view.set(value)
@property
def unsigned_a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
return data_view.get()
@unsigned_a_uint.setter
def unsigned_a_uint(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uint)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
data_view.set(value)
@property
def unsigned_a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
return data_view.get()
@unsigned_a_uint64.setter
def unsigned_a_uint64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uint64)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
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.a_path_size = 1
self.a_string_size = 5
self._batchedWriteValues = { }
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_objectId(self):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
data_view.set(value)
@property
def a_path(self):
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get(reserved_element_count=self.a_path_size)
@a_path.setter
def a_path(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_path)
data_view.set(value)
self.a_path_size = data_view.get_array_size()
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get(reserved_element_count=self.a_string_size)
@a_string.setter
def a_string(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def unsigned_a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
return data_view.get()
@unsigned_a_uchar.setter
def unsigned_a_uchar(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
data_view.set(value)
@property
def unsigned_a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
return data_view.get()
@unsigned_a_uint.setter
def unsigned_a_uint(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
data_view.set(value)
@property
def unsigned_a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
return data_view.get()
@unsigned_a_uint64.setter
def unsigned_a_uint64(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
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 = OgnTutorialSimpleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialSimpleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialSimpleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 20,824 | Python | 44.769231 | 201 | 0.618565 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialExtendedTypesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypes
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types.
"""
from typing import Any
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 OgnTutorialExtendedTypesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.flexible
inputs.floatOrToken
inputs.toNegate
inputs.tuple
Outputs:
outputs.doubledResult
outputs.flexible
outputs.negatedResult
outputs.tuple
"""
# 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:flexible', 'float[3][],token', 1, 'Flexible Values', 'Flexible data type input', {}, True, None, False, ''),
('inputs:floatOrToken', 'float,token', 1, 'Float Or Token', 'Attribute that can either be a float value or a token value', {}, True, None, False, ''),
('inputs:toNegate', 'bool[],float[]', 1, 'To Negate', 'Attribute that can either be an array of booleans or an array of floats', {}, True, None, False, ''),
('inputs:tuple', 'any', 2, 'Tuple Values', 'Variable size/type tuple values', {}, True, None, False, ''),
('outputs:doubledResult', 'any', 2, 'Doubled Input Value', "If the input 'simpleInput' is a float this is 2x the value.\nIf it is a token this contains the input token repeated twice.", {}, True, None, False, ''),
('outputs:flexible', 'float[3][],token', 1, 'Inverted Flexible Values', 'Flexible data type output', {}, True, None, False, ''),
('outputs:negatedResult', 'bool[],float[]', 1, 'Negated Array Values', "Result of negating the data from the 'toNegate' input", {}, True, None, False, ''),
('outputs:tuple', 'any', 2, 'Negative Tuple Values', 'Negated values of the tuple input', {}, 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 flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, True)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def floatOrToken(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.floatOrToken"""
return og.RuntimeAttribute(self._attributes.floatOrToken.get_attribute_data(), self._context, True)
@floatOrToken.setter
def floatOrToken(self, value_to_set: Any):
"""Assign another attribute's value to outputs.floatOrToken"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.floatOrToken.value = value_to_set.value
else:
self.floatOrToken.value = value_to_set
@property
def toNegate(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.toNegate"""
return og.RuntimeAttribute(self._attributes.toNegate.get_attribute_data(), self._context, True)
@toNegate.setter
def toNegate(self, value_to_set: Any):
"""Assign another attribute's value to outputs.toNegate"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.toNegate.value = value_to_set.value
else:
self.toNegate.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, True)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.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 doubledResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.doubledResult"""
return og.RuntimeAttribute(self._attributes.doubledResult.get_attribute_data(), self._context, False)
@doubledResult.setter
def doubledResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.doubledResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.doubledResult.value = value_to_set.value
else:
self.doubledResult.value = value_to_set
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, False)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def negatedResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.negatedResult"""
return og.RuntimeAttribute(self._attributes.negatedResult.get_attribute_data(), self._context, False)
@negatedResult.setter
def negatedResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.negatedResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.negatedResult.value = value_to_set.value
else:
self.negatedResult.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, False)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.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 = OgnTutorialExtendedTypesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialExtendedTypesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialExtendedTypesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,390 | Python | 49.687805 | 221 | 0.648893 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundleAddAttributesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributes
This is a tutorial node. It exercises functionality for adding and removing attributes on output bundles.
"""
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 OgnTutorialBundleAddAttributesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.addedAttributeNames
inputs.removedAttributeNames
inputs.typesToAdd
inputs.useBatchedAPI
Outputs:
outputs.bundle
"""
# 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:addedAttributeNames', 'token[]', 0, None, "Names for the attribute types to be added. The size of this array must match the size\nof the 'typesToAdd' array to be legal.", {}, True, [], False, ''),
('inputs:removedAttributeNames', 'token[]', 0, None, 'Names for the attribute types to be removed. Non-existent attributes will be ignored.', {}, True, [], False, ''),
('inputs:typesToAdd', 'token[]', 0, 'Attribute Types To Add', 'List of type descriptions to add to the bundle. The strings in this list correspond to the\nstrings that represent the attribute types in the .ogn file (e.g. float[3][], colord[3], bool', {}, True, [], False, ''),
('inputs:useBatchedAPI', 'bool', 0, None, 'Controls whether or not to used batched APIS for adding/removing attributes', {}, True, False, False, ''),
('outputs:bundle', 'bundle', 0, 'Constructed Bundle', 'This is the bundle with all attributes added by compute.', {}, 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.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._batchedReadAttributes = []
self._batchedReadValues = []
@property
def addedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
return data_view.get()
@addedAttributeNames.setter
def addedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.addedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
data_view.set(value)
self.addedAttributeNames_size = data_view.get_array_size()
@property
def removedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
return data_view.get()
@removedAttributeNames.setter
def removedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.removedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
data_view.set(value)
self.removedAttributeNames_size = data_view.get_array_size()
@property
def typesToAdd(self):
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
return data_view.get()
@typesToAdd.setter
def typesToAdd(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.typesToAdd)
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
data_view.set(value)
self.typesToAdd_size = data_view.get_array_size()
@property
def useBatchedAPI(self):
data_view = og.AttributeValueHelper(self._attributes.useBatchedAPI)
return data_view.get()
@useBatchedAPI.setter
def useBatchedAPI(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.useBatchedAPI)
data_view = og.AttributeValueHelper(self._attributes.useBatchedAPI)
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 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
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 = OgnTutorialBundleAddAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundleAddAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundleAddAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,372 | Python | 49.137724 | 284 | 0.671046 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStatePyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.StatePy
This is a tutorial node. It makes use of internal state information to continuously increment an output.
"""
import carb
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 OgnTutorialStatePyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.StatePy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.override
inputs.overrideValue
Outputs:
outputs.monotonic
"""
# 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:override', 'bool', 0, None, 'When true get the output from the overrideValue, otherwise use the internal value', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:overrideValue', 'int64', 0, None, "Value to use instead of the monotonically increasing internal one when 'override' is true", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:monotonic', 'int64', 0, None, 'Monotonically increasing output, set by internal state information', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"override", "overrideValue", "_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.override, self._attributes.overrideValue]
self._batchedReadValues = [False, 0]
@property
def override(self):
return self._batchedReadValues[0]
@override.setter
def override(self, value):
self._batchedReadValues[0] = value
@property
def overrideValue(self):
return self._batchedReadValues[1]
@overrideValue.setter
def overrideValue(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 = {"monotonic", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def monotonic(self):
value = self._batchedWriteValues.get(self._attributes.monotonic)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
self._batchedWriteValues[self._attributes.monotonic] = 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 = OgnTutorialStatePyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStatePyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStatePyDatabase.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(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.StatePy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialStatePyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialStatePyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialStatePyDatabase(node)
try:
compute_function = getattr(OgnTutorialStatePyDatabase.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 OgnTutorialStatePyDatabase.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):
OgnTutorialStatePyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialStatePyDatabase.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(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialStatePyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialStatePyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialStatePyDatabase.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(OgnTutorialStatePyDatabase.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.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Internal States")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It makes use of internal state information to continuously increment an output.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.StatePy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialStatePyDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialStatePyDatabase.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):
OgnTutorialStatePyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialStatePyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.StatePy")
| 12,036 | Python | 46.203921 | 197 | 0.638003 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialArrayDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ArrayData
This is a tutorial node. It will compute the array 'result' as the input array 'original' with every element multiplied
by the constant 'multiplier'.
"""
import carb
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 OgnTutorialArrayDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ArrayData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.gates
inputs.info
inputs.multiplier
inputs.original
Outputs:
outputs.infoSize
outputs.negativeValues
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:gates', 'bool[]', 0, None, 'Boolean mask telling which elements of the array should be multiplied', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:info', 'token[]', 0, None, 'List of strings providing commentary', {ogn.MetadataKeys.DEFAULT: '["There", "is", "no", "data"]'}, True, ['There', 'is', 'no', 'data'], False, ''),
('inputs:multiplier', 'float', 0, None, 'Multiplier of the array elements', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:original', 'float[]', 0, None, 'Array to be multiplied', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:infoSize', 'int', 0, None, 'Number of letters in all strings in the info input', {}, True, None, False, ''),
('outputs:negativeValues', 'bool[]', 0, None, "Array of booleans set to true if the corresponding 'result' is negative", {}, True, None, False, ''),
('outputs:result', 'float[]', 0, None, 'Multiplied array', {}, 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 gates(self):
data_view = og.AttributeValueHelper(self._attributes.gates)
return data_view.get()
@gates.setter
def gates(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gates)
data_view = og.AttributeValueHelper(self._attributes.gates)
data_view.set(value)
self.gates_size = data_view.get_array_size()
@property
def info(self):
data_view = og.AttributeValueHelper(self._attributes.info)
return data_view.get()
@info.setter
def info(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.info)
data_view = og.AttributeValueHelper(self._attributes.info)
data_view.set(value)
self.info_size = data_view.get_array_size()
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
return data_view.get()
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.set(value)
@property
def original(self):
data_view = og.AttributeValueHelper(self._attributes.original)
return data_view.get()
@original.setter
def original(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.original)
data_view = og.AttributeValueHelper(self._attributes.original)
data_view.set(value)
self.original_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.negativeValues_size = None
self.result_size = None
self._batchedWriteValues = { }
@property
def infoSize(self):
data_view = og.AttributeValueHelper(self._attributes.infoSize)
return data_view.get()
@infoSize.setter
def infoSize(self, value):
data_view = og.AttributeValueHelper(self._attributes.infoSize)
data_view.set(value)
@property
def negativeValues(self):
data_view = og.AttributeValueHelper(self._attributes.negativeValues)
return data_view.get(reserved_element_count=self.negativeValues_size)
@negativeValues.setter
def negativeValues(self, value):
data_view = og.AttributeValueHelper(self._attributes.negativeValues)
data_view.set(value)
self.negativeValues_size = data_view.get_array_size()
@property
def result(self):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get(reserved_element_count=self.result_size)
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
data_view.set(value)
self.result_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 = OgnTutorialArrayDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialArrayDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialArrayDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,507 | Python | 44.989189 | 193 | 0.645233 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuBundlesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundles
This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles
whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found,
computes their dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results
are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This
node is identical to OgnTutorialCpuGpuBundlesPy.ogn, except it is implemented in C++.
"""
import carb
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 OgnTutorialCpuGpuBundlesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundles
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuBundle
inputs.gpu
inputs.gpuBundle
Outputs:
outputs.cpuGpuBundle
Predefined Tokens:
tokens.points
tokens.dotProducts
"""
# 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:cpuBundle', 'bundle', 0, 'CPU Input Bundle', 'Input bundle whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then copy gpuBundle onto the output, otherwise copy cpuBundle', {}, True, False, False, ''),
('inputs:gpuBundle', 'bundle', 0, 'GPU Input Bundle', 'Input bundle whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuBundle', 'bundle', 0, 'Constructed Bundle', "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this\nbundle's contents will be entirely on the GPU, otherwise they will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, True, None, False, ''),
])
class tokens:
points = "points"
dotProducts = "dotProducts"
@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.cpuBundle = og.AttributeRole.BUNDLE
role_data.inputs.gpuBundle = og.AttributeRole.BUNDLE
role_data.outputs.cpuGpuBundle = 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, ['inputs:gpuBundle'], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def cpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.cpuBundle"""
return self.__bundles.cpuBundle
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def gpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.gpuBundle"""
return self.__bundles.gpuBundle
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, ['outputs_cpuGpuBundle'], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def cpuGpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.cpuGpuBundle"""
return self.__bundles.cpuGpuBundle
@cpuGpuBundle.setter
def cpuGpuBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.cpuGpuBundle 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.cpuGpuBundle.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 = OgnTutorialCpuGpuBundlesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuBundlesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuBundlesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,696 | Python | 50.313333 | 305 | 0.680223 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTokensDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.Tokens
This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has
been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token
list.
"""
import carb
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 OgnTutorialTokensDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.Tokens
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.valuesToCheck
Outputs:
outputs.isColor
Predefined Tokens:
tokens.red
tokens.green
tokens.blue
"""
# 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:valuesToCheck', 'token[]', 0, None, 'Array of tokens that are to be checked', {}, True, [], False, ''),
('outputs:isColor', 'bool[]', 0, None, 'True values if the corresponding input value appears in the token list', {}, True, None, False, ''),
])
class tokens:
red = "red"
green = "green"
blue = "blue"
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 valuesToCheck(self):
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
return data_view.get()
@valuesToCheck.setter
def valuesToCheck(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.valuesToCheck)
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
data_view.set(value)
self.valuesToCheck_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.isColor_size = None
self._batchedWriteValues = { }
@property
def isColor(self):
data_view = og.AttributeValueHelper(self._attributes.isColor)
return data_view.get(reserved_element_count=self.isColor_size)
@isColor.setter
def isColor(self, value):
data_view = og.AttributeValueHelper(self._attributes.isColor)
data_view.set(value)
self.isColor_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 = OgnTutorialTokensDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTokensDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTokensDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,709 | Python | 44.31746 | 148 | 0.673148 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialSimpleDataPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.SimpleDataPy
This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are
modified in a simple way so that the compute modifies values. It is the same as node omni.graph.tutorials.SimpleData, except
it is implemented in Python instead of C++.
"""
import carb
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 OgnTutorialSimpleDataPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.SimpleDataPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_bool
inputs.a_constant_input
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int64
inputs.a_objectId
inputs.a_path
inputs.a_string
inputs.a_token
inputs.a_uchar
inputs.a_uint
inputs.a_uint64
Outputs:
outputs.a_a_boolUiName
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int64
outputs.a_nodeTypeUiName
outputs.a_objectId
outputs.a_path
outputs.a_string
outputs.a_token
outputs.a_uchar
outputs.a_uint
outputs.a_uint64
"""
# 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_bool', 'bool', 0, 'Simple Boolean Input', 'This is an attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'true'}, False, True, False, ''),
('inputs:a_constant_input', 'int', 0, None, 'This is an input attribute whose value can be set but can only be connected as a source.', {ogn.MetadataKeys.OUTPUT_ONLY: '1'}, True, 0, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_half', 'half', 0, None, 'This is an attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_objectId', 'objectId', 0, None, 'This is an attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_path', 'path', 0, None, 'This is an attribute of type path', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {ogn.MetadataKeys.DEFAULT: '"helloString"'}, True, "helloString", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"helloToken"'}, True, "helloToken", False, ''),
('inputs:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:a_a_boolUiName', 'string', 0, None, 'Computed attribute containing the UI name of input a_bool', {}, True, None, False, ''),
('outputs:a_bool', 'bool', 0, None, 'This is a computed attribute of type boolean', {}, True, None, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {}, True, None, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {}, True, None, False, ''),
('outputs:a_half', 'half', 0, None, 'This is a computed attribute of type 16 bit float', {}, True, None, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {}, True, None, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {}, True, None, False, ''),
('outputs:a_nodeTypeUiName', 'string', 0, None, 'Computed attribute containing the UI name of this node type', {}, True, None, False, ''),
('outputs:a_objectId', 'objectId', 0, None, 'This is a computed attribute of type objectId', {}, True, None, False, ''),
('outputs:a_path', 'path', 0, None, 'This is a computed attribute of type path', {ogn.MetadataKeys.DEFAULT: '"/Child"'}, True, "/Child", False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {ogn.MetadataKeys.DEFAULT: '"This string is empty"'}, True, "This string is empty", False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {}, True, None, False, ''),
('outputs:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {}, True, None, False, ''),
('outputs:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {}, True, None, False, ''),
('outputs:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {}, 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.a_objectId = og.AttributeRole.OBJECT_ID
role_data.inputs.a_path = og.AttributeRole.PATH
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_a_boolUiName = og.AttributeRole.TEXT
role_data.outputs.a_nodeTypeUiName = og.AttributeRole.TEXT
role_data.outputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.outputs.a_path = og.AttributeRole.PATH
role_data.outputs.a_string = og.AttributeRole.TEXT
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"a_bool", "a_constant_input", "a_double", "a_float", "a_half", "a_int", "a_int64", "a_objectId", "a_path", "a_string", "a_token", "a_uchar", "a_uint", "a_uint64", "_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.a_bool, self._attributes.a_constant_input, self._attributes.a_double, self._attributes.a_float, self._attributes.a_half, self._attributes.a_int, self._attributes.a_int64, self._attributes.a_objectId, self._attributes.a_path, self._attributes.a_string, self._attributes.a_token, self._attributes.a_uchar, self._attributes.a_uint, self._attributes.a_uint64]
self._batchedReadValues = [True, 0, 0, 0, 0.0, 0, 0, 0, "", "helloString", "helloToken", 0, 0, 0]
@property
def a_bool(self):
return self._batchedReadValues[0]
@a_bool.setter
def a_bool(self, value):
self._batchedReadValues[0] = value
@property
def a_constant_input(self):
return self._batchedReadValues[1]
@a_constant_input.setter
def a_constant_input(self, value):
self._batchedReadValues[1] = value
@property
def a_double(self):
return self._batchedReadValues[2]
@a_double.setter
def a_double(self, value):
self._batchedReadValues[2] = value
@property
def a_float(self):
return self._batchedReadValues[3]
@a_float.setter
def a_float(self, value):
self._batchedReadValues[3] = value
@property
def a_half(self):
return self._batchedReadValues[4]
@a_half.setter
def a_half(self, value):
self._batchedReadValues[4] = value
@property
def a_int(self):
return self._batchedReadValues[5]
@a_int.setter
def a_int(self, value):
self._batchedReadValues[5] = value
@property
def a_int64(self):
return self._batchedReadValues[6]
@a_int64.setter
def a_int64(self, value):
self._batchedReadValues[6] = value
@property
def a_objectId(self):
return self._batchedReadValues[7]
@a_objectId.setter
def a_objectId(self, value):
self._batchedReadValues[7] = value
@property
def a_path(self):
return self._batchedReadValues[8]
@a_path.setter
def a_path(self, value):
self._batchedReadValues[8] = value
@property
def a_string(self):
return self._batchedReadValues[9]
@a_string.setter
def a_string(self, value):
self._batchedReadValues[9] = value
@property
def a_token(self):
return self._batchedReadValues[10]
@a_token.setter
def a_token(self, value):
self._batchedReadValues[10] = value
@property
def a_uchar(self):
return self._batchedReadValues[11]
@a_uchar.setter
def a_uchar(self, value):
self._batchedReadValues[11] = value
@property
def a_uint(self):
return self._batchedReadValues[12]
@a_uint.setter
def a_uint(self, value):
self._batchedReadValues[12] = value
@property
def a_uint64(self):
return self._batchedReadValues[13]
@a_uint64.setter
def a_uint64(self, value):
self._batchedReadValues[13] = 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 = {"a_a_boolUiName", "a_bool", "a_double", "a_float", "a_half", "a_int", "a_int64", "a_nodeTypeUiName", "a_objectId", "a_path", "a_string", "a_token", "a_uchar", "a_uint", "a_uint64", "_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.a_a_boolUiName_size = None
self.a_nodeTypeUiName_size = None
self.a_path_size = 6
self.a_string_size = 20
self._batchedWriteValues = { }
@property
def a_a_boolUiName(self):
value = self._batchedWriteValues.get(self._attributes.a_a_boolUiName)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_a_boolUiName)
return data_view.get()
@a_a_boolUiName.setter
def a_a_boolUiName(self, value):
self._batchedWriteValues[self._attributes.a_a_boolUiName] = value
@property
def a_bool(self):
value = self._batchedWriteValues.get(self._attributes.a_bool)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
self._batchedWriteValues[self._attributes.a_bool] = value
@property
def a_double(self):
value = self._batchedWriteValues.get(self._attributes.a_double)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
self._batchedWriteValues[self._attributes.a_double] = value
@property
def a_float(self):
value = self._batchedWriteValues.get(self._attributes.a_float)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
self._batchedWriteValues[self._attributes.a_float] = value
@property
def a_half(self):
value = self._batchedWriteValues.get(self._attributes.a_half)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
self._batchedWriteValues[self._attributes.a_half] = value
@property
def a_int(self):
value = self._batchedWriteValues.get(self._attributes.a_int)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
self._batchedWriteValues[self._attributes.a_int] = value
@property
def a_int64(self):
value = self._batchedWriteValues.get(self._attributes.a_int64)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
self._batchedWriteValues[self._attributes.a_int64] = value
@property
def a_nodeTypeUiName(self):
value = self._batchedWriteValues.get(self._attributes.a_nodeTypeUiName)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_nodeTypeUiName)
return data_view.get()
@a_nodeTypeUiName.setter
def a_nodeTypeUiName(self, value):
self._batchedWriteValues[self._attributes.a_nodeTypeUiName] = value
@property
def a_objectId(self):
value = self._batchedWriteValues.get(self._attributes.a_objectId)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
self._batchedWriteValues[self._attributes.a_objectId] = value
@property
def a_path(self):
value = self._batchedWriteValues.get(self._attributes.a_path)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get()
@a_path.setter
def a_path(self, value):
self._batchedWriteValues[self._attributes.a_path] = value
@property
def a_string(self):
value = self._batchedWriteValues.get(self._attributes.a_string)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
self._batchedWriteValues[self._attributes.a_string] = value
@property
def a_token(self):
value = self._batchedWriteValues.get(self._attributes.a_token)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
self._batchedWriteValues[self._attributes.a_token] = value
@property
def a_uchar(self):
value = self._batchedWriteValues.get(self._attributes.a_uchar)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
self._batchedWriteValues[self._attributes.a_uchar] = value
@property
def a_uint(self):
value = self._batchedWriteValues.get(self._attributes.a_uint)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
self._batchedWriteValues[self._attributes.a_uint] = value
@property
def a_uint64(self):
value = self._batchedWriteValues.get(self._attributes.a_uint64)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
self._batchedWriteValues[self._attributes.a_uint64] = 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 = OgnTutorialSimpleDataPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialSimpleDataPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialSimpleDataPyDatabase.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(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.SimpleDataPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialSimpleDataPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialSimpleDataPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialSimpleDataPyDatabase(node)
try:
compute_function = getattr(OgnTutorialSimpleDataPyDatabase.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 OgnTutorialSimpleDataPyDatabase.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):
OgnTutorialSimpleDataPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialSimpleDataPyDatabase.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(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialSimpleDataPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialSimpleDataPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialSimpleDataPyDatabase.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(OgnTutorialSimpleDataPyDatabase.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.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Attributes With Simple Data")
node_type.set_metadata(ogn.MetadataKeys.ICON_COLOR, "#FF00FF00")
node_type.set_metadata(ogn.MetadataKeys.ICON_BACKGROUND_COLOR, "#7FFF0000")
node_type.set_metadata(ogn.MetadataKeys.ICON_BORDER_COLOR, "#FF0000FF")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are modified in a simple way so that the compute modifies values. It is the same as node omni.graph.tutorials.SimpleData, except it is implemented in Python instead of C++.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.SimpleDataPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialSimpleDataPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialSimpleDataPyDatabase.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):
OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialSimpleDataPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.SimpleDataPy")
| 27,413 | Python | 44.163097 | 415 | 0.605735 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial2/tutorial2.rst | .. _ogn_tutorial_simpleData:
Tutorial 2 - Simple Data Node
=============================
The simple data node creates one input attribute and one output attribute of each of the simple types, where "simple"
refers to data types that have a single component and are not arrays. (e.g. "float" is simple, "float[3]" is not, nor is
"float[]"). See also :ref:`ogn_tutorial_simpleDataPy` for a similar example in Python.
OgnTutorialSimpleData.ogn
-------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.SimpleData", which has one
input and one output attribute of each simple type.
.. literalinclude:: OgnTutorialSimpleData.ogn
:linenos:
:language: json
OgnTutorialSimpleData.cpp
-------------------------
The *cpp* file contains the implementation of the compute method, which modifies
each of the inputs in a simple way to create outputs that have different values.
.. literalinclude:: OgnTutorialSimpleData.cpp
:linenos:
:language: c++
Note how the attribute values are available through the OgnTutorialSimpleDataDatabase class. The generated interface
creates access methods for every attribute, named for the attribute itself. Inputs will be returned as const
references, outputs will be returned as non-const references.
Attribute Data
--------------
Two types of attribute data are created, which help with ease of access and of use - the attribute name lookup
information, and the attribute type definition.
Attribute data is accessed via a name-based lookup. This is not particularly efficient, so to facilitate this process
the attribute name is translated into a fast access token. In addition, the information about the attribute's type and
default value is constant for all nodes of the same type so that is stored as well, in static data.
Normally you would use an *auto* declaration for attribute types. Sometimes you want to pass around attribute data so
it is helpful to have access to the attribute's data type. In the generated code a ``using namespace`` is set up to
provide a very simple syntax for accessing the attribute's metadata from within the node:
.. code-block:: c++
std::cout << "Attribute name is " << inputs::a_bool.m_name << std::endl;
std::cout << "Attribute type is " << inputs::a_bool.m_dataType << std::endl;
extern "C" void processAttribute(inputs::a_bool_t& value);
// Equivalent to extern "C" void processAttribute(bool& value);
Attribute Data Access
---------------------
The attributes are automatically namespaced with *inputs* and *outputs*. In the USD file the attribute names
will appear as *inputs:XXX* or *outputs:XXX*. In the C++ interface the colon is illegal so a contained struct
is used to make use of the period equivalent, as *inputs.XXX* or *outputs.XXX*.
The minimum information provided by these wrapper classes is a reference to the underlying data, accessed by
``operator()``. For this class, these are the types it provides:
+--------------------+--------------------+
| Database Function | Returned Type |
+====================+====================+
| inputs.a_bool() | const bool& |
+--------------------+--------------------+
| inputs.a_half() | const pxr::GfHalf& |
+--------------------+--------------------+
| inputs.a_int() | const int& |
+--------------------+--------------------+
| inputs.a_int64() | const int64_t& |
+--------------------+--------------------+
| inputs.a_float() | const float& |
+--------------------+--------------------+
| inputs.a_double() | const double& |
+--------------------+--------------------+
| inputs.a_path() | const std::string& |
+--------------------+--------------------+
| inputs.a_string() | const std::string& |
+--------------------+--------------------+
| inputs.a_token() | const NameToken& |
+--------------------+--------------------+
| outputs.a_bool() | bool& |
+--------------------+--------------------+
| outputs.a_half() | pxr::GfHalf& |
+--------------------+--------------------+
| outputs.a_int() | int& |
+--------------------+--------------------+
| outputs.a_int64() | int64_t& |
+--------------------+--------------------+
| outputs.a_float() | float& |
+--------------------+--------------------+
| outputs.a_double() | double& |
+--------------------+--------------------+
| outputs.a_string() | std::string& |
+--------------------+--------------------+
| outputs.a_token() | NameToken& |
+--------------------+--------------------+
The data returned are all references to the real data in the FlatCache, our managed memory store, pointed to the
correct location at evaluation time.
Note how input attributes return *const* data while output attributes do not. This reinforces the restriction that
input data should never be written to, as it would cause graph synchronization problems.
The type *pxr::GfHalf* is an implementation of a 16-bit floating point value, though any other may also be used with
a runtime cast of the value. *omni::graph::core::NameToken* is a simple token through which a unique string can be
looked up at runtime.
Helpers
-------
A few helpers are provided in the database class definition to help make coding with it more natural.
initializeType
++++++++++++++
Function signature ``static void initializeType(const NodeTypeObj& nodeTypeObj)`` is an implementation of the ABI
function that is called once for each node type, initializing such things as its mandatory attributes and their default
values.
validate
++++++++
Function signature ``bool validate()``. If any of the mandatory attributes do not have values then the generated code
will exit early with an error message and not actually call the node's compute method.
token
+++++
Function signature ``NameToken token(const char* tokenName)``.
Provides a simple conversion from a string to the unique token representing that string, for fast comparison of
strings and for use with the attributes whose data types are *token*.
Compute Status Logging
++++++++++++++++++++++
Two helper functions are providing in the database class to help provide more information when the compute method of
a node has failed. Two methods are provided, both taking printf-like variable sets of parameters.
``void logError(Args...)`` is used when the compute has run into some inconsistent or unexpected data, such as two
input arrays that are supposed to have the same size but do not, like the normals and vertexes on a mesh.
``void logWarning(Args...)`` can be used when the compute has hit an unusual case but can still provide a consistent
output for it, for example the deformation of an empty mesh would result in an empty mesh and a warning since that is
not a typical use for the node.
typedefs
++++++++
Although not part of the database class per se, a typedef alias is created for every attribute so that you can
use its type directly without knowing the detailed type; a midway point between exact types and *auto*. The main
use for such types might be passing attribute data between functions.
Here are the corresponding typedef names for each of the attributes:
+--------------------+--------------------+
| Typedef Alias | Actual Type |
+====================+====================+
| inputs.a_bool_t | const bool& |
+--------------------+--------------------+
| inputs.a_half_t | const pxr::GfHalf& |
+--------------------+--------------------+
| inputs.a_int_t | const int& |
+--------------------+--------------------+
| inputs.a_int64_t | const int64_t& |
+--------------------+--------------------+
| inputs.a_float_t | const float& |
+--------------------+--------------------+
| inputs.a_double_t | const double& |
+--------------------+--------------------+
| inputs.a_token_t | const NameToken& |
+--------------------+--------------------+
| outputs.a_bool_t | bool& |
+--------------------+--------------------+
| outputs.a_half_t | pxr::GfHalf& |
+--------------------+--------------------+
| outputs.a_int_t | int& |
+--------------------+--------------------+
| outputs.a_int64_t | int64_t& |
+--------------------+--------------------+
| outputs.a_float_t | float& |
+--------------------+--------------------+
| outputs.a_double_t | double& |
+--------------------+--------------------+
| outputs.a_token_t | NameToken& |
+--------------------+--------------------+
Notice the similarity between this table and the one above. The typedef name is formed by adding the extension *_t*
to the attribute accessor name, similar to C++ standard type naming conventions. The typedef should always correspond
to the return value of the attribute's ``operator()``.
Direct ABI Access
+++++++++++++++++
All of the generated database classes provide access to the underlying *INodeType* ABI for those rare situations
where you want to access the ABI directly. There are two methods provided, which correspond to the objects passed
in to the ABI compute method.
Context function signature ``const GraphContextObj& abi_context() const``, for accessing the underlying OmniGraph
evaluation context and its interface.
Node function signature ``const NodeObj& nodeObj abi_node() const``, for accessing the underlying OmniGraph node
object and its interface.
In addition, the attribute ABI objects are extracted into a shared structure so that they can be accessed in a
manner similar to the attribute data. For example ``db.attributes.inputs.a_bool()`` returns the `AttributeObj` that
refers to the input attribute named `a_bool`. It can be used to directly call ABI functions when required, though
again it should be emphasized that this will be a rare occurrence - all of the common operations can be performed
more easily using the database interfaces.
Node Computation Tests
----------------------
The "tests" section of the .ogn file contains a list of tests consisting of a description and attribute values,
both inputs and outputs, that will be used for the test.
The test runs by setting all of the named input attributes to their values, running the compute, then comparing the
resulting output attribute values against those specified by the test.
For example to test the computation of the boolean attribute, whose output is the negation of the input, these
two test values could be specified:
.. code::json
{
"tests": [
{
"description": "Check that true becomes false",
"inputs": {
"a_bool": true
},
"outputs": {
"a_bool": false
}
}
]
}
The "description" field is optional, though highly recommended to aid in debugging which tests are failing.
Any unspecified inputs take their default value, and any unspecified outputs do not get checked after the compute.
For simple attribute lists an abbreviated version of the syntax can be used, where the inputs and outputs get their
fully namespaced names so that there is no need for the "inputs" and "outputs" objects.
.. code::json
{
"tests": [
{
"description": "Check that false becomes true",
"inputs:a_bool": false,
"outputs:a_bool": true
}
]
}
| 11,492 | reStructuredText | 44.607143 | 120 | 0.607031 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial2/OgnTutorialSimpleData.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 <OgnTutorialSimpleDataDatabase.h>
#include <string>
// Even though the path is stored as a string this tutorial will use the SdfPath API to manipulate it
#include <pxr/usd/sdf/path.h>
// This class exercises access to the DataModel through the generated database class for all simple data types
// It's a good practice to namespace your nodes, so that they are guaranteed to be unique. Using this practice
// you can shorten your class names as well. This class could have equally been named "OgnSimpleData", since
// the "Tutorial" part of it is just another incarnation of the namespace.
namespace omni
{
namespace graph
{
namespace core
{
namespace tutorial
{
class OgnTutorialSimpleData
{
public:
static bool compute(OgnTutorialSimpleDataDatabase& db)
{
// Inside the database the contained object "inputs" holds the data references for all input attributes and the
// contained object "outputs" holds the data references for all output attributes.
// Each of the attribute accessors are named for the name of the attribute, with the ":" replaced by "_".
// The colon is used in USD as a convention for creating namespaces so it's safe to replace it without
// modifying the meaning. The "inputs:" and "outputs:" prefixes in the generated attributes are matched
// by the container names.
//
// For example attribute "inputs:translate:x" would be accessible as "db.inputs.translate_x" and attribute
// "outputs:matrix" would be accessible as "db.outputs.matrix".
// The "compute" of this method modifies each attribute in a subtle way so that a test can be written
// to verify the operation of the node. See the .ogn file for a description of tests.
db.outputs.a_bool() = !db.inputs.a_bool();
db.outputs.a_half() = 1.0f + db.inputs.a_half();
db.outputs.a_int() = 1 + db.inputs.a_int();
db.outputs.a_int64() = 1 + db.inputs.a_int64();
db.outputs.a_double() = 1.0 + db.inputs.a_double();
db.outputs.a_float() = 1.0f + db.inputs.a_float();
db.outputs.a_objectId() = 1 + db.inputs.a_objectId();
// The namespace separator ":" has special meaning in C++ so it is replaced by "_" when it appears in names
// Attribute "outputs:unsigned:a_uchar" becomes "outputs.unsigned_a_uchar".
db.outputs.unsigned_a_uchar() = 1 + db.inputs.unsigned_a_uchar();
db.outputs.unsigned_a_uint() = 1 + db.inputs.unsigned_a_uint();
db.outputs.unsigned_a_uint64() = 1 + db.inputs.unsigned_a_uint64();
// Internally the string type is more akin to a std::string_view, not available until C++17.
// The data is a pair of (const char*, size_t), but the interface provided through the accessor is
// castable to a std::string.
//
// This code shows the recommended way to use it, extracting inputs into a std::string for manipulation and
// then assigning outputs from the results. Using the referenced object directly could cause a lot of
// unnecessary fabric allocations. (i.e. avoid auto& outputStringView = db.outputs.a_string())
std::string outputString(db.inputs.a_string());
if (outputString.length() > 0)
{
auto foundStringAt = outputString.find("hello");
if (foundStringAt != std::string::npos)
{
outputString.replace(foundStringAt, 5, "world");
}
db.outputs.a_string() = outputString;
}
else
{
db.outputs.a_string() = "";
}
// The token interface is made available in the database as well, for convenience.
// By calling "db.stringToToken()" you can look up the token ID of a given string.
// There is also a symmetrical "db.tokenToString()" for going the other way.
std::string outputTokenString = db.tokenToString(db.inputs.a_token());
if (outputTokenString.length() > 0)
{
auto foundTokenAt = outputTokenString.find("hello");
if (foundTokenAt != std::string::npos)
{
outputTokenString.replace(foundTokenAt, 5, "world");
db.outputs.a_token() = db.stringToToken(outputTokenString.c_str());
}
}
else
{
db.outputs.a_token() = db.stringToToken("");
}
// Path just gets a new child named "Child". There's not requirement that the path point to anything
// that exists in the scene so any string will work here.
//
std::string outputPath = (std::string)db.inputs.a_path();
// In the implementation the string is manipulated directly, as it does not care if the SdfPath is valid or
// not. If you want to manipulate it using the pxr::SdfPath API this is how you could do it:
//
// pxr::SdfPath sdfPath{outputPath};
// pxr::TfToken childToken{asTfToken(db.stringToToken("/Child"))};
// if (sdfPath.IsValid())
// {
// db.outputs.a_path() = sdfPath.AppendChild(childToken).GetString();
// }
//
outputPath += "/Child";
db.outputs.a_path() = outputPath;
// Drop down to the ABI to find attribute metadata, currently not available through the database
auto& nodeObj = db.abi_node();
auto attributeObj = nodeObj.iNode->getAttribute(nodeObj, "inputs:a_bool");
// The hardcoded metadata keyword is available through the node
auto uiName = attributeObj.iAttribute->getMetadata(attributeObj, kOgnMetadataUiName);
std::string expectedUiName{ "Sample Boolean Input" };
CARB_ASSERT(uiName && (expectedUiName == uiName));
// Confirm that the piece of metadata that differentiates objectId from regular uint64 is in place
auto objectIdAttributeObj = nodeObj.iNode->getAttribute(nodeObj, "inputs:a_objectId");
auto objectIdMetadata = attributeObj.iAttribute->getMetadata(objectIdAttributeObj, kOgnMetadataObjectId);
CARB_ASSERT(objectIdMetadata);
return true;
}
};
// namespaces are closed after the registration macro, to ensure the correct class is registered
REGISTER_OGN_NODE()
} // namespace tutorial
} // namespace core
} // namespace graph
} // namespace omni
| 6,814 | C++ | 46.657342 | 119 | 0.657617 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial20/OgnTutorialTokens.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 <OgnTutorialTokensDatabase.h>
class OgnTutorialTokens
{
public:
static bool compute(OgnTutorialTokensDatabase& db)
{
const auto& valuesToCheck = db.inputs.valuesToCheck();
auto& isColor = db.outputs.isColor();
isColor.resize( valuesToCheck.size() );
if (valuesToCheck.size() == 0)
{
return true;
}
// Walk the list of inputs, setting the corresponding output to true if and only if the input is in
// the list of allowable tokens.
size_t index{ 0 };
for (const auto& inputValue : valuesToCheck)
{
// When the database is available you can use it to access the token values directly. When it is not
// you can access them statically (e.g. OgnTutorialTokensDatabase.token.red)
if ((inputValue == db.tokens.red) || (inputValue == db.tokens.green) || (inputValue == db.tokens.blue))
{
isColor[index] = true;
}
else
{
isColor[index] = false;
}
index++;
}
return true;
}
};
REGISTER_OGN_NODE()
| 1,617 | C++ | 32.708333 | 115 | 0.619666 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial20/OgnTutorialTokensPy.py | """
Implementation of a node handling hardcoded tokens. Tokens are a fixed set of strings, usually used for things
like keywords and enum names. In C++ tokens are more efficient than strings for lookup as they are represented
as a single long integer. The Python access methods are set up the same way, though at present there is no
differentiation between strings and tokens in Python code.
"""
class OgnTutorialTokensPy:
"""Exercise access to hardcoded tokens"""
@staticmethod
def compute(db) -> bool:
"""
Run through a list of input tokens and set booleans in a corresponding output array indicating if the
token appears in the list of hardcoded color names.
"""
values_to_check = db.inputs.valuesToCheck
# When assigning the entire array the size does not have to be set in advance
db.outputs.isColor = [value in [db.tokens.red, db.tokens.green, db.tokens.blue] for value in values_to_check]
return True
| 990 | Python | 38.639998 | 117 | 0.717172 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial20/tutorial20.rst | .. _ogn_tutorial_tokens:
Tutorial 20 - Tokens
====================
Tokens are a method of providing fast access to strings that have fixed contents. All strings with the same contents
can be translated into the same shared token. Token comparison is as fast as integer comparisons, rather than the more
expensive string comparisons you would need for a general string.
One example of where they are useful is in having a fixed set of allowable values for an input string. For example you
might choose a color channel by selecting from the names "red", "green", and "blue", or you might know that a mesh
bundle's contents always use the attribute names "normals", "points", and "faces".
Tokens can be accessed through the database methods ``tokenToString()`` and ``stringToToken()``. Using the ``tokens``
keyword in a .ogn file merely provides a shortcut to always having certain tokens available. In the color case then
if you have a token input containing the color your comparison code changes from this:
.. code-block:: c++
const auto& colorToken = db.inputs.colorToken();
if (colorToken == db.stringToToken("red"))
{
// do red stuff
}
else if (colorToken == db.stringToToken("green"))
{
// do green stuff
}
else if (colorToken == db.stringToToken("blue"))
{
// do blue stuff
}
to this, which has much faster comparison times:
.. code-block:: c++
const auto& colorToken = db.inputs.colorToken();
if (colorToken == db.tokens.red)
{
// do red stuff
}
else if (colorToken == db.tokens.green)
{
// do green stuff
}
else if (colorToken == db.tokens.blue)
{
// do blue stuff
}
In Python there isn't a first-class object that is a token but the same token access is provided for consistency:
.. code-block:: python
color_token = db.inputs.colorToken
if color_token == db.tokens.red:
# do red stuff
elif color_token == db.tokens.green:
# do green stuff
elif color_token == db.tokens.blue:
# do blue stuff
OgnTutorialTokens.ogn
---------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.Tokens", which contains some hardcoded
tokens to use in the compute method.
.. literalinclude:: OgnTutorialTokens.ogn
:linenos:
:language: json
OgnTutorialTokens.cpp
---------------------
The *cpp* file contains the implementation of the compute method. It illustrates how to access the hardcoded tokens
to avoid writing the boilerplate code yourself.
.. literalinclude:: OgnTutorialTokens.cpp
:linenos:
:language: c++
OgnTutorialTokensPy.py
----------------------
The *py* file contains the implementation of the compute method in Python. The .ogn file is the same as the above,
except for the addition of the implementation language key ``"language": "python"``. The compute follows the same
algorithm as the *cpp* equivalent.
.. literalinclude:: OgnTutorialTokensPy.py
:linenos:
:language: python
| 3,032 | reStructuredText | 32.32967 | 118 | 0.686016 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial7/tutorial7.rst | .. _ogn_tutorial_roleData:
Tutorial 7 - Role-Based Data Node
=================================
The role-based data node creates one input attribute and one output attribute of each of the role-based type. A
role-based type is defined as data with an underlying simple data type, with an interpretation of that simple
data, called a "role".
Examples of roles are **color**, **quat**, and **timecode**. For consistency the tuple counts for each of the
roles are included in the declaration so that the "shape" of the underlying data is more obvious.
OgnTutorialRoleData.ogn
-----------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.RoleData", which has one
input and one output attribute of each Role type.
.. literalinclude:: OgnTutorialRoleData.ogn
:linenos:
:language: json
OgnTutorialRoleData.cpp
-----------------------
The *cpp* file contains the implementation of the compute method, which modifies
each of the inputs by adding 1.0 to all components to create outputs that have different, testable, values.
.. literalinclude:: OgnTutorialRoleData.cpp
:linenos:
:language: c++
Role-Based Attribute Access
---------------------------
Here is a subset of the generated role-based attributes from the database. It contains color attributes, a matrix
attribute, and a timecode attribute. Notice how the underlying data types of the attributes are provided, again
with the ability to cast to different interface classes with the same memory layout.
+----------------------+-------------------+
| Database Function | Returned Type |
+======================+===================+
| inputs.a_color3d() | const GfVec3d& |
+----------------------+-------------------+
| inputs.a_color4f() | const GfVec4f& |
+----------------------+-------------------+
| inputs.a_frame() | const GfMatrix4d& |
+----------------------+-------------------+
| inputs.a_timecode() | const double& |
+----------------------+-------------------+
| outputs.a_color3d() | GfVec3d& |
+----------------------+-------------------+
| outputs.a_color4f() | GfVec4f& |
+----------------------+-------------------+
| outputs.a_frame() | GfMatrix4d& |
+----------------------+-------------------+
| outputs.a_timecode() | double& |
+----------------------+-------------------+
The full set of corresponding data types can be found in :ref:`ogn_attribute_roles`.
This role information is available on all attribute interfaces through the ``role()`` method. For example you can
find that the first attribute is a color by making this check:
.. code-block:: c++
static bool compute(OgnTutorialRoleDataDatabase& db)
{
if (db.inputs.a_color3d.role == eColor )
{
processValueAsAColor( db.inputs.a_color3d() );
}
}
| 2,856 | reStructuredText | 38.680555 | 113 | 0.576681 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial7/OgnTutorialRoleData.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 <OgnTutorialRoleDataDatabase.h>
// This class exercises access to the DataModel through the generated database class for all role-based data types
namespace
{
// Helper values to make it easy to add 1 to values of different lengths
GfHalf h1{ 1.0f };
GfVec2d increment2d{ 1.0, 1.0 };
GfVec2f increment2f{ 1.0f, 1.0f };
GfVec2h increment2h{ h1, h1 };
GfVec3d increment3d{ 1.0, 1.0, 1.0 };
GfVec3f increment3f{ 1.0f, 1.0f, 1.0f };
GfVec3h increment3h{ h1, h1, h1 };
GfVec4d increment4d{ 1.0, 1.0, 1.0, 1.0 };
GfVec4f increment4f{ 1.0f, 1.0f, 1.0f, 1.0f };
GfVec4h increment4h{ h1, h1, h1, h1 };
GfQuatd incrementQd{ 1.0, 1.0, 1.0, 1.0 };
GfQuatf incrementQf{ 1.0f, 1.0f, 1.0f, 1.0f };
GfQuath incrementQh{ h1, h1, h1, h1 };
GfMatrix4d incrementM4d{ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
GfMatrix3d incrementM3d{ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
GfMatrix2d incrementM2d{ 1.0, 1.0, 1.0, 1.0 };
}
// Helper macro to simplify the code but include all of the error checking
#define ComputeOne(ATTRIBUTE_NAME, INCREMENT_VARIABLE, ROLE_EXPECTED) \
foundError = false; \
if (db.inputs.ATTRIBUTE_NAME.role() != ROLE_EXPECTED) \
{ \
db.logWarning("Input role type %d != %d", (int)db.inputs.ATTRIBUTE_NAME.role(), (int)ROLE_EXPECTED); \
foundError = true; \
foundAnyErrors = true; \
} \
if (db.outputs.ATTRIBUTE_NAME.role() != ROLE_EXPECTED) \
{ \
db.logWarning("output role type %d != %d", (int)db.outputs.ATTRIBUTE_NAME.role(), (int)ROLE_EXPECTED); \
foundError = true; \
foundAnyErrors = true; \
} \
if (!foundError) \
{ \
db.outputs.ATTRIBUTE_NAME() = db.inputs.ATTRIBUTE_NAME() + INCREMENT_VARIABLE; \
}
class OgnTutorialRoleData
{
public:
static bool compute(OgnTutorialRoleDataDatabase& db)
{
// The roles for the attributes only serve to guide how to interpret them. When accessed from the
// database they take the form of their raw underlying type. For example a point3d will have the
// same GfVec3d type as a double[3], as will a vector3d and a normal3d.
// Keep track if any role errors were found with this, continuing to the end of evaluation after errors
bool foundAnyErrors{ false }; // Toggled on as soon as any error is found
bool foundError{ false }; // Toggled off and on for each attribute
// Walk through all of the data types, using the macro to perform error checking
ComputeOne(a_color3d, increment3d, AttributeRole::eColor);
ComputeOne(a_color3f, increment3f, AttributeRole::eColor);
ComputeOne(a_color3h, increment3h, AttributeRole::eColor);
//
ComputeOne(a_color4d, increment4d, AttributeRole::eColor);
ComputeOne(a_color4f, increment4f, AttributeRole::eColor);
ComputeOne(a_color4h, increment4h, AttributeRole::eColor);
//
ComputeOne(a_frame, incrementM4d, AttributeRole::eFrame);
//
ComputeOne(a_matrix2d, incrementM2d, AttributeRole::eMatrix
);
ComputeOne(a_matrix3d, incrementM3d, AttributeRole::eMatrix
);
ComputeOne(a_matrix4d, incrementM4d, AttributeRole::eMatrix
);
//
ComputeOne(a_normal3d, increment3d, AttributeRole::eNormal);
ComputeOne(a_normal3f, increment3f, AttributeRole::eNormal);
ComputeOne(a_normal3h, increment3h, AttributeRole::eNormal);
//
ComputeOne(a_point3d, increment3d, AttributeRole::ePosition);
ComputeOne(a_point3f, increment3f, AttributeRole::ePosition);
ComputeOne(a_point3h, increment3h, AttributeRole::ePosition);
//
ComputeOne(a_quatd, incrementQd, AttributeRole::eQuaternion);
ComputeOne(a_quatf, incrementQf, AttributeRole::eQuaternion);
ComputeOne(a_quath, incrementQh, AttributeRole::eQuaternion);
//
ComputeOne(a_texcoord2d, increment2d, AttributeRole::eTexCoord);
ComputeOne(a_texcoord2f, increment2f, AttributeRole::eTexCoord);
ComputeOne(a_texcoord2h, increment2h, AttributeRole::eTexCoord);
//
ComputeOne(a_texcoord3d, increment3d, AttributeRole::eTexCoord);
ComputeOne(a_texcoord3f, increment3f, AttributeRole::eTexCoord);
ComputeOne(a_texcoord3h, increment3h, AttributeRole::eTexCoord);
//
ComputeOne(a_timecode, 1.0, AttributeRole::eTimeCode);
//
ComputeOne(a_vector3d, increment3d, AttributeRole::eVector);
ComputeOne(a_vector3f, increment3f, AttributeRole::eVector);
ComputeOne(a_vector3h, increment3h, AttributeRole::eVector);
return foundAnyErrors;
}
};
REGISTER_OGN_NODE()
| 6,498 | C++ | 55.025862 | 120 | 0.538319 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial29/OgnTutorialVectorizedABIPassthrough.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 <OgnTutorialVectorizedABIPassthroughDatabase.h>
// The method used by the computation to perform the passthrough
// 0 = simple copy, no vectorization
#define TUTO_ABI_PASSTHROUGH_METHOD_SIMPLE 0
// 1 = vectorized copy by indexing the instance directly per attribute
#define TUTO_ABI_PASSTHROUGH_METHOD_ATTR 1
// 2 = vectorized copy by mutating attribute data handles
#define TUTO_ABI_PASSTHROUGH_METHOD_MUTATE 2
// 3 = vectorized copy using raw data
#define TUTO_ABI_PASSTHROUGH_METHOD_RAW 3
//By default, use the most efficient method
#define TUTO_ABI_PASSTHROUGH_METHOD TUTO_ABI_PASSTHROUGH_METHOD_RAW
// This node perform a copy of its input to its output
class OgnTutorialVectorizedABIPassthrough
{
public:
#if TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_SIMPLE
// begin-regular
static bool compute(GraphContextObj const& contextObj, NodeObj const& nodeObj)
{
NodeContextHandle nodeHandle = nodeObj.nodeContextHandle;
auto inputValueAttr =
getAttributeR(contextObj, nodeHandle, Token("inputs:value"), kAccordingToContextIndex);
const float* inputValue = getDataR<float>(contextObj, inputValueAttr);
auto outputValueAttr =
getAttributeW(contextObj, nodeHandle, Token("outputs:value"), kAccordingToContextIndex);
float* outputValue = getDataW<float>(contextObj, outputValueAttr);
if(inputValue && outputValue)
{
*outputValue = *inputValue;
return true;
}
return false;
}
// end-regular
#elif TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_ATTR
// begin-attr
static size_t computeVectorized(GraphContextObj const& contextObj, NodeObj const& nodeObj, size_t count)
{
GraphContextObj const* contexts = nullptr;
NodeObj const* nodes = nullptr;
//When using auto instancing, similiar graphs can get merged together, and computed vectorized
// In such case, each instance represent a different node in a different graph
// Accessing the data either through the provided node, or through the actual auto-insance node would work properly
// But any other ABI call requiring the node would need to provide the proper node
// While not necessary in this contezt, do the work of using the proper auto-instance node
// in order to demonstrate how to use it.
size_t handleCount = nodeObj.iNode->getAutoInstances(nodeObj, contexts, nodes);
auto nodeHandle = [&](InstanceIndex index) -> NodeContextHandle
{ return nodes[handleCount == 1 ? 0 : index.index].nodeContextHandle; };
auto context = [&](InstanceIndex index) -> GraphContextObj
{ return contexts[handleCount == 1 ? 0 : index.index]; };
size_t ret = 0;
const float* inputValue{ nullptr };
float* outputValue{ nullptr };
auto inToken = Token("inputs:value");
auto outToken = Token("outputs:value");
for (InstanceIndex idx{ 0 }; idx < InstanceIndex{ count }; ++idx)
{
auto inputValueAttr = getAttributeR(context(idx), nodeHandle(idx), inToken, idx);
inputValue = getDataR<float>(context(idx), inputValueAttr);
auto outputValueAttr = getAttributeW(context(idx), nodeHandle(idx), outToken, idx);
outputValue = getDataW<float>(context(idx), outputValueAttr);
if(inputValue && outputValue)
{
*outputValue = *inputValue;
++ret;
}
}
return ret;
}
// end-attr
#elif TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_MUTATE
// begin-mutate
static size_t computeVectorized(GraphContextObj const& contextObj, NodeObj const& nodeObj, size_t count)
{
NodeContextHandle nodeHandle = nodeObj.nodeContextHandle;
size_t ret = 0;
const float* inputValue{ nullptr };
float* outputValue{ nullptr };
auto inputValueAttr =
getAttributeR(contextObj, nodeHandle, Token("inputs:value"), kAccordingToContextIndex);
auto outputValueAttr =
getAttributeW(contextObj, nodeHandle, Token("outputs:value"), kAccordingToContextIndex);
while (count--)
{
inputValue = getDataR<float>(contextObj, inputValueAttr);
outputValue = getDataW<float>(contextObj, outputValueAttr);
if(inputValue && outputValue)
{
*outputValue = *inputValue;
++ret;
}
inputValueAttr = contextObj.iAttributeData->moveToAnotherInstanceR(contextObj, inputValueAttr, 1);
outputValueAttr = contextObj.iAttributeData->moveToAnotherInstanceW(contextObj, outputValueAttr, 1);
}
return ret;
}
// end-mutate
#elif TUTO_ABI_PASSTHROUGH_METHOD == TUTO_ABI_PASSTHROUGH_METHOD_RAW
// begin-raw
static size_t computeVectorized(GraphContextObj const& contextObj, NodeObj const& nodeObj, size_t count)
{
NodeContextHandle nodeHandle = nodeObj.nodeContextHandle;
auto inputValueAttr =
getAttributeR(contextObj, nodeHandle, Token("inputs:value"), kAccordingToContextIndex);
const float* inputValue = getDataR<float>(contextObj, inputValueAttr);
auto outputValueAttr =
getAttributeW(contextObj, nodeHandle, Token("outputs:value"), kAccordingToContextIndex);
float* outputValue = getDataW<float>(contextObj, outputValueAttr);
if(inputValue && outputValue)
{
memcpy(outputValue, inputValue, count * sizeof(float));
return count;
}
return 0;
}
// end-raw
#endif
};
REGISTER_OGN_NODE()
| 6,186 | C++ | 38.407643 | 123 | 0.676043 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial17/tutorial17.rst | .. _ogn_tutorial_state_attributes_py:
Tutorial 17 - Python State Attributes Node
==========================================
This node illustrates how you can use state attributes. These are attributes that are not meant to be connected to
other nodes as they maintain a node's internal state, persistent from one evaluation to the next.
As they are persistent, care must be taken that they be initialized properly. This can take the form of a reset
flag, as seen on this node, state flag values with known defaults that describe the validity of the state attribute
data, or using a checksum on inputs, among other possibilities.
State attributes can be both read and written, like output attributes. The presence of state attributes will also
inform the evaluators on what type of parallel scheduling is appropriate.
These attributes provide a similar functionality to those found in :ref:`ogn_tutorial_state_py`, except that being
node attributes the structure is visible to the outside world, making it easier to construct UI and visualizers for
it.
OgnTutorialStateAttributesPy.ogn
--------------------------------
The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.StateAttributesPy", with a couple of state
attributes that both read and write values during the compute.
.. literalinclude:: OgnTutorialStateAttributesPy.ogn
:linenos:
:language: json
OgnTutorialStateAttributesPy.py
-------------------------------
The *.py* file contains the compute method that uses the state attributes to run the algorithm.
.. literalinclude:: OgnTutorialStateAttributesPy.py
:linenos:
:language: python
Test Script
-----------
The .ogn test infrastructure currently only supports single evaluation, which will not be sufficient to test state
attribute manipulations. This test script runs multiple evaluations and verifies that the state information is
updated as expected after each evaluation.
.. literalinclude:: ../../python/tests/test_tutorial_state_attributes_py.py
:linenos:
:language: python
| 2,060 | reStructuredText | 42.851063 | 126 | 0.752913 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial17/OgnTutorialStateAttributesPy.py | """
Implementation of a Python node that uses state attributes to maintain information between evaluations.
The node has a simple monotonically increasing state output "monotonic" that can be reset by setting the state
attribute "reset" to true.
"""
class OgnTutorialStateAttributesPy:
"""Use internal node state information in addition to inputs"""
@staticmethod
def compute(db) -> bool:
"""Compute the output based on inputs and internal state"""
# State attributes are the only ones guaranteed to remember and modify their values.
# Care must be taken to set proper defaults when the node initializes, otherwise you could be
# starting in an unknown state.
if db.state.reset:
db.state.monotonic = 0
db.state.reset = False
else:
db.state.monotonic = db.state.monotonic + 1
return True
| 897 | Python | 33.53846 | 110 | 0.688963 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial11/tutorial11.rst | .. _ogn_tutorial_complexData_py:
Tutorial 11 - Complex Data Node in Python
=========================================
This node fills on the remainder of the (CPU for now) data types available through Python. It combines the
progressive introduction in C++ of :ref:`ogn_tutorial_tupleData`, :ref:`ogn_tutorial_arrayData`,
:ref:`ogn_tutorial_tupleArrays`, and :ref:`ogn_tutorial_roleData`.
Rather than providing an exhaustive set of attribute types there will be one chosen from each of the
aforementioned categories of types. See the section `Pythonic Complex Attribute Type Access`_ for details on
how to access the representative types.
OgnTutorialComplexDataPy.ogn
----------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.ComplexDataPy", which has one
input and one output attribute of each complex (arrays, tuples, roles) type.
.. literalinclude:: OgnTutorialComplexDataPy.ogn
:linenos:
:language: json
OgnTutorialComplexDataPy.py
---------------------------
The *py* file contains the implementation of the compute method, which modifies
each of the inputs in a simple way to create outputs that have different values.
.. literalinclude:: OgnTutorialComplexDataPy.py
:linenos:
:language: python
Note how the attribute values are available through the ``OgnTutorialComplexDataPyDatabase`` class. The generated
interface creates access methods for every attribute, named for the attribute itself. They are all implemented as Python
properties, where inputs only have get methods and outputs have both get and set methods.
Pythonic Complex Attribute Type Access
--------------------------------------
Complex data in Python takes advantage of the numpy library to handle arrays so you should always include this
line at the top of your node if you have array data:
.. code-block:: python
import numpy
+----------------------+---------------------+-------------------------+
| Database Property | Representative Type | Returned Type |
+======================+=====================+=========================+
| inputs.a_float3 | Tuple | [float, float, float] |
+----------------------+---------------------+-------------------------+
| inputs.a_floatArray | Array | numpy.ndarray[float, 1] |
+----------------------+---------------------+-------------------------+
| inputs.a_point3Array | Role-Based | numpy.ndarray[float, 3] |
+----------------------+---------------------+-------------------------+
As with simple data, the values returned are all references to the real data in the FlatCache, our managed memory store,
pointing to the correct location at evaluation time.
Python Role Information
-----------------------
The attribute roles can be checked in Python similar to C++ by using the ``role()`` method on the generated database
class.
.. code-block:: python
def compute(db) -> bool:
"""Run my algorithm"""
if db.role(db.outputs.a_pointArray) == db.ROLE_POINT:
print("Hey, I did get the correct role")
This table shows the list of Python role names and the corresponding attribute types that match them:
+-----------------+---------------------------------+
| Python Role | Attribute Types |
+=================+=================================+
| ROLE_COLOR | colord, colorf, colorh |
+-----------------+---------------------------------+
| ROLE_FRAME | frame |
+-----------------+---------------------------------+
| ROLE_NORMAL | normald, normalf, normalh |
+-----------------+---------------------------------+
| ROLE_POSITION | positiond, positionf, positionh |
+-----------------+---------------------------------+
| ROLE_QUATERNION | quatd, quatf, quath |
+-----------------+---------------------------------+
| ROLE_TEXCOORD | texcoordd, texcoordf, texcoordh |
+-----------------+---------------------------------+
| ROLE_TIMECODE | timecode |
+-----------------+---------------------------------+
| ROLE_TRANSFORM | transform |
+-----------------+---------------------------------+
| ROLE_VECTOR | vectord, vectorf, vectorh |
+-----------------+---------------------------------+
| 4,331 | reStructuredText | 43.659793 | 120 | 0.525745 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial11/OgnTutorialComplexDataPy.py | """
Implementation of a node handling complex attribute data
"""
# This class exercises access to the DataModel through the generated database class for a representative set of
# complex data types, including tuples, arrays, arrays of tuples, and role-based attributes. More details on
# individual type definitions can be found in the earlier C++ tutorial nodes where each of those types are
# explored in detail.
# Any Python node with array attributes will receive its data wrapped in a numpy array for efficiency.
# Unlike C++ includes, a Python import is not transitive so this has to be explicitly imported here.
import numpy
import omni.graph.core as og
class OgnTutorialComplexDataPy:
"""Exercise a sample of complex data types through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""
Multiply a float array by a float[3] to yield a float[3] array, using the point3f role.
Practically speaking the data in the role-based attributes is no different than the underlying raw data
types. The role only helps you understand what the intention behind the data is, e.g. to differentiate
surface normals and colours, both of which might have float[3] types.
"""
# Verify that the output array was correctly set up to have a "point" role
assert db.role.outputs.a_productArray == og.AttributeRole.POSITION
multiplier = db.inputs.a_vectorMultiplier
input_array = db.inputs.a_inputArray
input_array_size = len(db.inputs.a_inputArray)
# The output array should have the same number of elements as the input array.
# Setting the size informs fabric that when it retrieves the data it should allocate this much space.
db.outputs.a_productArray_size = input_array_size
# The assertions illustrate the type of data that should have been received for inputs and set for outputs
assert isinstance(multiplier, numpy.ndarray) # numpy.ndarray is the underlying type of tuples
assert multiplier.shape == (3,)
assert isinstance(input_array, numpy.ndarray) # numpy.ndarray is the underlying type of simple arrays
assert input_array.shape == (input_array_size,)
# If the input array is empty then the output is empty and does not need any computing
if input_array.shape[0] == 0:
db.outputs.a_productArray = []
assert db.outputs.a_productArray.shape == (0, 3)
return True
# numpy has a nice little method for replicating the multiplier vector the number of times required
# by the size of the input array.
# e.g. numpy.tile( [1, 2], (3, 1) ) yields [[1, 2], [1, 2], [1, 2]]
product = numpy.tile(multiplier, (input_array_size, 1))
# Multiply each of the tiled vectors by the corresponding constant in the input array
for i in range(0, product.shape[0]):
product[i] = product[i] * input_array[i]
db.outputs.a_productArray = product
# Make sure the correct type of array was produced
assert db.outputs.a_productArray.shape == (input_array_size, 3)
# Create the output token array by copying the input array with the elements changed to strings
db.outputs.a_tokenArray = numpy.array([str(x) for x in input_array])
# Note that at the time of this writing you are not able to assign token arrays element-by-element as you
# might do for other types of arrays. So this coding method, usable for other types of arrays such as float[],
# would issue a warning and then fail to set the values on the output:
# db.outputs.a_tokenArray_size = input_array_size
# for index, element in enumerate(input_array):
# db.outputs.a_tokenArray[index] = str(element)
return True
| 3,862 | Python | 51.202702 | 118 | 0.690316 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial12/OgnTutorialABIPy.py | """
Implementation of the Python node accessing all of the simple data types.
This class exercises access to the DataModel through the generated database class for all simple data types.
It implements the same algorithm as the C++ node OgnTutorialABI.cpp
"""
import colorsys
from contextlib import suppress
import carb
import omni.graph.core as og
class OgnTutorialABIPy:
"""Illustrate overrides of the various ABI functions available to a Python OmniGraph node"""
@staticmethod
def compute(context, node) -> bool:
"""
Convert a color into components using the raw ABI function without the nice Database interface.
Rarely Overridden:
Usually you will implement the much more friendly and Pythonic compute(OgnTutorialABIDatabasePy)
method so that you can have easier access to your data.
"""
# Manually acquire the data on the known attributes
input_color_attr = node.get_attribute("inputs:color")
# Extract the input value from the controller
input_color = og.Controller.get(input_color_attr)
output_hue_attr = node.get_attribute("outputs:h")
output_saturation_attr = node.get_attribute("outputs:s")
output_value_attr = node.get_attribute("outputs:v")
(h, s, v) = colorsys.rgb_to_hsv(*input_color)
# This exception is triggered if you accidentally reverse the parameters to set_attr_value.
# The error isn't recovered, to prevent proliferation of inconsistent calls. The exception is
# thrown to help with debugging. (As this is an example the exception is caught and ignored here.)
with suppress(og.OmniGraphError):
og.Controller.set(h, output_hue_attr)
og.Controller.set(output_hue_attr, h)
og.Controller.set(output_saturation_attr, s)
og.Controller.set(output_value_attr, v)
#
# For comparison, here is the same algorithm implemented using "compute(db)"
#
# def compute(db) -> bool:
# (db.outputs.h, db.outputs.s, db.outputs.v) = colorsys.rgb_to_hsv(*db.inputs.color)
return True
# ----------------------------------------------------------------------
@staticmethod
def get_node_type() -> str:
"""
Rarely overridden
This should almost never be overridden as the auto-generated code will handle the name
"""
carb.log_info("Python ABI override of get_node_type")
return "omni.graph.tutorials.AbiPy"
# ----------------------------------------------------------------------
@staticmethod
def initialize(graph_context, node):
"""
Occasionally overridden
This method might be overridden to set up initial conditions when a node of this type is created.
Note that overridding this puts the onus on the node writer to set up initial conditions such as
attribute default values and metadata.
When a node is created this will be called
"""
carb.log_info("Python ABI override of initialize")
# There is no default behaviour on initialize so nothing else is needed for this tutorial to function
# ----------------------------------------------------------------------
@staticmethod
def initialize_type(node_type) -> bool:
"""
Rarely overridden
This method might be overridden to set up initial conditions when a node type is registered.
Note that overriding this puts the onus on the node writer to initialize the attributes and metadata.
By returning "True" the function is requesting that the attributes and metadata be initialized upon return,
otherwise the caller will assume that this override has already done that.
"""
carb.log_info("Python ABI override of initialize_type")
return True
# ----------------------------------------------------------------------
@staticmethod
def release(node):
"""
Occasionally overridden
After a node is removed it will get a release call where anything set up in initialize() can be torn down
"""
carb.log_info("Python ABI override of release")
# There is no default behaviour on release so nothing else is needed for this tutorial to function
# ----------------------------------------------------------------------
@staticmethod
def update_node_version(graph_context, node, old_version: int, new_version: int):
"""
Occasionally overridden
This is something you do want to override when you have more than version of your node.
In it you would translate attribute information from older versions into the current one.
"""
carb.log_info(f"Python ABI override of update_node_version from {old_version} to {new_version}")
# There is no default behaviour on update_node_version so nothing else is needed for this tutorial to function
return old_version < new_version
# ----------------------------------------------------------------------
@staticmethod
def on_connection_type_resolve(node):
"""
Occasionally overridden
When there is a connection change to this node which results in an extended type attribute being automatically
resolved, this callback gives the node a change to resolve other extended type attributes. For example a generic
'Increment' node can resolve its output to an int only after its input has been resolved to an int. Attribute
types are resolved using omni.graph.attribute.set_resolved_type(), or the utility functions such as
og.resolve_fully_coupled().
"""
carb.log_info("Python ABI override of on_connection_type_resolve")
# There is no default behaviour for on_connection_type_resolve so nothing else is needed for this
# tutorial to function
| 5,945 | Python | 43.373134 | 120 | 0.632296 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial12/tutorial12.rst | .. _ogn_tutorial_abi_py:
Tutorial 12 - Python ABI Override Node
======================================
Although the .ogn format creates an easy-to-use interface to the ABI of the OmniGraph node and the associated
data model, there may be cases where you want to override the ABI to perform special processing.
OgnTutorialABIPy.ogn
--------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.AbiPy", in its first
version, with a simple description.
.. literalinclude:: OgnTutorialABIPy.ogn
:linenos:
:language: json
OgnTutorialABIPy.py
-------------------
The *py* file contains the implementation of the node class with every possible
ABI method replaced with customized processing. The node still functions the same as any other node, although it
is forced to write a lot of extra boilerplate code to do so.
.. literalinclude:: OgnTutorialABIPy.py
:linenos:
:language: python
Metadata Attached To Attributes
-------------------------------
This file introduces the *metadata* keyword to attributes, whose value is a dictionary of key/value pairs associated
with the attribute in which it appears that may be extracted using the ABI metadata functions. These are not persisted
in any files and so must be set either in the .ogn file or in an override of the **initialize()** method in the node
definition.
| 1,368 | reStructuredText | 39.264705 | 118 | 0.720029 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial4/tutorial4.rst | .. _ogn_tutorial_tupleData:
Tutorial 4 - Tuple Data Node
============================
Tuple data, also referred to as fixed array data, consists of multiple elements of a simple type.
For example *float[3]* or *double[4]*. This node creates one input attribute and one output attribute
of each of the simple data types with an element count greater than 1.
OgnTutorialTupleData.ogn
------------------------
The *ogn* file shows the implementation of a node named
"omni.tutorials.TupleData", which has one input and one matching output attribute of each simple type with element counts
greater than one.
.. literalinclude:: OgnTutorialTupleData.ogn
:linenos:
:language: json
:emphasize-lines: 2,12
New Concept - Tags
------------------
Often it is helpful to group nodes with common functionality together in some way in the UI. To help with this you
can specific values for the **tags** keyword. The values can either be a comma-separated string, or a list, that will
be rendered into a comma-separated string when added to the metadata.
New Concept - Namespaced Node Type Name
---------------------------------------
The standard naming convention uses a simple ``CamelCase`` name, with the extension of origin prepended onto the name
to ensure uniqueness. Sometimes you may wish to manage your own namespace, e.g. when you anticipate moving nodes
between extensions so the extension name will not be consistent. All you have to do to override the default behaviour
is to specify a namespace for the node type name (i.e. include a `.` separator in it).
.. warning::
Once you have overridden the node type name with such an absolute value you are now responsible for ensuring
uniqueness so be sure you have some scheme that will help you with that. The prefix **omni.** is reserved for
NVIDIA nodes. Everything else is legal, so long as the entire name itself is legal.
OgnTutorialTupleData.cpp
------------------------
The *cpp* file contains the implementation of the compute method, which
modifies each of the inputs in a simple way to create outputs that have different values.
.. literalinclude:: OgnTutorialTupleData.cpp
:linenos:
:language: c++
Note how by default some of the attribute value types are USD types and some are generic *ogn::tuple* types.
See :ref:`ogn_attribute_types` for the full set of type definitions.
Tuple Attribute Access
----------------------
The attribute access is as described in :ref:`ogn_tutorial_simpleData` except that the exact return types
of the attributes are different in order to support tuple member access. In practice you would use
an *auto* declaration. The types are shown only for illustrative purposes.
The data types for tuples that correspond to existing USD types use the ``pxr::gf`` versions of those types,
so the database accessors in this node will return these types:
+---------------------+----------------+
| Database Function | Returned Type |
+=====================+================+
| inputs.a_double2() | const GfVec2d& |
+---------------------+----------------+
| inputs.a_float2() | const GfVec2f& |
+---------------------+----------------+
| inputs.a_half2() | const GfVec2h& |
+---------------------+----------------+
| inputs.a_int2() | const GfVec2i& |
+---------------------+----------------+
| inputs.a_float3() | const GfVec3f& |
+---------------------+----------------+
| outputs.a_double2() | GfVec2d& |
+---------------------+----------------+
| outputs.a_float2() | GfVec2f& |
+---------------------+----------------+
| outputs.a_half2() | GfVec2h& |
+---------------------+----------------+
| outputs.a_int2() | GfVec2i& |
+---------------------+----------------+
| outputs.a_float3() | GfVec3f& |
+---------------------+----------------+
Tuple Data Compute Validation
-----------------------------
As with simple data types the existence of the mandatory inputs is confirmed before proceeding to the compute
method.
Tuple Data Node Computation Tests
---------------------------------
In the *"tests"* section of the .ogn file there are some simple tests exercising the basic functionality of the
compute method. In practice it is a good idea to include more thorough tests which exercise different data values,
especially potential edge cases.
| 4,326 | reStructuredText | 44.547368 | 121 | 0.631068 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial4/OgnTutorialTupleData.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 <OgnTutorialTupleDataDatabase.h>
#include <algorithm>
#include <iostream>
// This class exercises access to the DataModel through the generated database class for supported data types
// with element counts greater than 1.
class OgnTutorialTupleData
{
public:
static bool compute(OgnTutorialTupleDataDatabase& db)
{
// For each piece of data apply a transforming operation so that compute does something testable.
// The transformation adds 1 to the input to compute the matching output. Notice how the recognized
// USD types can make use of the built-in manipulation functions while the generic types have to
// manually apply the algorithm.
db.outputs.a_double2() = db.inputs.a_double2() + GfVec2d(1.0, 1.0);
db.outputs.a_double3() = db.inputs.a_double3() + GfVec3d(1.0, 1.0, 1.0);
db.outputs.a_float2() = db.inputs.a_float2() + GfVec2f(1.0f, 1.0f);
db.outputs.a_half2() = db.inputs.a_half2() + GfVec2h(1.0, 1.0);
db.outputs.a_int2() = db.inputs.a_int2() + GfVec2i(1, 1);
// If you have your own data types which are memory-layout-compatible with the defaults provided
// you can use a simple cast operation to force a specific data type. Be careful not to cast away
// the "const" on inputs or your data could get out of sync.
const carb::Float3& inFloat3 = reinterpret_cast<const carb::Float3&>(db.inputs.a_float3());
carb::Float3& outFloat3 = reinterpret_cast<carb::Float3&>(db.outputs.a_float3());
outFloat3.x = inFloat3.x + 1.0f;
outFloat3.y = inFloat3.y + 1.0f;
outFloat3.z = inFloat3.z + 1.0f;
return true;
}
};
REGISTER_OGN_NODE()
| 2,152 | C++ | 46.844443 | 109 | 0.697491 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial3/OgnTutorialABI.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 <OgnTutorialABIDatabase.h>
using omni::graph::core::Token;
#include <string>
#include <unordered_map>
// Set this value true to enable messages when the ABI overrides are called
const bool debug_abi{ false };
#define DEBUG_ABI if (debug_abi) CARB_LOG_INFO
// In most cases the generated compute method is all that a node will need to implement. If for
// some reason the node wants to access the omni::graph::core::INodeType ABI directly and override
// any of its behaviour it can. This set of functions shows how every method in the ABI might be
// overridden.
//
// Note that certain ABI functions, though listed, are not implemented as a proper implementation would be more
// complicated than warranted for this simple example. All are rarely overridden; in fact no known cases exist.
class OgnTutorialABI
{
static std::unordered_map<std::string, std::string> s_metadata; // Alternative metadata implementation
public:
// ----------------------------------------------------------------------
// Almost always overridden indirectly
//
// ABI compute method takes the interface definitions of both the evaluation context and the node.
// When using a .ogn generated class this function will be overridden by the generated code and the
// node will implement the generated version of this method "bool compute(OgnTutorialABIDatabase&)".
// Overriding this method directly, while possible, does not add any extra capabilities as the two
// parameters are also available through the database (contextObj = db.abi_context(), nodeObj = db.abi_node())
static bool compute(const GraphContextObj& contextObj, const NodeObj& nodeObj)
{
DEBUG_ABI("Computing the ABI node");
// The computation still runs the same as for the standard compute method by using the more
// complex ABI-based access patterns. First get the ABI-compliant structures needed.
NodeContextHandle nodeHandle = nodeObj.nodeContextHandle;
const INode* iNode = nodeObj.iNode;
// Use the multiple-input template to access a pointer to the input boolean value
auto inputValueAttr = getAttributesR<ConstAttributeDataHandle>(
contextObj, nodeHandle, std::make_tuple(Token("inputs:namespace:a_bool")), kAccordingToContextIndex);
const bool* inputValue{ nullptr };
std::tie(inputValue) = getDataR<bool*>(contextObj, inputValueAttr);
// Use the single-output template to access a pointer to the output boolean value
auto outputValueAttr =
getAttributeW(contextObj, nodeHandle, Token("outputs:namespace:a_bool"), kAccordingToContextIndex);
bool* outputValue = getDataW<bool>(contextObj, outputValueAttr);
// Since the generated code isn't in control you are responsible for your own error checking
if (!inputValue)
{
// Not having access to the generated database class with its error interface we have to resort
// to using the native error logging.
CARB_LOG_ERROR("Failed compute on %s: No input attribute", iNode->getPrimPath(nodeObj));
return false;
}
if (!outputValue)
{
CARB_LOG_ERROR("Failed compute on %s: No output attribute", iNode->getPrimPath(nodeObj));
return false;
}
// The actual computation of the node
*outputValue = !*inputValue;
return true;
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// These will almost never be overridden, specifically because the low level implementation lives in
// the omni.graph.core extension and is not exposed through the ABI so it would be very difficult
// for a node to be able to do the right thing when this function is called.
// static void addInput
// static void addOutput
// static void addState
// ----------------------------------------------------------------------
// Rarely overridden
//
// This should almost never be overridden as the auto-generated code will handle the name.
// This particular override is used to bypass the unique naming feature of the .ogn name, where only names
// with a namespace separator (".") do not have the extension name added as a prefix to the unique name.
// This should only done for backward compatibility, and only until the node type name versioning is available.
// Note that when you do this you will still be able to create a node using the generated node type name, as
// that is required in order for the automated testing to work. The name returned here can be thought of as an
// alias for the underlying name.
static const char* getNodeType()
{
DEBUG_ABI("ABI override of getNodeType");
static const char* _nodeType{ "OmniGraphABI" };
return _nodeType;
}
// ----------------------------------------------------------------------
// Occasionally overridden
//
// When a node is created this will be called
static void initialize(const GraphContextObj&, const NodeObj&)
{
DEBUG_ABI("ABI override of initialize");
// There is no default behaviour on initialize so nothing else is needed for this tutorial to function
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// This method might be overridden to set up initial conditions when a node type is registered, or
// to replace initialization if the auto-generated version has some problem.
static void initializeType(const NodeTypeObj& nodeType)
{
DEBUG_ABI("ABI override of initializeType");
// The generated initializeType will always be called so nothing needs to happen here
}
// ----------------------------------------------------------------------
// Occasionally overridden
//
// This is called while registering a node type. It is used to initialize tasks that can be used for
// making compute more efficient by using Realm events.
static void registerTasks()
{
DEBUG_ABI("ABI override of registerTasks");
}
// ----------------------------------------------------------------------
// Occasionally overridden
//
// After a node is removed it will get a release call where anything set up in initialize() can be torn down
static void release(const NodeObj&)
{
DEBUG_ABI("ABI override of release");
// There is no default behaviour on release so nothing else is needed for this tutorial to function
}
// ----------------------------------------------------------------------
// Occasionally overridden
//
// This is something you do want to override when you have more than version of your node.
// In it you would translate attribute information from older versions into the current one.
static bool updateNodeVersion(const GraphContextObj&, const NodeObj&, int oldVersion, int newVersion)
{
DEBUG_ABI("ABI override of updateNodeVersion from %d to %d", oldVersion, newVersion);
// There is no default behaviour on updateNodeVersion so nothing else is needed for this tutorial to function
return oldVersion < newVersion;
}
// ----------------------------------------------------------------------
// Occasionally overridden
//
// When there is a connection change to this node which results in an extended type attribute being automatically
// resolved, this callback gives the node a change to resolve other extended type attributes. For example a generic
// 'Increment' node can resolve its output to an int only after its input has been resolved to an int. Attribute
// types are resolved using IAttribute::setResolvedType() or the utility functions such as
// INode::resolvePartiallyCoupledAttributes()
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
DEBUG_ABI("ABI override of onConnectionTypeResolve()");
// There is no default behaviour on onConnectionTypeResolve so nothing else is needed for this tutorial to
// function
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// You may want to provide an alternative method of metadata storage.
// This method can be used to intercept requests for metadata to provide those alternatives.
static size_t getAllMetadata(const NodeTypeObj& nodeType, const char** keyBuf, const char** valueBuf, size_t bufSize)
{
DEBUG_ABI("ABI override of getAllMetadata(%zu)", bufSize);
if (s_metadata.size() > bufSize)
{
CARB_LOG_ERROR("Not enough space for metadata - needed %zu, got %zu", s_metadata.size(), bufSize);
return 0;
}
size_t index = 0;
for (auto& metadata : s_metadata)
{
keyBuf[index] = metadata.first.c_str();
valueBuf[index] = metadata.second.c_str();
++index;
}
return s_metadata.size();
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// You may want to provide an alternative method of metadata storage.
// This method can be used to intercept requests for metadata to provide those alternatives.
static const char* getMetadata(const NodeTypeObj& nodeType, const char* key)
{
DEBUG_ABI("ABI override of getMetadata('%s')", key);
auto found = s_metadata.find(std::string(key));
if (found != s_metadata.end())
{
return (*found).second.c_str();
}
return nullptr;
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// You may want to provide an alternative method of metadata storage.
// This method can be used to intercept requests for the number of metadata elements to provide those alternatives.
static size_t getMetadataCount(const NodeTypeObj& nodeType)
{
DEBUG_ABI("ABI override of getMetadataCount()");
return s_metadata.size();
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// You may want to provide an alternative method of metadata storage.
// This method can be used to intercept requests to set metadata and use those alternatives.
static void setMetadata(const NodeTypeObj& nodeType, const char* key, const char* value)
{
DEBUG_ABI("ABI override of setMetadata('%s' = '%s')", key, value);
s_metadata[std::string(key)] = std::string(value);
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// Subnode types are used when a single node type is shared among a set of other nodes, e.g. the way that
// PythonNode is the node type for all nodes implemented in Python, while the subNodeType is the actual node type.
// Overriding these functions let you implement different methods of managing those relationships.
//
static void addSubNodeType(const NodeTypeObj& nodeType, const char* subNodeTypeName, const NodeTypeObj& subNodeType)
{
DEBUG_ABI("ABI override of addSubNodeType('%s')", subNodeTypeName);
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// Subnode types are used when a single node type is shared among a set of other nodes, e.g. the way that
// PythonNode is the node type for all nodes implemented in Python, while the subNodeType is the actual node type.
// Overriding these functions let you implement different methods of managing those relationships.
//
static NodeTypeObj getSubNodeType(const NodeTypeObj& nodeType, const char* subNodeTypeName)
{
DEBUG_ABI("ABI override of getSubNodeType('%s')", subNodeTypeName);
return NodeTypeObj{ nullptr, kInvalidNodeTypeHandle };
}
// ----------------------------------------------------------------------
// Rarely overridden
//
// Subnode types are used when a single node type is shared among a set of other nodes, e.g. the way that
// PythonNode is the node type for all nodes implemented in Python, while the subNodeType is the actual node type.
// Overriding these functions let you implement different methods of managing those relationships.
//
static NodeTypeObj createNodeType(const char* nodeTypeName, int version)
{
DEBUG_ABI("ABI override of createNodeType('%s')", nodeTypeName);
return NodeTypeObj{ nullptr, kInvalidNodeTypeHandle };
}
};
std::unordered_map<std::string, std::string> OgnTutorialABI::s_metadata;
// ============================================================
// The magic for recognizing and using the overridden ABI code is in here. The generated interface
// is still available, as seen in the initializeType implementation, although it's not required.
REGISTER_OGN_NODE()
| 13,602 | C++ | 47.931655 | 121 | 0.63101 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial1/tutorial1.rst | .. _ogn_tutorial_empty:
Tutorial 1 - Trivial Node
=========================
The simplest possible node is one that implements only the mandatory fields in a node. These are the "version" and
"description" fields.
The existence of the file *OgnTutorialEmpty.svg* will automatically install this icon into the build directory and
add its path to the node type's metadata. The installed file will be named after the node type, not the class type,
so it will be installed at the path `$BUILD/exts/omni.graph.tutorials/ogn/icons/Empty.svg`.
OgnTutorialEmpty.ogn
--------------------
The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.Empty", in its first
version, with a simple description.
.. literalinclude:: OgnTutorialEmpty.ogn
:linenos:
:language: json
OgnTutorialEmpty.cpp
--------------------
The *.cpp* file contains the minimum necessary implementation of the node class, which
contains only the empty compute method. It contains a detailed description of the necessary code components.
.. literalinclude:: OgnTutorialEmpty.cpp
:linenos:
:language: c++
| 1,113 | reStructuredText | 36.133332 | 115 | 0.730458 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial1/OgnTutorialEmpty.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.
//
// ============================================================
// Note the name of the generated include file, taken from the name of the file with "Database.h" appended.
// The build system should have added the include path that picks this file up directly.
#include <OgnTutorialEmptyDatabase.h>
// ============================================================
// The class name should match the file name to avoid confusion as the file name will be used
// as a base for the names in the generated interface.
//
class OgnTutorialEmpty
{
public:
// ------------------------------------------------------------
// Note the name of the generated computation database, the same as the name of the include file,
// auto-generated by appending "Database" to the file name.
//
static bool compute(OgnTutorialEmptyDatabase&)
{
// This node correctly does nothing, but it must return true to indicate a successful compute.
//
return true;
}
};
// ============================================================
// Now that the node has been defined it can be registered for use. This registration takes care of
// automatic registration of the node when the extension loads and deregistration when it unloads.
REGISTER_OGN_NODE()
| 1,711 | C++ | 44.05263 | 107 | 0.638223 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial24/OgnTutorialOverrideType.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 <OgnTutorialOverrideTypeDatabase.h>
// The include files required by the type definition override is in the database definition so it does not have to
// be directly included here.
namespace omni
{
namespace graph
{
namespace core
{
namespace tutorial
{
class OgnTutorialOverrideType
{
public:
static bool compute(OgnTutorialOverrideTypeDatabase& db)
{
// Usually you would use an "auto" declaration. The type is explicit here to show how the override has
// changed the generated type.
const carb::Float3& inputTypedData = db.inputs.typedData();
carb::Float3& outputTypedData = db.outputs.typedData();
const pxr::GfVec3d& inputStandardData = db.inputs.data();
pxr::GfVec3d& outputStandardData = db.outputs.data();
// Rearrange the components as a simple way to verify that compute happened
outputTypedData.x = inputTypedData.y;
outputTypedData.y = inputTypedData.z;
outputTypedData.z = inputTypedData.x;
outputStandardData.Set(inputStandardData[1], inputStandardData[2], inputStandardData[0]);
return true;
}
};
// namespaces are closed after the registration macro, to ensure the correct class is registered
REGISTER_OGN_NODE()
} // namespace tutorial
} // namespace core
} // namespace graph
} // namespace omni
| 1,776 | C++ | 31.907407 | 114 | 0.73536 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial24/tutorial24.rst | .. _ogn_tutorial_overrideTypes:
Tutorial 24 - Overridden Types
==============================
By default the code generator will provide POD types for simple data, and USD types for tuple data (e.g. ``float`` and
``pxr::GfVec3f``). Sometimes you may have your own favourite math library and want to use its data types directly
rather than constantly using a _reinterpret_cast_ on the attribute values. To facilitate this, JSON data which
contains type overrides for one or more of the attribute types may be provided so that the generated code will use
those types directly.
OgnTutorialOverrideType.ogn
---------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.OverrideType", which has one
input and one output attribute that use an overridden type for ``float[3]``.
.. literalinclude:: OgnTutorialOverrideType.ogn
:linenos:
:language: json
OgnTutorialOverrideType.cpp
---------------------------
The *cpp* file contains the implementation of the compute method. The default type implementation would have a return
type of ``pxr::GfVec3f`` but this one uses the override type of ``carb::Float3``
.. literalinclude:: OgnTutorialOverrideType.cpp
:linenos:
:language: c++
| 1,240 | reStructuredText | 40.366665 | 118 | 0.720161 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial15/OgnTutorialBundlesPy.py | """
Implementation of the Python node accessing attributes through the bundle in which they are contained.
"""
import omni.graph.core as og
# Types recognized by the integer filter
_INTEGER_TYPES = [og.BaseDataType.INT, og.BaseDataType.UINT, og.BaseDataType.INT64, og.BaseDataType.UINT64]
class OgnTutorialBundlesPy:
"""Exercise the bundled data types through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Implements the same algorithm as the C++ node OgnTutorialBundles.cpp"""
full_bundle = db.inputs.fullBundle
filtered_bundle = db.inputs.filteredBundle
filters = db.inputs.filters
output_bundle = db.outputs.combinedBundle
# This does a copy of the full bundle contents from the input bundle to the output bundle
output_bundle.bundle = full_bundle
# Extract the filter flags from the contents of the filters array
filter_big_arrays = "big" in filters
filter_type_int = "int" in filters
filter_name_x = "x" in filters
# The "attributes" member is a list that can be iterated. The members of the list do not contain real
# og.Attribute objects, which must always exist, they are wrappers on og.AttributeData objects, which can
# come and go at runtime.
for bundled_attribute in filtered_bundle.attributes:
# The two main accessors for the bundled attribute provide the name and type information
name = bundled_attribute.name
attribute_type = bundled_attribute.type
# Check each of the filters to see which attributes are to be skipped
if filter_type_int and attribute_type.base_type in _INTEGER_TYPES:
continue
if filter_name_x and name.find("x") >= 0:
continue
# A method on the bundled attribute provides access to array size (non-arrays are size 1)
if filter_big_arrays and bundled_attribute.size > 10:
continue
# All filters have been passed so the attribute is eligible to be copied onto the output.
output_bundle.insert(bundled_attribute)
return True
| 2,203 | Python | 39.814814 | 113 | 0.671811 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial15/OgnTutorialBundles.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 <OgnTutorialBundlesDatabase.h>
using omni::graph::core::BaseDataType;
using omni::graph::core::NameToken;
using omni::graph::core::Type;
namespace
{
// Tokens to use for checking filter names
static NameToken s_filterBigArrays;
static NameToken s_filterNameX;
static NameToken s_filterTypeInt;
}
class OgnTutorialBundles
{
public:
// Overriding the initialize method allows caching of the name tokens which will avoid string comparisons
// at evaluation time.
static void initialize(const GraphContextObj& contextObj, const NodeObj&)
{
s_filterBigArrays = contextObj.iToken->getHandle("big");
s_filterNameX = contextObj.iToken->getHandle("x");
s_filterTypeInt = contextObj.iToken->getHandle("int");
}
static bool compute(OgnTutorialBundlesDatabase& db)
{
// Bundle attributes are extracted from the database in the same way as any other attribute.
// The only difference is that a different interface is provided, suited to bundle manipulation.
const auto& fullBundle = db.inputs.fullBundle();
const auto& filteredBundle = db.inputs.filteredBundle();
const auto& filters = db.inputs.filters();
auto& outputBundle = db.outputs.combinedBundle();
// The first thing this node does is to copy the contents of the fullBundle to the output bundle.
// operator=() has been defined on bundles to make this a one-step operation. Note that this completely
// replaces any previous bundle contents. If you wish to append another bundle then you would use:
// outputBundle.insertBundle(fullBundle);
outputBundle = fullBundle;
// Set some booleans that determine which filters to apply
bool filterBigArrays{ false };
bool filterNameX{ false };
bool filterTypeInt{ false };
for (const auto& filterToken : filters)
{
if (filterToken == s_filterBigArrays)
{
filterBigArrays = true;
}
else if (filterToken == s_filterNameX)
{
filterNameX = true;
}
else if (filterToken == s_filterTypeInt)
{
filterTypeInt = true;
}
else
{
db.logWarning("Unrecognized filter name '%s'", db.tokenToString(filterToken));
}
}
// The bundle object has an iterator for looping over the attributes within in
for (const auto& bundledAttribute : filteredBundle)
{
// The two main accessors for the bundled attribute provide the name and type information
NameToken name = bundledAttribute.name();
Type type = bundledAttribute.type();
// Check each of the filters to see which attributes are to be skipped
if (filterTypeInt)
{
if ((type.baseType == BaseDataType::eInt) || (type.baseType == BaseDataType::eUInt) ||
(type.baseType == BaseDataType::eInt64) || (type.baseType == BaseDataType::eUInt64))
{
continue;
}
}
if (filterNameX)
{
std::string nameString(db.tokenToString(name));
if (nameString.find('x') != std::string::npos)
{
continue;
}
}
if (filterBigArrays)
{
// A simple utility method on the bundled attribute provides access to array size
if (bundledAttribute.size() > 10)
{
continue;
}
}
// All filters have been passed so the attribute is eligible to be copied onto the output.
outputBundle.insertAttribute(bundledAttribute);
}
return true;
}
};
REGISTER_OGN_NODE()
| 4,380 | C++ | 37.095652 | 111 | 0.611416 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial15/tutorial15.rst | .. _ogn_tutorial_bundle_manipulation:
Tutorial 15 - Bundle Manipulation
=================================
Attribute bundles are a construct that packages up groups of attributes into a single entity that can be passed
around the graph. Some advantages of a bundle are that they greatly simplify graph connections, only requiring a single
connection between nodes rather than dozens or even hundreds, and they do not require static definition of the data
they contain so it can change as the evaluation of the nodes dictate. The only disadvantage is that the node writer is
responsible for analyzing the contents of the bundle and deciding what to do with them.
OgnTutorialBundles.ogn
----------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleManipulation", which has some bundles as
inputs and outputs. It's called "manipulation" as the focus of this tutorial node is on operations applied directly
to the bundle itself, as opposed to on the data on the attributes contained within the bundles. See future tutorials
for information on how to deal with that.
.. literalinclude:: OgnTutorialBundles.ogn
:linenos:
:language: json
OgnTutorialBundles.cpp
----------------------
The *cpp* file contains the implementation of the compute method. It exercises each of the available bundle
manipulation functions.
.. literalinclude:: OgnTutorialBundles.cpp
:linenos:
:language: c++
OgnTutorialBundlesPy.py
-----------------------
The *py* file duplicates the functionality in the *cpp* file, except that it is implemented in Python.
.. literalinclude:: OgnTutorialBundlesPy.py
:linenos:
:language: python
Bundle Notes
------------
Bundles are implemented in USD as "virtual primitives". That is, while regular attributes appear in a USD file
as attributes on a primitive, a bundle appears as a nested primitive with no members.
Naming Convention
-----------------
Attributes can and do contain namespaces to make them easier to work with. For example, ``outputs:operations`` is
the namespaced name for the output attribute ``operations``. However as USD does not allow colons in the names of
the primitives used for implementing attriute bundles they will be replaced by underscores, vis ``outputs_operations``.
Bundled Attribute Manipulation Methods
--------------------------------------
There are a few methods for manipulating the bundle contents, independent of the actual data inside. The actual
implementation of these methods may change over time however the usage should remain the same.
The Bundle As A Whole
+++++++++++++++++++++
.. code-block:: cpp
:emphasize-lines: 2,5,8,11
// The bundle attribute is extracted from the database in exactly the same way as any other attribute.
const auto& inputBundle = db.inputs.myBundle();
// Output and state bundles are the same, except not const
auto& outputBundle = db.outputs.myBundle();
// The size of a bundle is the number of attributes it contains
auto bundleAttributeCount = inputBundle.size();
// Full bundles can be copied using the assignment operator
outputBundle = inputBundle;
Accessing Attributes By Name
++++++++++++++++++++++++++++
.. code-block:: cpp
:emphasize-lines: 2,8-9
// The attribute names should be cached somewhere as a token for fast access.
static const NameToken normalsName = db.stringToToken("normals");
// Then it's a call into the bundle to find an attribute with matching name.
// Names are unique so there is at most one match, and bundled attributes do not have the usual attribute
// namespace prefixes "inputs:", "outputs:", or "state:"
const auto& inputBundle = db.inputs.myBundle();
auto normals = inputBundle.attributeByName(normalsName);
if (normals.isValid())
{
// If the attribute is not found in the bundle then isValid() will return false.
}
Putting An Attribute Into A Bundle
++++++++++++++++++++++++++++++++++
.. code-block:: cpp
:emphasize-lines: 8,10
// Once an attribute has been extracted from a bundle a copy of it can be added to a writable bundle.
const auto& inputBundle = db.inputs.myBundle();
auto& outputBundle = db.outputs.myBundle();
auto normals = inputBundle.attributeByName(normalsToken);
if (normals.isValid())
{
// Clear the contents of stale data first since it will not be reused here.
outputBundle.clear();
// The attribute wrapper knows how to insert a copy into a bundle
outputBundle.insertAttribute(normals);
}
Iterating Over Attributes
+++++++++++++++++++++++++
.. code-block:: cpp
:emphasize-lines: 3,7
// The range-based for loop provides a method for iterating over the bundle contents.
const auto& inputBundle = db.inputs.myBundle();
for (const auto& bundledAttribute : inputBundle)
{
// Type information is available from a bundled attribute, consisting of a structure defined in
// include/omni/graph/core/Type.h
auto type = bundledAttribute.type();
// The type has four pieces, the first is the basic data type...
assert( type.baseType == BaseDataType::eFloat );
// .. the second is the role, if any
assert( type.role == AttributeRole::eNormal );
// .. the third is the number of tuple components (e.g. 3 for float[3] types)
assert( type.componentCount == 3 );
// .. the last is the array depth, either 0 or 1
assert( type.arrayDepth == 0 );
}
| 5,532 | reStructuredText | 40.601503 | 124 | 0.696855 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/conversionTutorial/node_conversion.rst | .. _ogn_node_conversion:
Tutorial - OmniGraph .ogn Conversion
====================================
This is a walkthrough of the conversion of an OmniGraph node written under the original DataModel and ABI architectures
to the .ogn format, which uses the new DataModel architecture.
.. note:: If you do not have build support for .ogn files yet, refer first to the :ref:`ogn_build_conversion` document.
The test node used will be the **Time** node, in the `omni.graph.core` extension. In order to fully convert
the file a series of steps must be followed.
.. note:: bash/gitbash commands are used to illustrate actions where required. Any other equivalent method is fine.
For the commands the current directory is assumed to be ``source/extensions/omni.graph.core/``.
.. note:: This tutorial is focussed on conversion of C++ nodes. Other types will be handled in separate tutorials.
Before the node can be converted the build has to first be set up to
.. contents:: Node Conversion Steps
Identify attribute names
------------------------
Before modifying any code the .ogn file should be created, in the location described by :ref:`ogn_build_conversion`.
The key components of that file are the node type name, description, version, and the list of attributes, their types,
descriptions, and defaults.
The node type name for most existing nodes is found in the ``getNodeType()`` method.
By looking at the ``initializeType()`` method in the current node it's easy to determine the name of all of the
attributes.
.. code-block:: c++
:linenos:
:emphasize-lines: 5,11-15
struct TimeComputeNode
{
static const char* getNodeType()
{
return "Time";
}
static void initializeType(const NodeTypeObj& nodeTypeObj)
{
const INodeType* iNodeType = nodeTypeObj.iNodeType;
iNodeType->addOutput(nodeTypeObj, "output:time", "double", true, nullptr, nullptr);
iNodeType->addOutput(nodeTypeObj, "output:frame", "double", true, nullptr, nullptr);
iNodeType->addOutput(nodeTypeObj, "output:fps", "double", true, nullptr, nullptr);
iNodeType->addOutput(nodeTypeObj, "output:elapsedTime", "double", true, nullptr, nullptr);
iNodeType->addOutput(nodeTypeObj, "output:timeSinceStart", "double", true, nullptr, nullptr);
}
From this little bit of information the skeleton of the file ``OgnTime.ogn`` can be put in place. In this case we
see that all of the attributes are outputs of type `double` so that dictates the basic contents. It's a bit of an
unusual node in that almost every node will have both inputs and outputs. For the purposes of conversion the principles
are the same, you just put the attributes into the `inputs` subsection instead of `outputs`.
.. note::
Not all attributes might be added to the node in the above way, relying on USD contents to set up the missing
attributes. You can find any missing attributes by examining the USD file, which will contain the attribute's
type and any non-standard default values.
.. code-block:: json
{
"Time" :
{
"version" : 1,
"description" : [""],
"outputs" :
{
"time":
{
"description": [""],
"type": "double"
},
"frame":
{
"description": [""],
"type": "double"
},
"fps":
{
"description": [""],
"type": "double"
},
"elapsedTime":
{
"description": [""],
"type": "double"
},
"timeSinceStart":
{
"description": [""],
"type": "double"
}
}
}
}
A key point to note here is that attributes generated from a .ogn file are automatically namespaced; **inputs:** for
input attributes and **outputs:** for output attributes, so existing USD files or scripts that use the above attribute
names may have to be changed.
Also, in order to keep node names unique, the name of the extension is prepended to the name of the node. So for all
scripts and USD files you will need to perform this renaming:
+----------------+------------------------+
| Old Name | New Name |
+================+========================+
| Time | omni.graph.core.Time |
+----------------+------------------------+
| time | outputs:time |
+----------------+------------------------+
| frame | outputs:frame |
+----------------+------------------------+
| fps | outputs:fps |
+----------------+------------------------+
| elapsedTime | outputs:elapsedTime |
+----------------+------------------------+
| timeSinceStart | outputs:timeSinceStart |
+----------------+------------------------+
The descriptions of the attributes and the node may be found in the node's comments, or may just be understood by
the node writer. They can be filled in directly.
.. code-block:: c++
:linenos:
:emphasize-lines: 5-9
static bool compute(const GraphContextObj& contextObj, const NodeObj& node)
{
const GraphContext::Globals globals = contextObj.context->getGlobals();
setAttributeValue(contextObj, nodeObj, "output:time", (double)globals.currentTime);
setAttributeValue(contextObj, nodeObj, "output:frame", (double)globals.frameTime);
setAttributeValue(contextObj, nodeObj, "output:fps", (double)globals.fps);
setAttributeValue(contextObj, nodeObj, "output:elapsedTime", (double)globals.elapsedTime);
setAttributeValue(contextObj, nodeObj, "output:timeSinceStart", (double)globals.timeSinceStart);
return true;
}
Details of the C++ types available and their corresponding .ogn types can be found in :ref:`ogn_attribute_types`,
which we can use to deduce the types of this node's attributes. (Certain types are modified due to them being different
between the previous and current implementations of the DataModel; they should be relatively obvious on inspection of
the .ogn types document.)
Potential default values can also be deduced from the node algorithm. In this case zero values for every attribute
seems reasonable. When no default values are specified in the .ogn file zeroes are assumed so they do not need to be
explicitly added.
On inspection it seems like some of the attributes can have a minimum value set. In particular, `fps`, `elapsedTime`,
and `timeSinceStart` don't seem like they could be negative values so a minimum of 0.0 is appropriate. Although the .ogn
file will not yet enforce limits at runtime that is the intention in the future so these limits should be recorded.
This is all the information required to complete the .ogn file:
.. code-block:: json
{
"Time" :
{
"version" : 1,
"description" : ["System built-in node to return various time information from kit."],
"outputs" :
{
"time":
{
"description": ["Current global time, in seconds"],
"type": "double"
},
"frame":
{
"description": ["Current global frame time, in seconds"],
"type": "double"
},
"fps":
{
"description": ["Current evaluation rate, in frames per second"],
"type": "double",
"minimum": 0.0
},
"elapsedTime":
{
"description": ["Elapsed time in the current evaluation, in seconds"],
"type": "double",
"minimum": 0.0
},
"timeSinceStart":
{
"description": ["Elapsed time since the start of the session, in seconds"],
"type": "double",
"minimum": 0.0
}
}
}
}
Paring down the includes
------------------------
The generated OGN header file will include everything it needs in order to access the DataModel so the redundant
includes can be removed from the source file **OgnTime.cpp**. The simplest approach is to remove all but the one
necessary inclusion of the database file and add back in any that are missing. In this case only one more file
is necessary, to access the global time information.
.. code-block:: c++
:linenos:
:emphasize-lines: 1
#include <OgnTimeDatabase.h>
#include "GraphContext.h"
Set Up Node Type
----------------
For consistency the class should be named the same as the file, and can be an actual *class* type since there are
no direct ties to the C ABI to it. The node type is set up by the generated code so this starting clause:
.. code-block:: c++
struct TimeComputeNode
{
static const char* getNodeType()
{
return "Time";
}
can be replaced with the single declaration:
.. code-block:: c++
class OgnTime
{
public:
Remove Unnecessary ABI Setup
----------------------------
The generated code handles interfacing with the OmniGraph ABI so the function to get that interface can be deleted:
.. code-block:: c++
:linenos:
:emphasize-lines: 1-11
INodeType getNodeInterfaceTime()
{
INodeType iface = {};
iface.getNodeType = TimeComputeNode::getNodeType;
iface.compute = TimeComputeNode::compute;
iface.initialize = TimeComputeNode::initialize;
iface.release = TimeComputeNode::release;
return iface;
}
It also handles the registration and deregistration of the node type interfaces so that code can be deleted, shown
in the file *omni.graph.core/plugins/PluginInterface.cpp* here:
.. code-block:: c++
:linenos:
:emphasize-lines: 1-4,10-21,26-33
namespace
{
std::vector<const NodeTypeRegistration*> pluginNodeTypeRegistrations;
}
const IToken* Token::iToken = nullptr;
CARB_EXPORT void carbOnPluginStartup()
{
auto iComputeGraph = carb::getFramework()->acquireInterface<IGraphRegistry>();
if (!iComputeGraph)
{
CARB_LOG_ERROR("omni.graph.expression failed to register nodes due to missing interface");
return;
}
std::for_each(pluginNodeTypeRegistrations.begin(), pluginNodeTypeRegistrations.end(),
[&iComputeGraph](const NodeTypeRegistration* nodeTypeRegistration) {
iComputeGraph->registerNodeType(
nodeTypeRegistration->nodeTypeInterface(), nodeTypeRegistration->nodeTypeVersion());
});
}
CARB_EXPORT void carbOnPluginShutdown()
{
auto iComputeGraph = carb::getFramework()->acquireInterface<IGraphRegistry>();
if (!iComputeGraph)
return;
std::for_each(pluginNodeTypeRegistrations.begin(), pluginNodeTypeRegistrations.end(),
[&iComputeGraph](const NodeTypeRegistration* nodeTypeRegistration) {
iComputeGraph->unregisterNodeType(nodeTypeRegistration->nodeTypeInterface().getNodeType());
});
}
The extension must also create the OGN node registration support so that all of its nodes are registered and
deregistered at the proper times. To do so, inclusion of the file *omni/graph/core/OgnHelpers.h* must be added,
and the two relevant macros it defines must be inserted. *DECLARE_OGN_NODES()* appears at file-static level, which
is easiest after the *CARB_PLUGIN* macros, *INITIALIZE_OGN_NODES()* is added in the *carbOnPluginStartup()* method,
and *RELEASE_OGN_NODES()* is added in the *carbOnPluginShutdown()* method.
.. code-block:: c++
:linenos:
:emphasize-lines: 1,28,38,43
#include <omni/graph/core/OgnHelpers.h>
#include <omni/graph/core/iComputeGraph.h>
const struct carb::PluginImplDesc kPluginImpl = { "omni.graph.core.plugin", "OmnIGraph Core", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
CARB_PLUGIN_IMPL(kPluginImpl,
omni::graph::core::ComputeGraph,
omni::graph::core::IAttribute,
omni::graph::core::IAttributeData,
omni::graph::core::IAttributeType,
omni::graph::core::IBundle,
omni::graph::core::IGraph,
omni::graph::core::IGraphContext,
omni::graph::core::IGraphRegistry,
omni::graph::core::INode,
omni::graph::core::IScheduleNode,
omni::graph::core::IDataStealingPrototype,
omni::graph::core::IGatherPrototype)
CARB_PLUGIN_IMPL_DEPS(carb::flatcache::FlatCache,
carb::flatcache::IPath,
carb::flatcache::IToken,
carb::graphics::Graphics,
carb::filesystem::IFileSystem,
omni::gpucompute::GpuCompute,
carb::settings::ISettings)
DECLARE_OGN_NODES()
// carbonite interface for this plugin (may contain multiple compute nodes)
void fillInterface(omni::kit::ITime& iface)
{
iface = {};
}
CARB_EXPORT void carbOnPluginStartup()
{
INITIALIZE_OGN_NODES()
}
CARB_EXPORT void carbOnPluginShutdown()
{
RELEASE_OGN_NODES()
}
.. note::
The functions *carbOnPluginStartup()* and *carbOnPluginShutdown()* are required by the extension manager, even if
they are empty.
Modify Compute Signature
------------------------
The *compute* method required by the generated code has a different signature than the ABI. It is passed a single
parameter, which is a reference to the node's database interface object. Any access required to the former ABI
parameters for other reasons can be accomplished by going through the database object, hence this:
.. code-block:: c++
static bool compute(const GraphContextObj& contextObj, const NodeObj& nodeObj)
{
const IGraphContext* const iContext = contextObj.iContext;
const INode* const iNode = nodeObj.iNode;
becomes this:
.. code-block:: c++
static bool compute(OgnTimeDatabase& db)
{
Refactor Input Attribute Value access
-------------------------------------
Nodes are currently using direct access to the DataModel, either old or new, to get the values of their input
attributes. This is the primary function provided by the generated database class so that access must be
refactored to make use of it.
Often what you'll see in your compute method, when it contains input attributes, are calls like this:
.. code-block:: c++
float noiseRatio, frequency;
noiseRatio = getDataR<float>(contextObj, iNode->getAttribute(nodeObj, "noiseRatio"));
frequency = getDataR<float>(contextObj, iNode->getAttribute(nodeObj, "frequency"));
Although it's not necessary, it can help improve clarity if the values extracted from the database are placed into
local variables for more natural access. You can look up the exact data types returned for a given attribute type
in :ref:`ogn_user_guide`, though for most simple situations you can just use the *auto* declaration. The
highlighted comments are not included in the final code, they are just there for explanation:
.. code-block:: c++
:linenos:
:emphasize-lines: 1-2,4-7
// Inputs always appear in the db.inputs nested structure, and are named for the name of the attribute
// as it appears in the .ogn file. (Any colons used for subnamespaces are converted to underscore for the name.)
const auto& noiseRatio = db.inputs.noiseRatio();
// Actual data type of the above is "const float&" but it's easiest to use plain "const auto&". It also maintains
// consistency with more complex types.
// The original variable names are preserved here but it's a good idea to use the attribute name as the
// variable name, for consistency. (e.g. use "noiseFrequency" instead of "frequency")
const auto& frequency = db.inputs.noiseFrequency();
Refactor Setting Output Attribute Values
----------------------------------------
This snippet of code shows a similar conversion for the time node's setting of output values, whose original code
was seen above:
.. code-block:: c++
:linenos:
const GraphContext::Globals globals = db.abi_context().context->getGlobals();
db.outputs.time() = (double)globals.currentTime;
db.outputs.frame() = (double)globals.frameTime;
db.outputs.fps() = (double)globals.fps;
db.outputs.elapsedTime() = (double)globals.elapsedTime;
db.outputs.timeSinceStart() = (double)globals.timeSinceStart;
Adjust The Algorithm Data Types If Necessary
--------------------------------------------
Most existing nodes are using the USD data types as that is what the old DataModel supported (e.g. GfVec3f). If you've
already examined :ref:`ogn_user_guide` you'll note that the new DataModel uses these types by default. If you
are using anything else you would have to cast the values being returns as in :ref:`ogn_tutorial_tupleData`, or
modify the type definitions used by a file as in :ref:`ogn_type_definition_overrides`.
Add Tests
---------
This particular node uses global data and so is not suitable for adding localized test data for the automatically
generated tests. See :ref:`ogn_test_data` for more information on how to add tests of this nature. For this node we would
want to add scripted tests that do things like confirm that elapsedTime increases during evaluation, and that the time
values are changing during an animation playback.
Modify Attribute Names In Scripts Or USD Files
----------------------------------------------
Previously, attribute names had no well-defined structure and so there may be existing scripts or USD files (.usda in
particular) that reference those names which, under OGN rules may have changed. In extreme cases when content is in
USD binary format or in customer's hands where it can't be changed you may have to implemented the node's
*updateNodeVersion()* method to handle the renaming.
Here's an example of how this node looks in a USD file before conversion:
.. code-block:: usda
def ComputeNode "timeNode"
{
custom token node:type = "Time"
custom int node:typeVersion = 1
double output:time
}
To fix this we rename the existing attributes and node type, and add in the missing ones for completeness:
.. code-block:: usda
:linenos:
:emphasize-lines: 3,5-9
def ComputeNode "timeNode"
{
custom token node:type = "omni.graph.core.Time"
custom int node:typeVersion = 1
double outputs:time
double outputs:frame
double outputs:fps
double outputs:elapsedTime
double outputs:timeSinceStart
}
And this is a place where attributes were being accessed by a test script:
.. code-block:: python
time_node = graph.get_node("/defaultPrim/timeNode")
time_attr = time_node.get_attribute("output:time")
which is also corrected with a simple renaming:
.. code-block:: python
:linenos:
:emphasize-lines: 2
time_node = graph.get_node("/defaultPrim/timeNode")
time_attr = time_node.get_attribute("outputs:time")
Final Result - The Converted Node
---------------------------------
If all has gone well that should be all you need to do to fully convert your node to the .ogn format.
Adding the macro call ``REGISTER_OGN_NODE()`` at the end of the file ensures the node is properly registered when
the extension loads. Note the position of the namespaces.
Here is the final version of the Time node:
.. code-block:: c++
:linenos:
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnTimeDatabase.h>
#include "GraphContext.h"
namespace omni {
namespace graph {
namespace core {
class OgnTime
{
public:
static bool compute(OgnTimeDatabase& db)
{
const GraphContext::Globals globals = db.abi_context().context->getGlobals();
db.outputs.time() = (double)globals.currentTime;
db.outputs.frame() = (double)globals.frameTime;
db.outputs.fps() = (double)globals.fps;
db.outputs.elapsedTime() = (double)globals.elapsedTime;
db.outputs.timeSinceStart() = (double)globals.timeSinceStart;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace core
} // namespace graph
} // namespace omni | 21,359 | reStructuredText | 37.978102 | 121 | 0.635329 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/conversionTutorial/build_conversion.rst | .. _ogn_build_conversion:
Tutorial - OmniGraph Build Environment Conversion
=================================================
These steps will set up the extension to enable building the .ogn file generation and access the generated tests,
include file, and Python file. This only has to be done once per extension, after which any newly converted or
created nodes will be automatically picked up by the build.
Once the build has been set up any existing nodes can be converted to the .ogn format using the steps described
in :ref:`ogn_node_conversion`.
.. note::
If you are building outside Kit you will have to add access to the OGN processing tools in your main premake5.lua
file. See :ref:`ogn_building_outside_kit` for more details.
.. contents:: Build Conversion Steps
Step 1 : File Structure
-----------------------
These are a set of guidelines for file locations and contents that make things consistent, which in turn makes the
lives of developers easier when looking at different sections of code. See :ref:`ogn_recommended_directory_structure`
for more information on why the directory is structured this way.
Here is the file structure of the extension containing the jiggle node before conversion:
.. code-block:: text
omni.anim.jiggle/
βββ bindings/
| βββ BindingsPython.cpp
βββ config/
| βββ extension.toml
βββ plugins/
| βββ Deformer.cpp
| βββ IJiggleDeformer.h
| βββ JiggleDeformer.cpp
βββ premake5.lua
βββ python/
βββ __init__.py
βββ scripts/
βββ commands.py
βββ extension.py
βββ jiggleDeformer.py
βββ kit_utils.py
βββ menu.py
βββ test.py
Python Scripts
++++++++++++++
First thing to note is that we'd like to keep the utility scripts in the ``python`` subdirectory separate from
any tests. The directories can be rearranged with a simple git command:
.. code-block:: bash
git mv python/scripts/tests.py python/tests
That leaves the python directory with this structure:
.. code-block:: text
python/
βββ __init__.py
βββ scripts/
βββ commands.py
βββ extension.py
βββ jiggleDeformer.py
βββ kit_utils.py
βββ menu.py
βββ tests/
βββ test.py
.. note::
The reason that ``scripts/`` is a separate subdirectory is to allow the Python code to be linked as a whole
in the build rather than copied. That way you can drop any file into the ``scripts/`` directory in your source
tree, edit it in place, and have the extension system hot-reload it so that the new script is immediately
available while the app is running.
Nodes
+++++
There is no restriction on how many nodes an extension can support though in this example there is only one. Each
node will have two files; one with the suffix ``.ogn``, containing the node description, and one with the suffix
``.cpp``, containing the node class.
It is helpful to keep the node naming and location consistent. The convention established is to use **Ogn** as a
prefix to the class name, and to put the node files in a ``nodes/`` directory, parallel to ``plugins/``. In the
example here the means creating a new directory and renaming the node as follows:
.. code-block:: bash
mkdir nodes
git mv plugins/JiggleDeformer.cpp nodes/OgnJiggleDeformer.cpp
touch nodes/OgnJiggleDeformer.ogn
The last command creates a placeholder for the file to be populated later.
At this point all of the files are in their final location and the directory structure changes look like this:
.. code:: text
omni.anim.jiggle/ omni.anim.jiggle/
βββ bindings/ βββ bindings/
| βββ BindingsPython.cpp | βββ BindingsPython.cpp
βββ config/ βββ config/
| βββ extension.toml | βββ extension.toml
βββ nodes/ βββ plugins/
| βββ OgnJiggleDeformer.cpp | βββ JiggleDeformer.cpp
| βββ OgnJiggleDeformer.ogn | |
βββ plugins/ | |
| βββ Deformer.cpp | βββ Deformer.cpp
| βββ IJiggleDeformer.h | βββ IJiggleDeformer.h
βββ premake5.lua βββ premake5.lua
βββ python/ βββ python/
βββ __init__.py βββ __init__.py
βββ scripts/ ββββ scripts/
| βββ commands.py βββ commands.py
| βββ extension.py βββ extensions.py
| βββ jiggleDeformer.py βββ jiggleDeformer.py
| βββ kit_utils.py βββ kit_utils.py
| βββ menu.py βββ menu.py
βββ tests/ |
βββ test.py βββ test.py
Step 2 : Fix Python Imports
---------------------------
Since the python files have move the python import directives have to be updated to point to the new locations.
Most of them are okay as they are relative, only those whose relative position will change need to be adjusted
such as the import of the bindings from ``extension.py``. In addition, the generated ``ogn/`` subdirectory must
also be imported if you have any nodes implemented in Python.
.. code-block:: python
:linenos:
:emphasize-lines: 2,6-7
import omni.ext
from .bindings._anim_jiggle import *
from .menu import DeformerMenu
from .commands import *
from .test import *
class Extension(omni.ext.IExt):
def on_startup(self):
self._ext = acquire_interface()
self._menu = DeformerMenu(self._ext)
def on_shutdown(self):
release_interface(self._ext)
self._menu.on_shutdown()
self._menu = None
The bindings will now be at the same relative level so the first highlighted line changes to:
.. code-block:: python
from .bindings._anim_jiggle import *
and the tests will be automatically detected via a mechanism to be added later, :ref:`ogn_test_detection`, so the
second highlighted line will be deleted.
Also, due to the changing locations, the import of ``extension.py`` in the file ``__init__.py`` changes from this:
.. code-block:: python
from .scripts.extension import *
to this
.. code-block:: python
from .extension import *
Step 3 : Add Build Support
--------------------------
The OmniGraph nodes, and the .ogn files in particular, require some build support in order to be processed
correctly.
.. note:: This process assumes you are using the
`*extension 2.0* <https://drive.google.com/file/d/1R35g67nzD8tS-NUI0wiAFNyDWoCiklZk/view>`_ plugin interface
Here are the original contents of the Jiggle extension's ``premake5.lua`` file, with the areas that will be modified
highlighted:
.. code-block:: lua
:linenos:
:emphasize-lines: 3-8,11,14,17-23,25,36,40,42-45,47-65
local ext = get_current_extension_info()
-- change name of plugins here
local namespace = "omni/anim/jiggle"
-- lines below can be copied for other plugins
local python_source_path = "python"
local plugin_source_path = "plugins"
ext.group = "animation"
project_ext(ext)
project_ext_plugin(ext, "omni.anim.jiggle.plugin")
add_files("impl", "plugins")
add_files("iface", "%{root}/include/"..namespace)
exceptionhandling "On"
rtti "On"
removeflags { "NoPCH" } -- to speed up USD includes compiling
filter {}
includedirs {
"%{target_deps}/nv_usd/%{config}/include",
"%{target_deps}/rtx_plugins/include",
"%{target_deps}/cuda/include"
}
filter { "system:linux" }
removeflags { "FatalCompileWarnings", "UndefinedIdentifiers" }
includedirs { "%{target_deps}/python/include/python3.7m" }
filter { "system:windows" }
libdirs { "%{target_deps}/tbb/lib/intel64/vc14" }
filter {}
libdirs { "%{target_deps}/nv_usd/%{config}/lib" }
links {"ar","vt", "gf", "pcp", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel", "omni.usd"}
filter {}
project_ext_bindings {
ext = ext,
project_name = "omni.anim.jiggle.python",
module = "_anim_jiggle",
src = "bindings",
target_subdir = namespace.."/bindings"
}
vpaths {
['bindings'] = "bindings/*.*",
['python'] = python_source_path.."/*.py",
['python/scripts'] = python_source_path.."/scripts/*.py"
}
files {
python_source_path.."/*.py",
python_source_path.."/scripts/*.py"
}
includedirs { plugin_source_path }
repo_build.prebuild_link {
{ "python/scripts", ext.target_dir.."/"..namespace.."/scripts" },
}
repo_build.prebuild_copy {
{ "python/*.py", ext.target_dir.."/"..namespace },
}
Set up Helper Variables With Paths
++++++++++++++++++++++++++++++++++
The first change is to add a few helper variables containing directories of interest (fixing the generic
copy/pasted comments while we are in there). Similar to the *get_current_extension_info()* helper function there
is *get_ogn_project_information()* that defines a table of useful information for OGN projects, assuming a
common layout. See below for details on what it returns.
.. code-block:: lua
:linenos:
:emphasize-lines: 3-6,9
local ext = get_current_extension_info()
-- Helper variable containing standard configuration information for projects containing OGN files
local ogn = get_ogn_project_information(ext, "omni/anim/jiggle")
-- Grouping also tells the name of the premake file that calls this one - $TOP/premake5-{ext.group}.lua
ext.group = "animation"
-- Set up common project variables
project_ext( ext )
The usage of the ogn table will be illuminated below, as will the function definition that was
loaded from omni.graph.tools.
This is extracted from the documentation of the *get_ogn_project_information()* function:
.. code-block:: lua
-- These are the generated table contents:
-- Source Paths
-- bindings_path : Subdirectory containing the C++ implementing Python bindings
-- docs_path : Subdirectory containing the documentation to publish
-- nodes_path : Subdirectory containing the C++ OmniGraph nodes
-- plugin_path : Subdirectory containing the C++ implementing the plugin
-- python_path : Subdirectory containing the Python code
-- Target Paths
-- python_target_path : Path to the Python import directory of the extension
-- python_tests_target_path : Path to the Python tests import directory of the extension
-- bindings_module : Name of the Python bindings module for the extension
-- bindings_target_path : Pyton bindings module import path, relative to root of the extension's Python tree
-- Project Information
-- import_path : Subdirectory for both Python and C++ import/include
-- namespace : Prefix for project names (import_path with "/" replace by ".")
-- plugin_project : Name of the project that builds the C++ code
-- ogn_project : Name of the project that processes the .ogn files
-- python_project : Name of the project that processes the Python code
Add the .ogn files to the project
+++++++++++++++++++++++++++++++++
Although this project doesn't use the .ogn files directly it's useful to have them available in the project file.
Comments are also added while in here to make it clear what each section is doing.
.. code-block:: lua
:linenos:
:emphasize-lines: 1-3,6
-- ----------------------------------------------------------------------
-- Define the project containing the C++ code
project_ext_plugin(ext, ogn.plugin_project)
add_files("impl", ogn.plugin_path)
add_files("ogn", ogn.nodes_path)
The reference to the iface section was removed as it didn't contain any files and under extension 2.0 that is an error.
Add the generated code to the include path
++++++++++++++++++++++++++++++++++++++++++
The generated files must be accessible to the project so a helper function *add_ogn_dependencies()* was added to
make this common set of dependencies easy to implement. It handles *includedirs*, *libdirs*, *links*, and *dependson*
relationships needed by the OGN component of the project, as well as common project compiler configuration.
Thanks to those definitions the rest of the project is pared down to this:
.. code-block:: lua
:linenos:
:emphasize-lines: 1-2
-- Add the standard dependencies all OGN projects have
add_ogn_dependencies(ogn)
includedirs {
"%{target_deps}/rtx_plugins/include",
"%{target_deps}/cuda/include"
}
filter { "system:linux" }
removeflags { "FatalCompileWarnings", "UndefinedIdentifiers" }
includedirs { "%{target_deps}/python/include/python3.7m" }
filter { "system:windows" }
libdirs { "%{target_deps}/tbb/lib/intel64/vc14" }
filter {}
links {"ar", "vt", "gf", "pcp", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel", "omni.usd"}
Insert .ogn project
+++++++++++++++++++
The .ogn processing must precede the compiling of files including the generated headers so it must always happen
first. Unfortunately the current build system doesn't allow for individual file dependencies like that so instead
a secondary project must be set up that will process your .ogn files. The easiest place to insert it is just before
the Python project definition:
.. code-block:: lua
:linenos:
:emphasize-lines: 1-3
-- ----------------------------------------------------------------------
-- Breaking this out as a separate project ensures the .ogn files are processed before their results are needed
project_ext_ogn( ext, ogn )
Notice the *ogn* table defined earlier being passed in to the project definition function.
Update extension definition
+++++++++++++++++++++++++++
In some cases this may not be necessary but our example extension uses the old extension definition for its
Python files as follows:
.. code-block:: lua
:linenos:
:emphasize-lines: 8-16
project_ext_bindings {
ext = ext,
project_name = namespace..".python",
module = "_anim_jiggle",
src = "bindings",
target_subdir = import_path.."/bindings"
}
vpaths {
['bindings'] = "bindings/*.*",
['python'] = python_source_path.."/*.py",
['python/scripts'] = python_source_path.."/scripts/*.py"
}
files {
python_source_path.."/*.py",
python_source_path.."/scripts/*.py"
}
This combination of **vpaths** and **files** definitions is replaced under **extension 2.0** with the following,
also adding the new ``python/tests`` directory to the definition:
.. code-block:: lua
:linenos:
:emphasize-lines: 3,9-12
project_ext_bindings {
ext = ext,
project_name = python_project,
module = "_anim_jiggle",
src = "bindings",
target_subdir = import_path.."/bindings"
}
-- All Python script and documentation files are part of this project
add_files("bindings", "bindings/*.*")
add_files("python", "python/*.py")
add_files("python/scripts", "python/scripts/**.py")
add_files("python/tests", "python/tests/**.py")
The parameters to the project can be replaced with the ones defined in the *ogn* table:
.. code-block:: lua
:linenos:
:emphasize-lines: 1-2,5-8
-- ----------------------------------------------------------------------
-- Python support and scripts for the Jiggle deformer
project_ext_bindings {
ext = ext,
project_name = ogn.python_project,
module = ogn.bindings_module,
src = ogn.bindings_path,
target_subdir = ogn.bindings_target_path
}
Set up OGN Dependencies for Python Nodes
++++++++++++++++++++++++++++++++++++++++
Python nodes will function best if they have hot reloading capability (i.e. a change you make to the source file will
be immediately reflected in the running application). The function that sets up project dependencies for OGN,
**add_ogn_dependencies** has an extra parameter that is a table of directories in which Python OGN nodes live.
This is the directory where your OGN node files are named *OgnMyNode.py*. While it's helpful to have the .ogn file in
the same directory it's not necessary for this particular purpose.
By adding the relative path to all directories containing these nodes the extension configuration will automatically
pick them up and register the nodes with OmniGraph, as well as automatically updating them at runtime if the source
files change. Any future nodes added to the named directories will work with no further change to the build file.
The directory is linked in the build, not copied, so it picks up all subdirectories as well. The only time you need to
modify this table is if a new directory containing Python nodes is created that is a sibling to the currently named
directories. As the registration looks for the node file name pattern of **Ogn.*.py** you can put other files in the
directory without causing any registration problems. You could even include your top level **python/** directory to
ensure all Python nodes are picked up.
.. code-block:: lua
:linenos:
:emphasize-lines: 1-2
-- Add the standard dependencies all OGN projects have, and link directories with Python nodes
add_ogn_dependencies(ogn, {"python/nodes"})
Step 4 : Add Extension Support
------------------------------
The build system handles the compile-time support for the nodes, the extension support will add the link-time
support. For **extension 2.0** this exists in the form of the file ``config/extension.toml``. It must be taught
about the python test modules and the extension dependencies.
.. code-block:: lua
:linenos:
:emphasize-lines: 4,8-15,17,20,22-24
[package]
title = "Omniverse Jiggle Deformer"
# Main module of the python interface
[[python.module]]
name = "omni.anim.jiggle"
# Additional python module used to make .ogn test files auto-discoverable
[[python.module]]
name = "omni.anim.jiggle.ogn.tests"
# Watch the .ogn files for hot reloading (only for Python files)
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Other extensions that must be loaded before this one
[dependencies]
"omni.graph" = {}
"omni.graph.tools" = {}
"omni.kit.usd_undo" = {}
# The generated tests will make use of these modules
"omni.usd" = {}
"omni.kit.async_engine" = {}
[[native.plugin]]
path = "bin/${platform}/${config}/*.plugin"
recursive = false
.. _ogn_test_detection:
Step 5 : Add Python Initialization
----------------------------------
Even nodes written entirely in C++ will have Pythonic interfaces, and possibly Python test scripts. It's best if you
initialize the OGN code on startup in order to take advantage of it rather than trying to do it manually later.
So long as you have an `ogn/` subdirectory in your Python import path this will all be taken care of automatically for
your; both registration and deregistration of your nodes when the extension loads and unloads respectively.
Step 6 : Set up automatic test detection (optional)
---------------------------------------------------
While you could set up test inclusion manually, you would have to add every new test file you create as well.
A mechanism was created to automatically scan a directory for test files and add them to the list testrunner uses
for regression tests. This operates in a similar manner to how the build looks for test files, but at runtime rather
than build time.
To enable this test detection, create ``python/tests/__init__.py`` with the content below. (Other content is fine if
you need it for other tests, this code can appear anywhere in that file.)
.. code-block:: python
"""
Presence of this file allows the tests directory to be imported as a module so that all of its contents
can be scanned to automatically add tests that are placed into this directory.
"""
scan_for_test_modules = True
Now that the build can handle the .ogn files, existing nodes can be converted to the .ogn format using the steps
described in :ref:`ogn_node_conversion`.
Final Result - The Converted Build Script
-----------------------------------------
As reference, here is the final version of the file ``omni.anim.jiggle/premake5.lua`` with all new lines
highlighted:
.. code-block:: lua
:linenos:
:emphasize-lines: 4,7,14,17,20,23,39,46-49,58,63-66
local ext = get_current_extension_info()
-- Helper variable containing standard configuration information for projects containing OGN files
local ogn = get_ogn_project_information(ext, "omni/anim/jiggle")
-- Grouping also tells the name of the premake file that calls this one - $TOP/premake5-{ext.group}.lua
ext.group = "animation"
-- Set up common project variables
project_ext( ext )
-- ----------------------------------------------------------------------
-- Define the project containing the C++ code
project_ext_plugin(ext, ogn.plugin_project)
add_files("impl", ogn.plugin_path)
add_files("ogn", ogn.nodes_path)
-- Add the standard dependencies all OGN projects have
add_ogn_dependencies(ogn)
includedirs {
"%{target_deps}/rtx_plugins/include",
"%{target_deps}/cuda/include"
}
filter { "system:linux" }
removeflags { "FatalCompileWarnings", "UndefinedIdentifiers" }
includedirs { "%{target_deps}/python/include/python3.7m" }
filter { "system:windows" }
libdirs { "%{target_deps}/tbb/lib/intel64/vc14" }
filter {}
links {"ar", "vt", "gf", "pcp", "sdf", "arch", "usd", "tf", "usdUtils", "usdGeom", "usdSkel", "omni.usd"}
-- ----------------------------------------------------------------------
-- Breaking this out as a separate project ensures the .ogn files are processed before their results are needed
project_ext_ogn( ext, ogn )
-- ----------------------------------------------------------------------
-- Python support and scripts for the Jiggle deformer
project_ext_bindings {
ext = ext,
project_name = ogn.python_project,
module = ogn.bindings_module,
src = ogn.bindings_path,
target_subdir = ogn.bindings_target_path
}
-- All Python script and documentation files are part of this project
add_files("bindings", "bindings/*.*")
add_files("python", "python/*.py")
add_files("python/tests", "python/tests/**.py")
-- Add the standard dependencies all OGN projects have, and link directories with Python nodes
add_ogn_dependencies(ogn, {"python/nodes"})
-- Copy the init script directly into the build tree to avoid reload conflicts.
repo_build.prebuild_copy {
{ "python/__init__.py", ogn.python_target_path },
}
-- Linking directories allows them to hot reload when files are modified in the source tree
repo_build.prebuild_link {
{ "python/scripts", ogn.python_target_path.."/scripts" },
{ "python/tests", ogn.python_tests_target_path },
}
| 23,996 | reStructuredText | 37.580386 | 121 | 0.626563 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/conversionTutorial/building_outside_kit.rst | .. _ogn_building_outside_kit:
Tutorial - Building OmniGraph Outside Kit
=========================================
Every effort was made to make OmniGraph just work when you build using the Kit SDK, however there is still one piece
of configuration that must be done manually.
As the initial implementation of Kit does not use C++20, a helper package was installed to enable some advanced
features that the OGN generated code requires. To pick this package up you only have to add it to the filter in your
`deps/target-deps.packman.xml` file where Kit is referenced.
.. code-block:: xml
:linenos:
:emphasize-lines: 5
<!-- Import Kit SDk target-deps xml file to steal some deps from it: -->
<import path="../_build/kit_release/deps/target-deps.packman.xml">
<filter include="pybind11" />
<filter include="fmt" />
<filter include="gsl" />
</import>
That's all that is required to allow any extension in your build to access the .ogn file processing. In order to convert a specific
extension to handle .ogn files see the more detailed document on :ref:`ogn_build_conversion`.
| 1,116 | reStructuredText | 41.961537 | 131 | 0.706989 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial6/tutorial6.rst | .. _ogn_tutorial_tupleArrays:
Tutorial 6 - Array of Tuples
============================
Arrays and tuples can be combined to create common attribute types such as **float[3][]**, and array of
3 floats. This node takes two arrays of float[3]s and generates an output array consisting of the element-wise
dot products.
The *ogn* file shows the implementation of a node named
"omni.graph.tutorials.TupleArrays", which has two tuple-array inputs and a simple array output.
OgnTutorialTupleArrays.ogn
--------------------------
.. literalinclude:: OgnTutorialTupleArrays.ogn
:linenos:
:language: json
OgnTutorialTupleArrays.cpp
--------------------------
The *cpp* file contains the implementation of the compute method, which computes the dot products.
.. literalinclude:: OgnTutorialTupleArrays.cpp
:linenos:
:language: c++
There are typedefs set up for USD-compatible types, e.g. for *float[3]* you get *GfVec3f*. Other types, for whom
there is no USD equivalent, are implemented as *ogn::tuple<TYPE, N>*. See the complete table
of data types in :ref:`ogn_attribute_types`.
+-------------------+----------------------------------+
| Database Function | Returned Type |
+===================+==================================+
| inputs.a() | const ogn::const_array<GfVec3f>& |
+-------------------+----------------------------------+
| inputs.b() | const ogn::const_array<GfVec3f>& |
+-------------------+----------------------------------+
| outputs.result() | ogn::array<GfVec3f>& |
+-------------------+----------------------------------+
Note that the tuple array access is identical to the simple data array access, except that the types are now
the compound tuple types.
| 1,745 | reStructuredText | 39.60465 | 112 | 0.573639 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial6/OgnTutorialTupleArrays.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 <OgnTutorialTupleArraysDatabase.h>
#include <algorithm>
class OgnTutorialTupleArrays
{
public:
static bool compute(OgnTutorialTupleArraysDatabase& db)
{
// Use the "auto&" declarations to avoid long type names, prone to error
const auto& a = db.inputs.a();
const auto& b = db.inputs.b();
auto& result = db.outputs.result();
// Some simple error checking never hurts
if (a.size() != b.size())
{
db.logWarning("Input sizes did not match (%zu versus %zu)", a.size(), b.size());
return false;
}
// The output contents are unrelated to the input contents so resize rather than copying
result.resize(a.size());
// Illustrating how simple these operations are thanks to iterators and the built-in operator*
std::transform(a.begin(), a.end(), b.begin(), result.begin(),
[](const GfVec3f& valueA, const GfVec3f& valueB) -> float { return valueA * valueB; });
return true;
}
};
REGISTER_OGN_NODE()
| 1,501 | C++ | 35.634145 | 110 | 0.664224 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial5/OgnTutorialArrayData.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 <OgnTutorialArrayDataDatabase.h>
#include <algorithm>
class OgnTutorialArrayData
{
public:
static bool compute(OgnTutorialArrayDataDatabase& db)
{
// For clarity get the attribute values into separate variables. The type definitions are included to
// show exactly what data types are returned, though you should know that from your .ogn declaration.
// It's sufficient to use "const auto" for inputs or "auto" for outputs.
const float multiplier = db.inputs.multiplier();
const ::ogn::const_array<float>& inputArray = db.inputs.original();
const ::ogn::const_array<bool>& gateArray = db.inputs.gates();
::ogn::array<float>& outputArray = db.outputs.result();
::ogn::array<bool>& negativeValues = db.outputs.negativeValues();
if (gateArray.size() != inputArray.size())
{
db.logWarning("Gate array size %zu should equal input array size %zu", gateArray.size(), inputArray.size());
return false;
}
// Output array data has to be properly sized before filling as it will contain the same number
// of elements as the input the size is already known. You could also do an assignment and modify the
// output in place if that makes your algorithm more efficient:
// outputArray = inputArray;
outputArray.resize(inputArray.size());
negativeValues.resize(inputArray.size());
// The attribute array data wrapper is compatible with the STL algorithms so computations can be
// performed in a single std::algorithm call.
std::transform(inputArray.begin(), inputArray.end(), gateArray.begin(), outputArray.begin(),
[multiplier](const float& value, const bool& gate) -> float
{ return gate ? value * multiplier : value; });
std::transform(outputArray.begin(), outputArray.end(), negativeValues.begin(),
[](const float& value) -> bool { return value < 0.0f; });
// Regular iterators can also be applied
int totalCharacters{ 0 };
for (const auto& stringInput : db.inputs.info())
{
totalCharacters += int(std::strlen(db.tokenToString(stringInput)));
}
db.outputs.infoSize() = totalCharacters;
return true;
}
};
REGISTER_OGN_NODE()
| 2,812 | C++ | 46.677965 | 120 | 0.664296 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial5/tutorial5.rst | .. _ogn_tutorial_arrayData:
Tutorial 5 - Array Data Node
============================
Array data consists of multiple elements of a simple type whose count is only known at runtime.
For example *float[]* or *double[]*. This node takes an array of floats and a multiplier and generates an
output array consisting of the product of the two.
OgnTutorialArrayData.ogn
------------------------
The *ogn* file shows the implementation of a node named
"omni.graph.tutorials.ArrayData", which has a float value and float array input with one float array output.
.. literalinclude:: OgnTutorialArrayData.ogn
:linenos:
:language: json
OgnTutorialArrayData.cpp
------------------------
The *cpp* file contains the implementation of the compute method, which
multiplies the float value by each member of the float array.
Note how the attribute Array values can be accessed as though they were a simple *std::vector* type.
.. literalinclude:: OgnTutorialArrayData.cpp
:linenos:
:language: c++
Array Attribute Access
----------------------
The attribute access is as described in :ref:`ogn_tutorial_simpleData` except that the exact return types
of the attributes are different in order to support array member access.
Full definition of the array wrapper classes can be found in the interface file *omni/graph/core/ogn/array.h*,
though they do behave in a manner consistent with *std::array*, supporting iterators, standard algorithms, random access
through either ``operator[]`` or the ``at(index)`` function, the ``empty()`` and ``size()`` functions, and access to
the raw underlying data using the function ``data()``. The non-const version also supports assignment and the
``resize()`` function for modifying its contents.
+---------------------+--------------------------------+
| Database Function | Returned Type |
+=====================+================================+
| inputs.original() | const ogn::const_array<float>& |
+---------------------+--------------------------------+
| inputs.multiplier() | const float& |
+---------------------+--------------------------------+
| outputs.result() | ogn::array<float>& |
+---------------------+--------------------------------+
These wrapper classes are similar in concept to ``std::span``, which handles unmanaged pointer+size data. In this case
the data is being managed by the FlatCache. Modifications to the wrapper class data will directly modify the underlying
data in the FlatCache.
You can still use the *auto* declarations on these types, and the array attributes have an additional ``size()``
method added for convenience.
.. code-block:: c++
bool compute(OgnTutorialArrayDataDatabase& db)
{
const auto& multiplier = db.inputs.multiplier();
const auto& original = db.inputs.original();
size_t originalSize = db.inputs.original.size();
auto& result = db.outputs.result();
};
| 2,957 | reStructuredText | 43.149253 | 120 | 0.637809 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/OgnTutorialDynamicAttributes.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 <OgnTutorialDynamicAttributesDatabase.h>
#include <omni/graph/core/CppWrappers.h>
namespace omni {
namespace graph {
using core::AttributeRole;
namespace tutorials {
class OgnTutorialDynamicAttributes
{
public:
static bool compute(OgnTutorialDynamicAttributesDatabase& db)
{
auto iNode = db.abi_node().iNode;
// Get a copy of the input so that it can be modified in place
uint32_t rawOutput = db.inputs.value();
// Only run this section of code if the dynamic attribute is present
if (iNode->getAttributeExists(db.abi_node(), db.tokenToString(db.tokens.firstBit)))
{
AttributeObj firstBit = iNode->getAttributeByToken(db.abi_node(), db.tokens.firstBit);
// firstBit will invert the bit with its number, if present.
const auto firstBitPtr = getDataR<uint32_t>(
db.abi_context(), firstBit.iAttribute->getConstAttributeDataHandle(firstBit, db.getInstanceIndex()));
if (firstBitPtr)
{
if( 0 <= *firstBitPtr && *firstBitPtr <= 31)
{
rawOutput ^= 1 << *firstBitPtr;
}
else
{
db.logWarning("Could not xor bit %ud. Must be in [0, 31]", *firstBitPtr);
}
}
else
{
db.logError("Could not retrieve the data for firstBit");
}
}
if (iNode->getAttributeExists(db.abi_node(), db.tokenToString(db.tokens.secondBit)))
{
AttributeObj secondBit = iNode->getAttributeByToken(db.abi_node(), db.tokens.secondBit);
// secondBit will invert the bit with its number, if present
const auto secondBitPtr = getDataR<uint32_t>(
db.abi_context(), secondBit.iAttribute->getConstAttributeDataHandle(secondBit, db.getInstanceIndex()));
if (secondBitPtr)
{
if( 0 <= *secondBitPtr && *secondBitPtr <= 31)
{
rawOutput ^= 1 << *secondBitPtr;
}
else
{
db.logWarning("Could not xor bit %ud. Must be in [0, 31]", *secondBitPtr);
}
}
else
{
db.logError("Could not retrieve the data for secondBit");
}
}
if (iNode->getAttributeExists(db.abi_node(), db.tokenToString(db.tokens.invert)))
{
AttributeObj invert = iNode->getAttributeByToken(db.abi_node(), db.tokens.invert);
// invert will invert the bits, if the role is set and the attribute access is correct
const auto invertPtr = getDataR<double>(
db.abi_context(), invert.iAttribute->getConstAttributeDataHandle(invert, db.getInstanceIndex()));
if (invertPtr)
{
// Verify that the invert attribute has the (random) correct role before applying it
if (invert.iAttribute->getResolvedType(invert).role == AttributeRole::eTimeCode)
{
rawOutput ^= 0xffffffff;
}
}
else
{
db.logError("Could not retrieve the data for invert");
}
}
// Set the modified result onto the output as usual
db.outputs.result() = rawOutput;
return true;
}
};
REGISTER_OGN_NODE()
} // namespace tutorials
} // namespace graph
} // namespace omni
| 3,995 | C++ | 36 | 119 | 0.580225 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/OgnTutorialDynamicAttributesPy.py | """Implementation of the node OgnTutorialDynamicAttributesPy.ogn"""
from contextlib import suppress
from operator import xor
import omni.graph.core as og
class OgnTutorialDynamicAttributesPy:
@staticmethod
def compute(db) -> bool:
"""Compute the output based on the input and the presence or absence of dynamic attributes"""
raw_output = db.inputs.value
# The suppression of the AttributeError will just skip this section of code if the dynamic attribute
# is not present
with suppress(AttributeError):
# firstBit will invert the bit with its number, if present.
if 0 <= db.inputs.firstBit <= 31:
raw_output = xor(raw_output, 2**db.inputs.firstBit)
else:
db.log_error(f"Could not xor bit {db.inputs.firstBit}. Must be in [0, 31]")
with suppress(AttributeError):
# secondBit will invert the bit with its number, if present
if 0 <= db.inputs.secondBit <= 31:
raw_output = xor(raw_output, 2**db.inputs.secondBit)
else:
db.log_error(f"Could not xor bit {db.inputs.secondBit}. Must be in [0, 31]")
with suppress(AttributeError):
# invert will invert the bits, if the role is set and the attribute access is correct
_ = db.inputs.invert
if (
db.role.inputs.invert == og.AttributeRole.TIMECODE
and db.attributes.inputs.invert == db.abi_node.get_attribute(db.tokens.invert)
):
raw_output = xor(raw_output, 0xFFFFFFFF)
db.outputs.result = raw_output
| 1,652 | Python | 40.324999 | 108 | 0.621065 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial25/tutorial25.rst | .. _ogn_tutorial_dynamic_attributes:
Tutorial 25 - Dynamic Attributes
================================
A dynamic attribute is like any other attribute on a node, except that it is added at runtime rather than being part
of the .ogn specification. These are added through the ABI function ``INode::createAttribute`` and removed from the
node through the ABI function ``INode::removeAttribute``.
Once a dynamic attribute is added it can be accessed through the same ABI and script functions as regular attributes.
.. warning::
While the Python node database is able to handle the dynamic attributes through the same interface as regular
attributes (e.g. ``db.inputs.dynAttr``), the C++ node database is not yet similarly flexible and access to
dynamic attribute values must be done directly through the ABI calls.
OgnTutorialDynamicAttributes.ogn
--------------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.DynamicAttributes", which has a simple
float input and output.
.. literalinclude:: OgnTutorialDynamicAttributes.ogn
:linenos:
:language: json
OgnTutorialDynamicAttributes.cpp
--------------------------------
The *cpp* file contains the implementation of the compute method. It passes the input directly to the output unless it
finds a dynamic attribute named "multiplier", in which case it multiplies by that amount instead.
.. literalinclude:: OgnTutorialDynamicAttributes.cpp
:linenos:
:language: c++
OgnTutorialDynamicAttributesPy.py
---------------------------------
The *py* file contains the same algorithm as the C++ node, with only the implementation language being different.
.. literalinclude:: OgnTutorialDynamicAttributesPy.py
:linenos:
:language: python
Adding And Removing Dynamic Attributes
--------------------------------------
In addition to the above ABI functions the Python ``og.Controller`` class provides the ability to add and remove
dynamic attributes from a script.
To create a dynamic attribute you would use this function:
.. literalinclude:: ../../../omni.graph/python/_impl/node_controller.py
:language: python
:start-after: begin-create-attribute-function
:end-before: end-create-attribute-function
For example this is the code to create a `float[3]` input and a bundle output on an existing node:
.. code-block:: py
import omni.graph.core as og
new_input = og.Controller.create_attribute("/World/MyNode", "newInput", "float[3]")
new_output = og.Controller.create_attribute("/World/MyNode", "newOutput", "bundle", og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
# The proper namespace will be added to the attribute, though you can also be explicit about it
other_input = og.Controller.create_attribute("/World/MyNode", "inputs:otherInput", "float[3]")
When the node is deleted the dynamic attribute will also be deleted, and the attribute will be stored in the USD file.
If you want to remove the attribute from the node at any time you would use this function:
.. literalinclude:: ../../../omni.graph/python/_impl/node_controller.py
:language: python
:start-after: begin-remove-attribute-function
:end-before: end-remove-attribute-function
The second optional parameter is only needed when the attribute is passed as a string. When passing an `og.Attribute`
the node is already known, being part of the attribute.
.. code-block:: py
import omni.graph.core as og
new_attr = og.Controller.create_attribute("/World/MyNode", "newInput", "float[3]")
# When passing the attribute the node is not necessary
og.Controller.remove_attribute(new_attr)
# However if you don't have the attribute available you can still use the name, noting that the
# namespace must be present.
# og.Controller.remove_attribute("inputs:newInput", "/World/MyNode")
Adding More Information
+++++++++++++++++++++++
While the attribute name and type are sufficient to unambiguously create it there is other information you can add
that would normally be present in the .ogn file. It's a good idea to add some of the basic metadata for the UI.
.. code-block:: py
import omni.graph.core as og
new_attr = og.Controller.create_attribute("/World/MyNode", "newInput", "vectorf[3]")
new_attr.set_metadata(og.MetadataKeys.DESCRIPTION, "This is a new input with a vector in it")
new_attr.set_metadata(og.MetadataKeys.UI_NAME, "Input Vector")
While dynamic attributes don't have default values you can do the equivalent by setting a value as soon as you
create the attribute:
.. code-block:: py
import omni.graph.core as og
new_attr = og.Controller.create_attribute("/World/MyNode", "newInput", "vectorf[3]")
og.Controller.set(new_attr, [1.0, 2.0, 3.0])
This default value can also be changed at any time (even when the attribute is already connected):
.. code-block:: py
new_attr.set_default([1.0, 0.0, 0.0])
| 4,930 | reStructuredText | 41.878261 | 136 | 0.722718 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial18/tutorial18.rst | .. _ogn_tutorial_state:
Tutorial 18 - Node With Internal State
======================================
This node illustrates how you can use internal state information, so long as you inform OmniGraph that you are
doing so in order for it to make more intelligent execution scheduling decisions.
The advantage of using internal state data rather than state attributes is that the data can be in any structure
you choose, not just those supported by OmniGraph. The disadvantage is that being opaque, none of the generic UI
will be able to show information about that data.
OgnTutorialState.ogn
--------------------
The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.State". Unlike Python nodes with
internal state the C++ nodes do not require and empty `"state"` section as the presence of state information is
inferred from the data members in the node implementation class (i.e. `mIncrementValue` in this node).
.. literalinclude:: OgnTutorialState.ogn
:linenos:
:language: json
OgnTutorialState.cpp
--------------------
The *.cpp* file contains the compute method and the internal state information used to run the algorithm.
By adding non-static class members to your node OmniGraph will know to instantiate a unique instance of your
node for every evaluation context, letting you use those members as state data. The data in the node will be
invisible to OmniGraph as a whole and will be persistent between evaluations of the node.
.. literalinclude:: OgnTutorialState.cpp
:linenos:
:language: cpp
| 1,558 | reStructuredText | 44.85294 | 116 | 0.749679 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial18/OgnTutorialState.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 <OgnTutorialStateDatabase.h>
#include <atomic>
// Implementation of a C++ OmniGraph node that uses internal state information to compute outputs.
class OgnTutorialState
{
// ------------------------------------------------------------
// The presence of these members will be detected when a node of this type is being instantiated, at which
// time an instance of this node will be attached to the OmniGraph node and be made available in the
// database class as the member "db.internalState<OgnTutorialState>()".
//
// Start all nodes with a monotinic increment value of 0
size_t mIncrementValue{ 0 };
// ------------------------------------------------------------
// You can also define node-type static data, although you are responsible for dealing with any
// thread-safety issues that may arise from accessing it from multiple threads (or multiple hardware)
// at the same time. In this case it is a single value that is read and incremented so an atomic
// variable is sufficient. In real applications this would be a complex structure, potentially keyed off
// of combinations of inputs or real time information, requiring more stringent locking.
//
// This value increases for each node and indicates the value from which a node's own internal state value
// increments. e.g. the first instance of this node type will start its state value at 1, the second instance at 2,
// and so on...
static std::atomic<size_t> sStartingValue;
public:
// Operation of the state mechanism relies on the presence of a default constructor. If you don't have to do
// any initialization you can let the compiler provide the default implementation.
OgnTutorialState()
{
mIncrementValue = sStartingValue;
// Update the per-class state information for the next node. The values go up by 100 to make it easier for
// tests to compare the state information on different nodes.
sStartingValue += 100;
}
// Helper function to update the node's internal state based on the previous values and the per-class state.
// You could also do this in-place in the compute() function; pulling it out here makes the state manipulation
// more explicit.
void updateState()
{
mIncrementValue += 1;
}
public:
// Compute the output based on inputs and internal state
static bool compute(OgnTutorialStateDatabase& db)
{
// This illustrates how internal state and inputs can be used in conjunction. The inputs can be used
// to divert to a different computation path.
if (db.inputs.override())
{
db.outputs.monotonic() = db.inputs.overrideValue();
}
else
{
// OmniGraph ensures that the database contains the correct internal state information for the node
// being evaluated. Beyond that it has no knowledge of the data within that state.
auto& state = db.internalState<OgnTutorialState>();
db.outputs.monotonic() = state.mIncrementValue;
// Update the node's internal state data for the next evaluation.
state.updateState();
}
return true;
}
};
std::atomic<size_t> OgnTutorialState::sStartingValue{ 0 };
REGISTER_OGN_NODE()
| 3,784 | C++ | 44.059523 | 119 | 0.68129 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.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 <OgnTutorialVectorizedPassthroughDatabase.h>
// The method used by the computation to perform the passthrough
// 0 = simple copy, no vectorization
#define TUTO_PASSTHROUGH_METHOD_SIMPLE 0
// 1 = vectorized copy by moving the entire database to the next instance
#define TUTO_PASSTHROUGH_METHOD_DB 1
// 2 = vectorized copy by indexing the instance directly per attribute
#define TUTO_PASSTHROUGH_METHOD_ATTR 2
// 3 = vectorized copy using raw data
#define TUTO_PASSTHROUGH_METHOD_RAW 3
//By default, use the most efficient method
#define TUTO_PASSTHROUGH_METHOD TUTO_PASSTHROUGH_METHOD_RAW
// This node perform a copy of its input to its output
class OgnTutorialVectorizedPassthrough
{
public:
#if TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_SIMPLE
// begin-regular
static bool compute(OgnTutorialVectorizedPassthroughDatabase& db)
{
db.outputs.value() = db.inputs.value();
return true;
}
// end-regular
#elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_DB
// begin-db
static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count)
{
for(size_t idx = 0; idx < count; ++idx)
{
db.outputs.value() = db.inputs.value();
db.moveToNextInstance();
}
return count;
}
// end-db
#elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_ATTR
// begin-attr
static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count)
{
for(size_t idx = 0; idx < count; ++idx)
db.outputs.value(idx) = db.inputs.value(idx);
return count;
}
// end-attr
#elif TUTO_PASSTHROUGH_METHOD == TUTO_PASSTHROUGH_METHOD_RAW
// begin-raw
static size_t computeVectorized(OgnTutorialVectorizedPassthroughDatabase& db, size_t count)
{
auto spanIn = db.inputs.value.vectorized(count);
auto spanOut = db.outputs.value.vectorized(count);
memcpy(spanOut.data(), spanIn.data(), count * sizeof(float));
return count;
}
// end-raw
#endif
};
REGISTER_OGN_NODE()
| 2,547 | C++ | 32.526315 | 95 | 0.708677 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/tutorial21.rst | .. _ogn_tutorial_bundle_add_attributes:
Tutorial 21 - Adding Bundled Attributes
=======================================
Sometimes instead of simply copying data from an input or input bundle into an output bundle you might want to
construct a bundle from some other criteria. For example a bundle construction node could take in an array of names
and attribute types and output a bundle consisting of those attributes with some default values.
The bundle accessor provides a simple method that can accomplish this task. Adding a new attribute is as simple as
providing those two values to the bundle for every attribute you wish to add.
There is also a complementary function to remove named bundle attributes.
OgnTutorialBundleAddAttributes.ogn
----------------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleData", which has one input bundle and one
output bundle.
.. literalinclude:: OgnTutorialBundleAddAttributes.ogn
:linenos:
:language: json
OgnTutorialBundleAddAttributes.cpp
----------------------------------
The *cpp* file contains the implementation of the compute method. It accesses the attribute descriptions on the inputs
and creates a bundle with attributes matching those descriptions as its output.
.. literalinclude:: OgnTutorialBundleAddAttributes.cpp
:linenos:
:language: c++
OgnTutorialBundleAddAttributesPy.py
-----------------------------------
The *py* file contains the same algorithm as the C++ node, with only the implementation language being different.
.. literalinclude:: OgnTutorialBundleAddAttributesPy.py
:linenos:
:language: python
| 1,656 | reStructuredText | 40.424999 | 125 | 0.733092 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributesPy.py | """
Implementation of the Python node adding attributes with a given description to an output bundle.
"""
import omni.graph.core as og
class OgnTutorialBundleAddAttributesPy:
"""Exercise the bundled data types through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Implements the same algorithm as the C++ node OgnTutorialBundleAddAttributes.cpp using the Python
bindings to the bundle method
"""
# Start with an empty output bundle.
output_bundle = db.outputs.bundle
output_bundle.clear()
if db.inputs.useBatchedAPI:
attr_types = [og.AttributeType.type_from_ogn_type_name(type_name) for type_name in db.inputs.typesToAdd]
output_bundle.add_attributes(attr_types, db.inputs.addedAttributeNames)
output_bundle.remove_attributes(db.inputs.removedAttributeNames)
else:
for attribute_type_name, attribute_name in zip(db.inputs.typesToAdd, db.inputs.addedAttributeNames):
attribute_type = og.AttributeType.type_from_ogn_type_name(attribute_type_name)
output_bundle.insert((attribute_type, attribute_name))
# Remove attributes from the bundle that were already added. This is a somewhat contrived operation that
# allows testing of both adding and removal within a simple environment.
for attribute_name in db.inputs.removedAttributeNames:
output_bundle.remove(attribute_name)
return True
| 1,529 | Python | 41.499999 | 116 | 0.689993 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial21/OgnTutorialBundleAddAttributes.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 <OgnTutorialBundleAddAttributesDatabase.h>
#include <omni/graph/core/IAttributeType.h>
using omni::graph::core::Type;
class OgnTutorialBundleAddAttributes
{
public:
static bool compute(OgnTutorialBundleAddAttributesDatabase& db)
{
const auto& attributeTypeNames = db.inputs.typesToAdd();
const auto& attributeNames = db.inputs.addedAttributeNames();
const auto& useBatchedAPI = db.inputs.useBatchedAPI();
auto& outputBundle = db.outputs.bundle();
// The usual error checking. Being diligent about checking the data ensures you will have an easier time
// debugging the graph if anything goes wrong.
if (attributeTypeNames.size() != attributeNames.size())
{
db.logWarning(
"Number of attribute types (%zu) does not match number of attribute names (%zu)",
attributeTypeNames.size(), attributeNames.size()
);
return false;
}
// Make sure the bundle is starting from empty
outputBundle.clear();
if (useBatchedAPI)
{
//
// unfortunately we need to build a vector of the types
//
auto typeNameIt = std::begin(attributeTypeNames);
std::vector<Type> types;
types.reserve(attributeTypeNames.size());
for (; typeNameIt != std::end(attributeTypeNames); ++typeNameIt)
{
auto typeName = *typeNameIt;
types.emplace_back(db.typeFromName(typeName));
}
outputBundle.addAttributes(attributeTypeNames.size(), attributeNames.data(), types.data());
// Remove attributes from the bundle that were already added. This is a somewhat contrived operation that
// allows testing of both adding and removal within a simple environment.
if (db.inputs.removedAttributeNames().size()) {
outputBundle.removeAttributes(db.inputs.removedAttributeNames().size(), db.inputs.removedAttributeNames().data());
}
}
else
{
// Since the two arrays are the same size a dual loop can be used to walk them in pairs
auto typeNameIt = std::begin(attributeTypeNames);
auto attributeNameIt = std::begin(attributeNames);
for (; typeNameIt != std::end(attributeTypeNames) && attributeNameIt != std::end(attributeNames); ++typeNameIt, ++attributeNameIt)
{
auto typeName = *typeNameIt;
auto attributeName = *attributeNameIt;
auto typeNameString = db.tokenToString(typeName);
Type newType = db.typeFromName(typeName);
// Ignore the output since for this example there will not be any values set on the new attribute
(void)outputBundle.addAttribute(attributeName, newType);
}
// Remove attributes from the bundle that were already added. This is a somewhat contrived operation that
// allows testing of both adding and removal within a simple environment.
for (const auto& toRemove : db.inputs.removedAttributeNames())
{
outputBundle.removeAttribute(toRemove);
}
}
return true;
}
};
REGISTER_OGN_NODE()
| 3,786 | C++ | 42.03409 | 142 | 0.637612 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial8/tutorial8.rst | .. _ogn_tutorial_cudaData:
Tutorial 8 - GPU Data Node
==========================
The GPU data node creates various attributes for use in a CUDA-based GPU compute. Several representative
types are used, though the list of potential attribute types is not exhaustive. See :ref:`ogn_attribute_types`
for the full list.
This node also introduces the notion of attribute typedefs; a useful concept when passing data around in functions.
OgnTutorialCudaData.ogn
-----------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CudaData", which has inputs and outputs of
various types to use in various computations. Three different CUDA methods are created to show how each of the
types is passed through to the GPU and used by CUDA.
.. literalinclude:: OgnTutorialCudaData.ogn
:linenos:
:language: json
OgnTutorialCudaData.cpp
-----------------------
The *cpp* file contains the implementation of the compute method, which in turn calls the three CUDA algorithms.
.. literalinclude:: OgnTutorialCudaData.cpp
:linenos:
:language: c++
OgnTutorialCudaData_CUDA.cu
---------------------------
The *cu* file contains the implementation of the algorithms on the GPU using CUDA.
.. literalinclude:: OgnTutorialCudaData_CUDA.cu
:linenos:
:language: c++
GPU Attribute Access
--------------------
Here is the set of generated attributes from the database. The attributes living on the GPU return pointers to
memory as the CPU side cannot dereference it into its actual type (e.g. a `float` value, which would be returned as
a `float&` on the CPU side is returned instead as a `float*` on the GPU side.)
In addition, when calling into CUDA code the data changes type as it crosses the GPU boundary. On the CUDA side it
uses the CUDA native data types when it can, which are bytewise compatible with their CPU counterparts. Note that
in the case of the CPU attribute *multiplier* the data is passed to the CUDA code by value, since it has to be
copied from CPU to GPU.
+---------------------+---------+--------------------+-----------------+
| Database Function | Is GPU? | CPU Type | CUDA Type |
+=====================+=========+====================+=================+
| inputs.a() | Yes | const float* | const float* |
+---------------------+---------+--------------------+-----------------+
| inputs.b() | Yes | const float* | const float* |
+---------------------+---------+--------------------+-----------------+
| outputs.sum() | Yes | float* | float* |
+---------------------+---------+--------------------+-----------------+
| inputs.half() | Yes | const pxr::GfHalf* | __half* |
+---------------------+---------+--------------------+-----------------+
| outputs.half() | Yes | pxr::GfHalf* | __half* |
+---------------------+---------+--------------------+-----------------+
| inputs.color() | Yes | const GfVec3d* | const double3* |
+---------------------+---------+--------------------+-----------------+
| outputs.color() | Yes | GfVec3d* | double3* |
+---------------------+---------+--------------------+-----------------+
| inputs.matrix() | Yes | const GfMatrix4d* | const Matrix4d* |
+---------------------+---------+--------------------+-----------------+
| outputs.matrix() | Yes | GfMatrix4d* | Matrix4d* |
+---------------------+---------+--------------------+-----------------+
| inputs.multiplier() | No | const GfVec3f& | const float3 |
+---------------------+---------+--------------------+-----------------+
| inputs.points() | Yes | const GfVec3f* | const float3** |
+---------------------+---------+--------------------+-----------------+
| outputs.points() | Yes | GfVec3f* | float3** |
+---------------------+---------+--------------------+-----------------+
The array attribute *points* does not have an array-like wrapper as the CUDA code would rather deal with
raw pointers. In order to provide the size information, when calling the CUDA code the value ``inputs.points.size()``
should also be passed in.
Notice the subtle difference in types on the CPU side for GPU-based data. Instead of references to data there are
pointers, necessary since the data lives in a different memory-space, and all pointers have an extra level of
indirection for the same reason.
There is also a section of this generated file dedicated to information relevant to the CUDA code. In this section
the CUDA attribute data types are defined.
It is protected with ``#ifdef __CUDACC__`` so that it is only processed when included through the CUDA
compiler (and vice versa, so none of the other setup code will be processed on the CUDA side).
.. code-block:: c++
#include <cuda_fp16.h>
#include <omni/graph/core/cuda/CUDAUtils.h>
#include <omni/graph/core/cuda/Matrix4d.h>
namespace OgnTutorialCudaDataCudaTypes
{
namespace inputs
{
using a_t = const float*;
using b_t = const float*;
using points_t = const float3**;
using multiplier_t = const float3*;
using half_t = const __half*;
using color_t = const double3*;
using matrix_t = const Matrix4d*;
}
namespace outputs
{
using sum_t = float*;
using points_t = float3**;
using half_t = __half*;
using color_t = double3*;
using matrix_t = Matrix4d*;
}
}
using namespace OgnTutorialCudaDataCudaTypes;
Notice the inclusion of the file *cuda_fp16.h*, needed due to the use of the CUDA type *__half*, and the files
*omni/graph/core/cuda/CUDAUtils.h* and *omni/graph/core/cuda/Matrix4d.h*, which provide support functions for CUDA
math.
The data types used by CUDA are compatible with their equivalents on the C++ side, so you can specify passing arguments
into CUDA from C++ by using a declaration such as this on the C++ side:
.. code-block:: c++
// In this code "inputs::points_t" is the type "GfVec3f*".
// The size of that array must be passed in as well since it is not implicit in the data type.
extern "C" void cudaCompute(
inputs::points_t*,
size_t pointSize,
inputs::multiplier_t*,
outputs::points_t*
);
which corresponds to this function defined in the .cu file:
.. code-block:: c++
// In this code "inputs::points_t" is the type "float3*"
extern "C" void cudaCompute(
inputs::points_t* inPoints,
size_t pointSize,
inputs::multiplier_t* multiplier,
outputs::points_t* outPoints
)
{...}
Pointers are used in the calls rather than being part of the type definitions in order to emphasize the fact that the
values passed through are pointers to the real data in the flatcache, which in this case is data in GPU memory.
| 6,896 | reStructuredText | 44.375 | 120 | 0.571491 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial8/OgnTutorialCudaData.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 <omni/graph/core/GpuArray.h>
#include <OgnTutorialCudaDataDatabase.h>
// This function exercises referencing simple data types on the GPU, something you normally wouldn't do as
// there is no efficiency gain in doing that versus just passing in the CPU value.
extern "C" void applyAddGPU(outputs::sum_t sum, inputs::a_t a, inputs::b_t b);
// This function exercises referencing of array data on the GPU.
// The CUDA code takes its own "float3" data types, which are castable equivalents to the generated GfVec3f.
// The GpuArray/ConstGpuArray wrappers isolate the GPU pointers from the CPU code.
extern "C" void applyDeformationGPU(outputs::points_t outputPoints,
inputs::points_t inputPoints,
inputs::multiplier_t multiplier,
size_t numberOfPoints);
// This function exercises referencing non-standard data types on the GPU to illustrate how data of different
// types are passed to the GPU.
extern "C" void applyDataTypes(outputs::half_t halfOutput,
outputs::color_t colorOutput,
outputs::matrix_t matrixOutput,
inputs::half_t halfInput,
inputs::color_t colorInput,
inputs::matrix_t matrixInput);
// This node runs a couple of algorithms on the GPU, while accessing parameters from the CPU
class OgnTutorialCudaData
{
public:
static bool compute(OgnTutorialCudaDataDatabase& db)
{
// ================ algorithm 1 =========================================================
// It's an important distinction here that GPU data is always returned as raw pointers since the CPU code
// in the node cannot directly access it. The raw pointers are passed into the GPU code for dereferencing.
applyAddGPU(db.outputs.sum(), db.inputs.a(), db.inputs.b());
// ================ algorithm 2 =========================================================
size_t numberOfPoints = db.inputs.points.size();
db.outputs.points.resize(numberOfPoints);
const auto& multiplier = db.inputs.multiplier();
if (numberOfPoints > 0)
{
applyDeformationGPU(db.outputs.points(), db.inputs.points(), db.inputs.multiplier(), numberOfPoints);
}
// ================ algorithm 3 =========================================================
applyDataTypes(db.outputs.half(), db.outputs.color(), db.outputs.matrix(),
db.inputs.half(), db.inputs.color(), db.inputs.matrix());
return true;
}
};
REGISTER_OGN_NODE()
| 3,142 | C++ | 49.693548 | 114 | 0.614895 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial10/OgnTutorialSimpleDataPy.py | """
Implementation of the Python node accessing all of the simple data types.
This class exercises access to the DataModel through the generated database class for all simple data types.
It implements the same algorithm as the C++ node OgnTutorialSimpleData.cpp
"""
import omni.graph.tools.ogn as ogn
class OgnTutorialSimpleDataPy:
"""Exercise the simple data types through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Perform a trivial computation on all of the simple data types to make testing easy"""
# Inside the database the contained object "inputs" holds the data references for all input attributes and the
# contained object "outputs" holds the data references for all output attributes.
# Each of the attribute accessors are named for the name of the attribute, with the ":" replaced by "_".
# The colon is used in USD as a convention for creating namespaces so it's safe to replace it without
# modifying the meaning. The "inputs:" and "outputs:" prefixes in the generated attributes are matched
# by the container names.
# For example attribute "inputs:translate:x" would be accessible as "db.inputs.translate_x" and attribute
# "outputs:matrix" would be accessible as "db.outputs.matrix".
# The "compute" of this method modifies each attribute in a subtle way so that a test can be written
# to verify the operation of the node. See the .ogn file for a description of tests.
db.outputs.a_bool = not db.inputs.a_bool
db.outputs.a_half = 1.0 + db.inputs.a_half
db.outputs.a_int = 1 + db.inputs.a_int
db.outputs.a_int64 = 1 + db.inputs.a_int64
db.outputs.a_double = 1.0 + db.inputs.a_double
db.outputs.a_float = 1.0 + db.inputs.a_float
db.outputs.a_uchar = 1 + db.inputs.a_uchar
db.outputs.a_uint = 1 + db.inputs.a_uint
db.outputs.a_uint64 = 1 + db.inputs.a_uint64
db.outputs.a_string = db.inputs.a_string.replace("hello", "world")
db.outputs.a_objectId = 1 + db.inputs.a_objectId
# The token interface is made available in the database as well, for convenience.
# By calling "db.token" you can look up the token ID of a given string.
if db.inputs.a_token == "helloToken":
db.outputs.a_token = "worldToken"
# Path just gets a new child named "Child".
# In the implementation the string is manipulated directly, as it does not care if the SdfPath is valid or
# not. If you want to manipulate it using the pxr.Sdf.Path API this is how you could do it:
#
# from pxr import Sdf
# input_path Sdf.Path(db.inputs.a_path)
# if input_path.IsValid():
# db.outputs.a_path() = input_path.AppendChild("/Child").GetString();
#
db.outputs.a_path = db.inputs.a_path + "/Child"
# To access the metadata you have to go out to the ABI, though the hardcoded metadata tags are in the
# OmniGraph Python namespace
assert db.node.get_attribute("inputs:a_bool").get_metadata(ogn.MetadataKeys.UI_NAME) == "Simple Boolean Input"
# You can also use the database interface to get the same data
db.outputs.a_nodeTypeUiName = db.get_metadata(ogn.MetadataKeys.UI_NAME)
db.outputs.a_a_boolUiName = db.get_metadata(ogn.MetadataKeys.UI_NAME, db.attributes.inputs.a_bool)
return True
| 3,475 | Python | 52.476922 | 118 | 0.671655 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial10/tutorial10.rst | .. _ogn_tutorial_simpleDataPy:
Tutorial 10 - Simple Data Node in Python
========================================
The simple data node creates one input attribute and one output attribute of each of the simple types, where "simple"
refers to data types that have a single component and are not arrays. (e.g. "float" is simple, "float[3]" is not, nor is
"float[]"). See also :ref:`ogn_tutorial_simpleData` for a similar example in C++.
Automatic Python Node Registration
----------------------------------
By implementing the standard Carbonite extension interfact in Python, OmniGraph will know to scan your Python import
path for to recursively scan the directory, import all Python node files it finds, and register those nodes.
It will also deregister those nodes when the extension shuts down. Here is an example of the directory structure for
an extension with a single node in it. (For extensions that have a `premake5.lua` build script this will be in the
build directory. For standalone extensions it is in your source directory.)
.. code-block:: text
omni.my.extension/
omni/
my/
extension/
nodes/
OgnMyNode.ogn
OgnMyNode.py
OgnTutorialSimpleDataPy.ogn
---------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.SimpleDataPy", which has one
input and one output attribute of each simple type.
.. literalinclude:: OgnTutorialSimpleDataPy.ogn
:linenos:
:language: json
OgnTutorialSimpleDataPy.py
--------------------------
The *py* file contains the implementation of the compute method, which modifies
each of the inputs in a simple way to create outputs that have different values.
.. literalinclude:: OgnTutorialSimpleDataPy.py
:linenos:
:language: python
Note how the attribute values are available through the ``OgnTutorialSimpleDataPyDatabase`` class. The generated
interface creates access methods for every attribute, named for the attribute itself. They are all implemented as Python
properties, where inputs only have get methods and outputs have both get and set methods.
Pythonic Attribute Data
-----------------------
Three subsections are creating in the generated database class. The main section implements the node type ABI methods
and uses introspection on your node class to call any versions of the ABI methods you have defined (see later
tutorials for examples of how this works).
The other two subsections are classes containing attribute access properties for inputs and outputs. For naming
consistency the class members are called *inputs* and *outputs*. For example, you can access the value of the input
attribute named *foo* by referencing ``OgnTutorialSimpleDataPyDatabase.inputs.foo``.
For the curious, here is an example of how the boolean attribute access is set up on the simple tutorial node:
.. code-block:: python
class OgnTutorialSimpleDataPyDatabase:
class InputAttributes:
def __init__(self, context_helper, node):
self.context_helper = context_helper
self.node = node
# A lock is used to prevent inputs from inadvertently being modified during a compute.
# This is equivalent to the "const" approach used in C++.
self.setting_locked = False
# Caching the Attribute object lets future data access run faster
self._a_bool = node.get_attribute('inputs:a_bool')
@property
def a_bool(self):
return self.context_helper.get_attr_value(self._a_bool)
@a_bool.setter
def a_bool(self, value):
if self.setting_locked:
raise AttributeError('inputs:a_bool')
self.context_helper.set_attr_value(value, self._a_bool)
class OutputAttributes:
def __init__(self, context_helper, node):
self.context_helper = context_helper
self.node = node
self._a_bool = node.get_attribute('outputs:a_bool')
@property
def a_bool(self):
return self.context_helper.get_attr_value(self._a_bool)
@a_bool.setter
def a_bool(self, value):
self.context_helper.set_attr_value(value, self._a_bool)
def __init__(self, context, node):
self.context = context
self.node = node
self.context_helper = ContextHelper(context)
self.inputs = OgnTutorialSimpleDataPyDatabase.InputAttributes(self.context_helper, node)
self.outputs = OgnTutorialSimpleDataPyDatabase.OutputAttributes(self.context_helper, node)
Pythonic Attribute Access
-------------------------
In the USD file the attribute names are automatically namespaced as *inputs:FOO* or *outputs:BAR*. In the Python
interface the colon is illegal so the contained classes above are used to make use of the dot-separated equivalent,
as *inputs.FOO* or *outputs.BAR*.
While the underlying data types are stored in their exact form there is conversion when they are passed back to Python
as Python has a more limited set of data types, though they all have compatible ranges. For this class, these are the
types the properties provide:
+-------------------+---------------+
| Database Property | Returned Type |
+===================+===============+
| inputs.a_bool | bool |
+-------------------+---------------+
| inputs.a_half | float |
+-------------------+---------------+
| inputs.a_int | int |
+-------------------+---------------+
| inputs.a_int64 | int |
+-------------------+---------------+
| inputs.a_float | float |
+-------------------+---------------+
| inputs.a_double | float |
+-------------------+---------------+
| inputs.a_token | str |
+-------------------+---------------+
| outputs.a_bool | bool |
+-------------------+---------------+
| outputs.a_half | float |
+-------------------+---------------+
| outputs.a_int | int |
+-------------------+---------------+
| outputs.a_int64 | int |
+-------------------+---------------+
| outputs.a_float | float |
+-------------------+---------------+
| outputs.a_double | float |
+-------------------+---------------+
| outputs.a_token | str |
+-------------------+---------------+
The data returned are all references to the real data in the FlatCache, our managed memory store, pointed to the
correct location at evaluation time.
Python Helpers
--------------
A few helpers are provided in the database class definition to help make coding with it more natural.
Python logging
++++++++++++++
Two helper functions are providing in the database class to help provide more information when the compute method of
a node has failed. Two methods are provided, both taking a formatted string describing the problem.
``log_error(message)`` is used when the compute has run into some inconsistent or unexpected data, such as two
input arrays that are supposed to have the same size but do not, like the normals and vertexes on a mesh.
``log_warning(message)`` can be used when the compute has hit an unusual case but can still provide a consistent
output for it, for example the deformation of an empty mesh would result in an empty mesh and a warning since that is
not a typical use for the node.
Direct Pythonic ABI Access
++++++++++++++++++++++++++
All of the generated database classes provide access to the underlying *INodeType* ABI for those rare situations
where you want to access the ABI directly. There are two members provided, which correspond to the objects passed
in to the ABI compute method.
There is the graph evaluation context member, ``context: Py_GraphContext``, for accessing the underlying OmniGraph
evaluation context and its interface.
There is also the OmniGraph node member, ``node: Py_Node``, for accessing the underlying OmniGraph node
object and its interface.
| 8,133 | reStructuredText | 44.188889 | 120 | 0.628673 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial13/OgnTutorialStatePy.py | """
Implementation of a Python node that uses internal state information to compute outputs.
There are two types of state information in use here:
- OgnTutorialStatePy.step (per-class state information)
This is inherently dangerous in a multi-threaded multi-hardware evaluation so
it must be used with care. In this case the value is only used when a node is created, which for now is a safe
single-threaded operation
- per-node state information.
"""
class OgnTutorialStatePyInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
"""Instantiate the per-node state information.
Note: For convenience, per-node state data is maintained as members of this class, imposing the minor
restriction of having no parameters allowed in this constructor.
The presence of the "state" section in the .ogn node has flagged to omnigraph the fact that this node will
be managing some per-node state data.
"""
# Start all nodes with a monotinic increment value of 0
self.increment_value = 0
# Get this node's internal step value from the per-class state information
self.node_step = OgnTutorialStatePy.step
# Update the per-class state information for the next node
OgnTutorialStatePy.step += 1
def update_state(self):
"""Helper function to update the node's internal state based on the previous values and the per-class state"""
self.increment_value += self.node_step
class OgnTutorialStatePy:
"""Use internal node state information in addition to inputs"""
# This is a simplified bit of internal per-class state information. In real applications this would be a complex
# structure, potentially keyed off of combinations of inputs or real time information.
#
# This value increases for each node and indicates the value at which a node's own internal state value increments.
# e.g. the first instance of this node type will increment its state value by 1, the second instance of it by 2,
# and so on...
step = 1
# Defining this method, in conjunction with adding the "state" section in the .ogn file, tells OmniGraph that you
# intend to maintain opaque internal state information on your node. OmniGraph will ensure that your node is not
# scheduled for evaluation in such a way that it would compromise the thread-safety of your node due to this state
# information, however you are responsible for updating the values and/or maintaining your own dirty bits when
# required.
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnTutorialStatePyInternalState()
@staticmethod
def compute(db) -> bool:
"""Compute the output based on inputs and internal state"""
# This illustrates how internal state and inputs can be used in conjunction. The inputs can be used
# to divert to a different computation path.
if db.inputs.override:
db.outputs.monotonic = db.inputs.overrideValue
else:
# OmniGraph ensures that the database contains the correct internal state information for the node
# being evaluated. Beyond that it has no knowledge of the data within that state.
db.outputs.monotonic = db.internal_state.increment_value
# Update the node's internal state data for the next evaluation.
db.internal_state.update_state()
return True
| 3,600 | Python | 46.381578 | 119 | 0.709167 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial13/tutorial13.rst | .. _ogn_tutorial_state_py:
Tutorial 13 - Python State Node
===============================
This node illustrates how you can use internal state information, so long as you inform OmniGraph that you are
doing so in order for it to make more intelligent execution scheduling decisions.
OgnTutorialStatePy.ogn
----------------------
The *.ogn* file containing the implementation of a node named "omni.graph.tutorials.StatePy", with an empty state set to
inform OmniGraph of its intention to compute using internal state information.
.. literalinclude:: OgnTutorialStatePy.ogn
:linenos:
:language: json
OgnTutorialStatePy.py
---------------------
The *.py* file contains the compute method and the internal state information used to run the algorithm.
By overriding the special method ``internal_state`` you can define an object that will contain per-node data that
you can manage yourself. It will not be visible to OmniGraph.
.. literalinclude:: OgnTutorialStatePy.py
:linenos:
:language: python
| 1,017 | reStructuredText | 35.357142 | 120 | 0.725664 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypesPy.py | """
Implementation of the Python node accessing attributes whose type is determined at runtime.
This class exercises access to the DataModel through the generated database class for all simple data types.
"""
import omni.graph.core as og
# Hardcode each of the expected types for easy comparison
FLOAT_TYPE = og.Type(og.BaseDataType.FLOAT)
TOKEN_TYPE = og.Type(og.BaseDataType.TOKEN)
BOOL_ARRAY_TYPE = og.Type(og.BaseDataType.BOOL, array_depth=1)
FLOAT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, array_depth=1)
FLOAT3_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3)
INT2_TYPE = og.Type(og.BaseDataType.INT, tuple_count=2)
FLOAT3_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1)
class OgnTutorialExtendedTypesPy:
"""Exercise the runtime data types through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Implements the same algorithm as the C++ node OgnTutorialExtendedTypes.cpp.
It follows the same code pattern for easier comparison, though in practice you would probably code Python
nodes differently from C++ nodes to take advantage of the strengths of each language.
"""
def __compare_resolved_types(input_attribute, output_attribute) -> og.Type:
"""Returns the resolved type if they are the same, outputs a warning and returns None otherwise"""
resolved_input_type = input_attribute.type
resolved_output_type = output_attribute.type
if resolved_input_type != resolved_output_type:
db.log_warn(f"Resolved types do not match {resolved_input_type} -> {resolved_output_type}")
return None
return resolved_input_type if resolved_input_type.base_type != og.BaseDataType.UNKNOWN else None
# ---------------------------------------------------------------------------------------------------
def _compute_simple_values():
"""Perform the first algorithm on the simple input data types"""
# Unlike C++ code the Python types are flexible so you must check the data types to do the right thing.
# This works out better when the operation is the same as you don't even have to check the data type. In
# this case the "doubling" operation is slightly different for floats and tokens.
resolved_type = __compare_resolved_types(db.inputs.floatOrToken, db.outputs.doubledResult)
if resolved_type == FLOAT_TYPE:
db.outputs.doubledResult.value = db.inputs.floatOrToken.value * 2.0
elif resolved_type == TOKEN_TYPE:
db.outputs.doubledResult.value = db.inputs.floatOrToken.value + db.inputs.floatOrToken.value
# A Pythonic way to do the same thing by just applying an operation and checking for compatibility is:
# try:
# db.outputs.doubledResult = db.inputs.floatOrToken * 2.0
# except TypeError:
# # Gets in here for token types since multiplying string by float is not legal
# db.outputs.doubledResult = db.inputs.floatOrToken + db.inputs.floatOrToken
return True
# ---------------------------------------------------------------------------------------------------
def _compute_array_values():
"""Perform the second algorithm on the array input data types"""
resolved_type = __compare_resolved_types(db.inputs.toNegate, db.outputs.negatedResult)
if resolved_type == BOOL_ARRAY_TYPE:
db.outputs.negatedResult.value = [not value for value in db.inputs.toNegate.value]
elif resolved_type == FLOAT_ARRAY_TYPE:
db.outputs.negatedResult.value = [-value for value in db.inputs.toNegate.value]
return True
# ---------------------------------------------------------------------------------------------------
def _compute_tuple_values():
"""Perform the third algorithm on the 'any' data types"""
resolved_type = __compare_resolved_types(db.inputs.tuple, db.outputs.tuple)
# Notice how, since the operation is applied the same for both recognized types, the
# same code can handle both of them.
if resolved_type in (FLOAT3_TYPE, INT2_TYPE):
db.outputs.tuple.value = tuple(-x for x in db.inputs.tuple.value)
# An unresolved type is a temporary state and okay, resolving to unsupported types means the graph is in
# an unsupported configuration that needs to be corrected.
elif resolved_type is not None:
type_name = resolved_type.get_type_name()
db.log_error(f"Only float[3] and int[2] types are supported by this node, not {type_name}")
return False
return True
# ---------------------------------------------------------------------------------------------------
def _compute_flexible_values():
"""Perform the fourth algorithm on the multi-shape data types"""
resolved_type = __compare_resolved_types(db.inputs.flexible, db.outputs.flexible)
if resolved_type == FLOAT3_ARRAY_TYPE:
db.outputs.flexible.value = [(-x, -y, -z) for (x, y, z) in db.inputs.flexible.value]
elif resolved_type == TOKEN_TYPE:
db.outputs.flexible.value = db.inputs.flexible.value[::-1]
return True
# ---------------------------------------------------------------------------------------------------
compute_success = _compute_simple_values()
compute_success = _compute_array_values() and compute_success
compute_success = _compute_tuple_values() and compute_success
compute_success = _compute_flexible_values() and compute_success
# ---------------------------------------------------------------------------------------------------
# As Python has a much more flexible typing system it can do things in a few lines that require a lot
# more in C++. One such example is the ability to add two arbitrary data types. Here is an example of
# how, using "any" type inputs "a", and "b", with an "any" type output "result" you can generically
# add two elements without explicitly checking the type, failing only when Python cannot support
# the operation.
#
# try:
# db.outputs.result = db.inputs.a + db.inputs.b
# return True
# except TypeError:
# a_type = inputs.a.type().get_type_name()
# b_type = inputs.b.type().get_type_name()
# db.log_error(f"Cannot add attributes of type {a_type} and {b_type}")
# return False
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
# There are 4 sets of type-coupled attributes in this node, meaning that the base_type of the attributes
# must be the same for the node to function as designed.
# 1. floatOrToken <-> doubledResult
# 2. toNegate <-> negatedResult
# 3. tuple <-> tuple
# 4. flexible <-> flexible
#
# The following code uses a helper function to resolve the attribute types of the coupled pairs. Note that
# without this logic a chain of extended-attribute connections may result in a non-functional graph, due to
# the requirement that types be resolved before graph evaluation, and the ambiguity of the graph without knowing
# how the types are related.
og.resolve_fully_coupled(
[node.get_attribute("inputs:floatOrToken"), node.get_attribute("outputs:doubledResult")]
)
og.resolve_fully_coupled([node.get_attribute("inputs:toNegate"), node.get_attribute("outputs:negatedResult")])
og.resolve_fully_coupled([node.get_attribute("inputs:tuple"), node.get_attribute("outputs:tuple")])
og.resolve_fully_coupled([node.get_attribute("inputs:flexible"), node.get_attribute("outputs:flexible")])
| 8,136 | Python | 55.506944 | 120 | 0.599435 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/OgnTutorialExtendedTypes.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 <OgnTutorialExtendedTypesDatabase.h>
#include <algorithm>
//
// Attributes whose data types resolve at runtime ("any" or "union" types) are resolved by having connections made
// to them of a resolved type. Say you have a chain of A->B->C where B has inputs and outputs of these types. The
// connection from A->B will determine the type of data at B's input and the connection B->C will determine the type
// of data at B's output (assuming A's outputs and C's inputs are well-defined types).
//
// For this reason it is the node's responsibility to verify the type resolution of the attributes as part of the
// compute method. Any unresolved types (db.Xputs.attrName().resolved() == false) that are required by the compute
// should result in a warning and compute failure. Any attributes resolved to incompatible types, for example an input
// that resolves to a string where a number is needed, should also result in a warning and compute failure.
//
// It is up to the node to decide how flexible the resolution requirements are to be. In the string/number case above
// the node may choose to parse the string as a number instead of failing, or using the length of the string as the
// input number. The only requirement from OmniGraph is that the node handle all of the resolution types it has
// claimed it will handle in the .ogn file. "any" attributes must handle all data types, even if some types result in
// warnings or errors. "union" attributes must handle all types specified in the union.
//
class OgnTutorialExtendedTypes
{
public:
static bool compute(OgnTutorialExtendedTypesDatabase& db)
{
bool computedOne = false;
auto typeWarning = [&](const char* message, const Type& type1, const Type& type2) {
db.logWarning("%s (%s -> %s)", message, getOgnTypeName(type1).c_str(), getOgnTypeName(type2).c_str());
};
auto typeError = [&](const char* message, const Type& type1, const Type& type2) {
db.logError("%s (%s -> %s)", message, getOgnTypeName(type1).c_str(), getOgnTypeName(type2).c_str());
};
auto computeSimpleValues = [&]() {
// ====================================================================================================
// Compute for the union types that resolve to simple values.
// Accepted value types are floats and tokens. As these were the only types specified in the union definition
// the node does not have to worry about other numeric types, such as int or double.
// The node can decide what the meaning of an attempt to compute with unresolved types is.
// For this particular node they are treated as silent success.
const auto& floatOrToken = db.inputs.floatOrToken();
auto& doubledResult = db.outputs.doubledResult();
if (floatOrToken.resolved() && doubledResult.resolved())
{
// Check for an exact type match for the input and output
if (floatOrToken.type() != doubledResult.type())
{
// Mismatched types are possible, and result in no compute
typeWarning("Simple resolved types do not match", floatOrToken.type(), doubledResult.type());
return false;
}
// When extracting extended types the templated get<> method returns an object that contains the cast data.
// It can be cast to a boolean for quick checks for matching types.
//
// Note: The single "=" in these if statements is intentional. It facilitates one-line set-and-test of the
// typed values.
//
if (auto floatValue = floatOrToken.get<float>())
{
// Once the existence of the cast type is verified it can be dereferenced to get at the raw data,
// whose types are described in the tutorial on bundled data.
if (auto doubledValue = doubledResult.get<float>())
{
*doubledValue = *floatValue * 2.0f;
}
else
{
// This could be an assert because it should never happen. The types were confirmed above to match,
// so they should have cast to the same types without incident.
typeError("Simple types were matched as bool then failed to cast properly", floatOrToken.type(), doubledResult.type());
return false;
}
}
else if (auto tokenValue = floatOrToken.get<OgnToken>())
{
if (auto doubledValue = doubledResult.get<OgnToken>())
{
std::string inputString{ db.tokenToString(*tokenValue) };
inputString += inputString;
*doubledValue = db.stringToToken(inputString.c_str());
}
else
{
// This could be an assert because it should never happen. The types were confirmed above to match,
// so they should have cast to the same types without incident.
typeError("Simple types were matched as token then failed to cast properly", floatOrToken.type(), doubledResult.type());
return false;
}
}
else
{
// As Union types are supposed to restrict the data types being passed in to the declared types
// any unrecognized types are an error, not a warning.
typeError("Simple types resolved to unknown types", floatOrToken.type(), doubledResult.type());
return false;
}
}
else
{
// Unresolved types are reasonable, resulting in no compute
return true;
}
return true;
};
auto computeArrayValues = [&]() {
// ====================================================================================================
// Compute for the union types that resolve to arrays.
// Accepted value types are arrays of bool or arrays of float, which are extracted as interfaces to
// those values so that resizing can happen transparently through the fabric.
//
// These interfaces are similar to what you've seen in regular array attributes - they support resize(),
// operator[], and range-based for loops.
//
const auto& toNegate = db.inputs.toNegate();
auto& negatedResult = db.outputs.negatedResult();
if (toNegate.resolved() && negatedResult.resolved())
{
// Check for an exact type match for the input and output
if (toNegate.type() != negatedResult.type())
{
// Mismatched types are possible, and result in no compute
typeWarning("Array resolved types do not match", toNegate.type(), negatedResult.type());
return false;
}
// Extended types can be any legal attribute type. Here the types in the extended attribute can be either
// an array of booleans or an array of integers.
if (auto boolArray = toNegate.get<bool[]>())
{
auto valueAsBoolArray = negatedResult.get<bool[]>();
if (valueAsBoolArray)
{
valueAsBoolArray.resize( boolArray->size() );
size_t index{ 0 };
for (auto& value : *boolArray)
{
(*valueAsBoolArray)[index++] = ! value;
}
}
else
{
// This could be an assert because it should never happen. The types were confirmed above to match,
// so they should have cast to the same types without incident.
typeError("Array types were matched as bool[] then failed to cast properly", toNegate.type(), negatedResult.type());
return false;
}
}
else if (auto floatArray = toNegate.get<float[]>())
{
auto valueAsFloatArray = negatedResult.get<float[]>();
if (valueAsFloatArray)
{
valueAsFloatArray.resize( floatArray->size() );
size_t index{ 0 };
for (auto& value : *floatArray)
{
(*valueAsFloatArray)[index++] = - value;
}
}
else
{
// This could be an assert because it should never happen. The types were confirmed above to match,
// so they should have cast to the same types without incident.
typeError("Array types were matched as float[] then failed to cast properly", toNegate.type(), negatedResult.type());
return false;
}
}
else
{
// As Union types are supposed to restrict the data types being passed in to the declared types
// any unrecognized types are an error, not a warning.
typeError("Array type not recognized", toNegate.type(), negatedResult.type());
return false;
}
}
else
{
// Unresolved types are reasonable, resulting in no compute
return true;
}
return true;
};
auto computeTupleValues = [&]() {
// ====================================================================================================
// Compute for the "any" types that only handle tuple values. In practice you'd only use "any" when the
// type of data you handle is unrestricted. This is more an illustration to show how in practical use the
// two types of attribute are accessed exactly the same way, the only difference is restrictions that the
// OmniGraph system will put on potential connections.
//
// For simplicity this node will treat unrecognized type as a warning with success.
// Full commentary and error checking is elided as it will be the same as for the above examples.
// The algorithm for tuple values is a component-wise negation.
const auto& tupleInput = db.inputs.tuple();
auto& tupleOutput = db.outputs.tuple();
if (tupleInput.resolved() && tupleOutput.resolved())
{
if (tupleInput.type() != tupleOutput.type())
{
typeWarning("Tuple resolved types do not match", tupleInput.type(), tupleOutput.type());
return false;
}
// This node will only recognize the float[3] and int[2] cases, to illustrate that tuple count and
// base type are both flexible.
if (auto float3Input = tupleInput.get<float[3]>())
{
if (auto float3Output = tupleOutput.get<float[3]>())
{
(*float3Output)[0] = -(*float3Input)[0];
(*float3Output)[1] = -(*float3Input)[1];
(*float3Output)[2] = -(*float3Input)[2];
}
}
else if (auto int2Input = tupleInput.get<int[2]>())
{
if (auto int2Output = tupleOutput.get<int[2]>())
{
(*int2Output)[0] = -(*int2Input)[0];
(*int2Output)[1] = -(*int2Input)[1];
}
}
else
{
// As "any" types are not restricted in their data types but this node is only handling two of
// them an unrecognized type is just unimplemented code.
typeWarning("Unimplemented type combination", tupleInput.type(), tupleOutput.type());
return true;
}
}
else
{
// Unresolved types are reasonable, resulting in no compute
return true;
}
return true;
};
auto computeFlexibleValues = [&]() {
// ====================================================================================================
// Complex union type that handles both simple values and an array of tuples. It illustrates how the
// data types in a union do not have to be related in any way.
//
// Full commentary and error checking is elided as it will be the same as for the above examples.
// The algorithm for tuple array values is to negate everything in the float3 array values, and to reverse
// the string for string values.
const auto& flexibleInput = db.inputs.flexible();
auto& flexibleOutput = db.outputs.flexible();
if (flexibleInput.resolved() && flexibleOutput.resolved())
{
if (flexibleInput.type() != flexibleOutput.type())
{
typeWarning("Flexible resolved types do not match", flexibleInput.type(), flexibleOutput.type());
return false;
}
// Arrays of tuples are handled with the same interface as with normal attributes.
if (auto float3ArrayInput = flexibleInput.get<float[][3]>())
{
if (auto float3ArrayOutput = flexibleOutput.get<float[][3]>())
{
float3ArrayOutput.resize( float3ArrayInput.size() );
size_t index{ 0 };
for (auto& value : *float3ArrayInput)
{
(*float3ArrayOutput)[index][0] = - value[0];
(*float3ArrayOutput)[index][1] = - value[1];
(*float3ArrayOutput)[index][2] = - value[2];
index++;
}
}
}
else if (auto tokenInput = flexibleInput.get<OgnToken>())
{
if (auto tokenOutput = flexibleOutput.get<OgnToken>())
{
std::string toReverse{ db.tokenToString(*tokenInput) };
std::reverse( toReverse.begin(), toReverse.end() );
*tokenOutput = db.stringToToken(toReverse.c_str());
}
}
else
{
typeError("Unrecognized type combination", flexibleInput.type(), flexibleOutput.type());
return false;
}
}
else
{
// Unresolved types are reasonable, resulting in no compute
return true;
}
return true;
};
// This approach lets either section fail while still computing the other.
computedOne = computeSimpleValues();
computedOne = computeArrayValues() || computedOne;
computedOne = computeTupleValues() || computedOne;
computedOne = computeFlexibleValues() || computedOne;
if (! computedOne)
{
db.logWarning("None of the inputs had resolved type, resulting in no compute");
}
return ! computedOne;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
// The attribute types resolve in pairs
AttributeObj pairs[][2] {
{
nodeObj.iNode->getAttributeByToken(nodeObj, inputs::floatOrToken.token()),
nodeObj.iNode->getAttributeByToken(nodeObj, outputs::doubledResult.token())
},
{
nodeObj.iNode->getAttributeByToken(nodeObj, inputs::toNegate.token()),
nodeObj.iNode->getAttributeByToken(nodeObj, outputs::negatedResult.token())
},
{
nodeObj.iNode->getAttributeByToken(nodeObj, inputs::tuple.token()),
nodeObj.iNode->getAttributeByToken(nodeObj, outputs::tuple.token())
},
{
nodeObj.iNode->getAttributeByToken(nodeObj, inputs::flexible.token()),
nodeObj.iNode->getAttributeByToken(nodeObj, outputs::flexible.token())
}
};
for (auto& pair : pairs)
{
nodeObj.iNode->resolveCoupledAttributes(nodeObj, &pair[0], 2);
}
}
};
REGISTER_OGN_NODE()
| 17,881 | C++ | 49.230337 | 144 | 0.523125 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial19/tutorial19.rst | .. _ogn_tutorial_extended_types:
Tutorial 19 - Extended Attribute Types
======================================
Extended attribute types are so-named because they extend the types of data an attribute can accept from one type
to several types. Extended attributes come in two flavours. The _any_ type is the most flexible. It allows a connection
with any other attribute type:
.. code-block:: json
:emphasize-lines: 4
"inputs": {
"myAnyAttribute": {
"description": "Accepts an incoming connection from any type of attribute",
"type": "any",
}
}
The union type, represented as an array of type names, allows a connection from a limited subset of attribute types.
Here's one that can connect to attributes of type _float[3]_ and _double[3]_:
.. code-block:: json
:emphasize-lines: 4
"inputs": {
"myUnionAttribute": {
"description": "Accepts an incoming connection from attributes with a vector of a 3-tuple of numbers",
"type": ["float[3]", "double[3]"],
}
}
.. note::
"union" is not an actual type name, as the type names are specified by a list. It is just the nomenclature used
for the set of all attributes that can be specified in this way. More details about union types can be
found in :ref:`ogn_attribute_types`.
As you will see in the code examples, the value extracted from the database for such attributes has to be checked for
the actual resolved data type. Until an extended attribute is connected its data type will be unresolved and it will
not have a value. For this reason _"default"_ values are not allowed on extended attributes.
OgnTutorialExtendedTypes.ogn
----------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.ExtendedTypes", which has inputs and outputs
with the extended attribute types.
.. literalinclude:: OgnTutorialExtendedTypes.ogn
:linenos:
:language: json
OgnTutorialExtendedTypes.cpp
----------------------------
The *cpp* file contains the implementation of the compute method. It illustrates how to determine and set the data
types on extended attribute types.
.. literalinclude:: OgnTutorialExtendedTypes.cpp
:linenos:
:language: c++
Information on the raw types extracted from the extended type values can be seen in :ref:`ogn_tutorial_bundle_data`.
OgnTutorialExtendedTypesPy.py
-----------------------------
This is a Python version of the above C++ node with exactly the same set of attributes and the same algorithm. It
shows the parallels between manipulating extended attribute types in both languages. (The .ogn file is omitted for
brevity, being identical to the previous one save for the addition of a ``"language": "python"`` property.
.. literalinclude:: OgnTutorialExtendedTypesPy.py
:linenos:
:language: python
| 2,868 | reStructuredText | 38.301369 | 122 | 0.702232 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/tutorial23.rst | .. _ogn_tutorial_cpu_gpu_extended:
Tutorial 23 - Extended Attributes On The GPU
============================================
Extended attributes are no different from other types of attributes with respect to where their memory will be located.
The difference is that there is a slightly different API for accessing their data, illustrating by these examples.
This node also illustrates the new concept of having a node create an ABI function override that handles the runtime
type resolution of extended attribute types. In this case when any of the two input attributes or one output attribute
become resolved then the other two attributes are resolved to the same type, if possible.
OgnTutorialCpuGpuExtended.ogn
-----------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuExtended" with an input **'any'**
attribute on the CPU, an input **'any'** attribute on the GPU, and an output whose memory location is decided at runtime
by a boolean.
.. literalinclude:: OgnTutorialCpuGpuExtended.ogn
:linenos:
:language: json
OgnTutorialCpuGpuExtended.cpp
-----------------------------
The *cpp* file contains the implementation of the compute method. It sums two inputs on either the
CPU or GPU based on the input boolean. For simplicity only the **float[3][]** attribute type is processed, with
all others resulting in a compute failure.
.. literalinclude:: OgnTutorialCpuGpuExtended.cpp
:linenos:
:language: c++
OgnTutorialCpuGpuExtendedPy.py
------------------------------
The *py* file contains the same algorithm as the C++ node, with the node implementation language being different.
.. literalinclude:: OgnTutorialCpuGpuExtendedPy.py
:linenos:
:language: python
| 1,752 | reStructuredText | 42.824999 | 120 | 0.726027 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtended.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 <OgnTutorialCpuGpuExtendedDatabase.h>
extern "C" void cpuGpuSumCPU(float const(*p1)[3], float const(*p2)[3], float(*sums)[3], size_t);
extern "C" void cpuGpuSumGPU(float const (**p1)[3], float const (**p2)[3], float(**sums)[3]);
namespace omni {
namespace graph {
namespace tutorials {
// Only the pointf[3][] type is accepted. Make a shortcut to the type information describing it for comparison
core::Type acceptedType(core::BaseDataType::eFloat, 3, 1, core::AttributeRole::ePosition);
// Template for reporting type inconsistencies. The data types are different for the attributes but the checks are
// the same so this avoids duplication
template <typename P1, typename P2, typename P3>
bool verifyDataTypes(OgnTutorialCpuGpuExtendedDatabase& db, const P1& points1, const P2& points2, P3& sums, const char* type)
{
if (! points1)
{
db.logWarning("Skipping compute - The %s attribute was not a valid pointf[3][]", type);
}
else if (! points2)
{
db.logWarning("Skipping compute - The %s attribute was not a valid pointf[3][]", type);
}
else if (! sums)
{
db.logWarning("Skipping compute - The %s output attribute was not a valid pointf[3][]", type);
}
else if (points1.size() != points2.size())
{
db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size());
}
else
{
sums.resize(points1.size());
return true;
}
return false;
}
class OgnTutorialCpuGpuExtended
{
bool m_allAttributesResolved{ false };
public:
static bool compute(OgnTutorialCpuGpuExtendedDatabase& db)
{
if (! db.sharedState<OgnTutorialCpuGpuExtended>().m_allAttributesResolved)
{
db.logWarning("All types are not yet resolved. Cannot run the compute.");
return false;
}
const auto& gpu = db.inputs.gpu();
const auto cpuData = db.inputs.cpuData();
const auto gpuData = db.inputs.gpuData();
auto cpuGpuSum = db.outputs.cpuGpuSum();
if ((cpuData.type() != acceptedType) || (gpuData.type() != acceptedType) || (cpuGpuSum.type() != acceptedType))
{
db.logWarning("Skipping compute - All of the attributes do not have the accepted resolved type pointf[3][]");
return false;
}
if (gpu)
{
// Computation on the GPU has been requested so get the GPU versions of the attribute data
const auto points1 = cpuData.getGpu<float[][3]>();
const auto points2 = gpuData.get<float[][3]>();
auto sums = cpuGpuSum.getGpu<float[][3]>();
if (!verifyDataTypes(db, points1, points2, sums, "GPU"))
{
return false;
}
cpuGpuSumGPU(points1(), points2(), sums());
}
else
{
// Computation on the CPU has been requested so get the CPU versions of the attribute data
const auto points1 = cpuData.get<float[][3]>();
const auto points2 = gpuData.getCpu<float[][3]>();
auto sums = cpuGpuSum.getCpu<float[][3]>();
if (!verifyDataTypes(db, points1, points2, sums, "CPU"))
{
return false;
}
cpuGpuSumCPU(points1->data(), points2->data(), sums->data(), points1.size());
}
return true;
}
static void onConnectionTypeResolve(const NodeObj& nodeObj)
{
// If any one type is resolved the others should resolve to the same type. Calling this helper function
// makes that happen automatically. If it returns false then the resolution failed for some reason. The
// node's user data, which is just a copy of this class, is used to keep track of the resolution state so
// that the compute method can quickly exit when the types are not resolved.
AttributeObj attributes[3] {
nodeObj.iNode->getAttributeByToken(nodeObj, inputs::cpuData.token()),
nodeObj.iNode->getAttributeByToken(nodeObj, inputs::gpuData.token()),
nodeObj.iNode->getAttributeByToken(nodeObj, outputs::cpuGpuSum.token())
};
auto& state = OgnTutorialCpuGpuExtendedDatabase::sInternalState<OgnTutorialCpuGpuExtended>(nodeObj);
state.m_allAttributesResolved = nodeObj.iNode->resolveCoupledAttributes(nodeObj, attributes, 3);
}
};
REGISTER_OGN_NODE()
} // namespace tutorials
} // namespace graph
} // namespace omni
| 4,959 | C++ | 40.333333 | 125 | 0.647308 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial23/OgnTutorialCpuGpuExtendedPy.py | """
Implementation of the Python node accessing extended attributes whose memory location is determined at runtime.
"""
import omni.graph.core as og
# Only one type of data is handled by the compute - pointf[3][]
POINT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION)
class OgnTutorialCpuGpuExtendedPy:
"""Exercise GPU access for extended attributes through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Implements the same algorithm as the C++ node OgnTutorialCpuGpuExtended.cpp.
It follows the same code pattern for easier comparison, though in practice you would probably code Python
nodes differently from C++ nodes to take advantage of the strengths of each language.
"""
# Find and verify the attributes containing the points
if db.attributes.inputs.cpuData.get_resolved_type() != POINT_ARRAY_TYPE:
db.log_warning("Skipping compute - CPU attribute type did not resolve to pointf[3][]")
return False
if db.attributes.inputs.gpuData.get_resolved_type() != POINT_ARRAY_TYPE:
db.log_warning("Skipping compute - GPU attribute type did not resolve to pointf[3][]")
return False
if db.attributes.outputs.cpuGpuSum.get_resolved_type() != POINT_ARRAY_TYPE:
db.log_warning("Skipping compute - Sum attribute type did not resolve to pointf[3][]")
return False
# Put accessors into local variables for convenience
gpu_data = db.inputs.gpuData
cpu_data = db.inputs.cpuData
sums = db.outputs.cpuGpuSum
# Mismatched sizes cannot be computed
if gpu_data.size != cpu_data.size:
db.log_warning(f"Skipping compute - Point arrays are different sizes ({gpu_data.size} and {cpu_data.size})")
# Set the size to what is required for the dot product calculation
sums.size = cpu_data.size
# Use the correct data access based on whether the output is supposed to be on the GPU or not
if db.inputs.gpu:
# The second line is how the values would be extracted if Python supported GPU data extraction.
# When it does this tutorial will be updated
sums.cpu_value = cpu_data.value + gpu_data.cpu_value
# sums.gpu_value = cpu_data.gpu_value + gpu_data.value
else:
sums.cpu_value = cpu_data.value + gpu_data.cpu_value
return True
@staticmethod
def on_connection_type_resolve(node: og.Node) -> None:
"""Whenever any of the inputs or the output get a resolved type the others should get the same resolution"""
attribs = [
node.get_attribute("inputs:cpuData"),
node.get_attribute("inputs:gpuData"),
node.get_attribute("outputs:cpuGpuSum"),
]
og.resolve_fully_coupled(attribs)
| 2,925 | Python | 46.193548 | 120 | 0.666667 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundlesPy.py | """
Implementation of the Python node accessing attributes whose memory location is determined at runtime.
"""
import numpy as np
import omni.graph.core as og
# Types to check on bundled attributes
FLOAT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, array_depth=1)
FLOAT3_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION)
class OgnTutorialCpuGpuBundlesPy:
"""Exercise bundle members through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Implements the same algorithm as the C++ node OgnTutorialCpuGpuBundles.cpp.
It follows the same code pattern for easier comparison, though in practice you would probably code Python
nodes differently from C++ nodes to take advantage of the strengths of each language.
"""
if db.inputs.gpu:
# Invalid data yields no compute
if not db.inputs.gpuBundle.valid:
return True
db.outputs.cpuGpuBundle = db.inputs.gpuBundle
else:
if not db.inputs.cpuBundle.valid:
return True
db.outputs.cpuGpuBundle = db.inputs.cpuBundle
# Find and verify the attributes containing the points
cpu_points = db.inputs.cpuBundle.attribute_by_name(db.tokens.points)
if cpu_points.type != FLOAT3_ARRAY_TYPE:
db.log_warning(
f"Skipping compute - No valid float[3][] attribute named '{db.tokens.points}' on the CPU bundle"
)
return False
gpu_points = db.inputs.gpuBundle.attribute_by_name(db.tokens.points)
if gpu_points.type != FLOAT3_ARRAY_TYPE:
db.log_warning(
f"Skipping compute - No valid float[3][] attribute named '{db.tokens.points}' on the GPU bundle"
)
return False
# If the attribute is not already on the output bundle then add it
dot_product = db.outputs.cpuGpuBundle.attribute_by_name(db.tokens.dotProducts)
if dot_product is None:
dot_product = db.outputs.cpuGpuBundle.insert((og.Type(og.BaseDataType.FLOAT, array_depth=1), "dotProducts"))
elif dot_product.type != FLOAT_ARRAY_TYPE:
# Python types do not use a cast to find out if they are the correct type so explicitly check it instead
db.log_warning(
f"Skipping compute - No valid float[] attribute named '{db.tokens.dotProducts}' on the output bundle"
)
return False
# Set the size to what is required for the dot product calculation
dot_product.size = cpu_points.size
# Use the correct data access based on whether the output is supposed to be on the GPU or not
if db.inputs.gpu:
# The second line is how the values would be extracted if Python supported GPU data extraction.
# When it does this tutorial will be updated
dot_product.cpu_value = np.einsum("ij,ij->i", cpu_points.value, gpu_points.cpu_value)
# dot_product.gpu_value = np.einsum("ij,ij->i", cpu_points.gpu_value, gpu_points.value)
else:
dot_product.cpu_value = np.einsum("ij,ij->i", cpu_points.value, gpu_points.cpu_value)
return True
| 3,273 | Python | 45.771428 | 120 | 0.651085 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/OgnTutorialCpuGpuBundles.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 <OgnTutorialCpuGpuBundlesDatabase.h>
extern "C" void cpuGpuDotProductCPU(float const(*p1)[3], float const(*p2)[3], float*, size_t);
extern "C" void cpuGpuDotProductGPU(float const (**p1)[3], float const (**p2)[3], float**, size_t);
namespace omni {
namespace graph {
namespace tutorials {
class OgnTutorialCpuGpuBundles
{
public:
static bool compute(OgnTutorialCpuGpuBundlesDatabase& db)
{
const auto& gpu = db.inputs.gpu();
// Bundles are merely abstract representations of a collection of attributes so you don't have to do anything
// different when they are marked for GPU, or ANY memory location.
const auto& cpuBundle = db.inputs.cpuBundle();
const auto& gpuBundle = db.inputs.gpuBundle();
auto& outputBundle = db.outputs.cpuGpuBundle();
// Assign the correct destination bundle to the output based on the gpu flag
if (gpu)
{
outputBundle = gpuBundle;
}
else
{
outputBundle = cpuBundle;
}
// Get the attribute references. They're the same whether the bundles are on the CPU or GPU
const auto pointsCpuAttribute = cpuBundle.attributeByName(db.tokens.points);
const auto pointsGpuAttribute = gpuBundle.attributeByName(db.tokens.points);
auto dotProductAttribute = outputBundle.attributeByName(db.tokens.dotProducts);
if (! dotProductAttribute.isValid())
{
dotProductAttribute = outputBundle.addAttribute(db.tokens.dotProducts, Type(BaseDataType::eFloat, 1, 1));
}
// Find the bundle contents to be processed
if (gpu)
{
const auto points1 = pointsCpuAttribute.getGpu<float[][3]>();
const auto points2 = pointsGpuAttribute.get<float[][3]>();
auto dotProducts = dotProductAttribute.getGpu<float[]>();
if (! points1)
{
db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the CPU bundle", db.tokenToString(db.tokens.points));
return false;
}
if (! points2)
{
db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the GPU bundle", db.tokenToString(db.tokens.points));
return false;
}
if (points1.size() != points2.size())
{
db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size());
return false;
}
dotProducts.resize(points1.size());
if (! dotProducts)
{
db.logWarning("Skipping compute - No valid float[] attribute named '%s' on the output bundle", db.tokenToString(db.tokens.dotProducts));
return false;
}
cpuGpuDotProductGPU(points1(), points2(), dotProducts(), points1.size());
}
else
{
const auto points1 = pointsCpuAttribute.get<float[][3]>();
const auto points2 = pointsGpuAttribute.getCpu<float[][3]>();
auto dotProducts = dotProductAttribute.getCpu<float[]>();
if (! points1)
{
db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the CPU bundle", db.tokenToString(db.tokens.points));
return false;
}
if (! points2)
{
db.logWarning("Skipping compute - No valid float[3][] attribute named '%s' on the GPU bundle", db.tokenToString(db.tokens.points));
return false;
}
if (points1.size() != points2.size())
{
db.logWarning("Skipping compute - Point arrays are different sizes (%zu and %zu)", points1.size(), points2.size());
return false;
}
dotProducts.resize(points1.size());
if (! dotProducts)
{
db.logWarning("Skipping compute - No valid dot product attribute on the output bundle");
return false;
}
cpuGpuDotProductCPU(points1->data(), points2->data(), dotProducts->data(), points1.size());
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace tutorials
} // namespace graph
} // namespace omni
| 4,825 | C++ | 41.333333 | 152 | 0.602487 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial22/tutorial22.rst | .. _ogn_tutorial_cpu_gpu_bundles:
Tutorial 22 - Bundles On The GPU
================================
Bundles are not exactly data themselves, they are a representation of a collection of attributes whose composition is
determined at runtime. As such, they will always live on the CPU. However the attributes they are encapsulating have
the same flexibility as other attributes to live on the CPU, GPU, or have their location decided at runtime.
For that reason it's convenient to use the same "cpu", "cuda", and "any" memory types for the bundle attributes, with
a slightly different interpretation.
- **cpu** all attributes in the bundle will be on the CPU
- **gpu** all attributes in the bundle will be on the GPU
- **any** either some attributes in the bundle are on the CPU and some are on the GPU, or that decision will be made at runtime
For example if you had a bundle of attributes consisting of a large array of points and a boolean that controls the
type of operation you will perform on them it makes sense to leave the boolean on the CPU and move the points to the
GPU for more efficient processing.
OgnTutorialCpuGpuBundles.ogn
----------------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuBundles" with an input bundle on
the CPU, an input bundle on the GPU, and an output bundle whose memory location is decided at runtime by a boolean.
.. literalinclude:: OgnTutorialCpuGpuBundles.ogn
:linenos:
:language: json
OgnTutorialCpuGpuBundles.cpp
----------------------------------
The *cpp* file contains the implementation of the compute method. It creates a merged bundle in either the CPU or
GPU based on the input boolean and runs an algorithm on the output location.
.. literalinclude:: OgnTutorialCpuGpuBundles.cpp
:linenos:
:language: c++
OgnTutorialCpuGpuBundlesPy.py
-----------------------------------
The *py* file contains the same algorithm as the C++ node, with the node implementation language being different.
.. literalinclude:: OgnTutorialCpuGpuBundlesPy.py
:linenos:
:language: python
| 2,106 | reStructuredText | 43.829786 | 127 | 0.728395 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleDataPy.py | """
Implementation of the Python node accessing attributes through the bundle in which they are contained.
"""
import numpy as np
import omni.graph.core as og
# Types recognized by the integer filter
_INTEGER_TYPES = [og.BaseDataType.INT, og.BaseDataType.UINT, og.BaseDataType.INT64, og.BaseDataType.UINT64]
class OgnTutorialBundleDataPy:
"""Exercise the bundled data types through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Implements the same algorithm as the C++ node OgnTutorialBundleData.cpp
As Python is so much more flexible it doubles values on any attribute type that can handle it, unlike
the C++ node which only operates on integer types
"""
input_bundle = db.inputs.bundle
output_bundle = db.outputs.bundle
# This does a copy of the full bundle contents from the input bundle to the output bundle so that the
# output data can be modified directly.
output_bundle.bundle = input_bundle
# The "attributes" member is a list that can be iterated. The members of the list do not contain real
# og.Attribute objects, which must always exist, they are wrappers on og.AttributeData objects, which can
# come and go at runtime.
for bundled_attribute in output_bundle.attributes:
attribute_type = bundled_attribute.type
# Only integer types are recognized for this node's operation (doubling all integral values).
# It does operate on tuples and arrays though so that part does not need to be set.
# if attribute_type.base_type not in _INTEGER_TYPES:
# continue
# This operation does the right thing on all compatible types, unlike the C++ equivalent where it
# requires special handling for each variation of the data types it can handle.
if attribute_type.base_type == og.BaseDataType.TOKEN:
if attribute_type.array_depth > 0:
bundled_attribute.value = [f"{element}{element}" for element in bundled_attribute.value]
else:
bundled_attribute.value = f"{bundled_attribute.value}{bundled_attribute.value}"
elif attribute_type.role in [og.AttributeRole.TEXT, og.AttributeRole.PATH]:
bundled_attribute.value = f"{bundled_attribute.value}{bundled_attribute.value}"
else:
try:
bundled_attribute.value = np.multiply(bundled_attribute.value, 2)
except TypeError:
db.log_error(f"This node does not handle data of type {attribute_type.get_type_name()}")
return True
| 2,702 | Python | 48.145454 | 113 | 0.663583 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/tutorial16.rst | .. _ogn_tutorial_bundle_data:
Tutorial 16 - Bundle Data
=========================
Attribute bundles are a construct that packages up groups of attributes into a single entity that can be passed
around the graph. These attributes have all of the same properties as a regular attribute, you just have to go
through an extra step to access their values. This node illustrates how to break open a bundle to access and
modify values in the bundled attributes.
OgnTutorialBundleData.ogn
-------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.BundleData", which has one input bundle and one
output bundle.
.. literalinclude:: OgnTutorialBundleData.ogn
:linenos:
:language: json
OgnTutorialBundleData.cpp
-------------------------
The *cpp* file contains the implementation of the compute method. It accesses any attributes in the bundle that
have integral base types and doubles the values of those attributes.
.. literalinclude:: OgnTutorialBundleData.cpp
:linenos:
:language: c++
Bundled Attribute Data Manipulation Methods
-------------------------------------------
These are the methods for accessing the data that the bundled attributes encapsulate.
In regular attributes the code generated from the .ogn file provides accessors with predetermined data types.
The data types of attributes within bundles are unknown until compute time so it is up to the node writer to
explicitly cast to the correct data type.
Extracting Bundled Attribute Data - Simple Types
++++++++++++++++++++++++++++++++++++++++++++++++
For reference, simple types, tuple types, array types, tuple array types, and role types are all described in
:ref:`ogn_attribute_types`. However, unlike normal attributes the bundled attributes are always accessed as their
raw native data types. For example instead of ``pxr::GfVec3f`` you will access with ``float[3]``, which can always
be cast to the explicit types if desired.
.. note::
One exception to the type casting is tokens. In normal attributes you retrieve tokens as ``NameToken``.
Due to certain compiler restrictions the bundled attributes will be retrieved as the helper type
``OgnToken``, which is castable to ``NameToken`` for subsequent use.
.. code-block:: cpp
:emphasize-lines: 5
// As the attribute data types are only known at runtime you must perform a type-specific cast
// to get the data out in its native form.
const auto& inputBundle = db.inputs.bundle();
// Note the "const" here, to ensure we are not inadvertently modifying the input data.
const auto weight = inputBundle.attributeByName(weightToken);
const float* weightValue = weight.value<float>();
// nullptr return means the data is not of the requested type
asssert( nullptr == weight.value<int>() );
Extracting Bundled Attribute Data - Tuple Types
+++++++++++++++++++++++++++++++++++++++++++++++
.. code-block:: cpp
:emphasize-lines: 4
// The tuple data types can be accessed in exactly the same way as simple data types, with the proper cast.
const auto& inputBundle = db.inputs.bundle();
const auto weight3 = inputBundle.attributeByName(weight3Token);
const auto weight3Value = weight3.value<float[3]>();
// type of weight3Value == const float[3]*
// If you have a preferred library for manipulating complex types you can cast to them if they are compatible.
static_assert( std::is_convertible(pxr::GfVec3f, float[3]) );
const pxr::GfVec3f* usdWeight = reinterpret_cast<const pxr::GfVec3f*>(weight3Value);
Extracting Bundled Attribute Data - Array Types
+++++++++++++++++++++++++++++++++++++++++++++++
.. code-block:: cpp
:emphasize-lines: 4,11
// As with tuple types, the array types are extracted directly with the native array cast
const auto& inputBundle = db.inputs.bundle();
const auto weights = inputBundle.attributeByName(weightsToken);
const auto weightsValue = weights.value<float[]>();
// type == const float[]*
auto& outputBundle = db.outputs.bundle();
// As this is an output, the const is omitted so that the data can be modified
auto nWeights = outputBundle.attributeByName(nWeightsToken);
// As with regular attributes, bundled array outputs must be resized to allocate space before filling them.
// These array types also have the normal array capabilities, with a size() method and range-based for loops.
nWeights.resize( weights.size() );
size_t index = 0;
for (const auto& weightValue : *weightsValue)
{
nWeights[index++] = weightValue / 256.0f;
}
Extracting Bundled Attribute Data - Tuple Array Types
+++++++++++++++++++++++++++++++++++++++++++++++++++++
.. code-block:: cpp
:emphasize-lines: 4
// Tuple-arrays behave as you would expect, using the native tuple-array as the cast type
const auto& inputBundle = db.inputs.bundle();
const auto weights3 = inputBundle.attributeByName(weights3Token);
const auto weights3Value = weights.value<float[][3]>();
// type == const float[][3]*
OgnTutorialBundleDataPy.py
--------------------------
This is a Python version of the above C++ node with exactly the same set of attributes and a similar algorithm.
The main difference is that for the Python version the type definitions are much more flexible so the algorithm
can be applied to every type of bundled attribute with minimal code. (The .ogn file is omitted for
brevity, being identical to the previous one save for the addition of a ``"language": "python"`` property.)
.. literalinclude:: OgnTutorialBundleDataPy.py
:linenos:
:language: python
| 5,639 | reStructuredText | 45.229508 | 125 | 0.700656 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial16/OgnTutorialBundleData.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 <OgnTutorialBundleDataDatabase.h>
using omni::graph::core::Type;
using omni::graph::core::NameToken;
using omni::graph::core::BaseDataType;
namespace
{
// The function of this node is to double the values for all bundled attributes
// with integral types, including tuples and arrays.
//
// The parameter is a ogn::RuntimeAttribute<kOgnOutput, ogn::kCpu>, which is the type of data returned when iterating
// over an output bundle on the CPU.
// It contains a description of the attribute within the bundle and access to the attribute's data.
// BundledInput is a similar type, which is what you get when iterating over an input bundle. The main difference
// between the two is the ability to modify the attribute or its data.
template <typename POD>
bool doubleSimple(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute)
{
// When an attribute is cast to the wrong type (e.g. an integer attribute is extracted with a float
// template parameter on the get<,>() method) a nullptr is returned. That can be used to determine
// the attribute type. You can also use the bundledAttribute.type() method to access the full type
// information and select a code path using that.
auto podValue = bundledAttribute.get<POD>();
if (podValue)
{
*podValue *= 2;
return true;
}
return false;
};
// Array and tuple data has iterator capabilities for easy access to individual elements
template <typename CppType>
bool doubleArray(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute)
{
// Strings and paths look like uint8_t[] but are not, so don't process them
if ((bundledAttribute.type().role == AttributeRole::eText) || (bundledAttribute.type().role == AttributeRole::ePath))
{
return false;
}
auto arrayValue = bundledAttribute.get<CppType>();
if (arrayValue)
{
for (auto& arrayElement : *arrayValue)
{
arrayElement *= 2;
}
return true;
}
return false;
};
// Tuple arrays must have nested iteration
template <typename CppType>
bool doubleTupleArray(ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>& bundledAttribute)
{
auto tupleSize = bundledAttribute.type().componentCount;
auto tupleArrayValue = bundledAttribute.get<CppType>();
if (tupleArrayValue)
{
for (auto& arrayElement : *tupleArrayValue)
{
for (size_t i=0; i<tupleSize; ++i)
{
arrayElement[i] *= 2;
}
}
return true;
}
return false;
};
}
class OgnTutorialBundleData
{
public:
static bool compute(OgnTutorialBundleDataDatabase& db)
{
// Bundle attributes are extracted from the database in the same way as any other attribute.
// The only difference is that a different interface class is provided, suited to bundle manipulation.
const auto& inputBundle = db.inputs.bundle();
auto& outputBundle = db.outputs.bundle();
for (const auto& bundledAttribute : inputBundle)
{
auto podValue = bundledAttribute.get<int>();
}
// Copying the entire bundle is more efficient than adding one member at a time. As the output bundle
// will have the same attributes as the input, even though the values will be different, this is the best
// approach. If the attribute lists were different then you would copy or create the individual attributes
// as required.
outputBundle = inputBundle;
// Now walk the bundle to look for types to be modified
for (auto& bundledAttribute : outputBundle)
{
// This shows how using a templated function can simplify handling of several different bundled
// attribute types. The data types for each of the POD attributes is fully explained in the documentation
// page titled "Attribute Data Types". The list of available POD data types is:
//
// bool
// double
// float
// pxr::GfHalf
// int
// int64_t
// NameToken
// uint8_t
// uint32_t
// uint64_t
//
if (doubleSimple<int>(bundledAttribute)) continue;
if (doubleSimple<int64_t>(bundledAttribute)) continue;
if (doubleSimple<uint8_t>(bundledAttribute)) continue;
if (doubleSimple<uint32_t>(bundledAttribute)) continue;
if (doubleSimple<uint64_t>(bundledAttribute)) continue;
// Plain ints are the only integral types supporting tuples. Double those here
if (doubleArray<int[2]>(bundledAttribute)) continue;
if (doubleArray<int[3]>(bundledAttribute)) continue;
if (doubleArray<int[4]>(bundledAttribute)) continue;
// Arrays are looped differently than tupls so they are also handled differently
if (doubleArray<int[]>(bundledAttribute)) continue;
if (doubleArray<int64_t[]>(bundledAttribute)) continue;
if (doubleArray<uint8_t[]>(bundledAttribute)) continue;
if (doubleArray<uint32_t[]>(bundledAttribute)) continue;
if (doubleArray<uint64_t[]>(bundledAttribute)) continue;
// Tuple arrays require a two level iteration
if (doubleTupleArray<int[][2]>(bundledAttribute)) continue;
if (doubleTupleArray<int[][3]>(bundledAttribute)) continue;
if (doubleTupleArray<int[][4]>(bundledAttribute)) continue;
// Any attributes not passing the above tests are not integral and therefore not handled by this node.
}
return true;
}
};
REGISTER_OGN_NODE()
| 6,228 | C++ | 40.251655 | 121 | 0.657354 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial9/OgnTutorialCpuGpuData.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 <OgnTutorialCpuGpuDataDatabase.h>
// This helper file keeps the GPU and CPU functions organized for easy access.
// It's only for illustration purposes; you can choose to organize your functions any way you wish.
// The first algorithm is a simple add, to illustrate passing non-array types.
extern "C" void cpuGpuAddCPU(outputs::sum_t_cpu, inputs::a_t_cpu, inputs::b_t_cpu, size_t);
extern "C" void cpuGpuAddGPU(outputs::sum_t_gpu, inputs::a_t_gpu, inputs::b_t_gpu);
// The second algorithm shows the more common case of accessing array data.
extern "C" void cpuGpuMultiplierCPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t);
extern "C" void cpuGpuMultiplierGPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t);
class OgnTutorialCpuGpuData
{
public:
static bool compute(OgnTutorialCpuGpuDataDatabase& db)
{
// Computing the size of the output is independent of CPU/GPU as the size update is lazy and will happen
// when the data is requested from the fabric.
size_t numberOfPoints = db.inputs.points.size();
db.outputs.points.resize(numberOfPoints);
// Use the runtime input to determine where the calculation should take place.
//
// Another helpful use of this technique is to first measure the size of data being evaluated and
// if it meets a certain minimum threshold move the calculation to the GPU.
if (db.inputs.is_gpu())
{
cpuGpuAddGPU(db.outputs.sum.gpu(), db.inputs.a.gpu(), db.inputs.b.gpu());
// GPU data is just raw pointers so the size must be passed down to the algorithm
cpuGpuMultiplierGPU(
db.outputs.points.gpu(), db.inputs.multiplier.gpu(), db.inputs.points.gpu(), numberOfPoints);
}
else
{
// CPU version calls the shared CPU/GPU algorithm directly. This could also be implemented in the
// CUDA file as an extern "C" function but it is so simple that this is easier.
cpuGpuAddCPU(db.outputs.sum.cpu(), db.inputs.a.cpu(), db.inputs.b.cpu(), 0);
// Extract the CPU data and iterate over all of the points, calling the shared deformation algorithm.
// The data is passed through as raw CUDA-compatible bytes so that the deformation algorithm can live
// all in one file. If the code were all on the CPU side then the data types could be used as regular
// arrays, as showing in the tutorial on array data types.
auto rawOutputPoints = db.outputs.points.cpu().data();
auto rawInputPoints = db.inputs.points.cpu().data();
cpuGpuMultiplierCPU(&rawOutputPoints, &db.inputs.multiplier.cpu(), &rawInputPoints, numberOfPoints);
}
return true;
}
};
REGISTER_OGN_NODE()
| 3,302 | C++ | 50.609374 | 115 | 0.694428 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial9/tutorial9.rst | .. _ogn_tutorial_cpuGpuData:
Tutorial 9 - Runtime CPU/GPU Decision
=====================================
The CPU/GPU data node creates various attributes for use in a CUDA-based GPU compute or a CPU-based compute, where the
decision of which to use is made at runtime rather than compile time. A few representative
types are used, though the list of potential attribute types is not exhaustive. See :ref:`ogn_attribute_types`
for the full list.
OgnTutorialCpuGpuData.ogn
-------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CpuGpuData", which has attributes whose memory
type is determined at runtime by the input named *isGPU*. The algorithm of the node is implemented in CUDA, but
in such a way that it can run on either the CPU or the GPU, depending on where the attribute data lives.
.. literalinclude:: OgnTutorialCpuGpuData.ogn
:linenos:
:language: json
OgnTutorialCpuGpuData.cpp
-------------------------
The *cpp* file contains the implementation of the compute method, which checks the value of the *isGPU* attribute
and then extracts the data of the specified type to pass to the algorithm in the .cu file.
.. literalinclude:: OgnTutorialCpuGpuData.cpp
:linenos:
:language: c++
OgnTutorialCpuGpuData_CUDA.cu
-----------------------------
The *cu* file contains the implementation of the deformation on the CPU and GPU using CUDA.
.. literalinclude:: OgnTutorialCpuGpuData_CUDA.cu
:linenos:
:language: c++
CPU/GPU Attribute Access
------------------------
Here is how the attribute values are returned from the database. Up until now the attribute name has sufficed as the
database member that accesses the value through its *operator()*. The addition of the runtime switch of memory
locations is facilitated by the addition of the *gpu()* and *cpu()* members.
+-------------------------+----------------+-------------------------+-----------------+----------------+
| CPU Function | CPU Type | GPU Function | GPU Type | CUDA Type |
+=========================+================+=========================+=================+================+
| inputs.a.cpu() | const float& | inputs.a_t_gpu | const float* | const float* |
+-------------------------+----------------+-------------------------+-----------------+----------------+
| inputs.b.cpu() | const float& | inputs.b.gpu() | const float* | const float* |
+-------------------------+----------------+-------------------------+-----------------+----------------+
| outputs.sum.cpu() | float& | outputs.sum.gpu() | float* | float* |
+-------------------------+----------------+-------------------------+-----------------+----------------+
| inputs.multiplier.cpu() | const GfVec3f& | inputs.multiplier.gpu() | const GfVec3f* | const float3 |
+-------------------------+----------------+-------------------------+-----------------+----------------+
| inputs.points.cpu() | const GfVec3f* | inputs.points.gpu() | const GfVec3f** | const float3** |
+-------------------------+----------------+-------------------------+-----------------+----------------+
| outputs.points.cpu() | GfVec3f* | outputs.points.gpu() | const GfVec3f** | float3** |
+-------------------------+----------------+-------------------------+-----------------+----------------+
Type Information
++++++++++++++++
As there are three different potential types for each attribute when it varies location at runtime (CPU, CPU being
passed to GPU, and GPU) there are extra types introduced in order to handle each of them. The CUDA types are handled
as before, but on the CPU side there are extra types for the data being passed from the CPU to the GPU.
+----------------------+----------------+--------------------------+-----------------+
| CPU Type Method | CPU Data Type | GPU Type Method | GPU Data Type |
+======================+================+==========================+=================+
| inputs::a_t | const float& | inputs::a_t_gpu | const float* |
+----------------------+----------------+--------------------------+-----------------+
| inputs::b_t | const float& | inputs::b_t_gpu | const float* |
+----------------------+----------------+--------------------------+-----------------+
| outputs::sum_t | float& | outputs::sum_t_gpu | float* |
+----------------------+----------------+--------------------------+-----------------+
| inputs::multiplier_t | const GfVec3f& | inputs::multiplier_t_gpu | const GfVec3f* |
+----------------------+----------------+--------------------------+-----------------+
| inputs::points_t | const GfVec3f* | inputs::points_t_gpu | const GfVec3f** |
+----------------------+----------------+--------------------------+-----------------+
| outputs::points_t | GfVec3f* | outputs::points_t_gpu | const GfVec3f** |
+----------------------+----------------+--------------------------+-----------------+
On the C++ side the functions defined in the CUDA file are declared as:
.. code-block:: c++
extern "C" void cpuGpuMultiplierCPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t);
extern "C" void cpuGpuMultiplierGPU(outputs::points_t_gpu, inputs::multiplier_t_gpu, inputs::points_t_gpu, size_t);
The addition of the **_gpu** suffix mostly adds an extra layer of indirection to the values, since they exist in the
GPU memory namespace. Care must be taken to call the correct version with the correctly extracted data:
.. code-block:: c++
if (db.inputs.is_gpu())
{
cpuGpuMultiplierGPU(
db.outputs.points.gpu(),
db.inputs.multiplier.gpu(),
db.inputs.points.gpu(),
numberOfPoints
);
}
else
{
// Note how array data is extracted in its raw form for passing to the function on the CUDA side.
// This would be unnecessary if the implementation were entirely on the CPU side.
cpuGpuMultiplierCPU(
db.outputs.points.cpu().data(),
db.inputs.multiplier.cpu(),
db.inputs.points.cpu().data(),
numberOfPoints
);
}
On the CUDA side the function definitions use the existing CUDA types, so their signatures are:
.. code-block:: c++
extern "C" void cpuGpuMultiplierCPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t);
extern "C" void cpuGpuMultiplierGPU(outputs::points_t, inputs::multiplier_t, inputs::points_t, size_t);
| 6,658 | reStructuredText | 53.138211 | 124 | 0.499549 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpuPy.py | """
Implementation of the Python node accessing CUDA attributes in a way that accesses the GPU arrays with a CPU pointer.
No actual computation is done here as the tutorial nodes are not set up to handle GPU computation.
"""
import ctypes
import omni.graph.core as og
# Only one type of data is handled by the compute - pointf[3][]
POINT_ARRAY_TYPE = og.Type(og.BaseDataType.FLOAT, tuple_count=3, array_depth=1, role=og.AttributeRole.POSITION)
def get_address(attr: og.Attribute) -> int:
"""Returns the contents of the memory the attribute points to"""
ptr_type = ctypes.POINTER(ctypes.c_size_t)
ptr = ctypes.cast(attr.memory, ptr_type)
return ptr.contents.value
class OgnTutorialCudaDataCpuPy:
"""Exercise GPU access for extended attributes through a Python OmniGraph node"""
@staticmethod
def compute(db) -> bool:
"""Accesses the CUDA data, which for arrays exists as wrappers around CPU memory pointers to GPU pointer arrays.
No compute is done here.
"""
# Put accessors into local variables for convenience
input_points = db.inputs.points
multiplier = db.inputs.multiplier
# Set the size to what is required for the multiplication - this can be done without accessing GPU data.
# Notice that since this is CPU pointers to GPU data the size has to be taken from the data type description
# rather than the usual method of taking len(input_points).
db.outputs.points_size = input_points.dtype.size
# After changing the size the memory isn't allocated immediately (when necessary). It is delayed until you
# request access to it, which is what this line will do.
output_points = db.outputs.points
# This is a separate test to add a points attribute to the output bundle to show how when a bundle has
# CPU pointers to the GPU data that information propagates to its children
# Start with an empty output bundle.
output_bundle = db.outputs.outBundle
output_bundle.clear()
output_bundle.add_attributes([og.Type(og.BaseDataType.FLOAT, 3, 1)], ["points"])
bundle_attr = output_bundle.attribute_by_name("points")
# As for the main attributes, setting the bundle member size readies the buffer of the given size on the GPU
bundle_attr.size = input_points.dtype.size
# The output cannot be written to here through the normal assignment mechanisms, e.g. the typical step of
# copying input points to the output points, as the data is not accessible on the GPU through Python directly.
# Instead you can access the GPU memory pointers through the attribute values and send it to CUDA code, either
# generated from the Python code or accessed through something like pybind wrappers.
print("Locations in CUDA() should be in GPU memory space")
print(f" CPU Location for reference = {hex(id(db))}", flush=True)
print(f" Input points are {input_points} at CUDA({hex(get_address(input_points))})", flush=True)
print(f" Multiplier is CUDA({multiplier})", flush=True)
print(f" Output points are {output_points} at CUDA({hex(get_address(output_points))})", flush=True)
print(f" Bundle {bundle_attr.gpu_value} at CUDA({hex(get_address(bundle_attr.gpu_value))})", flush=True)
return True
| 3,391 | Python | 50.393939 | 120 | 0.699204 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/OgnTutorialCudaDataCpu.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 <omni/graph/core/GpuArray.h>
#include <OgnTutorialCudaDataCpuDatabase.h>
// This function exercises referencing of array data on the GPU.
// The CUDA code takes its own "float3" data types, which are castable equivalents to the generated GfVec3f.
// The GpuArray/ConstGpuArray wrappers isolate the GPU pointers from the CPU code.
extern "C" void applyDeformationCpuToGpu(pxr::GfVec3f* outputPoints,
const pxr::GfVec3f* inputPoints,
const pxr::GfVec3f* multiplier,
size_t numberOfPoints);
// This node runs a couple of algorithms on the GPU, while accessing parameters from the CPU
class OgnTutorialCudaDataCpu
{
public:
static bool compute(OgnTutorialCudaDataCpuDatabase& db)
{
size_t numberOfPoints = db.inputs.points.size();
db.outputs.points.resize(numberOfPoints);
if (numberOfPoints > 0)
{
// The main point to note here is how the pointer can be dereferenced on the CPU side, whereas normally
// you would have to send it to the GPU for dereferencing. (The long term purpose of the latter is to make
// it more efficient to handle arrays-of-arrays on the GPU, however since that is not yet implemented
// we can get away with a single dereference here.)
applyDeformationCpuToGpu(*db.outputs.points(), *db.inputs.points.gpu(), db.inputs.multiplier(), numberOfPoints);
// Just as a test now also reference the points as CPU data to ensure the value casts correctly
const float* pointsAsCpu = reinterpret_cast<const float*>(db.inputs.points.cpu().data());
}
return true;
}
};
REGISTER_OGN_NODE()
| 2,216 | C++ | 47.195651 | 124 | 0.686823 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial27/tutorial27.rst | .. _ogn_tutorial_cudaDataOnCpu:
Tutorial 27 - GPU Data Node with CPU Array Pointers
===================================================
The GPU data node illustrates the alternative method of extracting array data from the GPU by returning a CPU pointer
to the GPU array. Normally the data returns a GPU pointer to an array of GPU pointers, optimized for future use in
parallel processing of GPU array data. By returning a CPU pointer to the array you can use host-side processing to
dereference the pointers.
OgnTutorialCudaDataCpu.ogn
--------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.CudaCpuArrays", which has an input and
an output of type `float[3][]`, along with the special keyword to indicate that the pointer to the CUDA arrays should
be in CPU space.
.. literalinclude:: OgnTutorialCudaDataCpu.ogn
:linenos:
:language: json
:emphasize-lines: 5
OgnTutorialCudaDataCpu.cpp
--------------------------
The *cpp* file contains the implementation of the compute method, which in turn calls the CUDA algorithm.
.. literalinclude:: OgnTutorialCudaDataCpu.cpp
:linenos:
:language: c++
:emphasize-lines: 31-35
OgnTutorialCudaDataCpu_CUDA.cu
------------------------------
The *cu* file contains the implementation of the algorithm on the GPU using CUDA.
.. literalinclude:: OgnTutorialCudaDataCpu_CUDA.cu
:linenos:
:language: c++
OgnTutorialCudaDataCpuPy.py
---------------------------
The *py* file contains the implementation of the compute method, which for this example doesn't actually compute as
extra extension support is required for Python to run on the GPU (e.g. a Python -> CUDA compiler).
.. literalinclude:: OgnTutorialCudaDataCpuPy.py
:linenos:
:language: python
:emphasize-lines: 31-35
| 1,811 | reStructuredText | 35.979591 | 117 | 0.70127 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial30/OgnTutorialSIMDAdd.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.
//
#if !defined(__arm__) && !defined(__aarch64__)
#define SIMD_AVAILABLE
#endif
#include <OgnTutorialSIMDAddDatabase.h>
#ifdef SIMD_AVAILABLE
#include <immintrin.h>
#endif
// This node perform a sum using SIMD instruction set
class OgnTutorialSIMDAdd
{
public:
static size_t computeVectorized(OgnTutorialSIMDAddDatabase& db, size_t count)
{
// Constants
static size_t constexpr kSIMDSize = 4 * sizeof(float);
static size_t constexpr kMask = kSIMDSize - 1;
// Retrieve data
auto opA = db.inputs.a.vectorized(count);
auto opB = db.inputs.b.vectorized(count);
auto res = db.outputs.result.vectorized(count);
//Regular loop definition
auto regularLoop = [&](size_t const begin, size_t const end) -> size_t const
{
for (size_t idx = begin; idx < end; ++idx)
res[idx] = opA[idx] + opB[idx];
return end;
};
#ifdef SIMD_AVAILABLE
//Alignment must be identical
bool const correctlyAligned = ((size_t(opA.data()) & kMask) == (size_t(opB.data()) & kMask))
&& ((size_t(opA.data()) & kMask) == (size_t(res.data()) & kMask));
if (!correctlyAligned)
{
regularLoop(0, count);
}
else
{
// Unaligned elements
size_t const maskedAdress = (size_t(opA.data()) & kMask);
size_t const unalignedCount = maskedAdress
? regularLoop(0, (kSIMDSize - maskedAdress) / sizeof(float))
: 0;
// Vectorized elements
size_t const vectorizedCount = (count - unalignedCount) & (~kMask);
size_t const vectorizedLoop = vectorizedCount / (kSIMDSize / sizeof(float));
__m128* aSIMD = (__m128*)(opA.data() + unalignedCount);
__m128* bSIMD = (__m128*)(opB.data() + unalignedCount);
__m128* resSIMD = (__m128*)(res.data() + unalignedCount);
for (size_t idx = 0; idx < vectorizedLoop; ++idx)
resSIMD[idx] = _mm_add_ps(aSIMD[idx], bSIMD[idx]);
// Remaining elements
regularLoop(unalignedCount + vectorizedCount, count);
}
#else
regularLoop(0, count);
#endif
return count;
}
};
REGISTER_OGN_NODE()
| 2,795 | C++ | 31.511628 | 104 | 0.589982 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/extensionTutorial.rst | .. _ogn_extension_tutorial:
Example Setup - Creating An OGN-enabled Extension
=================================================
This document assumes familiarity with the extension 2.0 implementation described in the Extensions doc.
Implementation details that relate to the extension system but not to .ogn files in particular will not be described
in detail. Refer to the above document for more information.
.. only:: internal
Internal: link to Extensions / exts-main-doc broken until kit_repo_docs migration completed (bidirectional dependency bad)
For the purposes of illustration an extension names `omni.my.extension` will be created, with a single node `OgnMyNode`.
.. contents::
.. _ogn_recommended_directory_structure:
Recommended Directory Structure
-------------------------------
The OGN helper scripts presume a certain directory structure, setting up helper variables that default to values supporting
that structure. You're free to use any other structure, you will just have more work to do in your build file to support
them.
To start with are the directories.
.. code-block:: text
:emphasize-lines: 1,2,4,6,8,12,15,19,21,23,26
omni.my.extension/
βββ bindings/
| βββ BindingsPython.cpp
βββ config/
| βββ extension.toml
βββ data/
| βββ preview.png
βββ docs/
| βββ README.md
| βββ CHANGELOG.md
| βββ index.rst
βββ nodes/
| βββ OgnMyNode.cpp
| βββ OgnMyNode.ogn
βββ plugins/
| βββ PluginInterface.cpp
| βββ IMyExtension.h
βββ premake5.lua
βββ python/
βββ __init__.py
βββ _impl/
| extension.py
| βββ nodes/
| βββ OgnMyPythonNode.py
| βββ OgnMyPythonNode.ogn
βββ tests/
βββ test_my_extension.py
**omni.my.extension** is the top level directory for the extension, keeping all related files together.
**config** is the common location for the extension configuration file.
**data** is the common location for data files used by your extension.
**docs** is the common location for published documentation for your extension.
**nodes** is a directory you can put all of your node files. If there is a large number of nodes for a single extension then this
directory can be subdivided (e.g. **nodes/math**, **nodes/core**, **nodes/vectors**...)
**plugins** is for the common C++ code. In particular the files connecting to the Carbonite plugin ABI, but also other files used
by the plugin that aren't specifically node files.
**python** contains just the __init__.py script used to load the extension. The main feature of this file is that it
is used to import everything in the **python/_impl** subdirectory that will be exposed as the public API. Although this
is just a convention, as every function will always be accessible for the user that digs deep enough, setting up your
intended API in this way makes it more clear exactly what parts of your module are intended for public use, and hence
expected to be more stable.
**python/_impl** contains all of the Python scripts. At the top level this can be UI files, commands, and helper scripts.
**python/_impl/nodes** contains all of your nodes implemented in Python. Separating them into their own directory makes
it easier for the OGN processor to find them.
**python/tests** is for the scripts used to test the functionality in your extension. These are your armour, keeping
your extension safe from changes others make, and providing confidence when you refactor.
premake5.lua
------------
The *.lua* file containing an extension 2.0 implementation of an extension. The OGN-specific additions are commented. (Other lines would
normally be commented as well in good build code; omitted here for clarity.)
.. literalinclude:: premake5.lua
:linenos:
:language: lua
Here is that same file with appropriate comments that can be used as a starting template.
.. literalinclude:: premake5-template.lua
:linenos:
:language: lua
Changing Type Definitions
+++++++++++++++++++++++++
By default the code generator uses certain C++, CUDA, and Python data types for the code it produces. Sometimes you may
wish to use alternative types, e.g. your favourite math library's types. This information can be modified through a
type definition file. To modify the type definitions for an entire project you add an extra parameter to the call to
`get_ogn_project_information()` in your ``premake5.lua`` file, with details described in
:ref:`ogn_type_definition_overrides`.
bindings/BindingsPython.cpp
---------------------------
This file is set up as per the regular extension set up you can find in the Extensions doc with no OGN-specific changes
required.
.. only:: internal
Internal: link to Extensions / exts-main-doc broken until kit_repo_docs migration completed (bidirectional dependency bad)
config/extension.toml
---------------------
In addition to the other required dependencies, the OmniGraph dependencies need to be added for the extension loading to work properly.
These are the OmniGraph core, and the Kit async engine used for running tests.
.. code-block:: toml
:linenos:
:emphasize-lines: 8-11,15-16
[package]
title = "My Feature"
# Main module for the Python interface
[[python.module]]
name = "omni.my.feature"
# Watch the .ogn files for hot reloading (only works for Python files)
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Other extensions that need to load before this one
[dependencies]
"omni.graph" = {}
"omni.graph.tools" = {}
[[native.plugin]]
path = "bin/${platform}/${config}/*.plugin"
recursive = false
data/preview.png
----------------
This file is an image that will be displayed in the extension manager. Nothing extra needs to be done to make that
happen; just create the file and ensure that the **data/** directory is installed into the extension's destination
directory.
docs/README.md
--------------
Markdown format documentation for your extension that will appear in the extension manager. It should be a short
description of what the extension does. Here is a minimal version of a readme.
.. code-block:: md
# My Extension [omni.my.extension]
My extension can cook your breakfast, mow your lawn, and fix the clog in your kitchen sink.
docs/CHANGELOG.md
-----------------
Markdown format documentation for your extension changes that will appear in the extension manager. Here is a simple
template that uses a standard approach to maintaining change logs.
.. code-block:: md
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.0.0] - 2021-03-01
### Initial Version
docs/index.rst
--------------
ReStructuredText format documentation for your extension. The node's documentation will be generated automatically
by the OGN processor.
nodes/OgnMyNode.cpp,OgnMyNode.ogn
---------------------------------
These files contain the description and implementation of your node. See the detailed examples in
:ref:`ogn_tutorial_nodes` for information on what can go into these files.
The naming of the files is important. They must both have the same base name (``OgnMyNode`` in this case). It is also
a good idea to have the common prefix `Ogn` as that makes nodes easier to locate.
plugins/PluginInterface.cpp
---------------------------
This file sets up your plugin. The OGN processing requires a couple of small additions to enable the automatic
registration and deregistration of nodes when your plugin starts up and shuts down.
.. code-block:: c++
:linenos:
:emphasize-lines: 6,7,16-18,28,33
#include "IOmniMyFeature.h"
#include <carb/Framework.h>
#include <carb/PluginUtils.h>
#include <omni/graph/core/iComputeGraph.h>
#include <omni/graph/core/ogn/Registration.h>
#include <omni/kit/IEditor.h>
#include <omni/kit/IMinimal.h>
const struct carb::PluginImplDesc pluginDesc = { "omni.my.feature.plugin", "My Feature", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
CARB_PLUGIN_IMPL(pluginDesc, omni::my::feature::IOmniMyFeature)
CARB_PLUGIN_IMPL_DEPS(omni::kit::IEditor,
omni::graph::core::IGraphRegistry,
carb::flatcache::IToken)
DECLARE_OGN_NODES()
// carbonite interface for this plugin (may contain multiple compute nodes)
void fillInterface(omni::my::feature::IOmniMyFeature& iface)
{
iface = {};
}
CARB_EXPORT void carbOnPluginStartup()
{
INITIALIZE_OGN_NODES()
}
CARB_EXPORT void carbOnPluginShutdown()
{
RELEASE_OGN_NODES()
}
plugins/IMyExtension.h
----------------------
This file is set up as per the extension description with no OGN-specific changes required.
python/__init__.py
------------------
This file initializes the extension's Python module as per the extension model. This will import your intended Python
API for general use.
.. code-block:: python
from ._impl.utilities import useful_utility
from ._impl.utilities import other_utility
from ._impl.commands import cmds
With this setup the extension user can access your Python API through the main module (similarly to how popular
public packages such as `numpy` and `pandas` are structured).
.. code-block:: python
import omni.my.feature as mf
mf.useful_utility(["Bart", "Lisa", "Maggie", "Marge", "Homer"])
python/tests/__init__.py
------------------------
This file may contain setup code for your manually written test scripts that appear in this directory. It should
contain the snippet below, which will enable automatic registration of your tests at runtime.
.. code-block:: python
"""
Presence of this file allows the tests directory to be imported as a module so that all of its contents
can be scanned to automatically add tests that are placed into this directory.
"""
scan_for_test_modules = True
Test files should all have a PEP8-compliant name of the form ``test_my_good_test_file.py``. The `test` prefix ensures
that the files will be automatically recognized as containing Python unit tests.
Sample Skeleton Test
--------------------
Here's an example of a simple test that does nothing more than run a graph evaluation on a graph consisting of
two nodes with a connection between them, verifying the output of a node. While .ogn files have the ability to
specify their own automated test configurations, it is very limited and you'll want to use something like this for
more complex testing.
.. literalinclude:: test_example.py
:linenos:
:language: python
| 10,947 | reStructuredText | 36.365188 | 136 | 0.698273 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/extensionTutorial/test_example.py | """Tests for my simple math nodes"""
# To make code more concise use a shortform in the import, much as you would for numpy -> np
import omni.graph.core as og
# This module contains some useful testing utilities
import omni.graph.core.tests as ogts
# By using the standard test case base class you get scene setUp() and tearDown(), and the current set of default
# OmniGraph settings. If you wish to use any non-standard settings, leave the scene in place after the test completes,
# or add your own scoped setting variables see the set of classes that derive from ogts.OmniGraphTestCase and look at
# the test configuration factory function ogts.test_case_class().
class TestMySimpleNodes(ogts.OmniGraphTestCase):
"""Class containing tests for my simple nodes. The base class allows the tests to be run asynchronously"""
# ----------------------------------------------------------------------
async def test_math(self):
"""Run a node network with the math operation (A + 6) * 10 = B
Exercises the math nodes for addition (my.node.add) and multiplication (my.node.multiply)
"""
# The Controller class is useful for manipulating the OmniGraph. See the Python help on it for details.
# Using this shortcut keeps the graph configuration specification more readable.
keys = og.Controller.Keys
# This sets up the graph in the configuration required for the math operation to work
(graph, (plus_node, times_node), _, _) = og.Controller.edit(
"/mathGraph",
{
keys.CREATE_NODES: [("plus", "my.extension.addInts"), ("times", "my.extension.multiplyInts")],
keys.CONNECT: [("plus.outputs:result", "times.inputs:a")],
keys.SET_VALUES: [("plus.inputs:a", 6), ("times.inputs:b", 10)],
},
)
# This contains pairs of (A, B) values that should satisfy the math equation.
test_data = [(1, 70), (0, 60), (-6, 0)]
# Creating specific controllers tied to the attributes that will be accessed multiple times in the loop
# makes the access a little bit faster.
in_controller = og.Controller(og.Controller.attribute("inputs:b", plus_node))
out_controller = og.Controller(og.Controller.attribute("outputs:result", times_node))
# Loop through the operation to set the input and test the output
for (value_a, value_b) in test_data:
# Set the test input on the node
in_controller.set(value_a)
# This has to be done to ensure the nodes do their computation before testing the results
await og.Controller.evaluate(graph)
# Compare the expected value from the test data against the computed value from the node
self.assertEqual(value_b, out_controller.get())
| 2,843 | Python | 52.660376 | 118 | 0.65459 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial14/OgnTutorialDefaults.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 <OgnTutorialDefaultsDatabase.h>
class OgnTutorialDefaults
{
public:
static bool compute(OgnTutorialDefaultsDatabase& db)
{
// Simple values
db.outputs.a_bool() = db.inputs.a_bool();
db.outputs.a_half() = db.inputs.a_half();
db.outputs.a_int() = db.inputs.a_int();
db.outputs.a_int64() = db.inputs.a_int64();
db.outputs.a_double() = db.inputs.a_double();
db.outputs.a_float() = db.inputs.a_float();
db.outputs.a_uchar() = db.inputs.a_uchar();
db.outputs.a_uint() = db.inputs.a_uint();
db.outputs.a_uint64() = db.inputs.a_uint64();
db.outputs.a_token() = db.inputs.a_token();
db.outputs.a_string() = db.inputs.a_string();
// A few representative tuples
db.outputs.a_int2() = db.inputs.a_int2();
db.outputs.a_matrix() = db.inputs.a_matrix();
// And an array
db.outputs.a_array().resize(db.inputs.a_array().size());
db.outputs.a_array() = db.inputs.a_array();
return true;
}
};
REGISTER_OGN_NODE()
| 1,507 | C++ | 34.904761 | 77 | 0.642999 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial14/tutorial14.rst | .. _ogn_tutorial_defaults:
Tutorial 14 - Defaults
======================
While most inputs are required to have default values it's not strictly necessary to provide explicit values
for those defaults. If a default is required and not specified then it will get a default value equal to an
empty value. See the table at the bottom for what is considered an "empty" value for each type of attribute.
OgnTutorialDefaults.ogn
------------------------
The *ogn* file shows the implementation of a node named
"omni.graph.tutorials.Defaults", which has sample inputs of several types without default values and matching outputs.
.. literalinclude:: OgnTutorialDefaults.ogn
:linenos:
:language: json
OgnTutorialDefaults.cpp
------------------------
The *cpp* file contains the implementation of the compute method, which
copies the input values over to the corresponding outputs. All values should be the empty defaults.
.. literalinclude:: OgnTutorialDefaults.cpp
:linenos:
:language: c++
Empty Values For Attribute Types
--------------------------------
The empty values for each of the attribute types is defined below. Having no default specified in the .ogn file
for any of them is equivalent to defining a default of the given value.
+-----------+---------------+
| Type Name | Empty Default |
+===========+===============+
| bool | False |
+-----------+---------------+
| double | 0.0 |
+-----------+---------------+
| float | 0.0 |
+-----------+---------------+
| half | 0.0 |
+-----------+---------------+
| int | 0 |
+-----------+---------------+
| int64 | 0 |
+-----------+---------------+
| string | "" |
+-----------+---------------+
| token | "" |
+-----------+---------------+
| uchar | 0 |
+-----------+---------------+
| uint | 0 |
+-----------+---------------+
| uint64 | 0 |
+-----------+---------------+
.. note::
All attributes that are array types have empty defaults equal to the empty array []
.. note::
All tuple types have empty defaults equal to a tuple of the correct count, each member containing the empty
value for the base type. e.g. a float[2] will have empty default [0.0, 0.0], and a matrix[2] will have
empty default [[0.0, 0.0], [0.0, 0.0]]
| 2,381 | reStructuredText | 34.029411 | 118 | 0.524989 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial26/OgnTutorialGenericMathNode.py | import numpy as np
import omni.graph.core as og
# Mappings of possible numpy dtypes from the result data type and back
dtype_from_basetype = {
og.BaseDataType.INT: np.int32,
og.BaseDataType.INT64: np.int64,
og.BaseDataType.HALF: np.float16,
og.BaseDataType.FLOAT: np.float32,
og.BaseDataType.DOUBLE: np.float64,
}
supported_basetypes = [
og.BaseDataType.INT,
og.BaseDataType.INT64,
og.BaseDataType.HALF,
og.BaseDataType.FLOAT,
og.BaseDataType.DOUBLE,
]
basetype_resolution_table = [
[0, 1, 3, 3, 4], # Int
[1, 1, 4, 4, 4], # Int64
[3, 4, 2, 3, 4], # Half
[3, 4, 3, 3, 4], # Float
[4, 4, 4, 4, 4], # Double
]
class OgnTutorialGenericMathNode:
"""Node to multiple two values of any type"""
@staticmethod
def compute(db) -> bool:
"""Compute the product of two values, if the types are all resolved.
When the types are not compatible for multiplication, or the result type is not compatible with the
resolved output type, the method will log an error and fail
"""
try:
# To support multiplying array of vectors by array of scalars we need to broadcast the scalars to match the
# shape of the vector array, and we will convert the result to whatever the result is resolved to
atype = db.inputs.a.type
btype = db.inputs.b.type
rtype = db.outputs.product.type
result_dtype = dtype_from_basetype.get(rtype.base_type, None)
# Use numpy to perform the multiplication in order to automatically handle both scalar and array types
# and automatically convert to the resolved output type
if atype.array_depth > 0 and btype.array_depth > 0 and btype.tuple_count < atype.tuple_count:
r = np.multiply(db.inputs.a.value, db.inputs.b.value[:, np.newaxis], dtype=result_dtype)
else:
r = np.multiply(db.inputs.a.value, db.inputs.b.value, dtype=result_dtype)
db.outputs.product.value = r
except TypeError as error:
db.log_error(f"Multiplication could not be performed: {error}")
return False
return True
@staticmethod
def on_connection_type_resolve(node) -> None:
# Resolves the type of the output based on the types of inputs
atype = node.get_attribute("inputs:a").get_resolved_type()
btype = node.get_attribute("inputs:b").get_resolved_type()
productattr = node.get_attribute("outputs:product")
producttype = productattr.get_resolved_type()
# The output types can be only inferred when both inputs types are resolved.
if (
atype.base_type != og.BaseDataType.UNKNOWN
and btype.base_type != og.BaseDataType.UNKNOWN
and producttype.base_type == og.BaseDataType.UNKNOWN
):
# Resolve the base type using the lookup table
base_type = og.BaseDataType.DOUBLE
a_index = supported_basetypes.index(atype.base_type)
b_index = supported_basetypes.index(btype.base_type)
if a_index >= 0 and b_index >= 0:
base_type = supported_basetypes[basetype_resolution_table[a_index][b_index]]
productattr.set_resolved_type(
og.Type(base_type, max(atype.tuple_count, btype.tuple_count), max(atype.array_depth, btype.array_depth))
)
| 3,448 | Python | 37.322222 | 120 | 0.633991 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial26/tutorial26.rst | .. _ogn_tutorial_generic_math_node:
Tutorial 26 - Generic Math Node
================================
This tutorial demonstrates how to compose nodes that perform mathematical operations in python using numpy. Using numpy
has the advantage that it is api-compatible to cuNumeric. As demonstrated in the Extended Attributes tutorial, generic math nodes
use extended attributes to allow inputs and outputs of arbitrary numeric types, specified using the "numerics" keyword.
.. code-block:: json
"inputs": {
"myNumbericAttribute": {
"description": "Accepts an incoming connection from any type of numeric value",
"type": ["numerics"]
}
}
OgnTutorialGenericMathNode.ogn
--------------------------------
The *ogn* file shows the implementation of a node named "omni.graph.tutorials.GenericMathNode", which takes inputs
of any numeric types and performs a multiplication.
.. literalinclude:: OgnTutorialGenericMathNode.ogn
:linenos:
:language: json
OgnTutorialGenericMathNode.py
---------------------------------
The *py* file contains the implementation of the node. It takes two numeric inputs and performs a multiplication,
demonstrating how to handle cases where the inputs are both numeric types but vary in precision, format or
dimension.
.. literalinclude:: OgnTutorialGenericMathNode.py
:linenos:
:language: python
| 1,393 | reStructuredText | 36.675675 | 130 | 0.703518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.