file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMatrixMultiply.cpp
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnMatrixMultiplyDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/vec.h> #include <type_traits> using omni::math::linalg::base_matrix; using omni::math::linalg::base_vec; using ogn::compute::tryComputeWithArrayBroadcasting; namespace omni { namespace graph { namespace nodes { namespace { // Base type T, dimension N (eg: 2,3,4) template<typename T, size_t N> bool tryComputeAssumingType(OgnMatrixMultiplyDatabase& db) { auto matrixMatrixFn = [](auto const& a, auto const& b, auto& result) { const auto& aMatrix = *reinterpret_cast<const base_matrix<T, N>*>(a); const auto& bMatrix = *reinterpret_cast<const base_matrix<T, N>*>(b); auto& resultMatrix = *reinterpret_cast<base_matrix<T, N>*>(result); resultMatrix = aMatrix * bMatrix; }; auto matrixVectorFn = [](auto const& a, auto const& b, auto& result) { const auto& aMatrix = *reinterpret_cast<const base_matrix<T, N>*>(a); const auto& bVec = *reinterpret_cast<const base_vec<T, N>*>(b); auto& resultVec = *reinterpret_cast<base_vec<T, N>*>(result); resultVec = aMatrix * bVec; }; auto vectorMatrixFn = [](auto const& a, auto const& b, auto& result) { const auto& aVec = *reinterpret_cast<const base_vec<T, N>*>(a); const auto& bMatrix = *reinterpret_cast<const base_matrix<T, N>*>(b); auto& resultVec = *reinterpret_cast<base_vec<T, N>*>(result); resultVec = aVec * bMatrix; }; auto vectorVectorFn = [](auto const& a, auto const& b, auto& result) { const auto& aVec = *reinterpret_cast<const base_vec<T, N>*>(a); const auto& bVec = *reinterpret_cast<const base_vec<T, N>*>(b); result = aVec * bVec; }; if (N >= 3 && tryComputeWithArrayBroadcasting<T[N*N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), matrixMatrixFn)) return true; else if (N >= 3 && tryComputeWithArrayBroadcasting<T[N*N], T[N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), matrixVectorFn)) return true; else if (N >= 3 && tryComputeWithArrayBroadcasting<T[N], T[N*N], T[N]>(db.inputs.a(), db.inputs.b(), db.outputs.output(), vectorMatrixFn)) return true; else if (tryComputeWithArrayBroadcasting<T[N], T[N], T>(db.inputs.a(), db.inputs.b(), db.outputs.output(), vectorVectorFn)) return true; return false; } } // namespace class OgnMatrixMultiply { public: static bool compute(OgnMatrixMultiplyDatabase& db) { try { if (tryComputeAssumingType<double, 2>(db)) return true; else if (tryComputeAssumingType<double, 3>(db)) return true; else if (tryComputeAssumingType<double, 4>(db)) return true; else if (tryComputeAssumingType<float, 2>(db)) return true; else if (tryComputeAssumingType<float, 3>(db)) return true; else if (tryComputeAssumingType<float, 4>(db)) return true; else if (tryComputeAssumingType<pxr::GfHalf, 2>(db)) return true; else if (tryComputeAssumingType<pxr::GfHalf, 3>(db)) return true; else if (tryComputeAssumingType<pxr::GfHalf, 4>(db)) return true; else { db.logWarning("OgnMatrixMultiply: Failed to resolve input types"); } } catch (ogn::compute::InputError &error) { db.logWarning("OgnMatrixMultiply: %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node){ auto a = node.iNode->getAttributeByToken(node, inputs::a.token()); auto b = node.iNode->getAttributeByToken(node, inputs::b.token()); auto output = node.iNode->getAttributeByToken(node, outputs::output.token()); auto aType = a.iAttribute->getResolvedType(a); auto bType = b.iAttribute->getResolvedType(b); // Require inputs to be resolved before determining output's type if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown) { auto biggerDim = std::max(aType.componentCount, bType.componentCount); auto smallerDim = std::min(aType.componentCount, bType.componentCount); if (biggerDim != smallerDim && biggerDim != smallerDim * smallerDim) { CARB_LOG_WARN_ONCE("OgnMatrixMultiply: Inputs are not compatible with tuple counts %d and %d", aType.componentCount, bType.componentCount); return; } // Vector4 * Matrix4 = Vector4, Matrix4 * Vector4 = Vector4 and etc. auto tupleCount = smallerDim; auto role = aType.componentCount < bType.componentCount ? aType.role : bType.role; if (smallerDim == biggerDim && smallerDim <= 4) { // equivalent to dot product of two vectors tupleCount = 1; role = AttributeRole::eNone; } std::array<AttributeObj, 3> attrs { a, b, output }; std::array<uint8_t, 3> tupleCounts { aType.componentCount, bType.componentCount, tupleCount }; std::array<uint8_t, 3> arrayDepths { aType.arrayDepth, bType.arrayDepth, std::max(aType.arrayDepth, bType.arrayDepth) }; std::array<AttributeRole, 3> rolesBuf { aType.role, bType.role, role }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
6,428
C++
39.949044
155
0.61061
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDotProduct.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnDotProductDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <omni/math/linalg/vec.h> #include <carb/logging/Log.h> #include <cmath> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { template<typename T, size_t N> bool tryComputeAssumingType(OgnDotProductDatabase& db) { auto functor = [](auto const& a, auto const& b, auto& product) { const auto& vecA = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(a); const auto& vecB = *reinterpret_cast<const omni::math::linalg::base_vec<T, N>*>(b); product = vecA.Dot(vecB); }; return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N], T>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor); } } // namespace class OgnDotProduct { public: static bool compute(OgnDotProductDatabase& db) { try { auto& aType = db.inputs.a().type(); switch(aType.baseType) { case BaseDataType::eDouble: switch(aType.componentCount) { case 2: return tryComputeAssumingType<double, 2>(db); case 3: return tryComputeAssumingType<double, 3>(db); case 4: return tryComputeAssumingType<double, 4>(db); } case BaseDataType::eFloat: switch(aType.componentCount) { case 2: return tryComputeAssumingType<float, 2>(db); case 3: return tryComputeAssumingType<float, 3>(db); case 4: return tryComputeAssumingType<float, 4>(db); } case BaseDataType::eHalf: switch(aType.componentCount) { case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db); } default: db.logError("Failed to resolve input types"); } } catch (ogn::compute::InputError &error) { db.logError("%s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node) { auto a = node.iNode->getAttributeByToken(node, inputs::a.token()); auto b = node.iNode->getAttributeByToken(node, inputs::b.token()); auto product = node.iNode->getAttributeByToken(node, outputs::product.token()); // Require inputs to be resolved before determining product's type auto aType = a.iAttribute->getResolvedType(a); auto bType = b.iAttribute->getResolvedType(b); if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { a, b, product }; // a, b should all have the same tuple count std::array<uint8_t, 3> tupleCounts { aType.componentCount, bType.componentCount, 1 }; std::array<uint8_t, 3> arrayDepths { aType.arrayDepth, bType.arrayDepth, // Allow for a mix of singular and array inputs. If any input is an array, the output must be an array std::max(aType.arrayDepth, bType.arrayDepth) }; std::array<AttributeRole, 3> rolesBuf { aType.role, bType.role, AttributeRole::eNone }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni // end-compute-helpers
4,483
C++
37
149
0.581753
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomBoolean.cpp
// Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "random/RandomNodeBase.h" #include <OgnRandomBooleanDatabase.h> namespace omni { namespace graph { namespace nodes { using namespace random; class OgnRandomBoolean : public NodeBase<OgnRandomBoolean, OgnRandomBooleanDatabase> { public: static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj) { generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed); } static bool onCompute(OgnRandomBooleanDatabase& db, size_t count) { return computeRandoms(db, count, [](GeneratorState& gen) { return gen.nextUniformBool(); }); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
1,133
C++
26.658536
100
0.753751
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve.cpp
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnGetLocationAtDistanceOnCurveDatabase.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/base/gf/rotation.h> #include <omni/graph/core/PostUsdInclude.h> #include <omni/math/linalg/SafeCast.h> #include <cmath> #include "XformUtils.h" using omni::math::linalg::quatf; using omni::math::linalg::quatd; using omni::math::linalg::vec3d; using omni::math::linalg::matrix4d; // return the named unit vector X,Y or Z static vec3d axisToVec(NameToken axisToken, OgnGetLocationAtDistanceOnCurveDatabase::TokenManager& tokens) { if (axisToken == tokens.y || axisToken == tokens.Y) return vec3d::YAxis(); if (axisToken == tokens.z || axisToken == tokens.Z) return vec3d::ZAxis(); return vec3d::XAxis(); } class OgnGetLocationAtDistanceOnCurve { public: static bool compute(OgnGetLocationAtDistanceOnCurveDatabase& db) { /* This is a simple closed poly-line interpolation to find p, the point on the curve 1. find the total length of the curve 2. find the start and end cvs of the line segment which contains p 3. calculate the position on that line segment, and the rotation */ bool ok = false; const auto& curve_cvs_in = db.inputs.curve(); auto& locations = db.outputs.location(); auto& rotations = db.outputs.rotateXYZ(); auto& orientations = db.outputs.orientation(); const auto& distances = db.inputs.distance(); double curve_length = 0; // The total curve length std::vector<double> accumulated_lengths; // the length of the curve at each the end of each segment std::vector<double> segment_lengths; // the length of each segment size_t num_cvs = curve_cvs_in.size(); if (num_cvs == 0) return false; { CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "resize"); locations.resize(distances.size()); rotations.resize(distances.size()); orientations.resize(distances.size()); } if (num_cvs == 1) { std::fill(locations.begin(), locations.end(), curve_cvs_in[0]); std::fill(rotations.begin(), rotations.end(), vec3d(0, 0, 0)); return true; } std::vector<vec3d> curve_cvs; { CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "PreprocessCurve"); curve_cvs.resize(curve_cvs_in.size() + 1); std::copy(curve_cvs_in.begin(), curve_cvs_in.end(), curve_cvs.begin()); // add a cv to make a closed curve curve_cvs[curve_cvs_in.size()] = curve_cvs_in[0]; // calculate the total curve length and the length at the end of each segment const vec3d* p_a = curve_cvs.data(); for (size_t i = 1; i < curve_cvs.size(); ++i) { const vec3d& p_b = curve_cvs[i]; double segment_length = (p_b - *p_a).GetLength(); segment_lengths.push_back(segment_length); curve_length += segment_length; accumulated_lengths.push_back(curve_length); p_a = &p_b; } } const vec3d forwardAxis = axisToVec(db.inputs.forwardAxis(), db.tokens); const vec3d upAxis = axisToVec(db.inputs.upAxis(), db.tokens); // Calculate eye frame auto eyeUL = forwardAxis; auto eyeVL = upAxis; auto eyeWL = (eyeUL ^ eyeVL).GetNormalized(); eyeVL = eyeWL ^ eyeUL; // local transform from forward axis matrix4d localMat, localMatInv; localMat.SetIdentity(); localMat.SetRow3(0, eyeUL); localMat.SetRow3(1, eyeVL); localMat.SetRow3(2, eyeWL); localMatInv = localMat.GetInverse(); auto distanceIter = distances.begin(); auto locationIter = locations.begin(); auto rotationIter = rotations.begin(); auto orientationIter = orientations.begin(); { CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "ScanCurve"); for (; distanceIter != distances.end(); ++distanceIter, ++locationIter, ++rotationIter, ++orientationIter) { // wrap distance to range [0, 1.0] double normalized_distance = std::fmod(*distanceIter, 1.0); // the distance along the curve in world space double distance = curve_length * normalized_distance; // Find the location and direction double remaining_dist = 0; for (size_t i = 0; i < accumulated_lengths.size(); ++i) { double segment_length = accumulated_lengths[i]; if (segment_length >= distance) { if (i > 0) remaining_dist = distance - accumulated_lengths[i - 1]; else remaining_dist = distance; const auto& start_cv = curve_cvs[i]; const auto& end_cv = curve_cvs[i + 1]; const auto aimVec = end_cv - start_cv; const auto segment_unit_vec = aimVec / segment_lengths[i]; const auto point_on_segment = start_cv + segment_unit_vec * remaining_dist; *locationIter = point_on_segment; // calculate the rotation vec3d eyeU = segment_unit_vec; vec3d eyeV = upAxis; auto eyeW = (eyeU ^ eyeV).GetNormalized(); eyeV = eyeW ^ eyeU; matrix4d eyeMtx; eyeMtx.SetIdentity(); eyeMtx.SetTranslateOnly(point_on_segment); // eye aiming eyeMtx.SetRow3(0, eyeU); eyeMtx.SetRow3(1, eyeV); eyeMtx.SetRow3(2, eyeW); matrix4d orientMtx = localMatInv * eyeMtx; const quatd q = omni::graph::nodes::extractRotationQuatd(orientMtx); const pxr::GfRotation rotation(omni::math::linalg::safeCastToUSD(q)); const auto eulerRotations = rotation.Decompose(pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis()); pxr::GfVec3d eulerRotationsXYZ(eulerRotations[2], eulerRotations[1], eulerRotations[0]); *rotationIter = omni::math::linalg::safeCastToOmni(eulerRotationsXYZ); *orientationIter = quatf(q); ok = true; break; } } } } return ok; } }; REGISTER_OGN_NODE()
7,280
C++
37.523809
114
0.576786
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnATan2.py
""" This is the implementation of the OGN node defined in OgnATan2.ogn """ import math import omni.graph.core as og class OgnATan2: """ Calculates the arc tangent of A,B. This is the angle in radians between the ray ending at the origin and passing through the point (B, A). """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" try: db.outputs.result.value = math.degrees(math.atan2(db.inputs.a.value, db.inputs.b.value)) except TypeError as error: db.log_error(f"atan2 could not be performed: {error}") return False return True @staticmethod def on_connection_type_resolve(node) -> None: aattr = node.get_attribute("inputs:a") battr = node.get_attribute("inputs:b") resultattr = node.get_attribute("outputs:result") og.resolve_fully_coupled([aattr, battr, resultattr])
949
Python
27.787878
109
0.640674
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnModulo.cpp
// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnModuloDatabase.h> #include <cmath> #include <algorithm> #include <array> template <typename T, typename AttrInType, typename AttrOutType> void modulo(AttrInType& a, AttrInType& b, AttrOutType& result) { T bval = *b.template get<T>(); if (bval == 0) { *result.template get<T>() = 0; return; } *result.template get<T>() = *a.template get<T>() % bval; } class OgnModulo { public: static bool compute(OgnModuloDatabase& db) { const auto& a = db.inputs.a(); const auto& b = db.inputs.b(); auto& result = db.outputs.result(); if (!a.resolved()) return true; switch(a.type().baseType) { case BaseDataType::eInt: modulo<int>(a, b, result); break; case BaseDataType::eUInt: modulo<uint32_t>(a, b, result); break; case BaseDataType::eInt64: modulo<int64_t>(a, b, result); break; case BaseDataType::eUInt64: modulo<uint64_t>(a, b, result); break; default: break; } return true; } static void onConnectionTypeResolve(const NodeObj& node){ // Resolve fully-coupled types for the 3 attributes std::array<AttributeObj, 3> attrs { node.iNode->getAttribute(node, OgnModuloAttributes::inputs::a.m_name), node.iNode->getAttribute(node, OgnModuloAttributes::inputs::b.m_name), node.iNode->getAttribute(node, OgnModuloAttributes::outputs::result.m_name) }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } }; REGISTER_OGN_NODE()
2,148
C++
29.267605
87
0.616853
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide_Matrices.cpp
#include "OgnDivideHelper.h" namespace omni { namespace graph { namespace nodes { namespace OGNDivideHelper { template<size_t N> bool _tryCompute(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count) { if (tryComputeAssumingType<double, double, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<double, float, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<double, pxr::GfHalf, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<double, int32_t, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<double, int64_t, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<double, unsigned char, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<double, uint32_t, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<double, uint64_t, N>(db, a, b, result, count)) return true; return false; } bool tryComputeMatrices(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count) { // Matrix3f type if (_tryCompute<9>(db, a, b, result, count)) return true; // Matrix4f type if (_tryCompute<16>(db, a, b, result, count)) return true; return false; } } // namespace OGNDivideHelper } // namespace nodes } // namespace graph } // namespace omni
1,470
C++
35.774999
117
0.659864
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve2.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 <OgnGetLocationAtDistanceOnCurve2Database.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/base/gf/rotation.h> #include <omni/graph/core/PostUsdInclude.h> #include <omni/math/linalg/SafeCast.h> #include <cmath> #include "XformUtils.h" using omni::math::linalg::quatf; using omni::math::linalg::quatd; using omni::math::linalg::vec3d; using omni::math::linalg::matrix4d; // return the named unit vector X,Y or Z static vec3d axisToVec(NameToken axisToken, OgnGetLocationAtDistanceOnCurve2Database::TokenManager& tokens) { if (axisToken == tokens.y || axisToken == tokens.Y) return vec3d::YAxis(); if (axisToken == tokens.z || axisToken == tokens.Z) return vec3d::ZAxis(); return vec3d::XAxis(); } class OgnGetLocationAtDistanceOnCurve2 { public: static bool computeVectorized(OgnGetLocationAtDistanceOnCurve2Database& db, size_t count) { /* This is a simple closed poly-line interpolation to find p, the point on the curve 1. find the total length of the curve 2. find the start and end cvs of the line segment which contains p 3. calculate the position on that line segment, and the rotation */ bool ok = false; const auto& curve_cvs_in = db.inputs.curve(); auto locations = db.outputs.location.vectorized(count); auto rotations = db.outputs.rotateXYZ.vectorized(count); auto orientations = db.outputs.orientation.vectorized(count); const auto distances = db.inputs.distance.vectorized(count); double curve_length = 0; // The total curve length std::vector<double> accumulated_lengths; // the length of the curve at each the end of each segment std::vector<double> segment_lengths; // the length of each segment size_t num_cvs = curve_cvs_in.size(); if (num_cvs == 0) return false; if (num_cvs == 1) { std::fill(locations.begin(), locations.end(), curve_cvs_in[0]); std::fill(rotations.begin(), rotations.end(), vec3d(0, 0, 0)); return true; } std::vector<vec3d> curve_cvs; { CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "PreprocessCurve"); curve_cvs.resize(curve_cvs_in.size() + 1); std::copy(curve_cvs_in.begin(), curve_cvs_in.end(), curve_cvs.begin()); // add a cv to make a closed curve curve_cvs[curve_cvs_in.size()] = curve_cvs_in[0]; // calculate the total curve length and the length at the end of each segment const vec3d* p_a = curve_cvs.data(); for (size_t i = 1; i < curve_cvs.size(); ++i) { const vec3d& p_b = curve_cvs[i]; double segment_length = (p_b - *p_a).GetLength(); segment_lengths.push_back(segment_length); curve_length += segment_length; accumulated_lengths.push_back(curve_length); p_a = &p_b; } } const vec3d forwardAxis = axisToVec(db.inputs.forwardAxis(), db.tokens); const vec3d upAxis = axisToVec(db.inputs.upAxis(), db.tokens); // Calculate eye frame auto eyeUL = forwardAxis; auto eyeVL = upAxis; auto eyeWL = (eyeUL ^ eyeVL).GetNormalized(); eyeVL = eyeWL ^ eyeUL; // local transform from forward axis matrix4d localMat, localMatInv; localMat.SetIdentity(); localMat.SetRow3(0, eyeUL); localMat.SetRow3(1, eyeVL); localMat.SetRow3(2, eyeWL); localMatInv = localMat.GetInverse(); auto distanceIter = distances.begin(); auto locationIter = locations.begin(); auto rotationIter = rotations.begin(); auto orientationIter = orientations.begin(); { CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "ScanCurve"); for (; distanceIter != distances.end(); ++distanceIter, ++locationIter, ++rotationIter, ++orientationIter) { // wrap distance to range [0, 1.0] double normalized_distance = std::fmod(*distanceIter, 1.0); // the distance along the curve in world space double distance = curve_length * normalized_distance; // Find the location and direction double remaining_dist = 0; for (size_t i = 0; i < accumulated_lengths.size(); ++i) { double segment_length = accumulated_lengths[i]; if (segment_length >= distance) { if (i > 0) remaining_dist = distance - accumulated_lengths[i - 1]; else remaining_dist = distance; const auto& start_cv = curve_cvs[i]; const auto& end_cv = curve_cvs[i + 1]; const auto aimVec = end_cv - start_cv; const auto segment_unit_vec = aimVec / segment_lengths[i]; const auto point_on_segment = start_cv + segment_unit_vec * remaining_dist; *locationIter = point_on_segment; // calculate the rotation vec3d eyeU = segment_unit_vec; vec3d eyeV = upAxis; auto eyeW = (eyeU ^ eyeV).GetNormalized(); eyeV = eyeW ^ eyeU; matrix4d eyeMtx; eyeMtx.SetIdentity(); eyeMtx.SetTranslateOnly(point_on_segment); // eye aiming eyeMtx.SetRow3(0, eyeU); eyeMtx.SetRow3(1, eyeV); eyeMtx.SetRow3(2, eyeW); matrix4d orientMtx = localMatInv * eyeMtx; const quatd q = omni::graph::nodes::extractRotationQuatd(orientMtx); const pxr::GfRotation rotation(omni::math::linalg::safeCastToUSD(q)); const auto eulerRotations = rotation.Decompose(pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis()); pxr::GfVec3d eulerRotationsXYZ(eulerRotations[2], eulerRotations[1], eulerRotations[0]); *rotationIter = omni::math::linalg::safeCastToOmni(eulerRotationsXYZ); *orientationIter = quatf(q); ok = true; break; } } } } return ok; } }; REGISTER_OGN_NODE()
7,344
C++
38.918478
118
0.56427
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnExponent.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnExponentDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <math.h> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { // bool tryComputeAssumingScalarHalf(OgnExponentDatabase& db) { auto functor = [](auto const& base, auto const& exp, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::pow(static_cast<double>(static_cast<float>(base)), exp))); }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, int, pxr::GfHalf>(db.inputs.base(), db.inputs.exponent(), db.outputs.result(), functor); } template <typename T, typename M> bool tryComputeAssumingScalarType(OgnExponentDatabase& db) { auto functor = [](auto const& base, auto const& exp, auto& result) { result = static_cast<M>(std::pow(base, exp)); }; return ogn::compute::tryComputeWithArrayBroadcasting<T, int, M>(db.inputs.base(), db.inputs.exponent(), db.outputs.result(), functor); } template <size_t N> bool tryComputeAssumingTupleHalf(OgnExponentDatabase& db) { auto functor = [](auto const& base, auto const& exp, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::pow(static_cast<double>(static_cast<float>(base)), exp))); }; return ogn::compute::tryComputeWithTupleBroadcasting<N, pxr::GfHalf, int, pxr::GfHalf>(db.inputs.base(), db.inputs.exponent(), db.outputs.result(), functor); } template <typename T, size_t N, typename M> bool tryComputeAssumingTupleType(OgnExponentDatabase& db) { auto functor = [](auto const& base, auto const& exp, auto& result) { result = static_cast<M>(std::pow(base, exp)); }; return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int, M>(db.inputs.base(), db.inputs.exponent(), db.outputs.result(), functor); } } // unnamed namespace class OgnExponent { public: static bool compute(OgnExponentDatabase& db) { try { const auto& bType = db.inputs.base().type(); switch (bType.componentCount) { case 1: switch (bType.baseType) { case BaseDataType::eInt: return tryComputeAssumingScalarType<int32_t, double>(db); case BaseDataType::eInt64: return tryComputeAssumingScalarType<int64_t, double>(db); case BaseDataType::eUInt: return tryComputeAssumingScalarType<uint32_t, double>(db); case BaseDataType::eUInt64: return tryComputeAssumingScalarType<uint64_t, double>(db); case BaseDataType::eUChar: return tryComputeAssumingScalarType<unsigned char, double>(db); case BaseDataType::eHalf: return tryComputeAssumingScalarHalf(db); case BaseDataType::eDouble: return tryComputeAssumingScalarType<double, double>(db); case BaseDataType::eFloat: return tryComputeAssumingScalarType<float, float>(db); default: break; } case 2: switch (bType.baseType) { case BaseDataType::eInt: return tryComputeAssumingTupleType<int32_t, 2, double>(db); case BaseDataType::eDouble: return tryComputeAssumingTupleType<double, 2, double>(db); case BaseDataType::eFloat: return tryComputeAssumingTupleType<float, 2, float>(db); case BaseDataType::eHalf: return tryComputeAssumingTupleHalf<2>(db); default: break; } case 3: switch (bType.baseType) { case BaseDataType::eInt: return tryComputeAssumingTupleType<int32_t, 3, double>(db); case BaseDataType::eDouble: return tryComputeAssumingTupleType<double, 3, double>(db); case BaseDataType::eFloat: return tryComputeAssumingTupleType<float, 3, float>(db); case BaseDataType::eHalf: return tryComputeAssumingTupleHalf<3>(db); default: break; } case 4: switch (bType.baseType) { case BaseDataType::eInt: return tryComputeAssumingTupleType<int32_t, 4, double>(db); case BaseDataType::eDouble: return tryComputeAssumingTupleType<double, 4, double>(db); case BaseDataType::eFloat: return tryComputeAssumingTupleType<float, 4, float>(db); case BaseDataType::eHalf: return tryComputeAssumingTupleHalf<4>(db); default: break; } case 9: if (bType.baseType == BaseDataType::eDouble ) { return tryComputeAssumingTupleType<double, 9, double>(db); } case 16: if (bType.baseType == BaseDataType::eDouble ) { return tryComputeAssumingTupleType<double, 16, double>(db); } } throw ogn::compute::InputError("Failed to resolve input types"); } catch (ogn::compute::InputError &error) { db.logError(error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node) { auto base = node.iNode->getAttributeByToken(node, inputs::base.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto bType = base.iAttribute->getResolvedType(base); Type newType(BaseDataType::eDouble, bType.componentCount, bType.arrayDepth, bType.role); if (bType.baseType != BaseDataType::eUnknown) { switch (bType.baseType) { case BaseDataType::eUChar: case BaseDataType::eInt: case BaseDataType::eUInt: case BaseDataType::eInt64: case BaseDataType::eUInt64: result.iAttribute->setResolvedType(result, newType); break; default: std::array<AttributeObj, 2> attrs { base, result}; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); break; } } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
8,078
C++
40.010152
124
0.525006
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnInterpolateTo.cpp
// Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <algorithm> #include <OgnInterpolateToDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <omni/math/linalg/quat.h> #include "XformUtils.h" using omni::math::linalg::quatd; using omni::math::linalg::GfSlerp; namespace omni { namespace graph { namespace nodes { namespace { template<typename T> bool tryComputeAssumingType(OgnInterpolateToDatabase& db, double alpha, size_t count) { auto functor = [&](auto const& a, auto const& b, auto& result) { // Linear interpolation between a and b, alpha in [0, 1] result = a + (b - a) * (float) alpha; }; return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); } template<typename T, size_t N> bool tryComputeAssumingType(OgnInterpolateToDatabase& db, double alpha, size_t count) { auto functor = [&](auto const& a, auto const& b, auto& result) { // Linear interpolation between a and b, alpha in [0, 1] for (size_t i = 0; i < N; i++) { result[i] = a[i] + (b[i] - a[i]) * (float) alpha; } }; return ogn::compute::tryComputeWithArrayBroadcasting<T[N]>(db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); } template<> bool tryComputeAssumingType<double, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count) { auto currentAttribute = db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name); auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role; if (currentRole == AttributeRole::eQuaternion) { auto functor = [&](auto const& a, auto const& b, auto& result) { // Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha); result[0] = q.GetImaginary()[0]; result[1] = q.GetImaginary()[1]; result[2] = q.GetImaginary()[2]; result[3] = q.GetReal(); }; return ogn::compute::tryComputeWithArrayBroadcasting<double[4]>( db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); } else { auto functor = [&](auto const& a, auto const& b, auto& result) { // Linear interpolation between a and b, alpha in [0, 1] for (size_t i = 0; i < 4; i++) { result[i] = a[i] + (b[i] - a[i]) * (float)alpha; } }; return ogn::compute::tryComputeWithArrayBroadcasting<double[4]>( db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); } } template<> bool tryComputeAssumingType<float, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count) { auto currentAttribute = db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name); auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role; if (currentRole == AttributeRole::eQuaternion) { auto functor = [&](auto const& a, auto const& b, auto& result) { // Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha); result[0] = (float)q.GetImaginary()[0]; result[1] = (float)q.GetImaginary()[1]; result[2] = (float)q.GetImaginary()[2]; result[3] = (float)q.GetReal(); }; return ogn::compute::tryComputeWithArrayBroadcasting<float[4]>( db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); } else { auto functor = [&](auto const& a, auto const& b, auto& result) { // Linear interpolation between a and b, alpha in [0, 1] for (size_t i = 0; i < 4; i++) { result[i] = a[i] + (b[i] - a[i]) * (float)alpha; } }; return ogn::compute::tryComputeWithArrayBroadcasting<float[4]>( db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); }; } template<> bool tryComputeAssumingType<pxr::GfHalf, 4>(OgnInterpolateToDatabase& db, double alpha, size_t count) { auto currentAttribute = db.abi_node().iNode->getAttribute(db.abi_node(), OgnInterpolateToAttributes::inputs::current.m_name); auto currentRole = currentAttribute.iAttribute->getResolvedType(currentAttribute).role; if (currentRole == AttributeRole::eQuaternion) { auto functor = [&](auto const& a, auto const& b, auto& result) { // Note that in Fabric, quaternions are stored as XYZW, but quatd constructor requires WXYZ auto q = GfSlerp(quatd(a[3], a[0], a[1], a[2]), quatd(b[3], b[0], b[1], b[2]), alpha); result[0] = (float)q.GetImaginary()[0]; result[1] = (float)q.GetImaginary()[1]; result[2] = (float)q.GetImaginary()[2]; result[3] = (float)q.GetReal(); }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[4]>( db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); } else { auto functor = [&](auto const& a, auto const& b, auto& result) { // Linear interpolation between a and b, alpha in [0, 1] for (size_t i = 0; i < 4; i++) { result[i] = a[i] + (b[i] - a[i]) * (float)alpha; } }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[4]>( db.inputs.current(), db.inputs.target(), db.outputs.result(), functor, count); }; } } // namespace class OgnInterpolateTo { public: static bool computeVectorized(OgnInterpolateToDatabase& db, size_t count) { int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); float deltaSeconds = std::max(0.f, float(db.inputs.deltaSeconds())); // delta step float alpha = std::min(std::max(speed * deltaSeconds, 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha double alpha2 = 1.f - exponent(1.f - alpha, exp); auto& inputType = db.inputs.current().type(); // Compute the components, if the types are all resolved. try { switch (inputType.baseType) { case BaseDataType::eDouble: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<double>(db, alpha2, count); case 2: return tryComputeAssumingType<double, 2>(db, alpha2, count); case 3: return tryComputeAssumingType<double, 3>(db, alpha2, count); case 4: return tryComputeAssumingType<double, 4>(db, alpha2, count); case 9: return tryComputeAssumingType<double, 9>(db, alpha2, count); case 16: return tryComputeAssumingType<double, 16>(db, alpha2, count); default: break; } case BaseDataType::eFloat: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<float>(db, alpha2, count); case 2: return tryComputeAssumingType<float, 2>(db, alpha2, count); case 3: return tryComputeAssumingType<float, 3>(db, alpha2, count); case 4: return tryComputeAssumingType<float, 4>(db, alpha2, count); default: break; } case BaseDataType::eHalf: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<pxr::GfHalf>(db, alpha2, count); case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, alpha2, count); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, alpha2, count); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, alpha2, count); default: break; } default: break; } db.logWarning("Failed to resolve input types"); } catch (ogn::compute::InputError &error) { db.logWarning("OgnInterpolateTo: %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node){ auto current = node.iNode->getAttributeByToken(node, inputs::current.token()); auto target = node.iNode->getAttributeByToken(node, inputs::target.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto currentType = current.iAttribute->getResolvedType(current); auto targetType = target.iAttribute->getResolvedType(target); // Require current, target, and alpha to be resolved before determining result's type if (currentType.baseType != BaseDataType::eUnknown && targetType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { current, target, result }; std::array<uint8_t, 3> tupleCounts { currentType.componentCount, targetType.componentCount, std::max(currentType.componentCount, targetType.componentCount) }; std::array<uint8_t, 3> arrayDepths { currentType.arrayDepth, targetType.arrayDepth, std::max(currentType.arrayDepth, targetType.arrayDepth) }; std::array<AttributeRole, 3> rolesBuf { currentType.role, targetType.role, AttributeRole::eUnknown }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
10,834
C++
41.159533
141
0.592856
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnEachZero.cpp
// Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnEachZeroDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { namespace { static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input"; // Check whether a scalar attribute contains a value which lies within 'tolerance' of 0. // // 'tolerance' must be non-negative. It is ignored for bool values. // 'isZero' will be set true if 'value' contains a zero value, false otherwise. // // The return value is true if 'value' is a supported scalar type, false otherwise. // bool checkScalarForZero(OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break; case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break; case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break; case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break; case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break; case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break; case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break; case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break; case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break; default: return false; } return true; } // Determine which components of a decimal tuple attribute are within a given tolerance of zero. // (i.e. they lie within 'tolerance' of 0). // // T - type of the components of the tuple. // N - number of components in the tuple // // 'tolerance' must be non-negative // 'isZero' is an array of bool with one element for each component of the tuple. On return the elements // will be set true where the corresponding components lie within 'tolerance' of zero, false otherwise. // // The return value is true if 'value' is a supported tuple type, false otherwise. // template <typename T, uint8_t N> bool getTupleZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero) { CARB_ASSERT(tolerance >= 0.0); if (auto const tuple = value.get<T[N]>()) { for (uint8_t i = 0; i < N; ++i) { isZero[i] = (std::abs(tuple[i]) <= tolerance); } return true; } return false; } // Determine which components of a tuple attribute are zero // (i.e. they lie within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'isZero' is an array of bool with one element for each component of the tuple. On return the elements // will be set true where the corresponding components are zero, false otherwise. // // The return value is true if 'value' is a supported tuple type, false otherwise. // bool getTupleZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eDouble: switch (value.type().componentCount) { case 2: return getTupleZeroes<double, 2>(value, tolerance, isZero); case 3: return getTupleZeroes<double, 3>(value, tolerance, isZero); case 4: return getTupleZeroes<double, 4>(value, tolerance, isZero); case 9: return getTupleZeroes<double, 9>(value, tolerance, isZero); case 16: return getTupleZeroes<double, 16>(value, tolerance, isZero); default: break; } break; case BaseDataType::eFloat: switch (value.type().componentCount) { case 2: return getTupleZeroes<float, 2>(value, tolerance, isZero); case 3: return getTupleZeroes<float, 3>(value, tolerance, isZero); case 4: return getTupleZeroes<float, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eHalf: switch (value.type().componentCount) { case 2: return getTupleZeroes<pxr::GfHalf, 2>(value, tolerance, isZero); case 3: return getTupleZeroes<pxr::GfHalf, 3>(value, tolerance, isZero); case 4: return getTupleZeroes<pxr::GfHalf, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eInt: switch (value.type().componentCount) { case 2: return getTupleZeroes<int32_t, 2>(value, tolerance, isZero); case 3: return getTupleZeroes<int32_t, 3>(value, tolerance, isZero); case 4: return getTupleZeroes<int32_t, 4>(value, tolerance, isZero); default: break; } break; default: break; } return false; } // Determine which elements of an unsigned array attribute are zero (i.e. they lie // within 'tolerance' of 0). // // T - type of the elements of the array. Must be an unsigned type, other than bool. // // 'tolerance' must be non-negative // 'isZero' is an array of bool with one element for each element of the unsigned array. On return the elements // of 'isZero' will be set true where the corresponding elements in the unsigned array are zero, false otherwise. // // The return value is true if 'value' is a supported tuple type, false otherwise. // template <typename T> bool getUnsignedArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero) { static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required."); CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[]>()) { for (size_t i = 0; i < array.size(); ++i) isZero[i] = (array->at(i) <= (T)tolerance); return true; } return false; } // Determine which elements of a bool array attribute are zero/false. No tolerance // value is applied since tolerance is meaningless for bool. // // 'isZero' is an array of bool with one element for each element of the 'value' array. On return the elements // of 'isZero' will be set true where the corresponding elements in the 'value' array are zero, false otherwise. // // The return value is true if 'value' is a bool array type, false otherwise. // bool getBoolArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, ogn::array<bool>& isZero) { if (auto const array = value.get<bool[]>()) { for (size_t i = 0; i < array.size(); ++i) isZero[i] = !array->at(i); return true; } return false; } // Determine which elements of a signed array attribute are within a given tolerance of zero. // (i.e. they lie within 'tolerance' of 0). // // T - type of the elements of the array. Must be a signed type. // // 'tolerance' must be non-negative // 'isZero' is an array of bool with one element for each element of the signed array. On return the elements // of 'isZero' will be set true where the corresponding elements in the unsigned array are within 'tolerance' // of 0.0, false otherwise. // // The return value is true if 'value' is a supported tuple type, false otherwise. // template <typename T> bool getSignedArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero) { static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required."); CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[]>()) { for (size_t i = 0; i < array.size(); ++i) isZero[i] = (std::abs(array->at(i)) <= tolerance); return true; } return false; } // Determine which elements of a scalar array attribute are zero (i.e. they lie within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'isZero' is an array of bool with one element for each element of the scalar array. On return the elements // of 'isZero' will be set true where the corresponding elements in the scalar array are zero, false otherwise. // // The return value is true if 'value' is a supported tuple type, false otherwise. // bool getScalarArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eBool: return getBoolArrayZeroes(value, isZero); case BaseDataType::eDouble: return getSignedArrayZeroes<double>(value, tolerance, isZero); case BaseDataType::eFloat: return getSignedArrayZeroes<float>(value, tolerance, isZero); case BaseDataType::eHalf: return getSignedArrayZeroes<pxr::GfHalf>(value, tolerance, isZero); case BaseDataType::eInt: return getSignedArrayZeroes<int32_t>(value, tolerance, isZero); case BaseDataType::eInt64: return getSignedArrayZeroes<int64_t>(value, tolerance, isZero); case BaseDataType::eUChar: return getUnsignedArrayZeroes<unsigned char>(value, tolerance, isZero); case BaseDataType::eUInt: return getUnsignedArrayZeroes<uint32_t>(value, tolerance, isZero); case BaseDataType::eUInt64: return getUnsignedArrayZeroes<uint64_t>(value, tolerance, isZero); default: break; } return false; } // Returns true if all components of the tuple are zero. // (i.e. they lie within 'tolerance' of 0). // // T - base type of the tuple (e.g. float if tuple is float[2]). // N - number of components in the tuple (e.g. '2' in the example above). // // 'tolerance' must be non-negative // template <typename T, uint8_t N> bool isTupleZero(const T tuple[N], double tolerance) { CARB_ASSERT(tolerance >= 0.0); for (uint8_t i = 0; i < N; ++i) { if (std::abs(tuple[i]) > tolerance) return false; } return true; } // Determine which elements of a tuple array attribute are zero (i.e. all of the tuple's // components lie within a 'tolerance' of 0). // // T - type of the components of the tuple. // N - number of components in the tuple // // 'tolerance' must be non-negative // 'isZero' is an array of bool with one element for each tuple in the tuple array. On return the elements // of 'isZero' will be set true where the corresponding tuples are zero, false otherwise. // // The return value is true if 'value' is a supported tuple type, false otherwise. // template <typename T, uint8_t N> bool getTupleArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, double tolerance, ogn::array<bool>& isZero) { CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[][N]>()) { for (size_t i = 0; i < array.size(); ++i) isZero[i] = isTupleZero<T, N>(array->at(i), tolerance); return true; } return false; } // Determine which elements of a tuple array attribute are zero (i.e. all of the tuple's components // lie within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'isZero' is an array of bool with one element for each tuple in the tuple array. On return the elements // of 'isZero' will be set true where the corresponding tuples are zero, false otherwise. // // The return value is true if 'value' is a supported tuple type, false otherwise. // bool getTupleArrayZeroes(const OgnEachZeroAttributes::inputs::value_t& value, const double& tolerance, ogn::array<bool>& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eDouble: switch (value.type().componentCount) { case 2: return getTupleArrayZeroes<double, 2>(value, tolerance, isZero); case 3: return getTupleArrayZeroes<double, 3>(value, tolerance, isZero); case 4: return getTupleArrayZeroes<double, 4>(value, tolerance, isZero); case 9: return getTupleArrayZeroes<double, 9>(value, tolerance, isZero); case 16: return getTupleArrayZeroes<double, 16>(value, tolerance, isZero); default: break; } break; case BaseDataType::eFloat: switch (value.type().componentCount) { case 2: return getTupleArrayZeroes<float, 2>(value, tolerance, isZero); case 3: return getTupleArrayZeroes<float, 3>(value, tolerance, isZero); case 4: return getTupleArrayZeroes<float, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eHalf: switch (value.type().componentCount) { case 2: return getTupleArrayZeroes<pxr::GfHalf, 2>(value, tolerance, isZero); case 3: return getTupleArrayZeroes<pxr::GfHalf, 3>(value, tolerance, isZero); case 4: return getTupleArrayZeroes<pxr::GfHalf, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eInt: switch (value.type().componentCount) { case 2: return getTupleArrayZeroes<int32_t, 2>(value, tolerance, isZero); case 3: return getTupleArrayZeroes<int32_t, 3>(value, tolerance, isZero); case 4: return getTupleArrayZeroes<int32_t, 4>(value, tolerance, isZero); default: break; } break; default: break; } return false; } } // namespace class OgnEachZero { public: static bool compute(OgnEachZeroDatabase& db) { const auto& value = db.inputs.value(); if (!value.resolved()) return true; const auto& tolerance = db.inputs.tolerance(); auto& result = db.outputs.result(); try { bool foundType{ false }; // Arrays if (value.type().arrayDepth > 0) { if (auto resultArray = result.get<bool[]>()) { resultArray.resize(value.size()); // Arrays of tuples. if (value.type().componentCount > 1) { foundType = getTupleArrayZeroes(value, tolerance, *resultArray); } // Arrays of scalars. else { foundType = getScalarArrayZeroes(value, tolerance, *resultArray); } } else { throw ogn::compute::InputError("input value is an array but result is not bool[]"); } } // Tuples else if (value.type().componentCount > 1) { if (auto resultArray = result.get<bool[]>()) { resultArray.resize(value.type().componentCount); foundType = getTupleZeroes(value, tolerance, *resultArray); } else { throw ogn::compute::InputError("input value is a tuple but result is not bool[]"); } } // Scalars else { if (auto resultScalar = result.get<bool>()) { *resultScalar = false; foundType = checkScalarForZero(value, tolerance, *resultScalar); } else { throw ogn::compute::InputError("input value is a scalar but result is not bool"); } } if (! foundType) { throw ogn::compute::InputError(kValueTypeUnresolved); } } catch (ogn::compute::InputError &error) { db.logError("%s", error.what()); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node){ auto value = node.iNode->getAttributeByToken(node, inputs::value.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto valueType = value.iAttribute->getResolvedType(value); // Require value to be resolved before determining result's type if (valueType.baseType != BaseDataType::eUnknown) { // The result is bool for scalar values, and bool array for arrays and tuples. bool resultIsArray = ((valueType.arrayDepth > 0) || (valueType.componentCount > 1)); Type resultType(BaseDataType::eBool, 1, (resultIsArray ? 1 : 0)); result.iAttribute->setResolvedType(result, resultType); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
17,818
C++
37.238197
131
0.616399
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCos.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnCosDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <omni/math/linalg/math.h> #include <math.h> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Used when input type is resolved as non-int numeric type other than Half */ template <typename T> bool tryComputeAssumingType(OgnCosDatabase& db) { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::cos(pxr::GfDegreesToRadians(a))); }; return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor); } template <> bool tryComputeAssumingType<pxr::GfHalf>(OgnCosDatabase& db) { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::cos(pxr::GfDegreesToRadians(a)))); }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor); } } // namespace class OgnCos { public: static bool compute(OgnCosDatabase& db) { try { // All possible types excluding ogn::string and bool // scalers if (tryComputeAssumingType<double>(db)) return true; else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf else if (tryComputeAssumingType<float>(db)) return true; else { db.logWarning("Failed to resolve input types"); } } catch (std::exception &error) { db.logError("Could not perform Cosine funtion : %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node){ auto value = node.iNode->getAttributeByToken(node, inputs::value.token()); auto result = node.iNode->getAttributeByToken(node, outputs::value.token()); auto valueType = value.iAttribute->getResolvedType(value); // Require inputs to be resolved before determining output's type if (valueType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { value, result }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
2,915
C++
30.695652
118
0.664837
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnClamp.cpp
// Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnClampDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <omni/graph/core/ogn/UsdTypes.h> namespace omni { namespace graph { namespace nodes { namespace { template <typename T> void clamp(T const& input, T const& lower, T const& upper, T& result) { if (lower > upper) { throw ogn::compute::InputError("Lower is greater than upper!"); } if (input <= lower) { result = lower; } else if (input < upper) { result = input; } else { result = upper; } } template <typename T> bool tryComputeAssumingType(OgnClampDatabase& db, size_t count) { return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.input(), db.inputs.lower(), db.inputs.upper(), db.outputs.result(), &clamp<T>, count); } template<typename T, size_t tupleSize> bool tryComputeAssumingType(OgnClampDatabase& db, size_t count) { return ogn::compute::tryComputeWithTupleBroadcasting<tupleSize, T>( db.inputs.input(), db.inputs.lower(), db.inputs.upper(), db.outputs.result(), &clamp<T>, count); } } // namespace // Node to clamp an input value or array of values to some range [lower, upper], class OgnClamp { public: // Clamp a number or array of numbers to a specified range // If an array of numbers is provided as the input and lower/upper are scalers // Then each input numeric will be clamped to the range [lower, upper] // If all inputs are arrays, clamping will be done element-wise. lower & upper are broadcast against input static bool computeVectorized(OgnClampDatabase& db, size_t count) { auto& inputType = db.inputs.input().type(); // Compute the components, if the types are all resolved. try { switch (inputType.baseType) { case BaseDataType::eDouble: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<double>(db, count); case 2: return tryComputeAssumingType<double, 2>(db, count); case 3: return tryComputeAssumingType<double, 3>(db, count); case 4: return tryComputeAssumingType<double, 4>(db, count); case 9: return tryComputeAssumingType<double, 9>(db, count); case 16: return tryComputeAssumingType<double, 16>(db, count); default: break; } case BaseDataType::eFloat: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<float>(db, count); case 2: return tryComputeAssumingType<float, 2>(db, count); case 3: return tryComputeAssumingType<float, 3>(db, count); case 4: return tryComputeAssumingType<float, 4>(db, count); default: break; } case BaseDataType::eHalf: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count); case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count); default: break; } case BaseDataType::eInt: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<int32_t>(db, count); case 2: return tryComputeAssumingType<int32_t, 2>(db, count); case 3: return tryComputeAssumingType<int32_t, 3>(db, count); case 4: return tryComputeAssumingType<int32_t, 4>(db, count); default: break; } ; case BaseDataType::eInt64: return tryComputeAssumingType<int64_t>(db, count); case BaseDataType::eUChar: return tryComputeAssumingType<unsigned char>(db, count); case BaseDataType::eUInt: return tryComputeAssumingType<uint32_t>(db, count); case BaseDataType::eUInt64: return tryComputeAssumingType<uint64_t>(db, count); default: break; } db.logWarning("Failed to resolve input types"); } catch (const std::exception& e) { db.logError("Clamping could not be performed: %s", e.what()); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& nodeObj) { auto inputAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::input.token()); auto lowerAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::lower.token()); auto upperAttr = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::upper.token()); auto resultAttr = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::result.token()); auto inputType = inputAttr.iAttribute->getResolvedType(inputAttr); auto lowerType = lowerAttr.iAttribute->getResolvedType(lowerAttr); auto upperType = upperAttr.iAttribute->getResolvedType(upperAttr); // If one of the upper or lower is resolved we can resolve the other because they should match if ((lowerType == BaseDataType::eUnknown) != (upperType == BaseDataType::eUnknown)) { std::array<AttributeObj, 2> attrs { lowerAttr, upperAttr }; nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()); lowerType = lowerAttr.iAttribute->getResolvedType(lowerAttr); upperType = upperAttr.iAttribute->getResolvedType(upperAttr); } // The output shape must match the input shape and visa-versa, however we can't say anything // about the input base type until it's connected if (inputType.baseType != BaseDataType::eUnknown && lowerType != BaseDataType::eUnknown && upperType != BaseDataType::eUnknown) { if (inputType.baseType != lowerType.baseType || inputType.baseType != upperType.baseType) { nodeObj.iNode->logComputeMessageOnInstance( nodeObj, kAuthoringGraphIndex, ogn::Severity::eError, "Unable to connect inputs to clamp with different base types"); return; } std::array<AttributeObj, 2> attrs { inputAttr, resultAttr }; nodeObj.iNode->resolveCoupledAttributes(nodeObj, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE(); } } }
7,192
C++
39.410112
156
0.615823
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivideHelper.h
#include <omni/graph/core/iComputeGraph.h> #include <omni/graph/core/ogn/UsdTypes.h> #include <omni/graph/core/ogn/Database.h> #include <omni/graph/core/ogn/ComputeHelpers.h> namespace omni { namespace graph { namespace nodes { namespace OGNDivideHelper { using InType = ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>; using ResType = ogn::RuntimeAttribute<ogn::kOgnOutput, ogn::kCpu>; // Allow (AType[N] / BType) and (AType[N] / BType[N]) but not (AType / BType[N]) template<typename AType, typename BType, typename CType, size_t N, typename Functor> bool tryComputeWithLimitedTupleBroadcasting( InType const& a, InType const& b, ResType& result, Functor functor, size_t count) { if (ogn::compute::tryComputeWithArrayBroadcasting<AType[N], BType[N], CType[N]>(a, b, result, [&](auto const& a, auto const& b, auto& result) { for (size_t i = 0; i < N; i++) functor(a[i], b[i], result[i]); }, count)) return true; else if (ogn::compute::tryComputeWithArrayBroadcasting<AType[N], BType, CType[N]>(a, b, result, [&](auto const& a, auto const& b, auto& result) { for (size_t i = 0; i < N; i++) functor(a[i], b, result[i]); }, count)) return true; return false; } // AType is a vector of float's or double's template<typename AType, typename BType, size_t N> bool tryComputeAssumingType(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count, typename std::enable_if_t<!std::is_integral<AType>::value && !std::is_same<AType, pxr::GfHalf>::value, AType>* = 0) { auto functor = [&](auto const& a, auto const& b, auto& result) { if (static_cast<double>(b) == 0.0) { db.logWarning("OgnDivide: Divide by zero encountered"); } result = static_cast<AType>(static_cast<double>(a) / static_cast<double>(b)); }; return tryComputeWithLimitedTupleBroadcasting<AType, BType, AType, N>(a, b, result, functor, count); } // AType is a vector of half's template<typename AType, typename BType, size_t N> bool tryComputeAssumingType(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count, typename std::enable_if_t<std::is_same<AType, pxr::GfHalf>::value, AType>* = 0) { auto functor = [&](auto const& a, auto const& b, auto& result) { if (static_cast<double>(b) == 0.0) { db.logWarning("OgnDivide: Divide by zero encountered"); } result = static_cast<AType>(static_cast<float>(static_cast<double>(a) / static_cast<double>(b))); }; return tryComputeWithLimitedTupleBroadcasting<AType, BType, AType, N>(a, b, result, functor, count); } // AType is a vector of integrals => Force result to be a vector of doubles template<typename AType, typename BType, size_t N> bool tryComputeAssumingType(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count, typename std::enable_if_t<std::is_integral<AType>::value, AType>* = 0) { auto functor = [&](auto const& a, auto const& b, auto& result) { if (static_cast<double>(b) == 0.0) { db.logWarning("OgnDivide: Divide by zero encountered"); } result = static_cast<double>(a) / static_cast<double>(b); }; return tryComputeWithLimitedTupleBroadcasting<AType, BType, double, N>(a, b, result, functor, count); } template<typename T, size_t N> bool _tryComputeAssuming(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count) { if (tryComputeAssumingType<double, T, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<float, T, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<pxr::GfHalf, T, N>(db, a, b, result, count)) return true; if (tryComputeAssumingType<int32_t, T, N>(db, a, b, result, count)) return true; return false; } template<size_t N> bool _tryComputeTuple(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count) { if (_tryComputeAssuming<double, N>(db, a, b, result, count)) return true; if (_tryComputeAssuming<float, N>(db, a, b, result, count)) return true; if (_tryComputeAssuming<pxr::GfHalf, N>(db, a, b, result, count)) return true; if (_tryComputeAssuming<int32_t, N>(db, a, b, result, count)) return true; if (_tryComputeAssuming<int64_t, N>(db, a, b, result, count)) return true; if (_tryComputeAssuming<unsigned char, N>(db, a, b, result, count)) return true; if (_tryComputeAssuming<uint32_t, N>(db, a, b, result, count)) return true; if (_tryComputeAssuming<uint64_t, N>(db, a, b, result, count)) return true; return false; } bool tryComputeScalars(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count); bool tryComputeTuple2(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count); bool tryComputeTuple3(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count); bool tryComputeTuple4(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count); bool tryComputeMatrices(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count); } // namespace OGNDivideHelper } // namespace nodes } // namespace graph } // namespace omni
5,806
C
44.724409
143
0.628143
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAsin.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnAsinDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <omni/math/linalg/math.h> #include <math.h> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Used when input type is resolved as non-int numeric type other than Half */ template <typename T> bool tryComputeAssumingType(OgnAsinDatabase& db) { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfRadiansToDegrees(std::asin(a))); }; return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.value(), db.outputs.value(), functor); } template <> bool tryComputeAssumingType<pxr::GfHalf>(OgnAsinDatabase& db) { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(std::asin(a)))); }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf>(db.inputs.value(), db.outputs.value(), functor); } } // namespace class OgnAsin { public: static bool compute(OgnAsinDatabase& db) { try { // All possible types excluding ogn::string and bool // scalers if (tryComputeAssumingType<double>(db)) return true; else if (tryComputeAssumingType<pxr::GfHalf>(db)) return true; // Specifically for pxr::GfHalf else if (tryComputeAssumingType<float>(db)) return true; else { db.logWarning("Failed to resolve input types"); } } catch (std::exception &error) { db.logError("Could not perform Arcsine funtion : %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node){ auto value = node.iNode->getAttributeByToken(node, inputs::value.token()); auto result = node.iNode->getAttributeByToken(node, outputs::value.token()); auto valueType = value.iAttribute->getResolvedType(value); // Require inputs to be resolved before determining output's type if (valueType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { value, result }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
2,923
C++
30.782608
118
0.665754
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomNumeric.cpp
// Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnRandomNumericDatabase.h" #include "random/RandomNodeBase.h" #include <omni/graph/core/ogn/ComputeHelpers.h> namespace omni { namespace graph { namespace nodes { using namespace random; class OgnRandomNumeric : public NodeBase<OgnRandomNumeric, OgnRandomNumericDatabase> { template <typename T> static bool tryComputeAssumingType(OgnRandomNumericDatabase& db, size_t count) { return ogn::compute::tryComputeWithArrayBroadcasting<T>( db.state.gen(), db.inputs.min(), db.inputs.max(), db.outputs.random(), [](GenBuffer_t const& genBuffer, T const& min, T const& max, T& result) { // Generate next random result = asGenerator(genBuffer).nextUniform(min, max); }, count); } template <typename T, size_t N> static bool tryComputeAssumingType(OgnRandomNumericDatabase& db, size_t count) { return ogn::compute::tryComputeWithTupleBroadcasting<N, T>( db.state.gen(), db.inputs.min(), db.inputs.max(), db.outputs.random(), [](GenBuffer_t const& genBuffer, T const& min, T const& max, T& result) { // Generate next random result = asGenerator(genBuffer).nextUniform(min, max); }, count); } static bool defaultCompute(OgnRandomNumericDatabase& db, size_t count) { auto const genBuffers = db.state.gen.vectorized(count); if (genBuffers.size() != count) { db.logWarning("Failed to write to output using default range [0..1) (wrong genBuffers size)"); return false; } for (size_t i = 0; i < count; ++i) { auto outPtr = db.outputs.random(i).get<double>(); if (!outPtr) { db.logWarning("Failed to write to output using default range [0..1) (null output pointer)"); return false; } *outPtr = asGenerator(genBuffers[i]).nextUniform<double>(0.0, 1.0); } return true; } public: static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj) { generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed); // HACK: onConnectionTypeResolve is not called the first time, // but by setting the output type, we force it to be called. // // TODO: OGN should really support default inputs for union types! // See https://nvidia-omniverse.atlassian.net/browse/OM-67739 setDefaultOutputType(nodeObj, outputs::random.token()); } static bool onCompute(OgnRandomNumericDatabase& db, size_t count) { auto const& minAttr{ db.inputs.min() }; auto const& maxAttr{ db.inputs.max() }; auto const& outAttr{ db.outputs.random() }; if (!outAttr.resolved()) { // Output type not yet resolved, can't compute db.logWarning("Unsupported input types"); return false; } if (!minAttr.resolved() && !maxAttr.resolved()) { // Output using default min and max return defaultCompute(db, count); } // Inputs and outputs are resolved, try all possible types, excluding bool and ogn::string auto const outType = outAttr.type(); switch (outType.baseType) // NOLINT(clang-diagnostic-switch-enum) { case BaseDataType::eDouble: switch (outType.componentCount) { case 1: return tryComputeAssumingType<double>(db, count); case 2: return tryComputeAssumingType<double, 2>(db, count); case 3: return tryComputeAssumingType<double, 3>(db, count); case 4: return tryComputeAssumingType<double, 4>(db, count); case 9: return tryComputeAssumingType<double, 9>(db, count); case 16: return tryComputeAssumingType<double, 16>(db, count); default: break; } case BaseDataType::eFloat: switch (outType.componentCount) { case 1: return tryComputeAssumingType<float>(db, count); case 2: return tryComputeAssumingType<float, 2>(db, count); case 3: return tryComputeAssumingType<float, 3>(db, count); case 4: return tryComputeAssumingType<float, 4>(db, count); default: break; } case BaseDataType::eHalf: switch (outType.componentCount) { case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count); case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count); default: break; } case BaseDataType::eInt: switch (outType.componentCount) { case 1: return tryComputeAssumingType<int32_t>(db, count); case 2: return tryComputeAssumingType<int32_t, 2>(db, count); case 3: return tryComputeAssumingType<int32_t, 3>(db, count); case 4: return tryComputeAssumingType<int32_t, 4>(db, count); default: break; } case BaseDataType::eInt64: return tryComputeAssumingType<int64_t>(db, count); case BaseDataType::eUChar: return tryComputeAssumingType<unsigned char>(db, count); case BaseDataType::eUInt: return tryComputeAssumingType<uint32_t>(db, count); case BaseDataType::eUInt64: return tryComputeAssumingType<uint64_t>(db, count); default: break; } db.logWarning("Unsupported input types"); return false; } static void onConnectionTypeResolve(NodeObj const& node) { resolveOutputType(node, inputs::min.token(), inputs::max.token(), outputs::random.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
6,903
C++
32.678049
108
0.580762
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIncrement.cpp
// Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnIncrementDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Helper functions to try doing an addition operation on two input attributes. * We assume the runtime attributes have type T and the other one is double. * The first input is either an array or a singular value, and the second input is a single double value * * @param db: database object * @return True if we can get a result properly, false if not */ /** * Used when input type is resolved as Half */ bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count) { auto functor = [](auto const& a, auto const& b, auto& result) { result = a + static_cast<float>(b); }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, double, pxr::GfHalf>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count); } /** * Used when input type is resolved as any numeric type other than Half */ template<typename T> bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count) { auto functor = [](auto const& a, auto const& b, auto& result) { result = a + static_cast<T>(b); }; return ogn::compute::tryComputeWithArrayBroadcasting<T, double, T>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count); } /** * Used when input type is resolved as Half */ template <size_t N> bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count) { auto functor = [](auto const& a, auto const& b, auto& result) { result = a + static_cast<float>(b); }; return ogn::compute::tryComputeWithTupleBroadcasting<N, pxr::GfHalf, double, pxr::GfHalf>( db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count); } /** * Used when input type is resolved as any numeric type other than Half */ template<typename T, size_t N> bool tryComputeAssumingType(OgnIncrementDatabase& db, size_t count) { auto functor = [](auto const& a, auto const& b, auto& result) { result = a + static_cast<T>(b); }; return ogn::compute::tryComputeWithTupleBroadcasting<N, T, double, T>(db.inputs.value(), db.inputs.increment(), db.outputs.result(), functor, count); } } // namespace class OgnIncrement { public: static size_t computeVectorized(OgnIncrementDatabase& db, size_t count) { auto& inputType = db.inputs.value().type(); // Compute the components, if the types are all resolved. try { switch (inputType.baseType) { case BaseDataType::eDouble: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<double>(db, count); case 2: return tryComputeAssumingType<double, 2>(db, count); case 3: return tryComputeAssumingType<double, 3>(db, count); case 4: return tryComputeAssumingType<double, 4>(db, count); case 9: return tryComputeAssumingType<double, 9>(db, count); case 16: return tryComputeAssumingType<double, 16>(db, count); default: break; } case BaseDataType::eFloat: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<float>(db, count); case 2: return tryComputeAssumingType<float, 2>(db, count); case 3: return tryComputeAssumingType<float, 3>(db, count); case 4: return tryComputeAssumingType<float, 4>(db, count); default: break; } case BaseDataType::eHalf: switch (inputType.componentCount) { case 1: return tryComputeAssumingType(db, count); case 2: return tryComputeAssumingType<2>(db, count); case 3: return tryComputeAssumingType<3>(db, count); case 4: return tryComputeAssumingType<4>(db, count); default: break; } case BaseDataType::eInt: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<int32_t>(db, count); case 2: return tryComputeAssumingType<int32_t, 2>(db, count); case 3: return tryComputeAssumingType<int32_t, 3>(db, count); case 4: return tryComputeAssumingType<int32_t, 4>(db, count); default: break; } ; case BaseDataType::eInt64: return tryComputeAssumingType<int64_t>(db, count); case BaseDataType::eUChar: return tryComputeAssumingType<unsigned char>(db, count); case BaseDataType::eUInt: return tryComputeAssumingType<uint32_t>(db, count); case BaseDataType::eUInt64: return tryComputeAssumingType<uint64_t>(db, count); default: break; } db.logWarning("Failed to resolve input types"); } catch (ogn::compute::InputError &error) { db.logError(error.what()); } return 0; } static void onConnectionTypeResolve(const NodeObj& node){ auto value = node.iNode->getAttributeByToken(node, inputs::value.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto valueType = value.iAttribute->getResolvedType(value); // Require inputs to be resolved before determining sum's type if (valueType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { value, result }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
6,591
C++
38.005917
170
0.618874
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTrig.cpp
// Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnTrigDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <omni/math/linalg/math.h> #include <math.h> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** _____ ____ _ _ ____ _______ _____ ____ _______ __ | __ \ / __ \ | \ | |/ __ \__ __| / ____/ __ \| __ \ \ / / | | | | | | | | \| | | | | | | | | | | | | |__) \ \_/ / | | | | | | | | . ` | | | | | | | | | | | | ___/ \ / | |__| | |__| | | |\ | |__| | | | | |___| |__| | | | | |_____/ \____/ |_| \_|\____/ |_| \_____\____/|_| |_| This node uses a large cascading "if" to select operation type, which is not efficient. It will be eventually be refactored but until then do not propagate this anti-pattern. Thanks for keeping things fast! */ /** * Used when input type is resolved as non-int numeric type other than Half */ template <typename T> bool tryComputeAssumingType(OgnTrigDatabase& db, NameToken operation, size_t count) { if (operation == db.tokens.SIN) // Sine { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::sin(pxr::GfDegreesToRadians(a))); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } else if (operation == db.tokens.COS) // Cosine { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::cos(pxr::GfDegreesToRadians(a))); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } else if (operation == db.tokens.TAN) // Tangent { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(std::tan(pxr::GfDegreesToRadians(a))); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } else if (operation == db.tokens.ARCSIN) // Arcsine { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfRadiansToDegrees(std::asin(a))); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } else if (operation == db.tokens.ARCCOS) // Arccosine { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfRadiansToDegrees(std::acos(a))); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } else if (operation == db.tokens.ARCTAN) // Arctangent { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfRadiansToDegrees(std::atan(a))); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } else if (operation == db.tokens.DEGREES) // Degrees { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfRadiansToDegrees(a)); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } else if (operation == db.tokens.RADIANS) // Radians { auto functor = [](auto const& a, auto& result) { result = static_cast<T>(pxr::GfDegreesToRadians(a)); }; return ogn::compute::tryCompute(db.inputs.a().template get<T>(), db.outputs.result().template get<T>(), functor, count); } throw ogn::compute::InputError("Operation not one of sin, cos, tan, asin, acos, degrees, radians"); } template <> bool tryComputeAssumingType<pxr::GfHalf>(OgnTrigDatabase& db, NameToken operation, size_t count) { if (operation == db.tokens.SIN) // Sine { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::sin(pxr::GfDegreesToRadians(a)))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } else if (operation == db.tokens.COS) // Cosine { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::cos(pxr::GfDegreesToRadians(a)))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } else if (operation == db.tokens.TAN) // Tangent { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::tan(pxr::GfDegreesToRadians(a)))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } else if (operation == db.tokens.ARCSIN) // Arcsine { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::asin(pxr::GfDegreesToRadians(a)))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } else if (operation == db.tokens.ARCCOS) // Arccosine { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::acos(pxr::GfDegreesToRadians(a)))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } else if (operation == db.tokens.ARCTAN) // Arctangent { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(std::atan(pxr::GfDegreesToRadians(a)))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } else if (operation == db.tokens.DEGREES) // Degrees { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfRadiansToDegrees(a))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } else if (operation == db.tokens.RADIANS) // Radians { auto functor = [](auto const& a, auto& result) { result = static_cast<pxr::GfHalf>(static_cast<float>(pxr::GfDegreesToRadians(a))); }; return ogn::compute::tryCompute( db.inputs.a().template get<pxr::GfHalf>(), db.outputs.result().template get<pxr::GfHalf>(), functor, count); } throw ogn::compute::InputError("Operation not one of sin, cos, tan, asin, acos, degrees, radians"); } } // namespace class OgnTrig { public: static size_t computeVectorized(OgnTrigDatabase& db, size_t count) { NameToken const& operation = db.inputs.operation(); try { if (tryComputeAssumingType<double>(db, operation, count)) return count; else if (tryComputeAssumingType<pxr::GfHalf>(db, operation, count)) return count; else if (tryComputeAssumingType<float>(db, operation, count)) return count; else { db.logWarning("Failed to resolve input types"); } } catch (std::exception &error) { db.logError("Operation %s could not be performed : %s", db.tokenToString(operation), error.what()); } return 0; } static void onConnectionTypeResolve(const NodeObj& node){ auto a = node.iNode->getAttributeByToken(node, inputs::a.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto aType = a.iAttribute->getResolvedType(a); // Require inputs to be resolved before determining output's type if (aType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { a, result }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
8,956
C++
43.785
128
0.607191
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNegate.cpp
// Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnNegateDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { template<typename T> bool tryComputeAssumingType(OgnNegateDatabase& db, size_t count) { auto functor = [](auto const& input, auto& output) { output = input * -1; }; return ogn::compute::tryComputeWithArrayBroadcasting<T, T>(db.inputs.input(), db.outputs.output(), functor, count); } template<typename T, size_t N> bool tryComputeAssumingType(OgnNegateDatabase& db, size_t count) { auto functor = [](auto const& input, auto& output) { for (size_t i = 0; i < N; ++i) { output[i] = input[i] * -1; } }; return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T[N]>(db.inputs.input(), db.outputs.output(), functor, count); } } // namespace class OgnNegate { public: static bool computeVectorized(OgnNegateDatabase& db, size_t count) { auto& inputType = db.inputs.input().type(); // Compute the components, if the types are all resolved. try { switch (inputType.baseType) { case BaseDataType::eDouble: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<double>(db, count); case 2: return tryComputeAssumingType<double, 2>(db, count); case 3: return tryComputeAssumingType<double, 3>(db, count); case 4: return tryComputeAssumingType<double, 4>(db, count); case 9: return tryComputeAssumingType<double, 9>(db, count); case 16: return tryComputeAssumingType<double, 16>(db, count); default: break; } case BaseDataType::eFloat: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<float>(db, count); case 2: return tryComputeAssumingType<float, 2>(db, count); case 3: return tryComputeAssumingType<float, 3>(db, count); case 4: return tryComputeAssumingType<float, 4>(db, count); default: break; } case BaseDataType::eHalf: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count); case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count); default: break; } case BaseDataType::eInt: switch (inputType.componentCount) { case 1: return tryComputeAssumingType<int32_t>(db, count); case 2: return tryComputeAssumingType<int32_t, 2>(db, count); case 3: return tryComputeAssumingType<int32_t, 3>(db, count); case 4: return tryComputeAssumingType<int32_t, 4>(db, count); default: break; } ; case BaseDataType::eInt64: return tryComputeAssumingType<int64_t>(db, count); case BaseDataType::eUChar: return tryComputeAssumingType<unsigned char>(db, count); case BaseDataType::eUInt: return tryComputeAssumingType<uint32_t>(db, count); case BaseDataType::eUInt64: return tryComputeAssumingType<uint64_t>(db, count); default: break; } db.logWarning("Failed to resolve input types"); } catch (ogn::compute::InputError &error) { db.logError(error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node) { auto input = node.iNode->getAttributeByToken(node, inputs::input.token()); auto output = node.iNode->getAttributeByToken(node, outputs::output.token()); auto inputType = input.iAttribute->getResolvedType(input); // Require input to be resolved before determining output's type if (inputType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { input, output }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni // end-compute-helpers
5,225
C++
38.590909
125
0.593876
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIsZero.cpp
// Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnIsZeroDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { namespace { static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input"; // Check whether a scalar attribute contains a value which lies within 'tolerance' of 0. // // 'tolerance' must be non-negative. It is ignored for bool values. // 'isZero' will be set true if 'value' contains a zero value, false otherwise. // // The return value is true if 'value' is a supported scalar type, false otherwise. // bool checkScalarForZero(OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break; case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break; case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break; case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break; case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break; case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break; case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break; case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break; case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break; default: return false; } return true; } // Check whether a tuple attribute contains a tuple whose components are all zero. // (i.e. they lie within 'tolerance' of 0). // // T - type of the components of the tuple. // N - number of components in the tuple // // 'tolerance' must be non-negative // 'isZero' is assumed to be true on entry and will be set false if any component of the tuple is not zero. // // The return value is true if 'value' is a supported tuple type, false otherwise. // template <typename T, int N> bool checkTupleForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); CARB_ASSERT(isZero); if (auto const tuple = value.get<T[N]>()) { for (int i = 0; isZero && (i < N); ++i) { isZero = (std::abs(tuple[i]) <= tolerance); } return true; } return false; } // Check whether a tuple attribute contains a tuple whose components are all zero // (i.e. they lie within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'isZero' is assumed to be true on entry and will be set false if any component of the tuple is not zero. // // The return value is true if 'value' is a supported tuple type, false otherwise. // bool checkTupleForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); CARB_ASSERT(isZero); switch (value.type().baseType) { case BaseDataType::eDouble: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<double, 2>(value, tolerance, isZero); case 3: return checkTupleForZeroes<double, 3>(value, tolerance, isZero); case 4: return checkTupleForZeroes<double, 4>(value, tolerance, isZero); case 9: return checkTupleForZeroes<double, 9>(value, tolerance, isZero); case 16: return checkTupleForZeroes<double, 16>(value, tolerance, isZero); default: break; } break; case BaseDataType::eFloat: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<float, 2>(value, tolerance, isZero); case 3: return checkTupleForZeroes<float, 3>(value, tolerance, isZero); case 4: return checkTupleForZeroes<float, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eHalf: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<pxr::GfHalf, 2>(value, tolerance, isZero); case 3: return checkTupleForZeroes<pxr::GfHalf, 3>(value, tolerance, isZero); case 4: return checkTupleForZeroes<pxr::GfHalf, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eInt: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<int32_t, 2>(value, tolerance, isZero); case 3: return checkTupleForZeroes<int32_t, 3>(value, tolerance, isZero); case 4: return checkTupleForZeroes<int32_t, 4>(value, tolerance, isZero); default: break; } break; default: break; } return false; } // Check whether an unsigned array attribute's elements are all zero (i.e. they lie // within 'tolerance' of 0). // // T - type of the elements of the array. Must be an unsigned type, other than bool. // // 'tolerance' must be non-negative // 'isZero' will be set true if all elements of the array are zero, false otherwise. // // The return value is true if 'value' is a supported unsigned integer array type, false otherwise. // template <typename T> bool checkUnsignedArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const int& tolerance, bool& isZero) { static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required."); CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[]>()) { isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return element <= (T)tolerance; }); return true; } return false; } // Check whether a bool array attribute's elements are all zero/false. No tolerance // value is applied since tolerance is meaningless for bool. // // 'isZero' will be set true if all elements of the array are zero, false otherwise. // // The return value is true if 'value' is a bool array type, false otherwise. // bool checkBoolArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, bool& isZero) { if (auto const array = value.get<bool[]>()) { isZero = std::all_of(array->begin(), array->end(), [](auto element){ return !element; }); return true; } return false; } // Check whether a signed array attribute's elements are all zero (i.e. they lie // within 'tolerance' of 0). // // T - type of the elements of the array. Must be a signed type. // // 'tolerance' must be non-negative // 'isZero' will be set true if all elements of the array are zero, false otherwise. // // The return value is true if 'value' is a supported signed array type, false otherwise. // template <typename T> bool checkSignedArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required."); CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[]>()) { isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return (std::abs(element) <= tolerance); }); return true; } return false; } // Check whether a scalar array attribute's elements are all zero (i.e. they lie within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'isZero' will be set true if all elements of the array are zero, false otherwise. // // The return value is true if 'value' is a supported scalar array type, false otherwise. // bool checkScalarArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eBool: return checkBoolArrayForZeroes(value, isZero); case BaseDataType::eDouble: return checkSignedArrayForZeroes<double>(value, tolerance, isZero); case BaseDataType::eFloat: return checkSignedArrayForZeroes<float>(value, tolerance, isZero); case BaseDataType::eHalf: return checkSignedArrayForZeroes<pxr::GfHalf>(value, tolerance, isZero); case BaseDataType::eInt: return checkSignedArrayForZeroes<int32_t>(value, tolerance, isZero); case BaseDataType::eInt64: return checkSignedArrayForZeroes<int64_t>(value, tolerance, isZero); case BaseDataType::eUChar: return checkUnsignedArrayForZeroes<unsigned char>(value, (int)tolerance, isZero); case BaseDataType::eUInt: return checkUnsignedArrayForZeroes<uint32_t>(value, (int)tolerance, isZero); case BaseDataType::eUInt64: return checkUnsignedArrayForZeroes<uint64_t>(value, (int)tolerance, isZero); default: break; } return false; } // Returns true if all components of the tuple are zero. // (i.e. they lie within 'tolerance' of 0). // // T - base type of the tuple (e.g. float if tuple is float[2]). // N - number of components in the tuple (e.g. '2' in the example above). // // 'tolerance' must be non-negative // template <typename T, int N> bool isTupleZero(const T tuple[N], double tolerance) { CARB_ASSERT(tolerance >= 0.0); for (int i = 0; i < N; ++i) { if (std::abs(tuple[i]) > tolerance) return false; } return true; } // Check whether a tuple array attribute's elements are all zero tuples // (i.e. all of their components are within 'tolerance' of 0). // // T - type of the components of the tuple. // N - number of components in the tuple // // 'tolerance' must be non-negative // 'isZero' will be set true if all tuples in the array is are zero, false otherwise. // // The return value is true if 'value' is a supported decimal tuple array type, false otherwise. // template <typename T, int N> bool checkTupleArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, double tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[][N]>()) { isZero = std::all_of(array->begin(), array->end(), [tolerance](auto element){ return isTupleZero<T, N>(element, tolerance); }); return true; } return false; } // Check whether a tuple array attribute's elements are all zero tuples (i.e. all of their components // lie within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'isZero' will be set true if all tuples in the array is are zero, false otherwise. // // The return value is true if 'value' is a supported decimal tuple array type, false otherwise. // bool checkTupleArrayForZeroes(const OgnIsZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eDouble: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<double, 2>(value, tolerance, isZero); case 3: return checkTupleArrayForZeroes<double, 3>(value, tolerance, isZero); case 4: return checkTupleArrayForZeroes<double, 4>(value, tolerance, isZero); case 9: return checkTupleArrayForZeroes<double, 9>(value, tolerance, isZero); case 16: return checkTupleArrayForZeroes<double, 16>(value, tolerance, isZero); default: break; } break; case BaseDataType::eFloat: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<float, 2>(value, tolerance, isZero); case 3: return checkTupleArrayForZeroes<float, 3>(value, tolerance, isZero); case 4: return checkTupleArrayForZeroes<float, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eHalf: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<pxr::GfHalf, 2>(value, tolerance, isZero); case 3: return checkTupleArrayForZeroes<pxr::GfHalf, 3>(value, tolerance, isZero); case 4: return checkTupleArrayForZeroes<pxr::GfHalf, 4>(value, tolerance, isZero); default: break; } break; case BaseDataType::eInt: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<int32_t, 2>(value, tolerance, isZero); case 3: return checkTupleArrayForZeroes<int32_t, 3>(value, tolerance, isZero); case 4: return checkTupleArrayForZeroes<int32_t, 4>(value, tolerance, isZero); default: break; } break; default: break; } return false; } } // namespace class OgnIsZero { public: static bool compute(OgnIsZeroDatabase& db) { const auto& value = db.inputs.value(); if (!value.resolved()) return true; const auto& tolerance = std::abs(db.inputs.tolerance()); auto& result = db.outputs.result(); try { // Some of the functions below return as soon as they find a non-zero value, so // we start out assuming all values are zero and let them change that to false. // result = true; bool foundType{ false }; // Arrays if (value.type().arrayDepth > 0) { // Arrays of tuples. if (value.type().componentCount > 1) { foundType = checkTupleArrayForZeroes(value, tolerance, result); } // Arrays of scalars. else { foundType = checkScalarArrayForZeroes(value, tolerance, result); } } // Tuples else if (value.type().componentCount > 1) { foundType = checkTupleForZeroes(value, tolerance, result); } // Scalars else { foundType = checkScalarForZero(value, tolerance, result); } if (! foundType) { throw ogn::compute::InputError(kValueTypeUnresolved); } } catch (ogn::compute::InputError &error) { db.logError("OgnIsZero: %s", error.what()); return false; } return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
15,541
C++
37
135
0.628595
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnDivide_Tuple4.cpp
#include "OgnDivideHelper.h" namespace omni { namespace graph { namespace nodes { namespace OGNDivideHelper { bool tryComputeTuple4(ogn::OmniGraphDatabase& db, InType const& a, InType const& b, ResType& result, size_t count) { return _tryComputeTuple<4>(db, a, b, result, count); } } // namespace OGNDivideHelper } // namespace nodes } // namespace graph } // namespace omni
397
C++
18.899999
118
0.702771
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAnyZero.cpp
// Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnAnyZeroDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { namespace { static constexpr char kValueTypeUnresolved[] = "Failed to resolve type of 'value' input"; // Check whether a scalar attribute contains a value which lies within 'tolerance' of 0. // // 'tolerance' must be non-negative. It is ignored for bool values. // 'isZero' will be set true if 'value' contains a zero value, false otherwise. // // The return value is true if 'value' is a supported scalar type, false otherwise. // bool checkScalarForZero(OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& isZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eBool: isZero = ! *(value.get<bool>()); break; case BaseDataType::eDouble: isZero = std::abs(*(value.get<double>())) <= tolerance; break; case BaseDataType::eFloat: isZero = std::abs(*(value.get<float>())) <= tolerance; break; case BaseDataType::eHalf: isZero = std::abs(*(value.get<pxr::GfHalf>())) <= tolerance; break; case BaseDataType::eInt: isZero = std::abs(*(value.get<int32_t>())) <= (int32_t)tolerance; break; case BaseDataType::eInt64: isZero = std::abs(*(value.get<int64_t>())) <= (int64_t)tolerance; break; case BaseDataType::eUChar: isZero = *(value.get<unsigned char>()) <= (unsigned char)tolerance; break; case BaseDataType::eUInt: isZero = *(value.get<uint32_t>()) <= (uint32_t)tolerance; break; case BaseDataType::eUInt64: isZero = *(value.get<uint64_t>()) <= (uint64_t)tolerance; break; default: return false; } return true; } // Check whether a tuple attribute contains a value with at least one zero component // (i.e. its value lies within 'tolerance' of 0). // // T - type of the components of the tuple. // N - number of components in the tuple // // 'tolerance' must be non-negative // 'hasZero' is assumed to be false on entry and will be set true if any component of the tuple is zero. // // The return value is true if 'value' is a supported tuple type, false otherwise. // template <typename T, int N> bool checkTupleForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero) { CARB_ASSERT(tolerance >= 0.0); CARB_ASSERT(!hasZero); if (auto const tuple = value.get<T[N]>()) { for (int i = 0; !hasZero && (i < N); ++i) { hasZero = (std::abs(tuple[i]) <= tolerance); } return true; } return false; } // Check whether a tuple attribute contains a value with at least one zero component // (i.e. its value lies within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'hasZero' is assumed to be false on entry and will be set true if any component of the tuple is zero. // // The return value is true if 'value' is a supported tuple type, false otherwise. // bool checkTupleForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero) { CARB_ASSERT(tolerance >= 0.0); CARB_ASSERT(!hasZero); switch (value.type().baseType) { case BaseDataType::eDouble: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<double, 2>(value, tolerance, hasZero); case 3: return checkTupleForZeroes<double, 3>(value, tolerance, hasZero); case 4: return checkTupleForZeroes<double, 4>(value, tolerance, hasZero); case 9: return checkTupleForZeroes<double, 9>(value, tolerance, hasZero); case 16: return checkTupleForZeroes<double, 16>(value, tolerance, hasZero); } break; case BaseDataType::eFloat: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<float, 2>(value, tolerance, hasZero); case 3: return checkTupleForZeroes<float, 3>(value, tolerance, hasZero); case 4: return checkTupleForZeroes<float, 4>(value, tolerance, hasZero); } break; case BaseDataType::eHalf: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<pxr::GfHalf, 2>(value, tolerance, hasZero); case 3: return checkTupleForZeroes<pxr::GfHalf, 3>(value, tolerance, hasZero); case 4: return checkTupleForZeroes<pxr::GfHalf, 4>(value, tolerance, hasZero); } break; case BaseDataType::eInt: switch (value.type().componentCount) { case 2: return checkTupleForZeroes<int32_t, 2>(value, tolerance, hasZero); case 3: return checkTupleForZeroes<int32_t, 3>(value, tolerance, hasZero); case 4: return checkTupleForZeroes<int32_t, 4>(value, tolerance, hasZero); } break; default: break; } return false; } // Check whether an unsigned array attribute contains at least one element with a value of zero // (i.e. it lies within 'tolerance' of 0). // // T - type of the elements of the array. Must be an unsigned type, other than bool. // // 'tolerance' must be non-negative // 'hasZero' will be set true if any element of the array is zero, false otherwise. // // The return value is true if 'value' is a supported integer array type, false otherwise. // template <typename T> bool checkUnsignedArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero) { static_assert(std::is_unsigned<T>::value && !std::is_same<T, bool>::value, "Unsigned integer type required."); CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[]>()) { hasZero = std::any_of(array->begin(), array->end(), [tolerance](auto element){ return element <= (T)tolerance; }); return true; } return false; } // Check whether a bool array attribute contains at least one element with a value of zero (i.e. false). // No tolerance value is applied since tolerance is meaningless for bool. // // 'hasZero' will be set true if any element of the array is zero, false otherwise. // // The return value is true if 'value' is a bool array type, false otherwise. // bool checkBoolArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, bool& hasZero) { if (auto const array = value.get<bool[]>()) { hasZero = std::any_of(array->begin(), array->end(), [](auto element){ return !element; }); return true; } return false; } // Check whether a signed array attribute contains at least one element with a value of zero // (i.e. its value lies within 'tolerance' of 0). // // T - type of the elements of the array. Must be a decimal type. // // 'tolerance' must be non-negative // 'hasZero' will be set true if any element of the array is zero, false otherwise. // // The return value is true if 'value' is a supported decimal array type, false otherwise. // template <typename T> bool checkSignedArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero) { static_assert(std::is_signed<T>::value || pxr::GfIsFloatingPoint<T>::value, "Signed integer or decimal type required."); CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[]>()) { hasZero = std::any_of(array->begin(), array->end(), [tolerance](auto element){ return (std::abs(element) <= tolerance); }); return true; } return false; } // Check whether a scalar array attribute contains at least one element with a value of zero // (i.e. its value lies within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'hasZero' will be set true if any element of the array is zero, false otherwise. // // The return value is true if 'value' is a supported scalar array type, false otherwise. // bool checkScalarArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eBool: return checkBoolArrayForZeroes(value, hasZero); case BaseDataType::eDouble: return checkSignedArrayForZeroes<double>(value, tolerance, hasZero); case BaseDataType::eFloat: return checkSignedArrayForZeroes<float>(value, tolerance, hasZero); case BaseDataType::eHalf: return checkSignedArrayForZeroes<pxr::GfHalf>(value, tolerance, hasZero); case BaseDataType::eInt: return checkSignedArrayForZeroes<int32_t>(value, tolerance, hasZero); case BaseDataType::eInt64: return checkSignedArrayForZeroes<int64_t>(value, tolerance, hasZero); case BaseDataType::eUChar: return checkUnsignedArrayForZeroes<unsigned char>(value, tolerance, hasZero); case BaseDataType::eUInt: return checkUnsignedArrayForZeroes<uint32_t>(value, tolerance, hasZero); case BaseDataType::eUInt64: return checkUnsignedArrayForZeroes<uint64_t>(value, tolerance, hasZero); default: break; } return false; } // Returns true if all components of the tuple are zero. // (i.e. they lie within 'tolerance' of 0). // // T - base type of the tuple (e.g. float if tuple is float[2]). // N - number of components in the tuple (e.g. '2' in the example above). // // 'tolerance' must be non-negative // template <typename T, int N> bool isTupleZero(const T tuple[N], double tolerance) { CARB_ASSERT(tolerance >= 0.0); for (int i = 0; i < N; ++i) { if (std::abs(tuple[i]) > tolerance) return false; } return true; } // Check whether a tuple array attribute contains at least one element which is zero // (i.e. all of their components are within 'tolerance' of 0). // // T - type of the components of the tuple. Must be a decimal type. // N - number of components in the tuple // // 'tolerance' must be non-negative // 'hasZero' will be set true if any tuple in the array is zero, false otherwise. // // The return value is true if 'value' is a supported decimal tuple array type, false otherwise. // template <typename T, int N> bool checkTupleArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, double tolerance, bool& hasZero) { CARB_ASSERT(tolerance >= 0.0); if (auto const array = value.get<T[][N]>()) { hasZero = std::any_of(array->begin(), array->end(), [tolerance](auto element){ return isTupleZero<T, N>(element, tolerance); }); return true; } return false; } // Check whether a tuple array attribute contains at least one element which is zero // (i.e. all of their components are within 'tolerance' of 0). // // 'tolerance' must be non-negative // 'hasZero' will be set true if any tuple in the array is zero, false otherwise. // // The return value is true if 'value' is a supported decimal tuple array type, false otherwise. // bool checkTupleArrayForZeroes(const OgnAnyZeroAttributes::inputs::value_t& value, const double& tolerance, bool& hasZero) { CARB_ASSERT(tolerance >= 0.0); switch (value.type().baseType) { case BaseDataType::eDouble: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<double, 2>(value, tolerance, hasZero); case 3: return checkTupleArrayForZeroes<double, 3>(value, tolerance, hasZero); case 4: return checkTupleArrayForZeroes<double, 4>(value, tolerance, hasZero); case 9: return checkTupleArrayForZeroes<double, 9>(value, tolerance, hasZero); case 16: return checkTupleArrayForZeroes<double, 16>(value, tolerance, hasZero); } break; case BaseDataType::eFloat: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<float, 2>(value, tolerance, hasZero); case 3: return checkTupleArrayForZeroes<float, 3>(value, tolerance, hasZero); case 4: return checkTupleArrayForZeroes<float, 4>(value, tolerance, hasZero); } break; case BaseDataType::eHalf: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<pxr::GfHalf, 2>(value, tolerance, hasZero); case 3: return checkTupleArrayForZeroes<pxr::GfHalf, 3>(value, tolerance, hasZero); case 4: return checkTupleArrayForZeroes<pxr::GfHalf, 4>(value, tolerance, hasZero); } break; case BaseDataType::eInt: switch (value.type().componentCount) { case 2: return checkTupleArrayForZeroes<int32_t, 2>(value, tolerance, hasZero); case 3: return checkTupleArrayForZeroes<int32_t, 3>(value, tolerance, hasZero); case 4: return checkTupleArrayForZeroes<int32_t, 4>(value, tolerance, hasZero); } break; default: break; } return false; } } // namespace class OgnAnyZero { public: static bool compute(OgnAnyZeroDatabase& db) { const auto& value = db.inputs.value(); if (!value.resolved()) return true; const auto& tolerance = db.inputs.tolerance(); auto& result = db.outputs.result(); try { // Some of the functions below return as soon as they find a zero value, so // we start out assuming there are no zeroes and let them change that to true. // result = false; bool foundType{ false }; // Arrays if (value.type().arrayDepth > 0) { // Arrays of tuples. if (value.type().componentCount > 1) { foundType = checkTupleArrayForZeroes(value, tolerance, result); } else { // Arrays of scalars. foundType = checkScalarArrayForZeroes(value, tolerance, result); } } // Tuples else if (value.type().componentCount > 1) { foundType = checkTupleForZeroes(value, tolerance, result); } else { // Scalars foundType = checkScalarForZero(value, tolerance, result); } if (! foundType) { throw ogn::compute::InputError(kValueTypeUnresolved); } } catch (ogn::compute::InputError &error) { db.logError("OgnAnyZero: %s", error.what()); return false; } return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
15,509
C++
37.582089
136
0.635566
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNoise.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // This node implements the noise() function from Warp. Once Warp has been released // it will be reimplemented using Warp. // // If you're interested in how to use the output from this node to drive a procedural // noise texture, take a look at the core_definitions::perlin_noise_texture from the material library, // documented here: // // https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_material-graph/nodes/Texturing_High_Level/perlin-noise.html // // Its MDL implementation can be found in the omni-core-materials repo, in mdl/nvidia/core_definitions.mdl // That in turn calls base::perlin_noise_texture() which is implemented in the MDL-SDK repo, in src/shaders/mdl/base/base.mdl // #include <OgnNoiseDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "warp_noise.h" namespace omni { namespace graph { namespace nodes { namespace { template <typename T, typename PXRTYPE> bool getNoiseValues(uint32_t &rng_state, const OgnNoiseAttributes::inputs::position_t& position, ogn::array<float> &resultArray) { if (auto positionArray = position.get<T>()) { resultArray.resize(positionArray.size()); size_t i = 0; for (auto pos : *positionArray) { resultArray[i++] = noise(rng_state, *(const PXRTYPE*)pos); } return true; } return false; } // Specialization for non-tuple type. template <> bool getNoiseValues<float[],float>(uint32_t &rng_state, const OgnNoiseAttributes::inputs::position_t& position, ogn::array<float> &resultArray) { if (auto positionArray = position.get<float[]>()) { resultArray.resize(positionArray.size()); size_t i = 0; for (auto pos : *positionArray) { resultArray[i++] = noise(rng_state, pos); } return true; } return false; } } class OgnNoise { public: static bool compute(OgnNoiseDatabase& db) { const auto& position = db.inputs.position(); // If we don't have any positions to sample then there's nothing to do. if (!position.resolved()) return true; auto& result = db.outputs.result(); const auto& seed = db.inputs.seed(); uint32_t rng_state = rand_init(seed); try { if (position.type().arrayDepth == 0) { if (auto resultScalar = result.get<float>()) { switch (position.type().componentCount) { case 1: { *resultScalar = noise(rng_state, *position.get<float>()); return true; } case 2: { *resultScalar = noise(rng_state, *(GfVec2f*)(*position.get<float[2]>())); return true; } case 3: { *resultScalar = noise(rng_state, *(GfVec3f*)(*position.get<float[3]>())); return true; } case 4: { *resultScalar = noise(rng_state, *(GfVec4f*)(*position.get<float[4]>())); return true; } default: db.logError("'position' has invalid tuple size of %i.", position.type().componentCount); } } else { throw ogn::compute::InputError("'result' is an array but 'position' is not"); } } else if (auto resultArray = result.get<float[]>()) { switch (position.type().componentCount) { case 1: { if (getNoiseValues<float[], float>(rng_state, position, *resultArray)) return true; throw ogn::compute::InputError("could not resolve 'position' to float[]"); } case 2: { if (getNoiseValues<float[][2], GfVec2f>(rng_state, position, *resultArray)) return true; throw ogn::compute::InputError("could not resolve 'position' to float[2][]"); } case 3: { if (getNoiseValues<float[][3], GfVec3f>(rng_state, position, *resultArray)) return true; throw ogn::compute::InputError("could not resolve 'position' to float[3][]"); } case 4: { if (getNoiseValues<float[][4], GfVec4f>(rng_state, position, *resultArray)) return true; throw ogn::compute::InputError("could not resolve 'position' to float[4][]"); } default: db.logError("'position' has invalid tuple size of %i.", position.type().componentCount); } } else { throw ogn::compute::InputError("'position' is an array but 'result' is not"); } } catch (ogn::compute::InputError &error) { db.logError(error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node) { auto position = node.iNode->getAttributeByToken(node, inputs::position.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto positionType = position.iAttribute->getResolvedType(position); if (positionType.baseType != BaseDataType::eUnknown) { // 'result' is always float but has the same array depth as 'position'. Type type(BaseDataType::eFloat, 1, positionType.arrayDepth, AttributeRole::eNone); result.iAttribute->setResolvedType(result, type); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni // end-compute-helpers
6,563
C++
33.010363
143
0.551272
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadKeyboardState.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnReadKeyboardStateDatabase.h> #include <carb/input/IInput.h> #include <carb/input/InputTypes.h> #include <omni/kit/IAppWindow.h> using namespace carb::input; namespace omni { namespace graph { namespace action { // This list matches carb::input::KeyboardInput constexpr size_t s_numNames = size_t(carb::input::KeyboardInput::eCount); static constexpr std::array<const char*, s_numNames> s_keyNames = { "Unknown", "Space", "Apostrophe", "Comma", "Minus", "Period", "Slash", "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8", "Key9", "Semicolon", "Equal", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "LeftBracket", "Backslash", "RightBracket", "GraveAccent", "Escape", "Tab", "Enter", "Backspace", "Insert", "Del", "Right", "Left", "Down", "Up", "PageUp", "PageDown", "Home", "End", "CapsLock", "ScrollLock", "NumLock", "PrintScreen", "Pause", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "Numpad0", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Numpad5", "Numpad6", "Numpad7", "Numpad8", "Numpad9", "NumpadDel", "NumpadDivide", "NumpadMultiply", "NumpadSubtract", "NumpadAdd", "NumpadEnter", "NumpadEqual", "LeftShift", "LeftControl", "LeftAlt", "LeftSuper", "RightShift", "RightControl", "RightAlt", "RightSuper", "Menu" }; static_assert(s_keyNames.size() == size_t(carb::input::KeyboardInput::eCount), "enum must match this table"); static std::array<NameToken, s_numNames> s_keyTokens; class OgnReadKeyboardState { public: static bool compute(OgnReadKeyboardStateDatabase& db) { static NameToken const emptyToken = db.stringToToken(""); NameToken const& keyIn = db.inputs.key(); auto contextObj = db.abi_context(); // First time look up all the token string values static bool callOnce = ([&contextObj] { std::transform(s_keyNames.begin(), s_keyNames.end(), s_keyTokens.begin(), [&contextObj](auto const& s) { return contextObj.iToken->getHandle(s); }); } (), true); omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow(); if (!appWindow) { return false; } Keyboard* keyboard = appWindow->getKeyboard(); if (!keyboard) { CARB_LOG_ERROR_ONCE("No Keyboard!"); return false; } IInput* input = carb::getCachedInterface<IInput>(); if (!input) { CARB_LOG_ERROR_ONCE("No Input!"); return false; } bool isPressed = false; // Get the index of the token of the key of interest auto iter = std::find(s_keyTokens.begin(), s_keyTokens.end(), keyIn); if (iter != s_keyTokens.end()) { size_t index = iter - s_keyTokens.begin(); KeyboardInput key = KeyboardInput(index); isPressed = (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, key)); } db.outputs.shiftOut() = (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftShift)) || (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightShift)); db.outputs.ctrlOut() = (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftControl)) || (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightControl)); db.outputs.altOut() = (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eLeftAlt)) || (carb::input::kButtonFlagStateDown & input->getKeyboardButtonFlags(keyboard, KeyboardInput::eRightAlt)); db.outputs.isPressed() = isPressed; return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
4,887
C++
23.19802
121
0.581747
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadGamepadState.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnReadGamepadStateDatabase.h> #include <carb/input/IInput.h> #include <carb/input/InputTypes.h> #include <omni/kit/IAppWindow.h> using namespace carb::input; namespace omni { namespace graph { namespace nodes { // This is different from carb::input::GamepadInput::eCount by 4 because we combine the joystick inputs by axis (x/y) constexpr size_t s_numNames = size_t(carb::input::GamepadInput::eCount) - 4; static std::array<NameToken, s_numNames> s_elementTokens; class OgnReadGamepadState { public: static bool compute(OgnReadGamepadStateDatabase& db) { NameToken const& elementIn = db.inputs.gamepadElement(); const unsigned int gamepadId = db.inputs.gamepadId(); const float deadzone = db.inputs.deadzone(); // First time initialization of all the token values static bool callOnce = ([&db] { s_elementTokens = { db.tokens.LeftStickXAxis, db.tokens.LeftStickYAxis, db.tokens.RightStickXAxis, db.tokens.RightStickYAxis, db.tokens.LeftTrigger, db.tokens.RightTrigger, db.tokens.FaceButtonBottom, db.tokens.FaceButtonRight, db.tokens.FaceButtonLeft, db.tokens.FaceButtonTop, db.tokens.LeftShoulder, db.tokens.RightShoulder, db.tokens.SpecialLeft, db.tokens.SpecialRight, db.tokens.LeftStickButton, db.tokens.RightStickButton, db.tokens.DpadUp, db.tokens.DpadRight, db.tokens.DpadDown, db.tokens.DpadLeft }; } (), true); omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow(); if (!appWindow) { return false; } Gamepad* gamepad = appWindow->getGamepad(gamepadId); if (!gamepad) { db.logWarning("No Gamepad!"); return false; } IInput* input = carb::getCachedInterface<IInput>(); if (!input) { db.logWarning("No Input!"); return false; } bool isPressed = false; float value = 0.0; // Get the index of the token of the element of interest auto iter = std::find(s_elementTokens.begin(), s_elementTokens.end(), elementIn); if (iter != s_elementTokens.end()) { size_t index = iter - s_elementTokens.begin(); if (index < 4) { // We want to combine the joystick inputs by its axis (x/y instead of right/left/up/down) GamepadInput positiveElement = GamepadInput(2*index); GamepadInput negativeElement = GamepadInput(2*index+1); value = input->getGamepadValue(gamepad, positiveElement) - input->getGamepadValue(gamepad, negativeElement); } else { // index is offset by 4 because we combine the joystick x/y axis GamepadInput element = GamepadInput(index + 4); value = input->getGamepadValue(gamepad, element); } // Check for deadzone threshold if (std::abs(value) < deadzone) { value = 0.0; isPressed = false; } else { isPressed = true; } } db.outputs.isPressed() = isPressed; db.outputs.value() = value; return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
4,137
C++
31.84127
124
0.580131
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Quaternion.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnSetMatrix4QuaternionDatabase.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/quat.h> using omni::math::linalg::matrix4d; using omni::math::linalg::quatd; namespace omni { namespace graph { namespace nodes { namespace { void updateMatrix(const double input[16], double result[16], const double quaternion[4]) { matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result); memcpy(resultMat.data(), input, sizeof(double) * 16); resultMat.SetRotateOnly(quatd(quaternion[3], quaternion[0], quaternion[1], quaternion[2])); } } class OgnSetMatrix4Quaternion { public: static bool compute(OgnSetMatrix4QuaternionDatabase& db) { const auto& matrixInput = db.inputs.matrix(); const auto& quaternionInput = db.inputs.quaternion(); auto matrixOutput = db.outputs.matrix(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto quaternion = quaternionInput.get<double[4]>()) { if (auto output = matrixOutput.get<double[16]>()) { updateMatrix(*matrix, *output, *quaternion); failed = false; } } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto quaternions = quaternionInput.get<double[][4]>()) { if (auto output = matrixOutput.get<double[][16]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { updateMatrix((*matrices)[i], (*output)[i], (*quaternions)[i]); } failed = false; } } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, quaternion input with depth %s, and output with depth %s", matrixInput.type().arrayDepth, quaternionInput.type().arrayDepth, matrixOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node){ // Resolve fully-coupled types for the 2 attributes std::array<AttributeObj, 2> attrs { node.iNode->getAttribute(node, OgnSetMatrix4QuaternionAttributes::inputs::matrix.m_name), node.iNode->getAttribute(node, OgnSetMatrix4QuaternionAttributes::outputs::matrix.m_name) }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
3,340
C++
31.754902
151
0.592216
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToTarget.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnRotateToTargetDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/math.h> #include <omni/math/linalg/SafeCast.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/usdGeom/xformCache.h> #include <omni/graph/core/PostUsdInclude.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { namespace { constexpr double kUninitializedStartTime = -1.; } class OgnRotateToTarget { XformUtils::MoveState m_moveState; public: static bool compute(OgnRotateToTargetDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnRotateToTarget>(); double& startTime = state.m_moveState.startTime; pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName; quatd& startOrientation = state.m_moveState.startOrientation; vec3d& startEuler = state.m_moveState.startEuler; XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto sourcePrimPath = getPrimOrPath(contextObj, nodeObj, inputs::sourcePrim.token(), inputs::sourcePrimPath.token(), inputs::useSourcePath.token(), db.getInstanceIndex()); auto destPrimPath = getPrimOrPath(contextObj, nodeObj, inputs::targetPrim.token(), inputs::targetPrimPath.token(), inputs::useTargetPath.token(), db.getInstanceIndex()); if (sourcePrimPath.IsEmpty() || destPrimPath.IsEmpty()) return true; pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath); pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath); pxr::UsdGeomXformCache xformCache; matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim)); matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim)); quatd destWorldOrient = extractRotationQuatd(destWorldTransform).GetNormalized(); quatd sourceParentWorldOrient = extractRotationQuatd(sourceParentTransform).GetNormalized(); bool hasRotations = (destWorldOrient != quatd::GetIdentity()) or (sourceParentWorldOrient != quatd::GetIdentity()); if (startTime <= kUninitializedStartTime || now < startTime) { std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, sourcePrimPath); if (targetAttribName.IsEmpty()) { if (hasRotations) throw std::runtime_error( "RotateToTarget requires the source Prim to have xformOp:orient" " when the destination Prim or source Prim parent has rotation, please Add"); std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, sourcePrimPath); if (not targetAttribName.IsEmpty()) rotationMode = XformUtils::RotationMode::eEuler; } else rotationMode = XformUtils::RotationMode::eQuat; if (targetAttribName.IsEmpty()) throw std::runtime_error( formatString("Could not find suitable XformOp on %s, please add", sourcePrimPath.GetText())); startTime = now; // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); // Convert dest prim transform to the source's parent frame matrix4d destLocalTransform = destWorldTransform / sourceParentTransform; if (rotationMode == XformUtils::RotationMode::eQuat) { const quatd& targetOrientation = extractRotationQuatd(destLocalTransform).GetNormalized(); quatd quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized(); trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), quat); } else if (rotationMode == XformUtils::RotationMode::eEuler) { // FIXME: We previously checked that there is no rotation on the target, so we just have to interpolate // to identity. vec3d const targetRot{}; auto rot = GfLerp(alpha2, startEuler, targetRot); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), rot); } if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return false; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
6,759
C++
37.850574
183
0.62169
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTransformVector.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnTransformVectorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/vec.h> using omni::math::linalg::matrix4d; using omni::math::linalg::matrix3d; using omni::math::linalg::vec3; using ogn::compute::tryComputeWithArrayBroadcasting; namespace omni { namespace graph { namespace nodes { namespace { template<typename T> bool tryComputeWithMatrix3(OgnTransformVectorDatabase& db) { auto functor = [&](auto& matrix, auto& vector, auto& result) { auto& transformMat = *reinterpret_cast<const matrix3d*>(matrix); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); // left multiplication by row vector resultVec = vec3<T>(sourceVec * transformMat); }; return tryComputeWithArrayBroadcasting<double[9], T[3], T[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor); } template<typename T> bool tryComputeWithMatrix4(OgnTransformVectorDatabase& db) { auto functor = [&](auto& matrix, auto& vector, auto& result) { auto& transformMat = *reinterpret_cast<const matrix4d*>(matrix); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); resultVec = vec3<T>(transformMat.Transform(sourceVec)); }; return tryComputeWithArrayBroadcasting<double[16], T[3], T[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor); } /* FIXME: GfHalf has no explicit conversion from double to half, so we need to convert to a float first */ template<> bool tryComputeWithMatrix3<pxr::GfHalf>(OgnTransformVectorDatabase& db) { auto functor = [&](auto& matrix, auto& vector, auto& result) { auto& transformMat = *reinterpret_cast<const matrix3d*>(matrix); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); // left multiplication by row vector resultVec = vec3<pxr::GfHalf>(vec3<float>(sourceVec * transformMat)); }; return tryComputeWithArrayBroadcasting<double[9], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor); } template<> bool tryComputeWithMatrix4<pxr::GfHalf>(OgnTransformVectorDatabase& db) { auto functor = [&](auto& matrix, auto& vector, auto& result) { auto& transformMat = *reinterpret_cast<const matrix4d*>(matrix); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); resultVec = vec3<pxr::GfHalf>(vec3<float>(transformMat.Transform(sourceVec))); }; return tryComputeWithArrayBroadcasting<double[16], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.matrix(), db.inputs.vector(), db.outputs.result(), functor); } } // namespace class OgnTransformVector { public: static bool compute(OgnTransformVectorDatabase& db) { try { // matrix3 if (tryComputeWithMatrix3<double>(db)) return true; else if (tryComputeWithMatrix3<float>(db)) return true; else if (tryComputeWithMatrix3<pxr::GfHalf>(db)) return true; // matrix4 else if (tryComputeWithMatrix4<double>(db)) return true; else if (tryComputeWithMatrix4<float>(db)) return true; else if (tryComputeWithMatrix4<pxr::GfHalf>(db)) return true; else { db.logWarning("OgnTransformVector: Failed to resolve input types"); } } catch (ogn::compute::InputError &error) { db.logWarning("OgnTransformVector: %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node){ auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token()); auto matrix = node.iNode->getAttributeByToken(node, inputs::matrix.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto vectorType = vector.iAttribute->getResolvedType(vector); auto matrixType = matrix.iAttribute->getResolvedType(matrix); // Require vector, matrix to be resolved before determining result's type if (vectorType.baseType != BaseDataType::eUnknown && matrixType.baseType != BaseDataType::eUnknown) { Type resultType(vectorType.baseType, vectorType.componentCount, std::max(vectorType.arrayDepth, matrixType.arrayDepth), vectorType.role); result.iAttribute->setResolvedType(result, resultType); } } }; REGISTER_OGN_NODE() } } }
5,308
C++
38.325926
157
0.679352
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToLocation.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnTranslateToLocationDatabase.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/math.h> #include "PrimCommon.h" #include "XformUtils.h" using omni::math::linalg::vec3d; using omni::math::linalg::GfLerp; namespace omni { namespace graph { namespace nodes { namespace { constexpr double kUninitializedStartTime = -1.; } struct TranslateMoveState : public XformUtils::MoveState { vec3d targetTranslate; }; class OgnTranslateToLocation { TranslateMoveState m_moveState; public: static bool compute(OgnTranslateToLocationDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnTranslateToLocation>(); double& startTime = state.m_moveState.startTime; vec3d& startTranslation = state.m_moveState.startTranslation; vec3d& targetTranslation = state.m_moveState.targetTranslate; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(), inputs::usePath.token(), db.getInstanceIndex()); if (primPath.IsEmpty()) return true; if (startTime <= kUninitializedStartTime || now < startTime) { // Set state variables try { startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } startTime = now; targetTranslation = db.inputs.target(); // This is the first entry, start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation); // Write back to the prim try { trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr, translation); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return true; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
4,230
C++
29.65942
127
0.582033
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToTarget.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnTranslateToTargetDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/math.h> #include <omni/math/linalg/SafeCast.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/usdGeom/xformCache.h> #include <omni/graph/core/PostUsdInclude.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { namespace { constexpr double kUninitializedStartTime = -1.; } class OgnTranslateToTarget { XformUtils::MoveState m_moveState; public: static bool compute(OgnTranslateToTargetDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnTranslateToTarget>(); double& startTime = state.m_moveState.startTime; vec3d& startTranslation = state.m_moveState.startTranslation; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto sourcePrimPath = getPrimOrPath(contextObj, nodeObj, inputs::sourcePrim.token(), inputs::sourcePrimPath.token(), inputs::useSourcePath.token(), db.getInstanceIndex()); auto destPrimPath = getPrimOrPath(contextObj, nodeObj, inputs::targetPrim.token(), inputs::targetPrimPath.token(), inputs::useTargetPath.token(), db.getInstanceIndex()); if (sourcePrimPath.IsEmpty() || destPrimPath.IsEmpty()) return true; // First frame of the maneuver. if (startTime <= kUninitializedStartTime || now < startTime) { try { startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } startTime = now; // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath); pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath); pxr::UsdGeomXformCache xformCache; // Convert dest prim transform to the source's parent frame matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim)); matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim)); matrix4d destLocalTransform = destWorldTransform / sourceParentTransform; const vec3d& targetTranslation = destLocalTransform.ExtractTranslation(); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation); // Write back to the prim try { trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr, translation); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return true; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
5,199
C++
33.437086
118
0.604155
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToOrientation.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnRotateToOrientationDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { struct RotateMoveState: public XformUtils::MoveState { vec3d targetEuler; }; class OgnRotateToOrientation { public: RotateMoveState m_moveState; static bool compute(OgnRotateToOrientationDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnRotateToOrientation>(); double& startTime = state.m_moveState.startTime; pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName; quatd& startOrientation = state.m_moveState.startOrientation; vec3d& startEuler = state.m_moveState.startEuler; vec3d& targetEuler = state.m_moveState.targetEuler; XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(), inputs::usePath.token(), db.getInstanceIndex()); if (primPath.IsEmpty()) return true; // First frame of the maneuver. if (startTime <= XformUtils::kUninitializedStartTime || now < startTime) { try { std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, primPath); if (not targetAttribName.IsEmpty()) rotationMode = XformUtils::RotationMode::eQuat; else { std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, primPath); if (not targetAttribName.IsEmpty()) rotationMode = XformUtils::RotationMode::eEuler; } if (targetAttribName.IsEmpty()) throw std::runtime_error( formatString("Could not find suitable XformOp on %s, please add", primPath.GetText())); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } // Copy the target in case it changes during the movement targetEuler = db.inputs.target(); startTime = now; // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); try { if (rotationMode == XformUtils::RotationMode::eQuat) { quatd const& targetOrientation = eulerAnglesToQuaternion(GfDegreesToRadians(targetEuler), EulerRotationOrder::XYZ); auto const quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized(); // Write back to the prim trySetPrimAttribute( contextObj, nodeObj, primPath, targetAttribName.GetText(), quat); } else if (rotationMode == XformUtils::RotationMode::eEuler) { vec3d rot = lerp(startEuler, targetEuler, alpha2); // Write back to the prim trySetPrimAttribute( contextObj, nodeObj, primPath, targetAttribName.GetText(), rot); } } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return true; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
5,830
C++
34.773006
118
0.559863
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTransform.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnMoveToTransformDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/math.h> #include <omni/math/linalg/SafeCast.h> #include <cmath> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { namespace { constexpr double kUninitializedStartTime = -1.; } struct MoveMoveState : public XformUtils::MoveState { matrix4d targetTransform; }; class OgnMoveToTransform { public: MoveMoveState m_moveState; static bool compute(OgnMoveToTransformDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnMoveToTransform>(); double& startTime = state.m_moveState.startTime; pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName; quatd& startOrientation = state.m_moveState.startOrientation; vec3d& startTranslation = state.m_moveState.startTranslation; matrix4d& targetTransform = state.m_moveState.targetTransform; vec3d& startScale = state.m_moveState.startScale; XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(), inputs::usePath.token(), db.getInstanceIndex()); if (primPath.IsEmpty()) return true; // First frame of the maneuver. if (startTime <= kUninitializedStartTime || now < startTime) { try { std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, primPath); if (targetAttribName.IsEmpty()) throw std::runtime_error("MoveToTransform requires the source Prim to have xformOp:orient, please add"); rotationMode = XformUtils::RotationMode::eQuat; startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr); startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } startTime = now; targetTransform = db.inputs.target(); // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); try { if (rotationMode == XformUtils::RotationMode::eQuat) { quatd targetOrientation = extractRotationQuatd(targetTransform).GetNormalized(); quatd quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized(); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, primPath, targetAttribName.GetText(), quat); } vec3d targetTranslation = targetTransform.ExtractTranslation(); vec3d targetScale{ targetTransform.GetRow(0).GetLength(), targetTransform.GetRow(1).GetLength(), targetTransform.GetRow(2).GetLength() }; vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation); vec3d scale = GfLerp(alpha2, startScale, targetScale); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::TranslationAttrStr, translation); trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr, scale); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return false; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
6,047
C++
35
128
0.593187
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Rotation.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnSetMatrix4RotationDatabase.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <cmath> using omni::math::linalg::matrix4d; using omni::math::linalg::quatd; using omni::math::linalg::vec3d; namespace omni { namespace graph { namespace nodes { namespace { void updateMatrix(const double input[16], double result[16], vec3d axis, double angle) { matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result); memcpy(resultMat.data(), input, sizeof(double) * 16); axis.Normalize(); // 0.5 is because quaternions cover the space of rotations twice angle = 0.5f * omni::math::linalg::GfDegreesToRadians(angle); double c = std::cos(angle); double s = std::sin(angle); resultMat.SetRotateOnly(quatd(c, s * axis)); } } class OgnSetMatrix4Rotation { public: static bool compute(OgnSetMatrix4RotationDatabase& db) { vec3d axis(0); const auto& fixedRotationAxis = db.inputs.fixedRotationAxis(); if (fixedRotationAxis == db.tokens.X) { axis[0] = 1; } else if (fixedRotationAxis == db.tokens.Z) { axis[2] = 1; } else if (fixedRotationAxis == db.tokens.Y || fixedRotationAxis == omni::fabric::kUninitializedToken) { axis[1] = 1; } else { db.logError("fixedRotationAxis must be one of X,Y,Z"); return false; } const auto& matrixInput = db.inputs.matrix(); const auto& rotationAngleInput = db.inputs.rotationAngle(); auto matrixOutput = db.outputs.matrix(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto rotationAngle = rotationAngleInput.get<double>()) { if (auto output = matrixOutput.get<double[16]>()) { updateMatrix(*matrix, *output, axis, *rotationAngle); failed = false; } } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto rotationAngles = rotationAngleInput.get<double[]>()) { if (auto output = matrixOutput.get<double[][16]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { updateMatrix((*matrices)[i], (*output)[i], axis, (*rotationAngles)[i]); } failed = false; } } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, rotation angles input with depth %s, and output with depth %s", matrixInput.type().arrayDepth, rotationAngleInput.type().arrayDepth, matrixOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node){ // Resolve fully-coupled types for the 2 attributes std::array<AttributeObj, 2> attrs { node.iNode->getAttribute(node, OgnSetMatrix4RotationAttributes::inputs::matrix.m_name), node.iNode->getAttribute(node, OgnSetMatrix4RotationAttributes::outputs::matrix.m_name) }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
4,103
C++
32.639344
156
0.595662
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimDirectionVector.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnGetPrimDirectionVectorDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/SafeCast.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/usdGeom/xformCache.h> #include <omni/graph/core/PostUsdInclude.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { class OgnGetPrimDirectionVector { public: static bool compute(OgnGetPrimDirectionVectorDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; try { // Retrieve the prim path string in one of two ways bool usePath = db.inputs.usePath(); std::string primPathStr; if (usePath) { // Use the absolute path NameToken primPath = db.inputs.primPath(); primPathStr = db.tokenToString(primPath); if (primPathStr.empty()) { db.logWarning("No prim path specified"); return false; } } else { // Read the path from the relationship input on this compute node auto primPath = getRelationshipPrimPath( contextObj, nodeObj, OgnGetPrimDirectionVectorAttributes::inputs::prim.m_token, db.getInstanceIndex()); primPathStr = primPath.GetText(); } // Retrieve a reference to the prim pxr::UsdPrim prim = getPrim(contextObj, pxr::SdfPath(primPathStr)); // Extract the rotation from the local to world transformation matrix pxr::UsdGeomXformCache xformCache; matrix4d localWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(prim)); quatd rotation = extractRotationQuatd(localWorldTransform).GetNormalized(); // Apply the rotation to (0,1,0) to get the up vector vec3<double> upVector = rotation.Transform(vec3<double>::YAxis()); db.outputs.upVector() = upVector; db.outputs.downVector() = -upVector; // Apply the rotation to (0,0,-1) to get the forward vector vec3<double> forwardVector = rotation.Transform(-vec3<double>::ZAxis()); db.outputs.forwardVector() = forwardVector; db.outputs.backwardVector() = -forwardVector; // Apply the rotation to (1,0,0) to get the right vector vec3<double> rightVector = rotation.Transform(vec3<double>::XAxis()); db.outputs.rightVector() = rightVector; db.outputs.leftVector() = -rightVector; return true; } catch(const std::exception& e) { db.logError(e.what()); return false; } } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
3,520
C++
32.216981
123
0.617614
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Translation.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnGetMatrix4TranslationDatabase.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::matrix4d; using omni::math::linalg::vec3d; namespace omni { namespace graph { namespace nodes { namespace { void getTranslation(const double input[16], double result[4]) { vec3d translation = reinterpret_cast<const matrix4d*>(input)->ExtractTranslation(); memcpy(result, translation.data(), sizeof(double) * 3); } } class OgnGetMatrix4Translation { public: static bool computeVectorized(OgnGetMatrix4TranslationDatabase& db, size_t count) { const auto& matrixInput = db.inputs.matrix(); bool inOk = false; bool failed = true; // Singular case if (matrixInput.type().arrayDepth == 0) { if (auto matrix = matrixInput.get<double[16]>()) { inOk = true; auto translationOutput = db.outputs.translation(); if (auto output = translationOutput.get<double[3]>()) { auto matrices = matrix.vectorized(count); auto outputs = output.vectorized(count); for (size_t i = 0; i < count; ++i) getTranslation(matrices[i], outputs[i]); failed = false; } } } // Array case else { for (size_t inst = 0; inst < count; ++inst) { if (auto matrices = db.inputs.matrix(inst).get<double[][16]>()) { inOk = true; if (auto output = db.outputs.translation(inst).get<double[][3]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { getTranslation((*matrices)[i], (*output)[i]); } failed = false; } } } } if (!inOk) { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s", matrixInput.type().arrayDepth, db.outputs.translation().type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node) { auto start = node.iNode->getAttribute(node, OgnGetMatrix4TranslationAttributes::inputs::matrix.m_name); auto result = node.iNode->getAttribute(node, OgnGetMatrix4TranslationAttributes::outputs::translation.m_name); auto startType = start.iAttribute->getResolvedType(start); std::array<AttributeObj, 2> attrs { start, result }; std::array<uint8_t, 2> tupleCounts { 16, 3 }; std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth }; std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eVector }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
3,907
C++
32.689655
118
0.562836
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Rotation.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnGetMatrix4RotationDatabase.h> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/base/gf/rotation.h> #include <omni/graph/core/PostUsdInclude.h> namespace omni { namespace graph { namespace nodes { namespace { void getRotation(const double input[16], double result[3]) { pxr::GfVec3d rotation = reinterpret_cast<const pxr::GfMatrix4d*>(input)->DecomposeRotation(pxr::GfVec3d::XAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::ZAxis()); memcpy(result, rotation.data(), sizeof(double) * 3); } } class OgnGetMatrix4Rotation { public: static bool compute(OgnGetMatrix4RotationDatabase& db) { const auto& matrixInput = db.inputs.matrix(); auto rotationOutput = db.outputs.rotation(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto output = rotationOutput.get<double[3]>()) { getRotation(*matrix, *output); failed = false; } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto output = rotationOutput.get<double[][3]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { getRotation((*matrices)[i], (*output)[i]); } failed = false; } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s", matrixInput.type().arrayDepth, rotationOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node) { auto start = node.iNode->getAttribute(node, OgnGetMatrix4RotationAttributes::inputs::matrix.m_name); auto result = node.iNode->getAttribute(node, OgnGetMatrix4RotationAttributes::outputs::rotation.m_name); auto startType = start.iAttribute->getResolvedType(start); std::array<AttributeObj, 2> attrs { start, result }; std::array<uint8_t, 2> tupleCounts { 16, 3 }; std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth }; std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eVector }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
3,276
C++
32.438775
168
0.606227
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransform.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnMakeTransformDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::quatd; using omni::math::linalg::matrix4d; namespace omni { namespace graph { namespace nodes { class OgnMakeTransform { public: static bool compute(OgnMakeTransformDatabase& db) { auto& translation = db.inputs.translation(); auto& orientation = db.inputs.rotationXYZ(); auto& scale = db.inputs.scale(); const quatd q = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(orientation), omni::math::linalg::EulerRotationOrder::XYZ).GetNormalized(); db.outputs.transform() = matrix4d().SetScale(scale) * matrix4d().SetRotate(q) * matrix4d().SetTranslate(translation); return true; } }; REGISTER_OGN_NODE() } } }
1,264
C++
27.749999
162
0.732595
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Translation.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnSetMatrix4TranslationDatabase.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::matrix4d; namespace omni { namespace graph { namespace nodes { namespace { void updateMatrix(const double input[16], double result[16], const double translation[3]) { matrix4d& resultMat = *reinterpret_cast<matrix4d*>(result); memcpy(resultMat.data(), input, sizeof(double) * 16); resultMat.SetTranslateOnly({translation[0], translation[1], translation[2]}); } } class OgnSetMatrix4Translation { public: static bool compute(OgnSetMatrix4TranslationDatabase& db) { const auto& matrixInput = db.inputs.matrix(); const auto& translationInput = db.inputs.translation(); auto matrixOutput = db.outputs.matrix(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto translation = translationInput.get<double[3]>()) { if (auto output = matrixOutput.get<double[16]>()) { updateMatrix(*matrix, *output, *translation); failed = false; } } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto translations = translationInput.get<double[][3]>()) { if (auto output = matrixOutput.get<double[][16]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { updateMatrix((*matrices)[i], (*output)[i], (*translations)[i]); } failed = false; } } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, translation input with depth %s, and output with depth %s", matrixInput.type().arrayDepth, translationInput.type().arrayDepth, matrixOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node){ // Resolve fully-coupled types for the 2 attributes std::array<AttributeObj, 2> attrs { node.iNode->getAttribute(node, OgnSetMatrix4TranslationAttributes::inputs::matrix.m_name), node.iNode->getAttribute(node, OgnSetMatrix4TranslationAttributes::outputs::matrix.m_name) }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
3,266
C++
31.67
152
0.592162
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Quaternion.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnGetMatrix4QuaternionDatabase.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/quat.h> #include "XformUtils.h" using omni::math::linalg::matrix4d; using omni::math::linalg::quatd; namespace omni { namespace graph { namespace nodes { namespace { void getQuaternion(const double input[16], double result[4]) { quatd quat = extractRotationQuatd(*reinterpret_cast<const matrix4d*>(input)); // In fabric, quaternions are stored as (XYZW). Note the quatd constructor uses (WXYZ)s memcpy(&result[0], quat.GetImaginary().data(), sizeof(double) * 3); result[3] = quat.GetReal(); } } class OgnGetMatrix4Quaternion { public: static bool compute(OgnGetMatrix4QuaternionDatabase& db) { const auto& matrixInput = db.inputs.matrix(); auto quaternionOutput = db.outputs.quaternion(); bool failed = true; // Singular case if (auto matrix = matrixInput.get<double[16]>()) { if (auto output = quaternionOutput.get<double[4]>()) { getQuaternion(*matrix, *output); failed = false; } } // Array case else if (auto matrices = matrixInput.get<double[][16]>()) { if (auto output = quaternionOutput.get<double[][4]>()) { output->resize(matrices->size()); for (size_t i = 0; i < matrices.size(); i++) { getQuaternion((*matrices)[i], (*output)[i]); } failed = false; } } else { db.logError("Input type for matrix input not supported"); return false; } if (failed) { db.logError("Input and output depths need to align: Matrix input with depth %s, output with depth %s", matrixInput.type().arrayDepth, quaternionOutput.type().arrayDepth); return false; } return true; } static void onConnectionTypeResolve(const NodeObj& node) { auto start = node.iNode->getAttribute(node, OgnGetMatrix4QuaternionAttributes::inputs::matrix.m_name); auto result = node.iNode->getAttribute(node, OgnGetMatrix4QuaternionAttributes::outputs::quaternion.m_name); auto startType = start.iAttribute->getResolvedType(start); std::array<AttributeObj, 2> attrs { start, result }; std::array<uint8_t, 2> tupleCounts { 16, 4 }; std::array<uint8_t, 2> arrayDepths { startType.arrayDepth, startType.arrayDepth }; std::array<AttributeRole, 2> rolesBuf { AttributeRole::eNone, AttributeRole::eQuaternion }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } }; REGISTER_OGN_NODE() } } }
3,416
C++
32.5
116
0.61007
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateVector.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnRotateVectorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/quat.h> using omni::math::linalg::matrix4d; using omni::math::linalg::matrix3d; using omni::math::linalg::vec3; using omni::math::linalg::quat; using ogn::compute::tryComputeWithArrayBroadcasting; namespace omni { namespace graph { namespace nodes { namespace { template<typename T> bool tryComputeWithMatrix3(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix3d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); // left multiplication by row vector resultVec = vec3<T>(sourceVec * matrix); }; return tryComputeWithArrayBroadcasting<double[9], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<typename T> bool tryComputeWithMatrix4(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix4d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); resultVec = vec3<T>(matrix.TransformDir(sourceVec)); }; return tryComputeWithArrayBroadcasting<double[16], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<typename T> bool tryComputeWithQuat(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& quaternion = *reinterpret_cast<const quat<T>*>(rotation); auto& sourceVec = *reinterpret_cast<const vec3<T>*>(vector); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); resultVec = quaternion.Transform(sourceVec); }; return tryComputeWithArrayBroadcasting<T[4], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<typename T> bool tryComputeWithEulerAngles(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto eulerAngles = vec3<double>(*reinterpret_cast<const vec3<T>*>(rotation)); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<T>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<T>*>(result); auto quaternion = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(eulerAngles), omni::math::linalg::EulerRotationOrder::XYZ); resultVec = vec3<T>(quaternion.Transform(sourceVec)); }; return tryComputeWithArrayBroadcasting<T[3], T[3], T[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } /* FIXME: GfHalf has no explicit conversion from double to half, so we need to convert to a float first */ template<> bool tryComputeWithMatrix3<pxr::GfHalf>(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix3d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); // left multiplication by row vector resultVec = vec3<pxr::GfHalf>(vec3<float>(sourceVec * matrix)); }; return tryComputeWithArrayBroadcasting<double[9], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<> bool tryComputeWithMatrix4<pxr::GfHalf>(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto& matrix = *reinterpret_cast<const matrix4d*>(rotation); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); resultVec = vec3<pxr::GfHalf>(vec3<float>(matrix.TransformDir(sourceVec))); }; return tryComputeWithArrayBroadcasting<double[16], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } template<> bool tryComputeWithEulerAngles<pxr::GfHalf>(OgnRotateVectorDatabase& db) { auto functor = [&](auto& rotation, auto& vector, auto& result) { auto eulerAngles = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(rotation)); auto sourceVec = vec3<double>(*reinterpret_cast<const vec3<pxr::GfHalf>*>(vector)); auto& resultVec = *reinterpret_cast<vec3<pxr::GfHalf>*>(result); auto quaternion = omni::math::linalg::eulerAnglesToQuaternion(GfDegreesToRadians(eulerAngles), omni::math::linalg::EulerRotationOrder::XYZ); resultVec = vec3<pxr::GfHalf>(vec3<float>(quaternion.Transform(sourceVec))); }; return tryComputeWithArrayBroadcasting<pxr::GfHalf[3], pxr::GfHalf[3], pxr::GfHalf[3]>(db.inputs.rotation(), db.inputs.vector(), db.outputs.result(), functor); } } // namespace class OgnRotateVector { public: static bool compute(OgnRotateVectorDatabase& db) { try { // matrix3 if (tryComputeWithMatrix3<double>(db)) return true; else if (tryComputeWithMatrix3<float>(db)) return true; else if (tryComputeWithMatrix3<pxr::GfHalf>(db)) return true; // matrix4 else if (tryComputeWithMatrix4<double>(db)) return true; else if (tryComputeWithMatrix4<float>(db)) return true; else if (tryComputeWithMatrix4<pxr::GfHalf>(db)) return true; // quat else if (tryComputeWithQuat<double>(db)) return true; else if (tryComputeWithQuat<float>(db)) return true; else if (tryComputeWithQuat<pxr::GfHalf>(db)) return true; // euler angles else if (tryComputeWithEulerAngles<double>(db)) return true; else if (tryComputeWithEulerAngles<float>(db)) return true; else if (tryComputeWithEulerAngles<pxr::GfHalf>(db)) return true; else { db.logWarning("OgnRotateVector: Failed to resolve input types"); } } catch (ogn::compute::InputError &error) { db.logWarning("OgnRotateVector: %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node) { auto vector = node.iNode->getAttributeByToken(node, inputs::vector.token()); auto rotation = node.iNode->getAttributeByToken(node, inputs::rotation.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto vectorType = vector.iAttribute->getResolvedType(vector); auto rotationType = rotation.iAttribute->getResolvedType(rotation); // Require vector, rotation to be resolved before determining result's type if (vectorType.baseType != BaseDataType::eUnknown && rotationType.baseType != BaseDataType::eUnknown) { Type resultType(vectorType.baseType, vectorType.componentCount, std::max(vectorType.arrayDepth, rotationType.arrayDepth), vectorType.role); result.iAttribute->setResolvedType(result, resultType); } } }; REGISTER_OGN_NODE() } } }
7,929
C++
43.301676
163
0.679279
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTarget.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnMoveToTargetDatabase.h> #include <omni/math/linalg/quat.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/matrix.h> #include <omni/math/linalg/math.h> #include <omni/math/linalg/SafeCast.h> #include <cmath> #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/usdGeom/xformCache.h> #include <omni/graph/core/PostUsdInclude.h> #include "PrimCommon.h" #include "XformUtils.h" using namespace omni::math::linalg; namespace omni { namespace graph { namespace nodes { class OgnMoveToTarget { XformUtils::MoveState m_moveState; public: static bool compute(OgnMoveToTargetDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnMoveToTarget>(); double& startTime = state.m_moveState.startTime; pxr::TfToken& targetAttribName = state.m_moveState.targetAttribName; vec3d& startTranslation = state.m_moveState.startTranslation; quatd& startOrientation = state.m_moveState.startOrientation; vec3d& startEuler = state.m_moveState.startEuler; vec3d& startScale = state.m_moveState.startScale; XformUtils::RotationMode& rotationMode = state.m_moveState.rotationMode; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto sourcePrimPath = getPrimOrPath(contextObj, nodeObj, inputs::sourcePrim.token(), inputs::sourcePrimPath.token(), inputs::useSourcePath.token(), db.getInstanceIndex()); auto destPrimPath = getPrimOrPath(contextObj, nodeObj, inputs::targetPrim.token(), inputs::targetPrimPath.token(), inputs::useTargetPath.token(), db.getInstanceIndex()); if (sourcePrimPath.IsEmpty() || destPrimPath.IsEmpty()) return true; pxr::UsdPrim sourcePrim = getPrim(contextObj, sourcePrimPath); pxr::UsdPrim targetPrim = getPrim(contextObj, destPrimPath); pxr::UsdGeomXformCache xformCache; if (not sourcePrim or not targetPrim) { throw std::runtime_error("Could not find source or target prim"); } matrix4d destWorldTransform = safeCastToOmni(xformCache.GetLocalToWorldTransform(targetPrim)); matrix4d sourceParentTransform = safeCastToOmni(xformCache.GetParentToWorldTransform(sourcePrim)); quatd destWorldOrient = extractRotationQuatd(destWorldTransform).GetNormalized(); quatd sourceParentWorldOrient = extractRotationQuatd(sourceParentTransform).GetNormalized(); bool hasRotations = (destWorldOrient != quatd::GetIdentity()) or (sourceParentWorldOrient != quatd::GetIdentity()); // First frame of the maneuver. if (startTime <= XformUtils::kUninitializedStartTime || now < startTime) { std::tie(startOrientation, targetAttribName) = XformUtils::extractPrimOrientOp(contextObj, sourcePrimPath); if (targetAttribName.IsEmpty()) { if (hasRotations) throw std::runtime_error("MoveToTarget requires the source Prim to have xformOp:orient" " when the destination Prim or source Prim parent has rotation, please Add"); std::tie(startEuler, targetAttribName) = XformUtils::extractPrimEulerOp(contextObj, sourcePrimPath); if (not targetAttribName.IsEmpty()) rotationMode = XformUtils::RotationMode::eEuler; } else rotationMode = XformUtils::RotationMode::eQuat; if (targetAttribName.IsEmpty()) throw std::runtime_error( formatString("Could not find suitable XformOp on %s, please add", sourcePrimPath.GetText())); startTranslation = tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr); startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::ScaleAttrStr); startTime = now; // Start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); // Convert dest prim transform to the source's parent frame matrix4d destLocalTransform = destWorldTransform / sourceParentTransform; if (rotationMode == XformUtils::RotationMode::eQuat) { quatd targetOrientation = extractRotationQuatd(destLocalTransform).GetNormalized(); auto quat = GfSlerp(startOrientation, targetOrientation, alpha2).GetNormalized(); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), quat); } else if (rotationMode == XformUtils::RotationMode::eEuler) { // FIXME: We previously checked that there is no rotation on the target, so we just have to interpolate // to identity. vec3d const targetRot{}; auto rot = GfLerp(alpha2, startEuler, targetRot); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, targetAttribName.GetText(), rot); } vec3d targetTranslation = destLocalTransform.ExtractTranslation(); vec3d targetScale{destLocalTransform.GetRow(0).GetLength(), destLocalTransform.GetRow(1).GetLength(), destLocalTransform.GetRow(2).GetLength()}; vec3d translation = GfLerp(alpha2, startTranslation, targetTranslation); vec3d scale = GfLerp(alpha2, startScale, targetScale); // Write back to the prim trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::TranslationAttrStr, translation); trySetPrimAttribute(contextObj, nodeObj, sourcePrimPath, XformUtils::ScaleAttrStr, scale); if (alpha2 < 1) { // still waiting, output is disabled db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = XformUtils::kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return false; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
8,051
C++
40.081632
129
0.623401
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnScaleToSize.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnScaleToSizeDatabase.h> #include <omni/math/linalg/vec.h> #include <omni/math/linalg/math.h> #include "PrimCommon.h" #include "XformUtils.h" using omni::math::linalg::vec3d; using omni::math::linalg::GfLerp; namespace omni { namespace graph { namespace nodes { namespace { constexpr double kUninitializedStartTime = -1.; } struct ScaleMoveState : public XformUtils::MoveState { vec3d targetScale; }; class OgnScaleToSize { ScaleMoveState m_moveState; public: static bool compute(OgnScaleToSizeDatabase& db) { auto& nodeObj = db.abi_node(); const auto& contextObj = db.abi_context(); auto iContext = contextObj.iContext; double now = iContext->getTimeSinceStart(contextObj); auto& state = db.internalState<OgnScaleToSize>(); double& startTime = state.m_moveState.startTime; vec3d& startScale = state.m_moveState.startScale; vec3d& targetScale = state.m_moveState.targetScale; if (db.inputs.stop() != kExecutionAttributeStateDisabled) { startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } try { auto primPath = getPrimOrPath(contextObj, nodeObj, inputs::prim.token(), inputs::primPath.token(), inputs::usePath.token(), db.getInstanceIndex()); if (primPath.IsEmpty()) return true; if (startTime <= kUninitializedStartTime || now < startTime) { // Set state variables try { startScale = tryGetPrimVec3dAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } startTime = now; targetScale = db.inputs.target(); // This is the first entry, start sleeping db.outputs.finished() = kExecutionAttributeStateLatentPush; return true; } int exp = std::min(std::max(int(db.inputs.exponent()), 0), 10); float speed = std::max(0.f, float(db.inputs.speed())); // delta step float alpha = std::min(std::max(speed * float(now - startTime), 0.f), 1.f); // Ease out by applying a shifted exponential to the alpha float alpha2 = easeInOut<float>(0.f, 1.f, alpha, exp); vec3d scale = GfLerp(alpha2, startScale, targetScale); // Write back to the prim try { trySetPrimAttribute(contextObj, nodeObj, primPath, XformUtils::ScaleAttrStr, scale); } catch (std::runtime_error const& error) { db.logError(error.what()); return false; } if (alpha2 < 1) { // still waiting db.outputs.finished() = kExecutionAttributeStateDisabled; return true; } else { // Completed the maneuver startTime = kUninitializedStartTime; db.outputs.finished() = kExecutionAttributeStateLatentFinish; return true; } } catch(const std::exception& e) { db.logError(e.what()); return true; } } }; REGISTER_OGN_NODE() } // action } // graph } // omni
4,116
C++
28.833333
115
0.570457
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimLocalToWorldTransform.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/common.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/relationship.h> #include <pxr/usd/usdGeom/xformCache.h> #include <pxr/usd/usdUtils/stageCache.h> #include <omni/graph/core/PostUsdInclude.h> #include <omni/fabric/FabricUSD.h> #include <OgnGetPrimLocalToWorldTransformDatabase.h> #include <omni/math/linalg/SafeCast.h> #include "PrimCommon.h" using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { class OgnGetPrimLocalToWorldTransform { public: static bool compute(OgnGetPrimLocalToWorldTransformDatabase& db) { // Get interfaces auto& nodeObj = db.abi_node(); const IPath& iPath = *db.abi_context().iPath; const IToken& iToken = *db.abi_context().iToken; const INode& iNode = *nodeObj.iNode; bool usePath = db.inputs.usePath(); long stageId = db.abi_context().iContext->getStageId(db.abi_context()); auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logWarning("Could not find USD stage %ld", stageId); return true; } // Find the target prim path one of 2 ways std::string destPrimPathStr; if (usePath) { // Use the absolute path NameToken primPath = db.inputs.primPath(); destPrimPathStr = db.tokenToString(primPath); if (destPrimPathStr.empty()) { db.logWarning("No target prim path specified"); return true; } } else { // Read the path from the relationship input on this compute node const char* thisPrimPathStr = iNode.getPrimPath(nodeObj); // Find our stage long stageId = db.abi_context().iContext->getStageId(db.abi_context()); auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logWarning("Could not find USD stage %ld", stageId); return true; } // Find this prim const pxr::UsdPrim thisPrim = stage->GetPrimAtPath(pxr::SdfPath(thisPrimPathStr)); if (!thisPrim.IsValid()) { db.logError("GetPrimAttribute requires USD backing when 'usePath' is false."); return false; } try { // Find the relationship const pxr::SdfPath primPath = getRelationshipPrimPath( db.abi_context(), nodeObj, OgnGetPrimLocalToWorldTransformAttributes::inputs::prim.m_token, db.getInstanceIndex()); destPrimPathStr = primPath.GetString(); } catch (const std::exception& e) { db.logError(e.what()); return false; } } // Retrieve a reference to the prim PathC destPath = iPath.getHandle(destPrimPathStr.c_str()); pxr::UsdPrim prim = stage->GetPrimAtPath(pxr::SdfPath(toSdfPath(destPath))); if (!prim.IsValid()) { return true; } pxr::UsdGeomXformCache xformCache; pxr::GfMatrix4d usdTransform = xformCache.GetLocalToWorldTransform(prim); db.outputs.localToWorldTransform() = omni::math::linalg::safeCastToOmni(usdTransform); return true; } }; REGISTER_OGN_NODE() } } }
4,069
C++
31.301587
111
0.608258
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransformLookAt.cpp
// Copyright (c) 2022-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnMakeTransformLookAtDatabase.h> #include <omni/math/linalg/matrix.h> using omni::math::linalg::matrix4d; namespace omni { namespace graph { namespace nodes { class OgnMakeTransformLookAt { public: static bool compute(OgnMakeTransformLookAtDatabase& db) { const auto& eyeInput = db.inputs.eye(); const auto& centerInput = db.inputs.center(); const auto& upInput = db.inputs.up(); matrix4d matrix; matrix.SetLookAt(centerInput,eyeInput,upInput); db.outputs.transform() = matrix; return true; } }; REGISTER_OGN_NODE() } } }
1,050
C++
22.886363
77
0.721905
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnAnd.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnAndDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include "OperatorComputeWrapper.h" #include "ResolveBooleanOpAttributes.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean AND on two inputs. * If a and b are arrays, AND operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnAndDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(a && b); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } else { std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); auto functor = [](bool const& a, bool& result) { result = static_cast<bool>(result && a); }; return ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), functor); } } } // namespace class OgnAnd { public: static bool compute(OgnAndDatabase& db) { return tryComputeOperator<OgnAndDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
2,438
C++
30.675324
137
0.687449
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNot.cpp
// Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnNotDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> namespace omni { namespace graph { namespace nodes { class OgnNot { public: static bool compute(OgnNotDatabase& db) { auto functor = [](bool const& valueIn, bool& valueOut) { valueOut = static_cast<bool>(!valueIn); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool>(db.inputs.valueIn(), db.outputs.valueOut(), functor); } static void onConnectionTypeResolve(const NodeObj& node) { auto valueIn = node.iNode->getAttributeByToken(node, inputs::valueIn.token()); auto valueOut = node.iNode->getAttributeByToken(node, outputs::valueOut.token()); auto valueInType = valueIn.iAttribute->getResolvedType(valueIn); // Require inputs to be resolved before determining result type if (valueInType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 2> attrs { valueIn, valueOut }; node.iNode->resolveCoupledAttributes(node, attrs.data(), attrs.size()); } } }; REGISTER_OGN_NODE() } } }
1,580
C++
28.277777
125
0.693038
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnXor.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnXorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean XOR on two inputs. * If a and b are arrays, XOR operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnXorDatabase& db) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(a != b); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } } // namespace class OgnXor { public: static bool compute(OgnXorDatabase& db) { return tryComputeOperator<OgnXorDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpAttributes(node, inputs::a.token(), inputs::b.token(), outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
2,002
C++
30.296875
133
0.686813
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNand.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnNandDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean NAND on two inputs. * If a and b are arrays, NAND operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnNandDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { // if there are no dynamic inputs, compute the result in one call auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(!(a && b)); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool, bool, bool>( db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } // The NAND operator is not associative. // If we have dynamic inputs, we must compute the result in two steps std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); // 1. apply the OR operator for all inputs auto andFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(a && result); }; bool result = ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), andFunctor); // the output attribute has to be cast to an input so that we can write the final value on it auto resultInput = omni::graph::core::ogn::constructInputFromOutput(db, db.outputs.result(), outputs::result.token()); // 2. negate the result auto negateFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(!a); }; result = result && ogn::compute::tryComputeWithArrayBroadcasting<bool, bool>(resultInput, db.outputs.result(), negateFunctor); return result; } } // namespace class OgnNand { public: static bool compute(OgnNandDatabase& db) { return tryComputeOperator<OgnNandDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
3,142
C++
36.416666
130
0.707511
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNor.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnNorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean NOR on two inputs. * If a and b are arrays, NOR operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnNorDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(!(a || b)); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } // The NOR operator is not associative. // If we have dynamic inputs, we must compute the result in two steps std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); // 1. apply the OR operator for all inputs auto orFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(a || result); }; bool result = ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), orFunctor); // the output attribute has to be cast to an input so that we can write the final value on it auto resultInput = omni::graph::core::ogn::constructInputFromOutput(db, db.outputs.result(), outputs::result.token()); // 2. negate the result auto negateFunctor = [](bool const& a, bool& result) { result = static_cast<bool>(!a); }; result = result && ogn::compute::tryComputeWithArrayBroadcasting<bool, bool>(resultInput, db.outputs.result(), negateFunctor); return result; } } // namespace class OgnNor { public: static bool compute(OgnNorDatabase& db) { return tryComputeOperator<OgnNorDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
3,107
C++
33.153846
137
0.69617
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/ResolveBooleanOpAttributes.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "ResolveBooleanOpAttributes.h" #include <omni/graph/core/iComputeGraph.h> #include <algorithm> #include <array> namespace omni { namespace graph { namespace nodes { void resolveBooleanOpAttributes(const core::NodeObj& node, const core::NameToken aToken, const core::NameToken bToken, const core::NameToken resultToken) { auto a = node.iNode->getAttributeByToken(node, aToken); auto b = node.iNode->getAttributeByToken(node, bToken); auto result = node.iNode->getAttributeByToken(node, resultToken); auto aType = a.iAttribute->getResolvedType(a); auto bType = b.iAttribute->getResolvedType(b); // Require inputs to be resolved before determining result type if (aType.baseType != BaseDataType::eUnknown && bType.baseType != BaseDataType::eUnknown) { std::array<AttributeObj, 3> attrs { a, b, result }; std::array<uint8_t, 3> arrayDepths { aType.arrayDepth, bType.arrayDepth, // Allow for a mix of singular and array inputs. If any input is an array, the output must be an array std::max(aType.arrayDepth, bType.arrayDepth) }; std::array<AttributeRole, 3> rolesBuf { aType.role, bType.role, // Copy the attribute role from the resolved type to the output type AttributeRole::eUnknown }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), nullptr, // tupleCounts default to scalar arrayDepths.data(), rolesBuf.data(), attrs.size()); } } void resolveBooleanOpDynamicAttributes(const core::NodeObj& node, const core::NameToken resultToken) { auto totalCount = node.iNode->getAttributeCount(node); std::vector<AttributeObj> allAttributes(totalCount); node.iNode->getAttributes(node, allAttributes.data(), totalCount); std::vector<AttributeObj> attributes; std::vector<uint8_t> arrayDepths; std::vector<AttributeRole> roles; attributes.reserve(totalCount - 2); arrayDepths.reserve(totalCount - 2); roles.reserve(totalCount - 2); uint8_t maxArrayDepth = 0; uint8_t maxComponentCount = 0; for (auto const& attr : allAttributes) { if (attr.iAttribute->getPortType(attr) == AttributePortType::kAttributePortType_Input) { auto resolvedType = attr.iAttribute->getResolvedType(attr); // all inputs must be connected and resolved to complete the output port type resolution if (resolvedType.baseType == BaseDataType::eUnknown) return; arrayDepths.push_back(resolvedType.arrayDepth); roles.push_back(resolvedType.role); maxComponentCount = std::max(maxComponentCount, resolvedType.componentCount); maxArrayDepth = std::max(maxArrayDepth, resolvedType.arrayDepth); attributes.push_back(attr); } } attributes.push_back(node.iNode->getAttributeByToken(node, resultToken)); // Allow for a mix of singular and array inputs. If any input is an array, the output must be an array arrayDepths.push_back(maxArrayDepth); // Copy the attribute role from the resolved type to the output type roles.push_back(AttributeRole::eUnknown); node.iNode->resolvePartiallyCoupledAttributes( node, attributes.data(), nullptr, // tupleCounts default to scalar arrayDepths.data(), roles.data(), attributes.size()); } } } }
4,020
C++
37.295238
115
0.670647
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OperatorComputeWrapper.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { template <typename T, typename F> static bool tryComputeOperator(F&& f, T t) { try { return f(t); } catch (std::exception &error) { t.logError("Could not perform function: %s", error.what()); } return false; } } } }
794
C
21.083333
77
0.709068
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/ResolveBooleanOpAttributes.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "omni/graph/core/Handle.h" namespace omni { namespace graph { namespace core { struct NodeObj; } namespace nodes { extern void resolveBooleanOpAttributes(const core::NodeObj&, const core::NameToken aToken, const core::NameToken bToken, const core::NameToken resultToken); extern void resolveBooleanOpDynamicAttributes(const core::NodeObj& node, const core::NameToken resultToken); } // namespace nodes } // namespace graph } // namespace omni
1,024
C
31.031249
108
0.695312
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnBooleanExpr.py
""" NOTE: DEPRECATED AS OF 1.26.0 IN FAVOUR OF INDIVIDAL BOOLEAN OP NODES This is the implementation of the OGN node defined in OgnBooleanExpr.ogn """ class OgnBooleanExpr: """ Boolean AND of two inputs """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" # convert to numpy bool arrays a = db.inputs.a b = db.inputs.b op = db.inputs.operator.lower() if not op: return False if op == "and": result = a and b elif op == "or": result = a or b elif op == "nand": result = not (a and b) elif op == "nor": result = not (a or b) elif op in ["xor", "!="]: result = a != b elif op in ["xnor", "=="]: result = a == b else: return False db.outputs.result = result return True
947
Python
22.699999
72
0.498416
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnOr.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION Or its licensors retain all intellectual property // Or proprietary rights in nor to this software, related documentation // Or any modifications thereto. Any use, reproduction, disclosure or // distribution of this software Or related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnOrDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include "ResolveBooleanOpAttributes.h" #include "OperatorComputeWrapper.h" namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { /** * Boolean OR on two inputs. * If a and b are arrays, OR operations will be performed pair-wise. Sizes of a and b must match. * If only one input is an array, the other input will be broadcast to the size of the array. * Returns an array of booleans if either input is an array, otherwise returning a boolean. * * @param db: database object * @return True if we can get a result properly, false if not */ bool tryCompute(OgnOrDatabase& db) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](bool const& a, bool const& b, bool& result) { result = static_cast<bool>(a || b); }; return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor); } else { std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() }; inputs.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputs.emplace_back(input()); auto functor = [](bool const& a, bool& result) { result = static_cast<bool>(result || a); }; return ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), functor); } } } // namespace class OgnOr { public: static bool compute(OgnOrDatabase& db) { return tryComputeOperator<OgnOrDatabase>(tryCompute, db); } static void onConnectionTypeResolve(const NodeObj& node) { resolveBooleanOpDynamicAttributes(node, outputs::result.token()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
2,457
C++
30.51282
137
0.68661
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnAttrType.cpp
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnAttrTypeDatabase.h" namespace omni { namespace graph { namespace core { class OgnAttrType { public: // Queries information about the type of a specified attribute in an input prim static bool compute(OgnAttrTypeDatabase& db) { auto bundledAttribute = db.inputs.data().attributeByName(db.inputs.attrName()); if (!bundledAttribute.isValid()) { db.outputs.baseType() = -1; db.outputs.componentCount() = -1; db.outputs.arrayDepth() = -1; db.outputs.role() = -1; db.outputs.fullType() = -1; } else { auto& attributeType = bundledAttribute.type(); db.outputs.baseType() = int(attributeType.baseType); db.outputs.componentCount() = attributeType.componentCount; db.outputs.arrayDepth() = attributeType.arrayDepth; db.outputs.role() = int(attributeType.role); db.outputs.fullType() = int(omni::fabric::TypeC(attributeType).type); } return true; } }; REGISTER_OGN_NODE() } } }
1,532
C++
29.058823
87
0.6547
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractAttr.cpp
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnExtractAttrDatabase.h" namespace omni { namespace graph { namespace core { class OgnExtractAttr { public: // Copies a single attribute from an input prim to an output attribute directly on the node, // if it exists in the input prim and matches the type of the output attribute. static bool compute(OgnExtractAttrDatabase& db) { const auto& inputToken = db.inputs.attrName(); auto extractedBundledAttribute = db.inputs.data().attributeByName(inputToken); if (!extractedBundledAttribute.isValid()) { db.logWarning("No attribute matching '%s' was found in the input bundle", db.tokenToString(inputToken)); return false; } const Type& inputType = extractedBundledAttribute.type(); auto& outputAttribute = db.outputs.output(); // This compute is not creating the attribute data, that should have been done externally. // The attribute type should match the one extracted though, otherwise connections can go astray. if (!outputAttribute.resolved()) { // Not resolved, so we have to resolve it now. This node is unusual in that the resolved output type // depends on run-time state of the bundle. AttributeObj out = db.abi_node().iNode->getAttributeByToken(db.abi_node(), outputs::output.m_token); out.iAttribute->setResolvedType(out, inputType); outputAttribute.reset( db.abi_context(), out.iAttribute->getAttributeDataHandle(out, db.getInstanceIndex()), out); } else { Type outType = outputAttribute.type(); if (!inputType.compatibleRawData(outType)) { db.logWarning("Attribute '%s' of type %s in the input bundle is not compatible with type %s", db.tokenToString(inputToken), getOgnTypeName(inputType).c_str(), getOgnTypeName(outType).c_str()); return false; } } outputAttribute.copyData( extractedBundledAttribute ); return true; } }; REGISTER_OGN_NODE() } } }
2,613
C++
38.60606
116
0.657865
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnIsPrimActive.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. #include "OgnIsPrimActiveDatabase.h" #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usdUtils/stageCache.h> #include <omni/graph/core/PostUsdInclude.h> #include <omni/fabric/FabricUSD.h> namespace omni { namespace graph { namespace nodes { class OgnIsPrimActive { public: // ---------------------------------------------------------------------------- static bool compute(OgnIsPrimActiveDatabase& db) { // At some point, only target input types will be supported, so at the time that the path input is deprecated, // also rename "primTarget" to "prim" auto const& primPath = db.inputs.prim(); auto const& prim = db.inputs.primTarget(); if(prim.size() > 0 || pxr::SdfPath::IsValidPathString(primPath)) { // Find our stage const GraphContextObj& context = db.abi_context(); long stageId = context.iContext->getStageId(context); auto stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logError("Could not find USD stage %ld", stageId); return false; } pxr::UsdPrim targetPrim = stage->GetPrimAtPath(prim.size() == 0 ? pxr::SdfPath(primPath) : omni::fabric::toSdfPath(prim[0])); if (!targetPrim) { // Should this really be an error?? When prim path input is removed, might be worth changing this to // just a warning instead db.logError("Could not find prim \"%s\" in USD stage", prim.size() == 0 ? primPath.data() : db.pathToString(prim[0])); db.outputs.active() = false; return false; } db.outputs.active() = targetPrim.IsActive(); } return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
2,546
C++
34.873239
134
0.598193
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWriteSetting.cpp
// Copyright (c) 2022-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "PrimCommon.h" #include <OgnWriteSettingDatabase.h> #include <carb/settings/ISettings.h> #include <carb/settings/SettingsUtils.h> #include <carb/dictionary/IDictionary.h> using carb::dictionary::ItemType; namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { bool isValidInput(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); Type valueType = db.inputs.value().type(); ItemType pathType; if (settings->isAccessibleAsArray(settingPath)) pathType = settings->getPreferredArrayType(settingPath); else pathType = settings->getItemType(settingPath); if (pathType == ItemType::eCount) return true; if (pathType == ItemType::eDictionary) return false; if (pathType == ItemType::eBool && valueType.baseType != BaseDataType::eBool) return false; if (pathType == ItemType::eInt && valueType.baseType != BaseDataType::eInt && valueType.baseType != BaseDataType::eInt64) return false; if (pathType == ItemType::eFloat && valueType.baseType != BaseDataType::eFloat && valueType.baseType != BaseDataType::eDouble) return false; if (pathType == ItemType::eString && valueType.baseType != BaseDataType::eToken) return false; size_t arrayLen = settings->getArrayLength(settingPath); if (valueType.componentCount > 1 && valueType.arrayDepth == 0) return arrayLen == valueType.componentCount; else if (valueType.componentCount == 1 && valueType.arrayDepth == 0) return arrayLen == 0; else if (valueType.componentCount == 1 && valueType.arrayDepth == 1) return true; else return false; } template<typename T> void setSetting(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto const inputValue = db.inputs.value().template get<T>(); settings->set(settingPath, *inputValue); } template<typename T> void setSettingArray(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto const inputValue = db.inputs.value().template get<T[]>(); size_t arrayLen = (size_t)settings->getArrayLength(settingPath); settings->setArray(settingPath, inputValue->data(), arrayLen); } template<typename T, size_t N> void setSettingArray(OgnWriteSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto const inputValue = db.inputs.value().template get<T[N]>(); settings->setArray(settingPath, *inputValue, N); } } // namespace class OgnWriteSetting { public: static bool compute(OgnWriteSettingDatabase& db) { auto const valueType = db.inputs.value().type(); carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); if (!isValidInput(db)) { std::stringstream ss; ss << valueType; db.logError("Setting Path '%s' is not compatible with type '%s'", settingPath, ss.str()); return false; } switch (valueType.baseType) { case BaseDataType::eBool: switch (valueType.arrayDepth) { case 0: setSetting<bool>(db); break; case 1: setSettingArray<bool>(db); break; } break; case BaseDataType::eInt: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: setSetting<int32_t>(db); break; case 1: setSettingArray<int32_t>(db); break; } break; case 2: setSettingArray<int32_t, 2>(db); break; case 3: setSettingArray<int32_t, 3>(db); break; case 4: setSettingArray<int32_t, 4>(db); break; } break; case BaseDataType::eInt64: switch (valueType.arrayDepth) { case 0: setSetting<int64_t>(db); break; case 1: setSettingArray<int64_t>(db); break; } break; case BaseDataType::eFloat: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: setSetting<float>(db); break; case 1: setSettingArray<float>(db); break; } break; case 2: setSettingArray<float, 2>(db); break; case 3: setSettingArray<float, 3>(db); break; case 4: setSettingArray<float, 4>(db); break; } break; case BaseDataType::eDouble: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: setSetting<double>(db); break; case 1: setSettingArray<double>(db); break; } break; case 2: setSettingArray<double, 2>(db); break; case 3: setSettingArray<double, 3>(db); break; case 4: setSettingArray<double, 4>(db); break; } break; case BaseDataType::eToken: switch (valueType.arrayDepth) { case 0: { auto const inputValue = db.inputs.value().template get<OgnToken>(); char const* inputString = db.tokenToString(*inputValue); settings->set(settingPath, inputString); break; } case 1: { auto const inputValue = db.inputs.value().template get<OgnToken[]>(); std::vector<char const*> inputString(inputValue.size()); for (size_t i = 0; i < inputValue.size(); i++) inputString[i] = db.tokenToString((*inputValue)[i]); size_t arrayLen = settings->getArrayLength(settingPath); settings->setArray(settingPath, inputString.data(), arrayLen); break; } } break; default: { db.logError("Type %s not supported", getOgnTypeName(valueType).c_str()); return false; } } db.outputs.execOut() = kExecutionAttributeStateEnabled; return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
8,397
C++
30.931559
130
0.558176
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadTime.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnReadTimeDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnReadTime { public: static bool compute(OgnReadTimeDatabase& db) { const auto& contextObj = db.abi_context(); const IGraphContext* const iContext = contextObj.iContext; db.outputs.deltaSeconds() = iContext->getElapsedTime(contextObj); db.outputs.isPlaying() = iContext->getIsPlaying(contextObj); db.outputs.time() = iContext->getTime(contextObj); db.outputs.frame() = iContext->getFrame(contextObj); db.outputs.timeSinceStart() = iContext->getTimeSinceStart(contextObj); db.outputs.absoluteSimTime() = iContext->getAbsoluteSimTime(contextObj); return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
1,239
C++
27.837209
80
0.72155
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnHasAttr.cpp
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnHasAttrDatabase.h" namespace omni { namespace graph { namespace core { class OgnHasAttr { public: // Checks whether an input prim contains the specified attribute static bool compute(OgnHasAttrDatabase& db) { db.outputs.output() = db.inputs.data().attributeByName(db.inputs.attrName()).isValid(); return true; } }; REGISTER_OGN_NODE() } } }
825
C++
23.294117
95
0.74303
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractBundle.cpp
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "OgnExtractBundleDatabase.h" #include "ReadPrimCommon.h" #include <omni/fabric/FabricUSD.h> #include <omni/kit/commands/ICommandBridge.h> namespace omni { namespace graph { namespace nodes { class OgnExtractBundle { private: std::unordered_set<NameToken> m_added; public: static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { // When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected. AttributeObj inputBundleAttribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnExtractBundleAttributes::inputs::bundle.m_token); inputBundleAttribObj.iAttribute->registerValueChangedCallback( inputBundleAttribObj, onInputBundleValueChanged, true); } static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData) { NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); // If the graph is currently disabled then delay the update until the next compute. // Arguably this should be done at the message propagation layer, then this wouldn't be necessary. if (graphObj.iGraph->isDisabled(graphObj)) { return; } GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); cleanOutput(context, nodeObj, kAccordingToContextIndex); } static void cleanOutput(GraphContextObj const& contextObj, NodeObj const& nodeObj, InstanceIndex instanceIdx) { // clear the output bundles auto outputTokens = { OgnExtractBundleAttributes::outputs::passThrough.m_token }; for (auto& outputToken : outputTokens) { BundleHandle outBundle = contextObj.iContext->getOutputBundle(contextObj, nodeObj.nodeContextHandle, outputToken, instanceIdx); contextObj.iContext->clearBundleContents(contextObj, outBundle); } // remove dynamic attributes BundleType empty; updateAttributes(contextObj, nodeObj, empty, instanceIdx); } static void updateAttributes(GraphContextObj const& contextObj, NodeObj const& nodeObj, BundleType const& bundle, InstanceIndex instIdx) { OgnExtractBundle& state = OgnExtractBundleDatabase::sInternalState<OgnExtractBundle>(nodeObj); omni::kit::commands::ICommandBridge::ScopedUndoGroup scopedUndoGroup; extractBundle_reflectBundleDynamicAttributes(nodeObj, contextObj, bundle, state.m_added, instIdx); } // Copies attributes from an input bundle to attributes directly on the node static bool compute(OgnExtractBundleDatabase& db) { auto& contextObj = db.abi_context(); auto& nodeObj = db.abi_node(); auto const& inputBundle = db.inputs.bundle(); if (!inputBundle.isValid()) { cleanOutput(contextObj, nodeObj, db.getInstanceIndex()); return false; } // extract attributes directly from input bundle updateAttributes(contextObj, nodeObj, inputBundle, db.getInstanceIndex()); db.outputs.passThrough() = inputBundle; return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
3,936
C++
34.790909
118
0.692581
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetPrims.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnGetPrimsDatabase.h" #include "PrimCommon.h" namespace omni { namespace graph { namespace nodes { class OgnGetPrims { public: static bool compute(OgnGetPrimsDatabase& db) { IBundle2* outputBundle = db.outputs.bundle().abi_bundleInterface(); outputBundle->clearContents(true); IConstBundle2* inputBundle = db.inputs.bundle().abi_bundleInterface(); size_t const childBundleCount = inputBundle->getChildBundleCount(); // nothing to do if (childBundleCount == 0) { return true; } std::vector<ConstBundleHandle> childBundleHandles(childBundleCount); inputBundle->getConstChildBundles(childBundleHandles.data(), childBundleHandles.size()); std::vector<ConstBundleHandle> bundles; bundles.reserve(childBundleCount); GraphContextObj const& context = db.abi_context(); if (db.inputs.prims().size() != 0) { // We want to have same order of `prims` input in the output. // Unfortunately, the order of child bundles is not preserved, OM- // Construct children lookup map std::unordered_map<fabric::TokenC, ConstBundleHandle> pathToChildMap; for (ConstBundleHandle const& childBundleHandle : childBundleHandles) { ConstAttributeDataHandle const attr = getAttributeR(context, childBundleHandle, PrimAdditionalAttrs::kSourcePrimPathToken); if (fabric::Token const* data = getDataR<fabric::Token>(context, attr)) { pathToChildMap.emplace(data->asTokenC(), childBundleHandle); } } // Search for inputTargets auto const& inputPrims = db.inputs.prims(); for (auto const& inputTarget : inputPrims) { auto const asToken = fabric::asInt(fabric::toSdfPath(inputTarget).GetToken()); if(auto it = pathToChildMap.find(asToken); it != pathToChildMap.end()) { bundles.push_back(it->second); } } } else { // By default all primitives matching the path/type patterns are added to the output bundle; // when the "inverse" option is on, all mismatching primitives will be added instead. bool const inverse = db.inputs.inverse(); // Use wildcard pattern matching for prim type. std::string const typePattern(db.inputs.typePattern()); PatternMatcher const typeMatcher(typePattern); // Use wildcard pattern matching for prim path. std::string const pathPattern(db.inputs.pathPattern()); PatternMatcher const pathMatcher(pathPattern); auto matchesPattern = [&context](ConstBundleHandle& bundle, NameToken attrName, PatternMatcher const& patternMatcher) { ConstAttributeDataHandle attr = getAttributeR(context, bundle, attrName); return attr.isValid() && patternMatcher.matches(*getDataR<NameToken>(context, attr)); }; for (ConstBundleHandle& childBundleHandle : childBundleHandles) { bool const matched = matchesPattern(childBundleHandle, PrimAdditionalAttrs::kSourcePrimTypeToken, typeMatcher) && matchesPattern(childBundleHandle, PrimAdditionalAttrs::kSourcePrimPathToken, pathMatcher); if (matched != inverse) { bundles.push_back(childBundleHandle); } } } if (!bundles.empty()) { outputBundle->copyChildBundles(bundles.data(), bundles.size()); } return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
4,352
C++
35.579832
112
0.616728
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrims.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /* _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ OgnWritePrims is deprecated. Use WritePrimsV2 instead. OgnWritePrims always writes back to the original sourcePrimPath from input bundle. The successor OgnWritePrimsV2 removed this feedback loop. Target(s) is always required to write prims to. This old OgnWritePrims version is kept for backward compatibility. */ #include "OgnWritePrimsDatabase.h" #include "WritePrimCommon.h" #include "SpanUtils.h" namespace omni { namespace graph { namespace nodes { class OgnWritePrims { static size_t getConnectedPrimCount(OgnWritePrimsDatabase& db) { GraphContextObj const& contextObj = db.abi_context(); NodeObj const& nodeObj = db.abi_node(); NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle; NameToken const primsToken = inputs::primsBundle.token(); return contextObj.iContext->getInputTargetCount(contextObj, nodeHandle, primsToken, db.getInstanceIndex()); } public: static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { ogn::OmniGraphDatabase::logWarning(nodeObj, "WritePrim node is deprecated, use WritePrimV2 instead"); } static bool compute(OgnWritePrimsDatabase& db) { auto result = WritePrimResult::None; // Since the bundle input allows multiple connections, we need to collect all of them size_t const connectedPrimCount = getConnectedPrimCount(db); // Even when we have no connected prims, we still return true, because the node *did* compute, and execOut // attribute will be set. if (connectedPrimCount > 0) { auto handler = [&db, &result](gsl::span<ConstBundleHandle> connectedBundleHandles) { GraphContextObj const& contextObj = db.abi_context(); NodeObj const& nodeObj = db.abi_node(); NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle; NameToken const primsToken = inputs::primsBundle.token(); bool const usdWriteBack = db.inputs.usdWriteBack(); ogn::const_string const attrPattern = db.inputs.attrNamesToExport(); ogn::const_string const pathPattern = db.inputs.pathPattern(); ogn::const_string const typePattern = db.inputs.typePattern(); WritePrimMatchers const matchers{ attrPattern, pathPattern, typePattern }; contextObj.iContext->getInputTargets(contextObj, nodeHandle, primsToken, (omni::fabric::PathC*)(connectedBundleHandles.data()), db.getInstanceIndex()); // Write back all bundles WritePrimDiagnostics diagnostics; for (ConstBundleHandle const& bundleHandle : connectedBundleHandles) { WritePrimResult const subResult = writeBundleHierarchyToPrims( contextObj, nodeObj, diagnostics, bundleHandle, matchers, usdWriteBack); mergeWritePrimResult(result, subResult); } // Report skipped invalid bundles mergeWritePrimResult(result, diagnostics.report(contextObj, nodeObj)); }; withStackScopeBuffer<ConstBundleHandle>(connectedPrimCount, handler); } auto const ok = result != WritePrimResult::Fail; if (ok) { db.outputs.execOut() = kExecutionAttributeStateEnabled; } return ok; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
4,470
C++
37.213675
167
0.602461
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetGraphTargetPrim.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnGetGraphTargetPrimDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnGetGraphTargetPrim { public: static size_t computeVectorized(OgnGetGraphTargetPrimDatabase& db, size_t count) { auto targets = db.getGraphTargets(count); for (size_t idx = 0; idx < count; idx++) { auto outPrims = db.outputs.prim(idx); outPrims.resize(1); outPrims[0] = db.tokenToPath(targets[idx]); } return count; } }; REGISTER_OGN_NODE() } } }
1,038
C++
23.16279
84
0.696532
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnInsertAttr.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 "OgnInsertAttrDatabase.h" namespace omni { namespace graph { namespace core { class OgnInsertAttr { public: // Copies all attributes from an input prim to the output prim, as well as copying an additional // "attrToInsert" attribute from the node itself with a specified name. static bool compute(OgnInsertAttrDatabase& db) { const auto& outputAttrNameToken = db.inputs.outputAttrName(); const auto& inputBundle = db.inputs.data(); auto& outputBundle = db.outputs.data(); // Start by copying the input prim into the output prim. outputBundle = inputBundle; if (!outputBundle.isValid()) { db.logWarning("Failed to copy input bundle to the output"); return false; } const auto& inputToInsert = db.inputs.attrToInsert(); if (!inputToInsert.isValid()) { db.logWarning("Input attribute to insert is not valid"); return false; } outputBundle.insertAttribute(inputToInsert, outputAttrNameToken); return true; } }; REGISTER_OGN_NODE() } } }
1,568
C++
28.603773
100
0.684311
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimBundle.cpp
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. /* _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ ReadPrimBundle is deprecated and should not be used. First version of ReadPrimBundle outputs 'Single Primitive in a Bundle'(SPiB). The successor ReadPrimsBundle outputs 'Multiple Primitives in a Bundle'(MPiB). This operator is kept for backward compatibility. */ // clang-format off #include "UsdPCH.h" #include <omni/graph/core/PreUsdInclude.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/prim.h> #include <omni/graph/core/PostUsdInclude.h> // clang-format on #include "OgnReadPrimBundleDatabase.h" #include <omni/fabric/FabricUSD.h> #include "PrimCommon.h" #include "ReadPrimCommon.h" #include <omni/usd/UsdContext.h> using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { /************************************************************************/ /* */ /************************************************************************/ class OgnReadPrimBundle { public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { char const* primNodePath = nodeObj.iNode->getPrimPath(nodeObj); CARB_LOG_WARN("ReadPrimBundle node is deprecated: %s, use ReadPrims instead", primNodePath); // When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected. AttributeObj inputBundleAttribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimBundleAttributes::inputs::prim.m_token); inputBundleAttribObj.iAttribute->registerValueChangedCallback( inputBundleAttribObj, onInputBundleValueChanged, true); } // ---------------------------------------------------------------------------- static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData) { NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); // If the graph is currently disabled then delay the update until the next compute. // Arguably this should be done at the message propagation layer, then this wouldn't be necessary. if (graphObj.iGraph->isDisabled(graphObj)) { return; } // clear the output bundles GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); auto outputTokens = { OgnReadPrimBundleAttributes::outputs::primBundle.m_token }; for (auto& outputToken : outputTokens) { BundleHandle outBundle = context.iContext->getOutputBundle( context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex); context.iContext->clearBundleContents(context, outBundle); } } // ---------------------------------------------------------------------------- static PathC getPath(OgnReadPrimBundleDatabase& db) { return readPrimBundle_getPath(db.abi_context(), db.abi_node(), OgnReadPrimBundleAttributes::inputs::prim.m_token, db.inputs.usePath(), db.inputs.primPath(), db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static bool writeToBundle(OgnReadPrimBundleDatabase& db, PathC inputPath, bool force, pxr::UsdTimeCode const& time) { return readPrimBundle_writeToBundle(db.abi_context(), db.abi_node(), inputPath, db.inputs.attrNamesToImport(), db.outputs.primBundle(), force, db.inputs.computeBoundingBox(), time, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static void clean(OgnReadPrimBundleDatabase& db) { db.outputs.primBundle().clear(); } // ---------------------------------------------------------------------------- static bool compute(OgnReadPrimBundleDatabase& db) { bool inputChanged = false; if (db.state.usePath() != db.inputs.usePath()) { db.state.usePath() = db.inputs.usePath(); inputChanged = true; } // bounding box changed if (db.state.computeBoundingBox() != db.inputs.computeBoundingBox()) { db.state.computeBoundingBox() = db.inputs.computeBoundingBox(); inputChanged = true; } // attribute filter changed NameToken const attrNamesToImport = db.inputs.attrNamesToImport(); if (db.state.attrNamesToImport() != attrNamesToImport.token) { db.state.attrNamesToImport() = attrNamesToImport.token; inputChanged = true; } return readPrimBundle_compute<OgnReadPrimBundle>(db, inputChanged); } static bool updateNodeVersion(GraphContextObj const& context, NodeObj const& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { bool upgraded = false; if (oldVersion < 4) { // backward compatibility: `inputs:attrNamesToImport` // Prior to this version `inputs:attrNamesToImport` attribute did not support wild cards. // The meaning of an empty string was to include all attributes. With the introduction of the wild cards // we need to convert an empty string to "*" in order to include all attributes. static Token const value{ "*" }; if (nodeObj.iNode->getAttributeExists(nodeObj, "inputs:attrNamesToImport")) { AttributeObj attr = nodeObj.iNode->getAttribute(nodeObj, "inputs:attrNamesToImport"); auto roHandle = attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex); Token const* roValue = getDataR<Token const>(context, roHandle); if (roValue && roValue->getString().empty()) { Token* rwValue = getDataW<Token>( context, attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex)); *rwValue = value; } } else { nodeObj.iNode->createAttribute(nodeObj, "inputs:attrNamesToImport", Type(BaseDataType::eToken), &value, nullptr, kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr); } upgraded = true; } if (oldVersion < 6) { upgraded |= upgradeUsdTimeCodeInput(context, nodeObj); } return upgraded; } return false; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
7,985
C++
40.164948
137
0.542142
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetAttrNames.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 "OgnGetAttrNamesDatabase.h" #include <algorithm> namespace omni { namespace graph { namespace core { class OgnGetAttrNames { public: // Retrieves the names of all of the attributes contained in the input prim, optionally sorted. static bool compute(OgnGetAttrNamesDatabase& db) { auto& inputBundle = db.inputs.data(); auto attributesInBundle = inputBundle.attributeCount(); auto& arrayNames = db.outputs.output(); arrayNames.resize(attributesInBundle); // Empty bundles yield empty output arrays, which is okay if (attributesInBundle == 0) { return true; } // Get all of the bundle member names into the output (as-is for now). std::transform(inputBundle.begin(), inputBundle.end(), arrayNames.begin(), [](const ogn::RuntimeAttribute<ogn::kOgnInput, ogn::kCpu>& attribute) -> NameToken { return attribute.name(); }); // If sorting was requested do that now if (db.inputs.sort()) { auto sortByNameString = [&db](const NameToken& a, const NameToken& b) -> bool { const char* aString = db.tokenToString(a); const char* bString = db.tokenToString(b); return strcmp(aString, bString) < 0; }; std::sort(arrayNames.data(), arrayNames.data() + attributesInBundle, sortByNameString); } return true; } }; REGISTER_OGN_NODE() } } }
1,927
C++
31.677966
136
0.655423
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnArrayLength.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 "OgnArrayLengthDatabase.h" namespace omni { namespace graph { namespace core { class OgnArrayLength { public: // Outputs the length of a specified array attribute in an input prim, // or 1 if the attribute is not an array attribute. static bool compute(OgnArrayLengthDatabase& db) { auto bundledAttribute = db.inputs.data().attributeByName(db.inputs.attrName()); db.outputs.length() = bundledAttribute.isValid() ? bundledAttribute.size() : 0; return true; } }; REGISTER_OGN_NODE() } } }
980
C++
25.513513
87
0.736735
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadOmniGraphValue.cpp
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnReadOmniGraphValueDatabase.h> #include <omni/graph/core/IAttributeType.h> #include <omni/graph/core/StringUtils.h> #include <omni/graph/core/CppWrappers.h> #include <omni/usd/UsdContext.h> #include "PrimCommon.h" using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { class OgnReadOmniGraphValue { // ---------------------------------------------------------------------------- // Called by OG when our queried attrib changes. We want to catch the case of changing the queried attribute interactively static void onValueChanged(const AttributeObj& attrObj, void const* userData) { onConnectionTypeResolve(attrObj.iAttribute->getNode(attrObj)); } public: static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { // We need to check resolution if any of our relevant inputs change std::array<NameToken, 2> attribNames{ inputs::path.token(), inputs::name.token() }; for (auto const& attribName : attribNames) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); } } static void onConnectionTypeResolve(const NodeObj& nodeObj) { // FIXME: Be pedantic about validity checks - this can be run directly by the TfNotice so who knows // when or where this is happening GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) }; if (context.contextHandle == kInvalidGraphContextHandle) return; // reasoning on the "current" instance const auto instIdx = kAccordingToContextIndex; // Get the queried attribute path ConstAttributeDataHandle constHandle = getAttributeR(context, nodeObj.nodeContextHandle, inputs::path.token(), instIdx); if (!constHandle.isValid()) return; const char* pathCStr = *getDataR<const char*>(context, constHandle); if(!pathCStr) return; std::string pathStr(pathCStr, getElementCount(context, constHandle)); if (pathStr == "") return; auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>(); auto path = pathInterface->getHandle(std::string(pathStr).c_str()); // Get the queried attribute name constHandle = getAttributeR(context, nodeObj.nodeContextHandle, inputs::name.token(), instIdx); if (!constHandle.isValid()) return; NameToken attributeName = *getDataR<NameToken>(context, constHandle); const char* attributeNameStr = context.iToken->getText(attributeName); if (!attributeNameStr || strlen(attributeNameStr) == 0) return; // Get the queried attribute ConstAttributeDataHandle inputDataHandle; NodeObj inputNodeObj = graphObj.iGraph->getNode(graphObj, std::string(pathStr).c_str()); if(inputNodeObj.nodeHandle != kInvalidNodeHandle) { // node AttributeObj inputAttrib = inputNodeObj.iNode->getAttributeByToken(inputNodeObj, attributeName); if(!inputAttrib.iAttribute->isValid(inputAttrib)) return; inputDataHandle = inputAttrib.iAttribute->getConstAttributeDataHandle(inputAttrib, instIdx); } else { // bundle ConstBundleHandle attributeHandle(path.path); if(!attributeHandle.isValid()) return; const Token attrName(attributeName); inputDataHandle = getAttributeR(context, attributeHandle, attrName); } if(!inputDataHandle.isValid()) return; // Try resolve output Type attribType = context.iAttributeData->getType(context, inputDataHandle); tryResolveOutputAttribute(nodeObj, outputs::value.token(), attribType); } static bool compute(OgnReadOmniGraphValueDatabase& db) { // Get interfaces auto& nodeObj = db.abi_node(); const GraphContextObj context = db.abi_context(); GraphObj graph = nodeObj.iNode->getGraph(nodeObj); auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>(); // Get queried attribute path auto const& pathStr = db.inputs.path(); if(pathStr.empty()) { return false; } auto path = pathInterface->getHandle(std::string(pathStr).c_str()); // Get queried attribute name NameToken attributeName = db.inputs.name(); const char* attributeNameStr = db.tokenToString(attributeName); if(std::string(attributeNameStr) == "") { return false; } // Get queried attribute ConstAttributeDataHandle inputDataHandle; NodeObj inputNodeObj = graph.iGraph->getNode(graph, std::string(pathStr).c_str()); if(inputNodeObj.nodeHandle != kInvalidNodeHandle) { // node AttributeObj inputAttrib = inputNodeObj.iNode->getAttributeByToken(inputNodeObj, attributeName); if(inputAttrib.iAttribute->isValid(inputAttrib)) { inputDataHandle = inputAttrib.iAttribute->getConstAttributeDataHandle(inputAttrib, db.getInstanceIndex()); } } else { // bundle ConstBundleHandle attributeHandle(path.path); if(!attributeHandle.isValid()) { return false; } const Token attrName(attributeNameStr); inputDataHandle = getAttributeR(context, attributeHandle, attrName); } if(!inputDataHandle.isValid()) { db.logWarning("Attribute \"%s.%s\" can't be found in Fabric", ((std::string)pathStr).c_str(), attributeNameStr); return false; } Type attribType = context.iAttributeData->getType(context, inputDataHandle); // Determine if the output attribute has already been resolved to an incompatible type if (db.outputs.value().resolved()) { Type outType = db.outputs.value().type(); if (!attribType.compatibleRawData(outType)) { db.logError("%s is not compatible with type %s, please disconnect to change source attrib", attributeNameStr, getOgnTypeName(db.outputs.value().type()).c_str()); return false; } } // If it's resolved, we already know that it is compatible from the above check of the USD AttributeObj outAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::value.m_token); if (!db.outputs.value().resolved()) { outAttrib.iAttribute->setResolvedType(outAttrib, attribType); db.outputs.value().reset( context, outAttrib.iAttribute->getAttributeDataHandle(outAttrib, db.getInstanceIndex()), outAttrib); } // Copy queried attribute value to node's output AttributeDataHandle outDataHandle = outAttrib.iAttribute->getAttributeDataHandle(outAttrib, db.getInstanceIndex()); context.iAttributeData->copyData(outDataHandle, context, inputDataHandle); return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
8,149
C++
37.995215
126
0.63787
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadSetting.cpp
// Copyright (c) 2022-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "PrimCommon.h" #include <OgnReadSettingDatabase.h> #include <carb/settings/ISettings.h> #include <carb/settings/SettingsUtils.h> #include <carb/dictionary/IDictionary.h> using carb::dictionary::ItemType; namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { template<typename T> void getSetting(OgnReadSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto outputValue = db.outputs.value().template get<T>(); *outputValue = settings->get<T>(settingPath); } } // namespace class OgnReadSetting { public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { AttributeObj attrObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::settingPath.m_token); attrObj.iAttribute->registerValueChangedCallback(attrObj, onValueChanged, true); onValueChanged(attrObj, nullptr); } // ---------------------------------------------------------------------------- // Called by OG to resolve the input type static void onConnectionTypeResolve(NodeObj const& nodeObj) { auto attrObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::settingPath.m_token); auto graphObj = nodeObj.iNode->getGraph(nodeObj); if (graphObj.graphHandle == kInvalidGraphHandle) return; auto context = graphObj.iGraph->getDefaultGraphContext(graphObj); if (context.contextHandle == kInvalidGraphContextHandle) return; ConstAttributeDataHandle attrDataHandle = attrObj.iAttribute->getAttributeDataHandle(attrObj, kAccordingToContextIndex); if (!attrDataHandle.isValid()) return; Type type(BaseDataType::eUnknown); auto stringLen = getElementCount(context, attrDataHandle); auto cstrPtrPtr = getDataR<char const*>(context, attrDataHandle); if (stringLen && cstrPtrPtr && *cstrPtrPtr) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = std::string(*cstrPtrPtr, stringLen); char const* settingPath = strSettingPath.c_str(); ItemType pathType; if (settings->isAccessibleAsArray(settingPath)) pathType = settings->getPreferredArrayType(settingPath); else pathType = settings->getItemType(settingPath); if (pathType == ItemType::eBool) type.baseType = BaseDataType::eBool; else if (pathType == ItemType::eInt) type.baseType = BaseDataType::eInt; else if (pathType == ItemType::eFloat) type.baseType = BaseDataType::eFloat; else if (pathType == ItemType::eString) type.baseType = BaseDataType::eToken; else CARB_LOG_ERROR("Invalid Setting Path!"); if (settings->isAccessibleAsArray(settingPath)) { size_t arrayLen = (size_t)settings->getArrayLength(settingPath); if ((pathType == ItemType::eFloat || pathType == ItemType::eInt) && (arrayLen > 1 && arrayLen <= 4)) type.componentCount = (uint8_t)arrayLen; else type.arrayDepth = 1; } } omni::graph::nodes::tryResolveInputAttribute(nodeObj, outputs::value.m_token, type); } // ---------------------------------------------------------------------------- // Called by OG when the value of the settingPath changes static void onValueChanged(AttributeObj const& attrObj, void const* userData) { auto nodeObj = attrObj.iAttribute->getNode(attrObj); if (nodeObj.nodeHandle == kInvalidNodeHandle) return; onConnectionTypeResolve(nodeObj); } static bool compute(OgnReadSettingDatabase& db) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); std::string strSettingPath = db.inputs.settingPath(); char const* settingPath = strSettingPath.c_str(); auto const valueType = db.outputs.value().type(); size_t arrayLen = settings->getArrayLength(settingPath); switch (valueType.baseType) { case BaseDataType::eBool: switch (valueType.arrayDepth) { case 0: getSetting<bool>(db); break; case 1: { auto outputValue = db.outputs.value().template get<bool[]>(); outputValue->resize(arrayLen); settings->getAsBoolArray(settingPath, outputValue->data(), arrayLen); break; } } break; case BaseDataType::eInt: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: getSetting<int32_t>(db); break; case 1: { auto outputValue = db.outputs.value().template get<int32_t[]>(); outputValue->resize(arrayLen); settings->getAsIntArray(settingPath, outputValue->data(), arrayLen); break; } } break; case 2: { auto outputValue = db.outputs.value().template get<int32_t[2]>(); settings->getAsIntArray(settingPath, *outputValue, 2); break; } case 3: { auto outputValue = db.outputs.value().template get<int32_t[3]>(); settings->getAsIntArray(settingPath, *outputValue, 3); break; } case 4: { auto outputValue = db.outputs.value().template get<int32_t[4]>(); settings->getAsIntArray(settingPath, *outputValue, 4); break; } } break; case BaseDataType::eInt64: switch (valueType.arrayDepth) { case 0: getSetting<int64_t>(db); break; case 1: { auto outputValue = db.outputs.value().template get<int64_t[]>(); outputValue->resize(arrayLen); settings->getAsInt64Array(settingPath, outputValue->data(), arrayLen); break; } } break; case BaseDataType::eFloat: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: getSetting<float>(db); break; case 1: { auto outputValue = db.outputs.value().template get<float[]>(); outputValue->resize(arrayLen); settings->getAsFloatArray(settingPath, outputValue->data(), arrayLen); break; } } break; case 2: { auto outputValue = db.outputs.value().template get<float[2]>(); settings->getAsFloatArray(settingPath, *outputValue, 2); break; } case 3: { auto outputValue = db.outputs.value().template get<float[3]>(); settings->getAsFloatArray(settingPath, *outputValue, 3); break; } case 4: { auto outputValue = db.outputs.value().template get<float[4]>(); settings->getAsFloatArray(settingPath, *outputValue, 4); break; } } break; case BaseDataType::eDouble: switch (valueType.componentCount) { case 1: switch (valueType.arrayDepth) { case 0: getSetting<double>(db); break; case 1: { auto outputValue = db.outputs.value().template get<double[]>(); outputValue->resize(arrayLen); settings->getAsFloat64Array(settingPath, outputValue->data(), arrayLen); break; } } break; case 2: { auto outputValue = db.outputs.value().template get<double[2]>(); settings->getAsFloat64Array(settingPath, *outputValue, 2); break; } case 3: { auto outputValue = db.outputs.value().template get<double[3]>(); settings->getAsFloat64Array(settingPath, *outputValue, 3); break; } case 4: { auto outputValue = db.outputs.value().template get<double[4]>(); settings->getAsFloat64Array(settingPath, *outputValue, 4); break; } } break; case BaseDataType::eToken: switch (valueType.arrayDepth) { case 0: { auto outputValue = db.outputs.value().template get<OgnToken>(); std::string stringSetting = carb::settings::getString(settings, settingPath); *outputValue = db.stringToToken(stringSetting.c_str()); break; } case 1: { auto outputValue = db.outputs.value().template get<OgnToken[]>(); outputValue->resize(arrayLen); std::vector<std::string> stringSetting = carb::settings::getStringArray(settings, settingPath); for(size_t i = 0; i < arrayLen; i++) (*outputValue)[i] = db.stringToToken(stringSetting[i].c_str()); break; } } break; default: { db.logError("Type %s not supported", getOgnTypeName(valueType).c_str()); return false; } } return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
11,297
C++
34.980892
116
0.524653
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrim.cpp
// Copyright (c) 2019-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. // // WARNING! // The following code uses low-level ABI functionality and should not be copied for other purposes when such // low level access is not required. Please use the OGN-generated API whenever possible. // clang-format off #include "UsdPCH.h" // clang-format on #include "OgnWritePrimDatabase.h" #define RETURN_TRUE_EXEC \ { \ db.outputs.execOut() = kExecutionAttributeStateEnabled;\ return true; \ } #include <omni/fabric/FabricUSD.h> #include <omni/graph/core/IAttributeType.h> #include <omni/graph/core/StringUtils.h> #include <omni/kit/PythonInterOpHelper.h> #include <omni/usd/UsdContext.h> #include "PrimCommon.h" using namespace omni::fabric; constexpr size_t kNonDynamicAttributeCount = 2; namespace omni { namespace graph { namespace nodes { class OgnWritePrim { public: // ---------------------------------------------------------------------------- // Called by OG when our prim attrib changes. We want to catch the case of changing the prim attribute interactively static void onValueChanged(const AttributeObj& attrObj, const void* userData) { NodeObj nodeObj = attrObj.iAttribute->getNode(attrObj); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); updateForPrim(context, nodeObj, true /* removeStale */, kAccordingToContextIndex, pxr::SdfPath::EmptyPath(), false); } // ---------------------------------------------------------------------------- static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnWritePrimAttributes::inputs::prim.m_token); // Register for value changed - even when connected. Because it's possible that an OgnPrim // connection will be left dangling after clearing the relationship. attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); } /** ---------------------------------------------------------------------------- * Updates the dynamic attributes for the given node. * @param nodeObj The WritePrim node in question * @param removeStale true means we should remove any dynamic attributes which aren't for the current inputs:prim */ static bool updateForPrim(GraphContextObj context, NodeObj nodeObj, bool removeStale, InstanceIndex instanceIndex, pxr::SdfPath targetPrimPath, bool usdWriteBack) { const INode& iNode = *nodeObj.iNode; const IAttribute& iAttribute = *carb::getCachedInterface<IAttribute>(); // Find our stage auto iFabricUsd = carb::getCachedInterface<IFabricUsd>(); CARB_ASSERT(iFabricUsd); pxr::UsdStageRefPtr stage; omni::fabric::FabricId fabricId; std::tie(fabricId, stage) = getFabricForNode(context, nodeObj); if (fabricId == omni::fabric::kInvalidFabricId) return false; // Find the input prim via the relationship pxr::UsdPrim targetPrim; const char* thisPrimPathStr = iNode.getPrimPath(nodeObj); pxr::SdfPath thisPrimPath(thisPrimPathStr); { // Read the path from the relationship input on this compute node const pxr::UsdPrim thisPrim = stage->GetPrimAtPath(thisPrimPath); if (!thisPrim.IsValid()) { CARB_LOG_ERROR("ReadPrim requires USD backing."); return false; } if (!targetPrimPath.IsEmpty()) { targetPrim = stage->GetPrimAtPath(targetPrimPath); if (!targetPrim) { CARB_LOG_ERROR_ONCE("Could not find specified prim at path %s", targetPrimPath.GetText()); return false; } } else { // No input prim specified. This is ok, but we may have stale attributes. We rely on this function being // called with removeStale = true to do the clean up. if (!removeStale) return true; // If we have more attributes than we get by default, we know there is at least one dynamic attribute to // be removed size_t numAttributes = iNode.getAttributeCount(nodeObj); if (numAttributes > kNonDynamicAttributeCount) { // Build a python script to disconnect and delete all dynamic attribs in one shot static const char* cmdFmt = "import omni.graph.core as og\n" "og.remove_attributes_if(\"%s\", lambda a: a.is_dynamic() and og.is_attribute_plain_data(a))\n"; std::string fullCmd = formatString(cmdFmt, thisPrimPathStr); omni::kit::PythonInterOpHelper::executeCommand(fullCmd.c_str()); } // No need to do anything more since we have no prim specified return true; } } // ----------------------------------------------------------------------------------------- // Update / Add dynamic attributes. std::vector<AttrNameAndType> attrsOfInterest; bool ok = addDynamicAttribs( targetPrim, iFabricUsd, fabricId, targetPrimPath, nodeObj, thisPrimPathStr, true, attrsOfInterest); if (!ok) return false; // We always have to copy our attribute data to the prim for (auto iter = attrsOfInterest.begin(); iter != attrsOfInterest.end(); iter++) { TokenC primAttrName = iter->name; // our attribute name will automatically include the "inputs:" prefix NameToken thisAttrName = iAttribute.ensurePortTypeInName(primAttrName, AttributePortType::kAttributePortType_Input, false); copyAttributeDataToPrim(context, asInt(targetPrimPath), primAttrName, nodeObj, thisAttrName, instanceIndex, false, usdWriteBack); } return true; } static bool compute(OgnWritePrimDatabase& db) { pxr::SdfPath sdfPath; const auto& prims = db.inputs.prim(); if(prims.size() > 0) { sdfPath = omni::fabric::toSdfPath(prims[0]); } // Update attribs, but do not make any topological changes as this could destabilize the evaluation bool ok = updateForPrim(db.abi_context(), db.abi_node(), false /* removeStale */, db.getInstanceIndex(), sdfPath, db.inputs.usdWriteBack()); if (ok) RETURN_TRUE_EXEC return false; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
7,417
C++
39.758242
144
0.600512
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnCopyAttr.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 "OgnCopyAttrDatabase.h" #include "TokenUtils.h" #include <algorithm> #include <cstring> #include <string> #include <vector> namespace omni { namespace graph { namespace nodes { class OgnCopyAttr { public: // Copies all attributes from one input prim and specified attributes from a // second input prim to the output prim. static bool compute(OgnCopyAttrDatabase& db) { const auto& fullInputBundle = db.inputs.fullData(); auto& outputBundle = db.outputs.data(); // Set up the output, first by copying the input 'fullData' into the output if it exists, else clearing it outputBundle = db.inputs.fullData(); if (!outputBundle.isValid()) { db.logError("Failed to copy entire input bundle to the output"); return false; } // Find all of the attribute names for selection. std::vector<NameToken> inputAttrNames; std::vector<NameToken> outputAttrNames; if (!TokenHelper::splitNames(db.tokenToString(db.inputs.inputAttrNames()), inputAttrNames) || !TokenHelper::splitNames(db.tokenToString(db.inputs.outputAttrNames()), outputAttrNames)) { db.logError("Could not parse the attribute names"); return false; } // Mismatched name sizes are dealt with going with the minimum number, and reporting this warning if (inputAttrNames.size() != outputAttrNames.size()) { db.logWarning("Input name size %zu != output name size %zu", inputAttrNames.size(), outputAttrNames.size()); } // Loop through the name list, adding attributes from the input size_t nameCount = std::min(inputAttrNames.size(), outputAttrNames.size()); if (nameCount == 0) { return true; } // Figure out which bundle is to be used for renamed attributes const auto& partialInputBundle = db.inputs.partialData(); const auto& renamingBundle = partialInputBundle.isValid() ? partialInputBundle : fullInputBundle; auto& context = db.abi_context(); for (size_t name_index = 0; name_index < nameCount; ++name_index) { auto bundledAttribute = renamingBundle.attributeByName(inputAttrNames[name_index]); if (!bundledAttribute.isValid()) { db.logWarning("Input attribute '%s' not found in bundle", db.tokenToString(inputAttrNames[name_index])); continue; } outputBundle.insertAttribute(bundledAttribute, outputAttrNames[name_index]); } return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
3,144
C++
34.738636
120
0.658397
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimAttributes.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "OgnReadPrimAttributesDatabase.h" #include "ReadPrimCommon.h" #include <omni/kit/commands/ICommandBridge.h> namespace omni { namespace graph { namespace nodes { class OgnReadPrimAttributes { std::unordered_set<NameToken> m_added; public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { // When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected. AttributeObj inputBundleAttribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimAttributesAttributes::inputs::prim.m_token); inputBundleAttribObj.iAttribute->registerValueChangedCallback( inputBundleAttribObj, onInputBundleValueChanged, true); } // ---------------------------------------------------------------------------- static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData) { NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); // If the graph is currently disabled then delay the update until the next compute. // Arguably this should be done at the message propagation layer, then this wouldn't be necessary. if (graphObj.iGraph->isDisabled(graphObj)) { return; } // clear the output bundles GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); auto outputTokens = { OgnReadPrimAttributesAttributes::outputs::primBundle.m_token }; for (auto& outputToken : outputTokens) { BundleHandle outBundle = context.iContext->getOutputBundle( context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex); context.iContext->clearBundleContents(context, outBundle); } // Remove dynamic attributes BundleType empty; updateAttributes(context, nodeObj, empty, kAccordingToContextIndex); } // ---------------------------------------------------------------------------- static PathC getPath(OgnReadPrimAttributesDatabase& db) { GraphContextObj contextObj = db.abi_context(); std::string const primPathStr{ db.inputs.primPath() }; NameToken primPath = contextObj.iToken->getHandle(primPathStr.c_str()); return readPrimBundle_getPath(contextObj, db.abi_node(), OgnReadPrimAttributesAttributes::inputs::prim.m_token, db.inputs.usePath(), primPath, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static bool writeToBundle(OgnReadPrimAttributesDatabase& db, PathC inputPath, bool force, pxr::UsdTimeCode const& time) { GraphContextObj contextObj = db.abi_context(); NodeObj nodeObj = db.abi_node(); std::string attrNamesStr{ db.inputs.attrNamesToImport() }; NameToken attrNames = contextObj.iToken->getHandle(attrNamesStr.c_str()); return readPrimBundle_writeToBundle(contextObj, nodeObj, inputPath, attrNames, db.outputs.primBundle(), force, false, time, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static void clean(OgnReadPrimAttributesDatabase& db) { db.outputs.primBundle().clear(); // remove dynamic attributes BundleType empty; updateAttributes(db.abi_context(), db.abi_node(), empty, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static void updateAttributes(GraphContextObj const& contextObj, NodeObj const& nodeObj, BundleType const& bundle, InstanceIndex instIdx) { OgnReadPrimAttributes& state = OgnReadPrimAttributesDatabase::sInternalState<OgnReadPrimAttributes>(nodeObj); omni::kit::commands::ICommandBridge::ScopedUndoGroup scopedUndoGroup; extractBundle_reflectBundleDynamicAttributes(nodeObj, contextObj, bundle, state.m_added, instIdx); } // ---------------------------------------------------------------------------- static bool compute(OgnReadPrimAttributesDatabase& db) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); // import by pattern bool inputChanged = false; // attribute filter changed std::string attrNamesToImport{ db.inputs.attrNamesToImport() }; if (db.state.attrNamesToImport() != attrNamesToImport) { db.state.attrNamesToImport() = attrNamesToImport; inputChanged = true; } // compute bool result = readPrimBundle_compute<OgnReadPrimAttributes>(db, inputChanged); if (!result) return false; // update dynamic attributes BundleType outputBundle(context, db.outputs.primBundle().abi_bundleHandle()); updateAttributes(context, nodeObj, outputBundle, db.getInstanceIndex()); return outputBundle.isValid(); } // ---------------------------------------------------------------------------- static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { if (oldVersion < 2) { return upgradeUsdTimeCodeInput(context, nodeObj); } } return false; } }; REGISTER_OGN_NODE() } } }
6,350
C++
38.203703
123
0.59685
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimsV2.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" #include <carb/dictionary/DictionaryUtils.h> #include <omni/fabric/FabricUSD.h> #include <omni/kit/PythonInterOpHelper.h> #include "FindPrimsPathTracker.h" #include "ReadPrimCommonV2.h" #include "DebugUtils.h" #include "OgnReadPrimsV2Database.h" // clang-format on namespace omni { namespace graph { namespace nodes { class OgnReadPrimsV2 { fabric::FabricId m_fabricId; fabric::Token m_pathTrackerId; unstable::UsdPrimChangeTracker::Subscription m_changeTrackerSubscription; PrimPathsState m_inputPrimPaths; PrimPathsState m_primPaths; // Print debug stuff to the console? #if 0 # define debugPrintLn(nodeObj, fmt, ...) DebugHelper::printLn((nodeObj), (fmt), ##__VA_ARGS__) #else # define debugPrintLn(nodeObj, fmt, ...) ((void)0) #endif // ---------------------------------------------------------------------------- // OGN currently doesn't offer per-instance initialize/release callbacks, // so we must create per-instance state on demand, during compute static OgnReadPrimsV2& ensurePerInstanceState(OgnReadPrimsV2Database& db) { auto& internalState = db.perInstanceState<OgnReadPrimsV2>(); if (internalState.m_fabricId == fabric::kInvalidFabricId) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); // Initialize per-instance internal state. std::tie(internalState.m_fabricId, std::ignore) = getFabricForNode(context, nodeObj); // Initialize path tracker IToken const& iToken = *carb::getCachedInterface<omni::fabric::IToken>(); // Build a unique per-node-instance key for the path target. std::stringstream ss; ss << nodeObj.iNode->getPrimPath(nodeObj); auto const graphObj = nodeObj.iNode->getGraph(nodeObj); if (graphObj.iGraph->getInstanceCount(graphObj)) { // For instances, append the graph target. ss << iToken.getText(db.getGraphTarget()); } internalState.m_pathTrackerId = iToken.getHandle(PXR_NS::TfMakeValidIdentifier(ss.str()).c_str()); unstable::UsdPrimChangeTracker::AnyTrackedPrimChangedCallback primChangedCallback = [nodeObj]() { // If any tracked prim changes, force this node to recompute. debugPrintLn(nodeObj, "Any tracked prim was changed in instance '%s' => requesting re-computation", intToToken(nodeObj.iNode->getGraphInstanceID(nodeObj.nodeHandle, {})).GetText()); nodeObj.iNode->requestCompute(nodeObj); }; // Initialize prim change tracker if (internalState.m_changeTrackerSubscription.initialize(context)) { internalState.m_changeTrackerSubscription.setTrackedPrimChangedCallback(std::move(primChangedCallback)); } else { OgnReadPrimsV2Database::logError(nodeObj, "Failed to initialize USD prim change tracker!"); } } return internalState; } // ---------------------------------------------------------------------------- static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData) { NodeObj const nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj); GraphObj const graphObj = nodeObj.iNode->getGraph(nodeObj); // If the graph is currently disabled then delay the update until the next compute. // Arguably this should be done at the message propagation layer, then this wouldn't be necessary. if (graphObj.iGraph->isDisabled(graphObj)) { return; } // clear the output bundles GraphContextObj const context = graphObj.iGraph->getDefaultGraphContext(graphObj); auto const outputTokens = { OgnReadPrimsV2Attributes::outputs::primsBundle.m_token }; for (auto& outputToken : outputTokens) { BundleHandle const outBundle = context.iContext->getOutputBundle( context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex); context.iContext->clearBundleContents(context, outBundle); } } // ---------------------------------------------------------------------------- static PathVector getMatchedPaths(OgnReadPrimsV2Database const& db, PathVector const* primPaths) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); PathVector matchedPaths; if (!db.inputs.pathPattern().empty()) { auto [fabricId, stage] = getFabricForNode(context, nodeObj); PXR_NS::TfToken const pathPattern{ std::string{ db.inputs.pathPattern() } }; if (pathPattern.IsEmpty()) return {}; std::string const typePatternStr{ db.inputs.typePattern() }; PXR_NS::TfToken const typePattern{ typePatternStr }; if (!primPaths || primPaths->empty()) { PXR_NS::UsdPrim const startPrim = stage->GetPseudoRoot(); findPrims_findMatching( matchedPaths, startPrim, true, nullptr, typePattern, {}, {}, {}, pathPattern, true, true); } else { PXR_NS::SdfPathVector consolidatedPaths; consolidatedPaths.reserve(primPaths->size()); std::transform(primPaths->cbegin(), primPaths->cend(), std::back_inserter(consolidatedPaths), [](fabric::PathC pathC) { return fabric::toSdfPath(pathC); }); // There's no need to find prims in /foo/bar if /foo is already one of the search paths PXR_NS::SdfPath::RemoveDescendentPaths(&consolidatedPaths); for (auto const& path : consolidatedPaths) { if (PXR_NS::UsdPrim startPrim = stage->GetPrimAtPath(path)) { findPrims_findMatching( matchedPaths, startPrim, true, nullptr, typePattern, {}, {}, {}, pathPattern, true, true); } } } } else { matchedPaths = *primPaths; } return matchedPaths; } // ---------------------------------------------------------------------------- static bool writeToBundle(OgnReadPrimsV2Database& db, gsl::span<PathC const> inputPaths, bool forceFullUpdate, bool enableChangeTracking, pxr::UsdTimeCode const& time) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); std::string const attrNamesStr{ db.inputs.attrNamesToImport() }; NameToken const attrNames = context.iToken->getHandle(attrNamesStr.c_str()); bool const computeBoundingBox = db.inputs.computeBoundingBox(); auto& containerBundle = db.outputs.primsBundle(); int const debugStamp = db.inputs._debugStamp(); bool const timeSampling = pxr::UsdTimeCode::Default() != time; // Update or reset the USD prim change tracker. auto& subscription = db.perInstanceState<OgnReadPrimsV2>().m_changeTrackerSubscription; if (!subscription.isValid() || timeSampling || !enableChangeTracking) { debugPrintLn(nodeObj, "Doing full container bundle update (w/o change tracking)"); // We don't do any change tracking when time sampling the prims, this has overhead for nothing. // TODO: We could detect that the prim doesn't have any time sampled attributes! subscription.reset(); return readPrimsBundleV2_writeToBundle(context, nodeObj, inputPaths, attrNames, containerBundle, forceFullUpdate, computeBoundingBox, time, db.getInstanceIndex(), debugStamp); } // Update change tracking. // When doing a forced output update, we need to start change tracking now, // so we can get the changes in the next compute. // NOTE: We assume that `force` will be true when switching from animated to non-animate compute! unstable::UsdPrimChangeTracker::TrackOptions trackOptions; // TODO: We should make world matrices optional constexpr bool computeWorldMatrix = true; // NOTE: We output local bounding boxes, and these depend on the world matrix too. trackOptions.ancestors = computeBoundingBox || computeWorldMatrix; // When computing bounding boxes, we need to observe descendant changes. trackOptions.descendants = computeBoundingBox; auto const changedPrimPaths = forceFullUpdate ? subscription.track(inputPaths, trackOptions) : subscription.update(); if (!forceFullUpdate && readPrimsBundleV2_updateOutputBundle( context, nodeObj, changedPrimPaths, attrNames, containerBundle, computeBoundingBox, time, db.getInstanceIndex(), debugStamp)) { // Incremental update succeeded. return true; } // Full update debugPrintLn(nodeObj, "Doing full container bundle update (forced)"); return readPrimsBundleV2_writeToBundle( context, nodeObj, inputPaths, attrNames, containerBundle, true, computeBoundingBox, time, db.getInstanceIndex(), debugStamp); } // ---------------------------------------------------------------------------- static void clean(OgnReadPrimsV2Database& db) { db.outputs.primsBundle().clear(); if (db.inputs.enableBundleChangeTracking()) { db.outputs.primsBundle.changes().activate(); } else { db.outputs.primsBundle.changes().deactivate(); } } // ---------------------------------------------------------------------------- void updatePathTracker(bool hasPathPattern, PathVector const& rootPrimPaths) const { if (hasPathPattern) { if (rootPrimPaths.empty()) { setFindPrimsRootPrimPaths( m_fabricId, m_pathTrackerId, { fabric::asInt(PXR_NS::SdfPath::AbsoluteRootPath()) }); } else { setFindPrimsRootPrimPaths(m_fabricId, m_pathTrackerId, rootPrimPaths); } } else { setFindPrimsRootPrimPaths(m_fabricId, m_pathTrackerId, {}); } } public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { // When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected. AttributeObj const inputBundleAttribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimsV2Attributes::inputs::prims.m_token); inputBundleAttribObj.iAttribute->registerValueChangedCallback( inputBundleAttribObj, onInputBundleValueChanged, true); } // ---------------------------------------------------------------------------- ~OgnReadPrimsV2() { removeFindPrimsRootPrimPathsEntry(m_fabricId, m_pathTrackerId); } // ---------------------------------------------------------------------------- static bool compute(OgnReadPrimsV2Database& db) { auto& internalState = ensurePerInstanceState(db); auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); auto const prevPathPattern = db.state.pathPattern(); auto const& pathPattern = db.inputs.pathPattern(); bool const pathPatternChanged = prevPathPattern != pathPattern; // import by pattern bool inputChanged = pathPatternChanged || db.state.typePattern() != db.inputs.typePattern(); db.state.pathPattern() = pathPattern; db.state.typePattern() = db.inputs.typePattern(); // primPaths changed // primPaths serves two different purposes. // - if pathPattern not empty, primPaths are used as the root prims to apply pattern matching on // - if pathPattern is empty, primPaths are the prims to be read directly from auto primPaths = readPrimBundle_getPaths( context, nodeObj, OgnReadPrimsV2Attributes::inputs::prims.m_token, false, {}, db.getInstanceIndex()); bool const rootPrimPathsChanged = internalState.m_inputPrimPaths.changed(primPaths); if (rootPrimPathsChanged) { internalState.m_inputPrimPaths.store(primPaths); inputChanged = true; } // bounding box changed bool const computeBoundingBox = db.inputs.computeBoundingBox(); if (db.state.computeBoundingBox() != computeBoundingBox) { db.state.computeBoundingBox() = computeBoundingBox; inputChanged = true; } // attribute filter changed std::string const attrNamesToImport{ db.inputs.attrNamesToImport() }; if (db.state.attrNamesToImport() != attrNamesToImport) { db.state.attrNamesToImport() = attrNamesToImport; inputChanged = true; } // applySkelBinding toggle changed bool const applySkelBinding = db.inputs.applySkelBinding(); if (db.state.applySkelBinding() != applySkelBinding) { db.state.applySkelBinding() = applySkelBinding; inputChanged = true; } // enableChangeTracking toggle changed bool const enableUsdChangeTracking = db.inputs.enableChangeTracking(); if (db.state.enableChangeTracking() != enableUsdChangeTracking) { db.state.enableChangeTracking() = enableUsdChangeTracking; inputChanged = true; } bool const enableBundleChangeTracking = db.inputs.enableBundleChangeTracking(); if (db.state.enableBundleChangeTracking() != enableBundleChangeTracking) { db.state.enableBundleChangeTracking() = enableBundleChangeTracking; inputChanged = true; } // root prim paths changed or path pattern changed to/from empty if (rootPrimPathsChanged || (pathPatternChanged && (pathPattern.empty() || prevPathPattern.empty()))) { internalState.updatePathTracker(!pathPattern.empty(), primPaths); } // NOTE: we need to use UsdTimeCode to compare to current and previous time, // because unlike SdfTimeCode, UsdTimeCode correctly deals with Default (NaN) time. pxr::UsdTimeCode const time = getTime(db); if (time != db.state.usdTimecode()) { // time changed inputChanged = true; db.state.usdTimecode() = pxr::SdfTimeCode(time.GetValue()); } // matched paths changed PathVector const matchedPaths = getMatchedPaths(db, &primPaths); if (internalState.m_primPaths.changed(matchedPaths)) { internalState.m_primPaths.store(matchedPaths); inputChanged = true; } // clean this node only when something changed if (inputChanged) { clean(db); } // nothing to write if (matchedPaths.empty()) { return false; } // write the data bool outputChanged = writeToBundle(db, matchedPaths, inputChanged, enableUsdChangeTracking, time); if (applySkelBinding) { ogn::BundleContents<ogn::kOgnOutput, ogn::kCpu>& outputBundle = db.outputs.primsBundle(); if (readSkelBinding_compute(context, nodeObj, outputBundle, attrNamesToImport, inputChanged, computeBoundingBox, getTime(db))) { outputChanged |= applySkelBinding_compute(context, outputBundle); } } return outputChanged; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
16,839
C++
38.345794
141
0.596472
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnNoOp.cpp
// Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnNoOpDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnNoOp { public: // Do nothing static bool compute(OgnNoOpDatabase&) { return true; } }; REGISTER_OGN_NODE() } } }
673
C++
18.823529
77
0.73997
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimsBundle.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // clang-format off #include "UsdPCH.h" #include <omni/graph/core/PreUsdInclude.h> #include <omni/usd/UsdContext.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usdGeom/bboxCache.h> #include <omni/graph/core/PostUsdInclude.h> // clang-format on #include "OgnReadPrimsBundleDatabase.h" #include "PrimCommon.h" #include "ReadPrimCommon.h" namespace omni { namespace graph { namespace nodes { /************************************************************************/ /* */ /************************************************************************/ class OgnReadPrimsBundle { public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { // When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected. AttributeObj inputBundleAttribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimsBundleAttributes::inputs::prims.m_token); inputBundleAttribObj.iAttribute->registerValueChangedCallback( inputBundleAttribObj, onInputBundleValueChanged, true); } // ---------------------------------------------------------------------------- static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData) { NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); // If the graph is currently disabled then delay the update until the next compute. // Arguably this should be done at the message propagation layer, then this wouldn't be necessary. if (graphObj.iGraph->isDisabled(graphObj)) { return; } // clear the output bundles GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); auto outputTokens = { OgnReadPrimsBundleAttributes::outputs::primsBundle.m_token }; for (auto& outputToken : outputTokens) { BundleHandle outBundle = context.iContext->getOutputBundle( context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex); context.iContext->clearBundleContents(context, outBundle); } } // ---------------------------------------------------------------------------- static PathVector getMatchedPaths(OgnReadPrimsBundleDatabase& db, PathVector const* primPaths) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); return readPrimBundle_getPaths(context, nodeObj, OgnReadPrimsBundleAttributes::inputs::prims.m_token, db.inputs.usePaths(), db.inputs.primPaths(), db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static bool writeToBundle(OgnReadPrimsBundleDatabase& db, gsl::span<PathC const> inputPaths, bool force, pxr::UsdTimeCode const& time) { std::string attrNamesStr{ db.inputs.attrNamesToImport() }; NameToken attrNames = db.abi_context().iToken->getHandle(attrNamesStr.c_str()); return readPrimsBundle_writeToBundle( db.abi_context(), db.abi_node(), inputPaths, attrNames, db.outputs.primsBundle(), force, false, time, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static void clean(OgnReadPrimsBundleDatabase& db) { db.outputs.primsBundle().clear(); } // ---------------------------------------------------------------------------- static bool compute(OgnReadPrimsBundleDatabase& db) { bool inputChanged = false; if (db.state.usePaths() != db.inputs.usePaths()) { db.state.usePaths() = db.inputs.usePaths(); inputChanged = true; } // attribute filter changed std::string attrNamesToImport{ db.inputs.attrNamesToImport() }; if (db.state.attrNamesToImport() != attrNamesToImport) { db.state.attrNamesToImport() = attrNamesToImport; inputChanged = true; } return readPrimsBundle_compute<OgnReadPrimsBundle>(db, inputChanged); } // ---------------------------------------------------------------------------- static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { if (oldVersion < 2) { return upgradeUsdTimeCodeInput(context, nodeObj); } } return false; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
5,486
C++
37.914893
137
0.570179
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimRelationship.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 <OgnWritePrimRelationshipDatabase.h> #include "PrimCommon.h" namespace omni { namespace graph { namespace nodes { class OgnWritePrimRelationship { public: // ---------------------------------------------------------------------------- // Prefetch prim to fabric static void setup(NodeObj const& nodeObj, GraphObj const& graphObj, OgnWritePrimRelationshipDatabase& db, size_t offset) { db.state.correctlySetup(offset) = false; TargetPath prim = db.inputs.prim.firstOrDefault(offset); NameToken name = db.inputs.name(offset); std::set<omni::fabric::TokenC> attributes = {name.token}; prefetchPrim(graphObj, nodeObj, prim, attributes); db.state.correctlySetup(offset) = true; db.state.prim(offset).resize(1); db.state.prim(offset)[0] = prim; db.state.name(offset) = name; } static void onValueChanged(AttributeObj const& attrObj, void const* userData) { NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) }; if (nodeObj.nodeHandle == kInvalidNodeHandle) return; GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; GraphContextObj contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj); OgnWritePrimRelationshipDatabase db(contextObj, nodeObj); setup(nodeObj, graphObj, db, 0); } // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { std::array<NameToken, 2> attribNames{inputs::name.m_token, inputs::prim.m_token}; for (auto const& attribName : attribNames) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); } } // ---------------------------------------------------------------------------- static size_t computeVectorized(OgnWritePrimRelationshipDatabase& db, size_t count) { NodeObj nodeObj = db.abi_node(); GraphContextObj context = db.abi_context(); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); auto name = db.inputs.name.vectorized(count); auto usdWriteBack = db.inputs.usdWriteBack.vectorized(count); auto correctlySetup = db.state.correctlySetup.vectorized(count); auto nameState = db.state.name.vectorized(count); auto execOut = db.outputs.execOut.vectorized(count); for (size_t idx = 0; idx < count; ++idx) { TargetPath curPrim = db.inputs.prim.firstOrDefault(idx); if(!correctlySetup[idx] || db.state.prim(idx).size() == 0 || db.state.prim(idx)[0] != curPrim || nameState[idx] != name[idx]) { setup(nodeObj, graphObj, db, idx); } if(correctlySetup[idx]) { setRelationshipTargets(context, nodeObj, curPrim, name[idx], db.inputs.value(idx), usdWriteBack[idx]); execOut[idx] = kExecutionAttributeStateEnabled; } } return count; } }; REGISTER_OGN_NODE() }// namespace nodes }// namespace graph }// namespace omni
3,825
C++
36.145631
124
0.614641
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadVariable.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnReadVariableDatabase.h> #include <carb/events/EventsUtils.h> #include "PrimCommon.h" namespace omni { namespace graph { namespace core { class OgnReadVariable { public: carb::events::ISubscriptionPtr m_EventSubscription; // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); onConnectionTypeResolve(nodeObj); GraphObj graphObj{ context.iContext->getGraph(context) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; OgnReadVariableDatabase::sInternalState<OgnReadVariable>(nodeObj) .m_EventSubscription = carb::events::createSubscriptionToPop(graphObj.iGraph->getEventStream(graphObj).get(), [nodeObj](carb::events::IEvent* e) { switch (static_cast<IGraphEvent>(e->type)) { case IGraphEvent::eCreateVariable: case IGraphEvent::eRemoveVariable: case IGraphEvent::eVariableTypeChange: onConnectionTypeResolve(nodeObj); break; default: break; } }); } // ---------------------------------------------------------------------------- // Called by OG to resolve the output type static void onConnectionTypeResolve(const NodeObj& nodeObj) { onValueChanged(nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token), nullptr); } // ---------------------------------------------------------------------------- // Called by OG when the value of the variableName changes static void onValueChanged(AttributeObj const& attrObj, void const* userData) { auto nodeObj = attrObj.iAttribute->getNode(attrObj); if (nodeObj.nodeHandle == kInvalidNodeHandle) return; auto graphObj = nodeObj.iNode->getGraph(nodeObj); if (graphObj.graphHandle == kInvalidGraphHandle) return; auto context = graphObj.iGraph->getDefaultGraphContext(graphObj); if (context.contextHandle == kInvalidGraphContextHandle) return; Type type(BaseDataType::eUnknown); const auto token = getDataR<NameToken>( context, attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex)); if (token) { auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>(); auto variable = graphObj.iGraph->findVariable(graphObj, tokenInterface->getText(*token)); if (variable) { type = variable->getType(); } } omni::graph::nodes::tryResolveOutputAttribute(nodeObj, outputs::value.m_token, type); } static size_t computeVectorized(OgnReadVariableDatabase& db, size_t count) { auto variable = db.getVariable(db.inputs.variableName()); if (!variable.isValid()) return 0; auto& node = db.abi_node(); // make sure the types match if (variable.type() != db.outputs.value().type()) { auto attribute = node.iNode->getAttributeByToken(node, outputs::value.m_token); auto handle = db.outputs.value().abi_handle(); attribute.iAttribute->setResolvedType(attribute, variable.type()); db.outputs.value().reset(db.abi_context(), handle, attribute); return 0; } //if the variable name is not a constant (ie. each instance may point to a different variable) // or the type is an array type (may have/trigger CoW or data stealing), we cannot do a vectorized compute, // and going through the ABI is mandatory on a per instance basis auto varNameAttrib = node.iNode->getAttributeByToken(node, inputs::variableName.m_token); bool const isVarNameConstant = varNameAttrib.iAttribute->isRuntimeConstant(varNameAttrib); if (variable.type().arrayDepth || !isVarNameConstant) { auto varName = db.inputs.variableName(); for (size_t i = 0; i < count; ++i) { db.outputs.value().copyData(db.getVariable(varName)); db.moveToNextInstance(); } } else { uint8_t* dst = nullptr; size_t sd; db.outputs.value().rawData(dst, sd); uint8_t* src = nullptr; size_t ss; variable.rawData(src, ss); if (ss != sd) return 0; memcpy(dst, src, ss * count); } return count; } }; REGISTER_OGN_NODE() } // namespace examples } // namespace graph } // namespace omni
6,311
C++
40.801324
121
0.524164
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimsV2.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "FindPrimsPathTracker.h" #include "LayerIdentifierResolver.h" #include "OgnWritePrimsV2Database.h" #include "SpanUtils.h" #include "WritePrimCommon.h" namespace omni { namespace graph { namespace nodes { class OgnWritePrimsV2 { // keep a set of prims that has been *created* by this node. // If the node writes to an existing prim on the stage, it's not counted as created. // it will be reset every time removeMissingPrims is true to track the diff // track Usd and Fabric separately since usdWriteBack can be turned on or off PXR_NS::SdfPathUSet createdUsdPrims; PXR_NS::SdfPathUSet createdFabricPrims; // keep a map of attributes that has been *created* by this node. // If the node writes to an existing attribute on the stage, it's not counted as created. // it will be reset every time removeMissingAttributes is true to track the diff // track Usd and Fabric separately since usdWriteBack can be turned on or off PXR_NS::SdfPathUSet createdUsdAttributes; PXR_NS::SdfPathUSet createdFabricAttributes; PathToMetadataMap createdObjectMetadata; PrimPathsState targetPrimPaths; static size_t getConnectedPrimCount(OgnWritePrimsV2Database& db) { GraphContextObj const& contextObj = db.abi_context(); NodeObj const& nodeObj = db.abi_node(); NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle; NameToken const primsToken = inputs::primsBundle.token(); return contextObj.iContext->getInputTargetCount(contextObj, nodeHandle, primsToken, db.getInstanceIndex()); } //! Check if any of the targetPrim paths are descendants of any of the Root Prims paths in find/read prims. //! If any of the path is an descendant, then the output prim(s) can potentially mutate the input prims' states, //! creating a loop. This is undesirable and prohibited to prevent user errors. //! //! returns true if loop is detected. static bool detectFindPrimsPathsLoop(GraphContextObj const& context, const NodeObj& nodeObj, PathVector const& targetPrimPaths) { fabric::FabricId fabricId; std::tie(fabricId, std::ignore) = getFabricForNode(context, nodeObj); auto const rootPrimPaths = getRootPrimPathsSet(fabricId); if (rootPrimPaths.empty()) { return false; } // AbsoluteRootPath has to be the smallest path in the set if exists // a quick test if (*rootPrimPaths.begin() == PXR_NS::SdfPath::AbsoluteRootPath()) { ogn::OmniGraphDatabase::logError( nodeObj, "FindPrims/ReadPrims source contains absolute root path \"/\", writing to any target on the stage may mutate the input state. " "Please choose a different source root prim path for FindPrims/ReadPrims."); return true; } PXR_NS::SdfPathSet targetPrimPathsSet; std::transform(targetPrimPaths.cbegin(), targetPrimPaths.cend(), std::inserter(targetPrimPathsSet, targetPrimPathsSet.begin()), [](fabric::PathC pathC) { return fabric::toSdfPath(pathC); }); for (auto const& rootPrimPath : rootPrimPaths) { auto const lb = targetPrimPathsSet.lower_bound(rootPrimPath); // if a lower_bound in targetPrimPaths is a descendant of rootPrimPath, a loop could form if (lb != targetPrimPathsSet.end() && lb->HasPrefix(rootPrimPath)) { ogn::OmniGraphDatabase::logError( nodeObj, "Target prim '%s' is a descendant of FindPrims/ReadPrims source '%s', writing to the target may mutate the input state. Please choose a different target", lb->GetText(), rootPrimPath.GetText()); return true; } } return false; } static void handleMissingPrims(OgnWritePrimsV2Database& db, PXR_NS::SdfPathUSet const& createdPrimPaths, bool removeMissingPrims = true) { auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(db.abi_node()); auto& prevCreatedUsdPrims = internalState.createdUsdPrims; auto& prevCreatedFabricPrims = internalState.createdFabricPrims; // if removeMissingPrims and usdWriteBack, find the diff of this compute's createdPrimPaths vs last // removeMissingPrims's createdPrimPaths, and removes the ones that no longer exist in current // createdPrimPaths auto processMissingPrims = [&db, &createdPrimPaths, removeMissingPrims]( PXR_NS::SdfPathUSet& prevCreatedPrims, bool isUsd) { if (createdPrimPaths == prevCreatedPrims) { return; } if (removeMissingPrims) { // if removeMissingPrims is on: // - always removes missing prims from fabric // - if usdWriteBack is on, also remove missing prims from USD PXR_NS::SdfPathVector primPathsToRemove; primPathsToRemove.reserve(prevCreatedPrims.size()); for (const auto& path : prevCreatedPrims) { // previously created prim no longer exists if (createdPrimPaths.find(path) == createdPrimPaths.end()) { ogn::OmniGraphDatabase::logWarning( db.abi_node(), "Previously created prim %s no longer exists in upstream bundle. Removing it from %s...", path.GetText(), isUsd ? "USD" : "Fabric"); primPathsToRemove.push_back(path); } } if (!primPathsToRemove.empty()) { removePrims(db.abi_context(), db.abi_node(), primPathsToRemove, isUsd); } // now the accumulated created paths should be createdPrimPaths from this execution prevCreatedPrims = createdPrimPaths; } else { // else accumulate the written paths until next removeMissingPrims happens prevCreatedPrims.insert(createdPrimPaths.begin(), createdPrimPaths.end()); } }; // prims are always written to Fabric processMissingPrims(prevCreatedFabricPrims, false); // only when usdWriteBack is true will prims be written to USD if (db.inputs.usdWriteBack()) { processMissingPrims(prevCreatedUsdPrims, true); } } static void handleMissingAttributes(OgnWritePrimsV2Database& db, PXR_NS::SdfPathUSet const& createdAttributes, bool removeMissingAttrs = true) { auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(db.abi_node()); auto& prevCreatedUsdAttributes = internalState.createdUsdAttributes; auto& prevCreatedFabricAttributes = internalState.createdFabricAttributes; auto processMissingAttributes = [&db, &createdAttributes, removeMissingAttrs]( PXR_NS::SdfPathUSet& prevCreatedAttributes, bool isUsd) { if (createdAttributes == prevCreatedAttributes) { return; } if (removeMissingAttrs) { // if removeMissingAttrs is on: // - always removes missing attributes from fabric // - if usdWriteBack is on, also remove missing attributes from USD PXR_NS::SdfPathVector attrPathsToRemove; attrPathsToRemove.reserve(prevCreatedAttributes.size()); for (const auto& path : prevCreatedAttributes) { // previously created prim no longer exists if (createdAttributes.find(path) == createdAttributes.end()) { ogn::OmniGraphDatabase::logWarning( db.abi_node(), "Previously created attribute %s no longer exists in upstream bundle. Removing it from %s...", path.GetText(), isUsd ? "USD" : "Fabric"); attrPathsToRemove.push_back(path); } } if (!attrPathsToRemove.empty()) { removeAttributes(db.abi_context(), db.abi_node(), attrPathsToRemove, isUsd); } // now the accumulated created paths should be createdAttributes from this execution prevCreatedAttributes = createdAttributes; } else { // else accumulate the written attributes until next removeMissingAttrs happens prevCreatedAttributes.insert(createdAttributes.begin(), createdAttributes.end()); } }; // attributes are always written to Fabric processMissingAttributes(prevCreatedFabricAttributes, false); // only when usdWriteBack is true will attributes be written to USD if (db.inputs.usdWriteBack()) { processMissingAttributes(prevCreatedUsdAttributes, true); } } static void handleMissingMetadata(OgnWritePrimsV2Database& db, PathToMetadataMap const& createdObjectMetadata, bool removeMissingMetadata = true) { auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(db.abi_node()); auto& prevCreatedObjectMetadata = internalState.createdObjectMetadata; auto processMissingMetadata = [&db, &createdObjectMetadata, removeMissingMetadata]( PathToMetadataMap& prevCreatedObjectMetadata, bool isUsd) { if (createdObjectMetadata == prevCreatedObjectMetadata) { return; } if (removeMissingMetadata) { PathToMetadataMap metadataToRemove; for (const auto& objectMetadata : prevCreatedObjectMetadata) { const auto& objectPath = objectMetadata.first; const auto& prevMetadataKeys = objectMetadata.second; if (createdObjectMetadata.find(objectPath) == createdObjectMetadata.end()) { ogn::OmniGraphDatabase::logWarning( db.abi_node(), "Previously created metadata for object %s no longer exists in upstream bundle. Removing it from %s...", objectPath.GetText(), isUsd ? "USD" : "Fabric"); metadataToRemove[objectPath] = prevMetadataKeys; } else { const auto& metadataKeys = createdObjectMetadata.at(objectPath); for (const auto& key : prevMetadataKeys) { if (metadataKeys.find(key) == metadataKeys.end()) { ogn::OmniGraphDatabase::logWarning( db.abi_node(), "Previously created metadata %s for object %s no longer exists in upstream bundle. Removing it from %s...", key.GetText(), objectPath.GetText(), isUsd ? "USD" : "Fabric"); metadataToRemove[objectPath].insert(key); } } } } if (!metadataToRemove.empty()) { removeMetadata(db.abi_context(), db.abi_node(), metadataToRemove, isUsd); } prevCreatedObjectMetadata = createdObjectMetadata; } else { for (const auto& objectMetadata : createdObjectMetadata) { // accumulate created metadata until this function is invoked with removeMissingAttrs prevCreatedObjectMetadata[objectMetadata.first].insert(objectMetadata.second.begin(), objectMetadata.second.end()); } } }; // XXX: metadata export for fabric not yet implemented //processMissingMetadata(prevCreatedObjectMetadata, false); if (db.inputs.usdWriteBack()) { processMissingMetadata(prevCreatedObjectMetadata, true); } } static WritePrimResult scatterUnderTargets(GraphContextObj const& contextObj, NodeObj const& nodeObj, gsl::span<ConstBundleHandle> connectedBundleHandles, PathVector const& targetPrimPaths, bool const usdWriteBack, NameToken const& layerIdentifier, WritePrimMatchers const& matchers, WrittenPrimAndAttributesTracker& primAndAttrsTracker, WritePrimDiagnostics& diagnostics) { auto result = WritePrimResult::None; // a map to contain all valid bundle prims info from ALL connected bundles and descendant bundles. BundlePrimInfoMap bundlePrimInfoMap; for (ConstBundleHandle const& bundleHandle : connectedBundleHandles) { WritePrimResult const subResult = collectPrimsFromBundleHierarchy( contextObj, nodeObj, diagnostics, bundleHandle, matchers, bundlePrimInfoMap); mergeWritePrimResult(result, subResult); } auto writeUnderTarget = [&contextObj, &nodeObj, &diagnostics, usdWriteBack, layerIdentifier, &result, &bundlePrimInfoMap, &primAndAttrsTracker](PathC const& targetPrefix) { for (auto const& [_, info] : bundlePrimInfoMap) { WritePrimResult const subResult = writePrimAndAttributes( contextObj, nodeObj, diagnostics, info, usdWriteBack, layerIdentifier, targetPrefix, fabric::asInt(PXR_NS::SdfPath::AbsoluteRootPath()), primAndAttrsTracker); mergeWritePrimResult(result, subResult); } }; for (auto const& target : targetPrimPaths) { writeUnderTarget(target); } return result; } static WritePrimResult writeToTargets(GraphContextObj const& contextObj, NodeObj const& nodeObj, gsl::span<ConstBundleHandle> connectedBundleHandles, PathVector const& targetPrimPaths, bool const usdWriteBack, NameToken const& layerIdentifier, WritePrimMatchers const& matchers, WrittenPrimAndAttributesTracker& primAndAttrsTracker, WritePrimDiagnostics& diagnostics) { auto result = WritePrimResult::None; auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(nodeObj); size_t targetPrimIndex = 0; for (ConstBundleHandle const& bundleHandle : connectedBundleHandles) { // a map to contain all valid bundle prims info from ONE connected bundle and descendant bundles. BundlePrimInfoMap bundlePrimInfoMap; WritePrimResult const subResult = collectPrimsFromBundleHierarchy( contextObj, nodeObj, diagnostics, bundleHandle, matchers, bundlePrimInfoMap); mergeWritePrimResult(result, subResult); // remove the paths that are already prefixed by other paths. // similar to SdfPath::RemoveDescendentPaths, but BundlePrimInfoMap is already ordered so we don't have to // sort again PXR_NS::SdfPathVector uniqueRootPaths; uniqueRootPaths.reserve(bundlePrimInfoMap.size()); for (auto const& entry : bundlePrimInfoMap) { if (uniqueRootPaths.empty() || !entry.first.HasPrefix(uniqueRootPaths.back())) { uniqueRootPaths.push_back(entry.first); } } // index to the currently mapped unique root prim path size_t rootIndex = 0; for (auto const& [sourcePrimPath, info] : bundlePrimInfoMap) { // when the sourcePrimPath is no longer a descendant of current unique root, move it onto the next one if (rootIndex < uniqueRootPaths.size() && !sourcePrimPath.HasPrefix(uniqueRootPaths[rootIndex])) { rootIndex++; // each root index takes up a target prim index targetPrimIndex++; } if (targetPrimIndex >= targetPrimPaths.size()) { ogn::OmniGraphDatabase::logWarning( nodeObj, "Not enough 'prims' targets to write out all source prims. Skipping the rest of the prims"); break; } WritePrimResult const subResult = writePrimAndAttributes(contextObj, nodeObj, diagnostics, info, usdWriteBack, layerIdentifier, targetPrimPaths[(PathVector::size_type)targetPrimIndex], fabric::asInt(uniqueRootPaths[rootIndex]), primAndAttrsTracker); mergeWritePrimResult(result, subResult); } // always increment targetPrimIndex when moving onto next bundle targetPrimIndex++; } return result; } public: static bool compute(OgnWritePrimsV2Database& db) { auto result = WritePrimResult::None; auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); auto& internalState = OgnWritePrimsV2Database::sInternalState<OgnWritePrimsV2>(nodeObj); bool inputChanged = db.state.attrNamesToExport() != db.inputs.attrNamesToExport() || db.state.pathPattern() != db.inputs.pathPattern() || db.state.typePattern() != db.inputs.typePattern() || db.state.usdWriteBack() != db.inputs.usdWriteBack() || db.state.scatterUnderTargets() != db.inputs.scatterUnderTargets() || db.state.layerIdentifier() != db.inputs.layerIdentifier(); db.state.attrNamesToExport() = db.inputs.attrNamesToExport(); db.state.pathPattern() = db.inputs.pathPattern(); db.state.typePattern() = db.inputs.typePattern(); db.state.usdWriteBack() = db.inputs.usdWriteBack(); db.state.scatterUnderTargets() = db.inputs.scatterUnderTargets(); db.state.layerIdentifier() = db.inputs.layerIdentifier(); PathVector const targetPrimPaths = getPathsFromInputRelationship(context, nodeObj, inputs::prims.token(), db.getInstanceIndex()); if (internalState.targetPrimPaths.changed(targetPrimPaths)) { internalState.targetPrimPaths.store(targetPrimPaths); inputChanged = true; } #if 0 // TODO dirty tracking of primBundle if (!inputChanged) { return true; } #endif long stageId = context.iContext->getStageId(context); auto stage = PXR_NS::UsdUtilsStageCache::Get().Find(PXR_NS::UsdStageCache::Id::FromLongInt(stageId)); auto resolvedLayerIdentifier = resolveLayerIdentifier(nodeObj, stage, inputs::layerIdentifier.m_token, db.inputs.layerIdentifier()); // Since the bundle input allows multiple connections, we need to collect all of them size_t const connectedPrimCount = getConnectedPrimCount(db); PXR_NS::SdfPathUSet createdPrimPaths; PXR_NS::SdfPathUSet createdAttributes; PathToMetadataMap createdObjectMetadata; // Even when we have no connected prims, we still return true, because the node *did* compute, and execOut // attribute will be set. if (connectedPrimCount > 0) { auto handler = [&db, &result, &targetPrimPaths, &createdPrimPaths, &createdAttributes, &createdObjectMetadata, &internalState, &resolvedLayerIdentifier](gsl::span<ConstBundleHandle> connectedBundleHandles) { GraphContextObj const& contextObj = db.abi_context(); NodeObj const& nodeObj = db.abi_node(); if (detectFindPrimsPathsLoop(contextObj, nodeObj, targetPrimPaths)) { mergeWritePrimResult(result, WritePrimResult::Fail); // do not proceed return; } NodeContextHandle const nodeHandle = nodeObj.nodeContextHandle; NameToken const primsToken = inputs::primsBundle.token(); bool const usdWriteBack = db.inputs.usdWriteBack(); ogn::const_string const attrPattern = db.inputs.attrNamesToExport(); ogn::const_string const pathPattern = db.inputs.pathPattern(); ogn::const_string const typePattern = db.inputs.typePattern(); WritePrimMatchers const matchers{ attrPattern, pathPattern, typePattern }; contextObj.iContext->getInputTargets(contextObj, nodeHandle, primsToken, (omni::fabric::PathC*)(connectedBundleHandles.data()), db.getInstanceIndex()); // Write back all bundles WritePrimDiagnostics diagnostics; // NOTE: writing metadata is currently only implemented for USD writeback, // so no distinction in made for USD vs Fabric metadata collections. WrittenPrimAndAttributesTracker tracker( createdPrimPaths, usdWriteBack ? internalState.createdUsdPrims : internalState.createdFabricPrims, createdAttributes, usdWriteBack ? internalState.createdUsdAttributes : internalState.createdFabricAttributes, createdObjectMetadata, internalState.createdObjectMetadata); auto writeResult = WritePrimResult::None; if (db.inputs.scatterUnderTargets()) { writeResult = scatterUnderTargets(contextObj, nodeObj, connectedBundleHandles, targetPrimPaths, usdWriteBack, resolvedLayerIdentifier, matchers, tracker, diagnostics); } else { writeResult = writeToTargets(contextObj, nodeObj, connectedBundleHandles, targetPrimPaths, usdWriteBack, resolvedLayerIdentifier, matchers, tracker, diagnostics); } // Report skipped invalid bundles mergeWritePrimResult(result, diagnostics.report(contextObj, nodeObj)); }; withStackScopeBuffer<ConstBundleHandle>(connectedPrimCount, handler); } { PXR_NS::SdfChangeBlock changeblock; // Track primBundles content changes and remove no longer existing attributes or prims // TODO when dirtyId checking works correctly, only handle them when upstream bundle or related inputs // changed. handleMissingPrims(db, createdPrimPaths); // TODO ReadPrims node will *not* remove an attribute from the bundle if it's removed due to lack of USD // change tracking. The only way to trigger removal of missing attributes currently is to change filter // pattern or disconnect then reconnect primBundles connection to force a re-evaluation. handleMissingAttributes(db, createdAttributes); handleMissingMetadata(db, createdObjectMetadata); } auto const ok = result != WritePrimResult::Fail; if (ok) { db.outputs.execOut() = kExecutionAttributeStateEnabled; } return ok; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
25,845
C++
43.716263
174
0.580383
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrims.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /* _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ ReadPrims is deprecated. Use ReadPrimsV2 instead. ReadPrimsV2 added a new inputs:prims as the root prims to perform findPrims operation (instead of always starting from stage root "/"). It also removed inputs:useFindPrims. Instead, as long as input:pathPattern is non-empty, it acts as the on toggle in place of useFindPrims. */ // clang-format off #include "UsdPCH.h" // clang-format on #include <carb/dictionary/DictionaryUtils.h> #include <omni/fabric/FabricUSD.h> #include <omni/kit/PythonInterOpHelper.h> #include "OgnReadPrimsDatabase.h" #include "PrimCommon.h" #include "ReadPrimCommon.h" namespace omni { namespace graph { namespace nodes { class OgnReadPrims { public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, const NodeObj& nodeObj) { ogn::OmniGraphDatabase::logWarning(nodeObj, "ReadPrims node is deprecated, use ReadPrimsV2 instead"); // When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected. AttributeObj inputBundleAttribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimsAttributes::inputs::prims.m_token); inputBundleAttribObj.iAttribute->registerValueChangedCallback( inputBundleAttribObj, onInputBundleValueChanged, true); } // ---------------------------------------------------------------------------- static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData) { NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); // If the graph is currently disabled then delay the update until the next compute. // Arguably this should be done at the message propagation layer, then this wouldn't be necessary. if (graphObj.iGraph->isDisabled(graphObj)) { return; } // clear the output bundles GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); auto outputTokens = { OgnReadPrimsAttributes::outputs::primsBundle.m_token }; for (auto& outputToken : outputTokens) { BundleHandle outBundle = context.iContext->getOutputBundle( context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex); context.iContext->clearBundleContents(context, outBundle); } } // ---------------------------------------------------------------------------- static PathVector getMatchedPaths(OgnReadPrimsDatabase& db, PathVector const* primPaths) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); if (db.inputs.useFindPrims()) { pxr::UsdStageRefPtr stage; omni::fabric::FabricId fabricId; std::tie(fabricId, stage) = getFabricForNode(context, nodeObj); pxr::UsdPrim startPrim = stage->GetPseudoRoot(); pxr::TfToken pathPattern{ std::string{ db.inputs.pathPattern() } }; if (pathPattern.IsEmpty()) return {}; std::string typePatternStr{ db.inputs.typePattern() }; pxr::TfToken typePattern{ typePatternStr }; PathVector matchedPaths; findPrims_findMatching(matchedPaths, startPrim, true, nullptr, typePattern, {}, {}, {}, pathPattern, true); return matchedPaths; } return readPrimBundle_getPaths( context, nodeObj, OgnReadPrimsAttributes::inputs::prims.m_token, false, {}, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static bool writeToBundle(OgnReadPrimsDatabase& db, gsl::span<PathC const> inputPaths, bool force, pxr::UsdTimeCode const& time) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); std::string attrNamesStr{ db.inputs.attrNamesToImport() }; NameToken attrNames = db.abi_context().iToken->getHandle(attrNamesStr.c_str()); return readPrimsBundle_writeToBundle(context, nodeObj, inputPaths, attrNames, db.outputs.primsBundle(), force, db.inputs.computeBoundingBox(), time, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static void clean(OgnReadPrimsDatabase& db) { db.outputs.primsBundle().clear(); } // ---------------------------------------------------------------------------- static bool compute(OgnReadPrimsDatabase& db) { auto& context = db.abi_context(); auto& nodeObj = db.abi_node(); // import by pattern bool inputChanged = db.state.useFindPrims() != db.inputs.useFindPrims() || db.state.pathPattern() != db.inputs.pathPattern() || db.state.typePattern() != db.inputs.typePattern(); db.state.useFindPrims() = db.inputs.useFindPrims(); db.state.pathPattern() = db.inputs.pathPattern(); db.state.typePattern() = db.inputs.typePattern(); // bounding box changed bool const computeBoundingBox = db.inputs.computeBoundingBox(); if (db.state.computeBoundingBox() != computeBoundingBox) { db.state.computeBoundingBox() = computeBoundingBox; inputChanged = true; } // attribute filter changed std::string attrNamesToImport{ db.inputs.attrNamesToImport() }; if (db.state.attrNamesToImport() != attrNamesToImport) { db.state.attrNamesToImport() = attrNamesToImport; inputChanged = true; } // applySkelBinding toggle changed bool const applySkelBinding = db.inputs.applySkelBinding(); if (db.state.applySkelBinding() != applySkelBinding) { db.state.applySkelBinding() = applySkelBinding; inputChanged = true; } bool result = readPrimsBundle_compute<OgnReadPrims>(db, inputChanged); if (result && applySkelBinding) { ogn::BundleContents<ogn::kOgnOutput, ogn::kCpu>& outputBundle = db.outputs.primsBundle(); result = readSkelBinding_compute(context, nodeObj, outputBundle, attrNamesToImport, inputChanged, computeBoundingBox, getTime(db)) && applySkelBinding_compute(context, outputBundle); } return result; } // ---------------------------------------------------------------------------- static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { if (oldVersion < 3) { return upgradeUsdTimeCodeInput(context, nodeObj); } } return false; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
8,174
C++
38.302884
138
0.561292
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenderPostprocessEntry.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 "OgnRenderPostprocessEntryDatabase.h" #include <omni/graph/core/NodeTypeRegistrar.h> #include <omni/graph/core/GpuInteropEntryUserData.h> #include <omni/graph/core/iComputeGraph.h> namespace omni { namespace graph { namespace core { // OmniGraph nodes which postprocess the RTX renderer output need to be connected downstream of a RenderPostprocessEntry // node. The RenderPostprocessEntry outputs the R/W RgResource of the texture's final color (along with associated // metadata such as width, height, etc.) as OmniGraph attributes which can be read by downstream nodes. Modifications to // this RgResource will be reflected in the viewport. The format of the RgResource is an RgTexture created with CUDA // interoperability as opposed to a buffer. class OgnRenderPostprocessEntry { public: static bool compute(OgnRenderPostprocessEntryDatabase& db) { GpuInteropCudaEntryUserData* userData = static_cast<GpuInteropCudaEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node())); if (!userData) return false; GpuInteropCudaResourceMap& cudaRsrcMap = userData->cudaRsrcMap; std::string sourceName = db.inputs.sourceName(); auto it = cudaRsrcMap.find(sourceName); if (it == cudaRsrcMap.end()) { return false; } GpuInteropCudaResourceData& renderVarData = it->second; db.outputs.cudaMipmappedArray() = (uint64_t)renderVarData.cudaResource; db.outputs.width() = renderVarData.width; db.outputs.height() = renderVarData.height; db.outputs.mipCount() = (uint32_t)renderVarData.mipCount; db.outputs.format() = (uint64_t)renderVarData.format; db.outputs.stream() = (uint64_t)userData->cudaStream; db.outputs.simTime() = userData->simTime; db.outputs.hydraTime() = userData->hydraTime; return true; } static void initialize(const GraphContextObj&, const NodeObj&) { CARB_LOG_WARN_ONCE("OgnRenderPostprocessEntry is depreciated. Please use OgnGpuInteropCudaEntry"); } static void initializeType(const NodeTypeObj& nodeTypeObj) { OgnRenderPostprocessEntryDatabase::initializeType(nodeTypeObj); } }; REGISTER_OGN_NODE() } } }
2,712
C++
34.233766
139
0.724926
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimAttribute.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnReadPrimAttributeDatabase.h> #include <omni/graph/core/IAttributeType.h> #include <omni/graph/core/StringUtils.h> #include <omni/graph/core/CppWrappers.h> #include <omni/usd/UsdContext.h> #include <omni/fabric/FabricUSD.h> #include "PrimCommon.h" #include "ReadPrimCommon.h" using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { static thread_local bool recurseGuard{ false }; class OgnReadPrimAttribute { static bool importAtTime(omni::fabric::FabricId fabricId, NodeObj const& nodeObj, GraphContextObj const& context, pxr::UsdPrim const& prim, TokenC srcName, pxr::SdfTimeCode const& time, OgnReadPrimAttributeDatabase& db, size_t offset) { CARB_PROFILE_ZONE(1, "ImportAtTime"); IFabricUsd* iFabricUsd = carb::getCachedInterface<IFabricUsd>(); // Handle the case where the prim is not yet available if (! prim.IsValid()) { CARB_LOG_WARN("Attempted to import time from invalid prim from node '%s' and source '%s'", nodeObj.iNode->getPrimPath(nodeObj), omni::fabric::toTfToken(srcName).GetText() ); return false; } pxr::SdfPath importPath = prim.GetPath(); bool force = false; if (UsdTimeCode::Default() != time) { force = true; char const* primPath = nodeObj.iNode->getPrimPath(nodeObj); static constexpr char const kImportSubPath[] = "/Import"; std::string storingPath; storingPath.reserve(strlen(primPath) + sizeof(kImportSubPath)); storingPath = primPath; storingPath += kImportSubPath; importPath = pxr::SdfPath(storingPath); } { CARB_PROFILE_ZONE(1, "ImportUSDToFabric"); BucketId srcPrimBucketId = omni::graph::nodes::addAttribToCache(prim, importPath, srcName, iFabricUsd, fabricId, time, force); if (srcPrimBucketId == kInvalidBucketId) { OgnReadPrimAttributeDatabase::logError( nodeObj, "Unable to add prim %s to fabric", prim.GetPath().GetText()); return false; } } db.state.time(offset) = time.GetValue(); db.state.srcPath(offset) = asInt(prim.GetPath()).path; db.state.srcPathAsToken(offset) = asInt(prim.GetPath().GetAsToken()).token; db.state.importPath(offset) = asInt(importPath).path; db.state.srcAttrib(offset) = srcName.token; return true; } static void setup(NodeObj const& nodeObj, GraphContextObj const& context, pxr::SdfTimeCode const& time, OgnReadPrimAttributeDatabase& db, size_t offset, bool isInCompute) { if (recurseGuard) return; CARB_PROFILE_ZONE(1, "setup"); recurseGuard = true; std::shared_ptr<nullptr_t> atScopExist(nullptr, [](auto) { recurseGuard = false; }); auto typeInterface{ carb::getCachedInterface<omni::graph::core::IAttributeType>() }; InstanceIndex instanceIndex = db.getInstanceIndex() + offset; db.state.correctlySetup(offset) = false; pxr::UsdAttribute attrib; try { attrib = omni::graph::nodes::findSelectedAttribute(context, nodeObj, instanceIndex); } catch (std::runtime_error const& error) { if (isInCompute) OgnReadPrimAttributeDatabase::logError(nodeObj,error.what()); return; } if (!attrib) { // Couldn't get the indicated attribute for some expected reason if (isInCompute) OgnReadPrimAttributeDatabase::logError(nodeObj, "Prim has not been set"); return; } auto typeName{ attrib ? attrib.GetTypeName().GetAsToken() : pxr::TfToken() }; Type attribType{ typeInterface->typeFromSdfTypeName(typeName.GetText()) }; tryResolveOutputAttribute(nodeObj, outputs::value.m_token, attribType); // Get interfaces const INode& iNode = *nodeObj.iNode; pxr::UsdPrim prim{ attrib.GetPrim() }; if (!attrib.IsAuthored()) { if (UsdTimeCode::Default() != time) { CARB_LOG_ERROR("Access a non authored attrib %s:%s with a specific timestamp is not allowed", attrib.GetName().GetText(), prim.GetPath().GetText()); return; } // fabric only cares about _authored_ attributes, so in order to make use of fabric mirrored arrays we // have to contrive to have values authored, even if we just want to read them. // // FIXME: OM-36961 exists to work around this issue some other way. CARB_LOG_INFO("%s: Attribute %s is not authored, authoring now", iNode.getPrimPath(nodeObj), attrib.GetPath().GetText()); // -------------------------------------------------------------------------------------- // Get PrimVar into fabric by creating it on the prim if (pxr::UsdGeomPrimvar::IsPrimvar(attrib)) { try { addPrimvarToFabric(prim, attrib); } catch (std::runtime_error const& error) { OgnReadPrimAttributeDatabase::logError(nodeObj,error.what()); return; } } else { // -------------------------------------------------------------------------------------- // Get non-primvar into fabric by authoring the attribute with the composed value pxr::VtValue val; if (!attrib.Get(&val)) { OgnReadPrimAttributeDatabase::logError(nodeObj,"Unable to read %s of type %s", attrib.GetPath().GetText(), val.GetTypeName().c_str()); return; } if (!attrib.Set(val)) { OgnReadPrimAttributeDatabase::logError(nodeObj,"Unable to author %s with value of type %s", attrib.GetPath().GetText(), val.GetTypeName().c_str()); return; } } } // Fill Fabric with USD data pxr::UsdStageRefPtr stage; omni::fabric::FabricId fabricId; std::tie(fabricId, stage) = getFabricForNode(context, nodeObj); if (fabricId == omni::fabric::kInvalidFabricId) return; if (!importAtTime(fabricId, nodeObj, context, prim, asInt(attrib.GetName()), time, db, offset)) return; // If it's resolved, we already know that it is compatible from the above check of the USD AttributeObj outAttrib = nodeObj.iNode->getAttributeByToken(nodeObj, outputs::value.m_token); Type outType = outAttrib.iAttribute->getResolvedType(outAttrib); if (outType == Type()) { // Not resolved, so we have to resolve it now. This node is strange in that the resolved output type // depends on external state instead of other attributes. outAttrib.iAttribute->setResolvedType(outAttrib, attribType); } db.state.correctlySetup(offset) = true; } /** * Adds the given primvar attrib to fabric.At the moment this requires explicit authoring of the value * @param prim: The prim which is in FC, but doesn't have the given primvar * @param attrib: The primvar attribute for the prim, which has no value * @throws: std::runtime_error on failure * @ */ static void addPrimvarToFabric(pxr::UsdPrim prim, pxr::UsdAttribute& attrib) { // Primvars have to go through prim var api if (auto primVarAPI = pxr::UsdGeomPrimvarsAPI(prim)) { if (pxr::UsdGeomPrimvar primVar = primVarAPI.FindPrimvarWithInheritance(attrib.GetName())) { if (auto newPrimVar = primVarAPI.CreatePrimvar(attrib.GetName(), primVar.GetTypeName())) { if (auto& newAttr = newPrimVar.GetAttr()) { // Get the inherited primvar attrib value pxr::VtValue val; if (primVar.Get(&val)) { if (!newAttr.Set(val)) { throw std::runtime_error(formatString("Unable to author primvar %s with value of type %s", newAttr.GetPath().GetText(), val.GetTypeName().c_str())); } } else { // We don't have any value to copy, so lets use the default auto const& defaultValue = primVar.GetTypeName().GetDefaultValue(); if (!newAttr.Set(defaultValue)) { throw std::runtime_error( formatString("Unable to author primvar %s with default value", newAttr.GetPath().GetText())); } } } } } } } // ---------------------------------------------------------------------------- // Called by OG when our prim attrib changes. We want to catch the case of changing the prim attribute interactively static void onValueChanged(AttributeObj const& attrObj, void const* userData) { // FIXME: Be pedantic about validity checks - this can be run directly by the TfNotice so who knows // when or where this is happening NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) }; if (nodeObj.nodeHandle == kInvalidNodeHandle) return; GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; //no setup if graph is disabled (during python edition for instance) if (graphObj.iGraph->isDisabled(graphObj)) return; GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) }; if (context.contextHandle == kInvalidGraphContextHandle) return; OgnReadPrimAttributeDatabase db(context, nodeObj); setup(nodeObj, context, db.state.time(), db, 0, false); } public: // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { // We need to check resolution if any of our relevant inputs change std::array<NameToken, 4> attribNames{ inputs::name.m_token, inputs::usePath.m_token, inputs::primPath.m_token, inputs::prim.m_token }; for (auto const& attribName : attribNames) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); } } // ---------------------------------------------------------------------------- static void onConnectionTypeResolve(const NodeObj& nodeObj) { GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) }; if (context.contextHandle == kInvalidGraphContextHandle) return; OgnReadPrimAttributeDatabase db(context, nodeObj); setup(nodeObj, context, db.state.time(), db, 0, false); } // ---------------------------------------------------------------------------- static bool computeVectorized(OgnReadPrimAttributeDatabase& db, size_t count) { NodeObj nodeObj = db.abi_node(); GraphContextObj ctx = db.abi_context(); pxr::UsdStageRefPtr stage; omni::fabric::FabricId fabricId; std::tie(fabricId, stage) = getFabricForNode(ctx, nodeObj); if (fabricId == omni::fabric::kInvalidFabricId) return false; ////////////////////////////////////////////////////////////////////////// //Gather vectorized data auto time = db.inputs.usdTimecode.vectorized(count); auto usePath = db.inputs.usePath.vectorized(count); auto primPath = db.inputs.primPath.vectorized(count); auto name = db.inputs.name.vectorized(count); auto correctlySetup = db.state.correctlySetup.vectorized(count); auto stateTime = db.state.time.vectorized(count); auto importPath = db.state.importPath.vectorized(count); auto srcPath = db.state.srcPath.vectorized(count); auto srcPathAsToken = db.state.srcPathAsToken.vectorized(count); auto srcAttrib = db.state.srcAttrib.vectorized(count); ////////////////////////////////////////////////////////////////////////// // Make sure setup is correctly performed for (size_t idx = 0; idx < count; ++idx) { if (!correctlySetup[idx]) { setup(nodeObj, ctx, time[idx], db, idx, true); } else { auto pathToken = usePath[idx] ? primPath[idx] : db.pathToToken(db.inputs.prim.firstOrDefault(idx));; if (pathToken != srcPathAsToken[idx] || name[idx] != srcAttrib[idx]) setup(nodeObj, ctx, time[idx], db, idx, true); } if (correctlySetup[idx] && UsdTimeCode(time[idx]) != stateTime[idx]) { auto prim = stage->GetPrimAtPath(intToPath(srcPath[idx])); correctlySetup[idx] = importAtTime(fabricId, nodeObj, ctx, prim, name[idx], time[idx], db, idx); } } ////////////////////////////////////////////////////////////////////////// //Do the copy by the data model or by hand if possible // for array or GPU attributes, go through the data model to properly handle the copy Type const type = db.outputs.value().type(); bool const useDataModel = type.arrayDepth || ctx.iAttributeData->gpuValid(db.outputs.value().abi_handle(), ctx); if (useDataModel) { for (size_t idx = 0; idx < count; ++idx) { if (correctlySetup[idx]) { ConstAttributeDataHandle const src{ AttrKey{ importPath[idx], srcAttrib[idx] } }; db.abi_context().iAttributeData->copyData( db.outputs.value(idx).abi_handle(), ctx, src); } } } else { // gather dst base pointer uint8_t* dstData = nullptr; size_t stride = 0; db.outputs.value().rawData(dstData, stride); // retrieve src pointers std::vector<ConstAttributeDataHandle> srcHandles; srcHandles.resize(count); for (size_t idx = 0; idx < count; ++idx) { srcHandles[idx] = correctlySetup[idx] ? ConstAttributeDataHandle(AttrKey{ importPath[idx], srcAttrib[idx] }) : ConstAttributeDataHandle::invalidHandle(); } std::vector<void const*> srcData; srcData.resize(count); { CARB_PROFILE_ZONE(1, "Retrieve Pointers"); ctx.iAttributeData->getDataR(srcData.data(), ctx, srcHandles.data(), count); } for (size_t idx = 0; idx < count; ++idx) { if (correctlySetup[idx]) { void* dst = dstData + idx * stride; if (srcData[idx]) memcpy(dst, srcData[idx], stride); else db.logError("computeVectorized attempting to memcpy from nullptr"); } } } return true; } // ---------------------------------------------------------------------------- static bool updateNodeVersion(const GraphContextObj& context, const NodeObj& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { if (oldVersion < 2) { return upgradeUsdTimeCodeInput(context, nodeObj); } } return false; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
17,600
C++
38.911565
154
0.536705
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWriteVariable.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnWriteVariableDatabase.h> #include <carb/events/EventsUtils.h> #include "PrimCommon.h" namespace omni { namespace graph { namespace core { class OgnWriteVariable { public: carb::events::ISubscriptionPtr m_EventSubscription; // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); onConnectionTypeResolve(nodeObj); GraphObj graphObj{ context.iContext->getGraph(context) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; OgnWriteVariableDatabase::sInternalState<OgnWriteVariable>(nodeObj) .m_EventSubscription = carb::events::createSubscriptionToPop(graphObj.iGraph->getEventStream(graphObj).get(), [nodeObj](carb::events::IEvent* e) { switch (static_cast<IGraphEvent>(e->type)) { case IGraphEvent::eCreateVariable: case IGraphEvent::eRemoveVariable: case IGraphEvent::eVariableTypeChange: onConnectionTypeResolve(nodeObj); break; default: break; } }); } // ---------------------------------------------------------------------------- // Called by OG to resolve the input type static void onConnectionTypeResolve(const NodeObj& nodeObj) { onValueChanged(nodeObj.iNode->getAttributeByToken(nodeObj, inputs::variableName.m_token), nullptr); } // ---------------------------------------------------------------------------- // Called by OG when the value of the variableName changes static void onValueChanged(AttributeObj const& attrObj, void const* userData) { auto nodeObj = attrObj.iAttribute->getNode(attrObj); if (nodeObj.nodeHandle == kInvalidNodeHandle) return; auto graphObj = nodeObj.iNode->getGraph(nodeObj); if (graphObj.graphHandle == kInvalidGraphHandle) return; auto context = graphObj.iGraph->getDefaultGraphContext(graphObj); if (context.contextHandle == kInvalidGraphContextHandle) return; Type type(BaseDataType::eUnknown); const auto token = getDataR<NameToken>( context, attrObj.iAttribute->getConstAttributeDataHandle(attrObj, kAccordingToContextIndex)); if (token) { auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>(); auto variable = graphObj.iGraph->findVariable(graphObj, tokenInterface->getText(*token)); if (variable) { type = variable->getType(); } } omni::graph::nodes::tryResolveInputAttribute(nodeObj, inputs::value.m_token, type); omni::graph::nodes::tryResolveOutputAttribute(nodeObj, outputs::value.m_token, type); } static bool computeVectorized(OgnWriteVariableDatabase& db, size_t count) { auto variable = db.getVariable(db.inputs.variableName()); if (!variable.isValid()) return false; auto& node = db.abi_node(); if (!variable.type().compatibleRawData(db.outputs.value().type())) { db.logError("Variable %s with type %s is not compatible with type '%s', please disconnect", db.tokenToString(db.inputs.variableName()), variable.type().getTypeName().c_str(), db.outputs.value().typeName().c_str()); return false; } if (variable.type().role != db.outputs.value().type().role) { if (variable.type().role != AttributeRole ::eNone && db.outputs.value().type().role != AttributeRole::eNone) { db.logWarning("Roles between variable %s (%s) and output (%s) differs", db.tokenToString(db.inputs.variableName()), getAttributeRoleName(variable.type().role).c_str(), getAttributeRoleName(db.outputs.value().type().role).c_str()); } } if (variable.type() != db.inputs.value().type()) { auto attribute = db.abi_node().iNode->getAttributeByToken(node, inputs::value.m_token); attribute.iAttribute->setResolvedType(attribute, variable.type()); return 0; } // and going through the ABI is mandatory on a per instance basis auto varNameAttrib = node.iNode->getAttributeByToken(node, inputs::variableName.m_token); bool const isVarNameConstant = varNameAttrib.iAttribute->isRuntimeConstant(varNameAttrib); if (variable.type().arrayDepth || !isVarNameConstant) { auto varName = db.inputs.variableName(); for (size_t i = 0; i < count; ++i) { variable = db.getVariable(varName, {i}); variable.copyData(db.inputs.value(i)); // forces an access to trigger CoW and have a real copy if (variable.type().arrayDepth) { RawPtr ptr; size_t s; variable.rawData(ptr, s); } db.outputs.value(i).copyData(variable); } } else { uint8_t* dst = nullptr; size_t sd; variable.rawData(dst, sd); uint8_t const* src = nullptr; size_t ss; db.inputs.value().rawData(src, ss); if (ss != sd) return 0; memcpy(dst, src, ss * count); db.outputs.value().rawData(dst, sd); if (ss != sd) return 0; memcpy(dst, src, ss * count); } auto execOut = db.outputs.execOut.vectorized(count); std::fill(execOut.begin(), execOut.end(), kExecutionAttributeStateEnabled); return true; } }; REGISTER_OGN_NODE() } // namespace examples } // namespace graph } // namespace omni
7,662
C++
39.544973
121
0.512268
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnExtractPrim.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "OgnExtractPrimDatabase.h" #include "ReadPrimCommon.h" namespace omni { namespace graph { namespace nodes { class OgnExtractPrim { public: // Copies attributes from an input bundle to attributes directly on the node static bool compute(OgnExtractPrimDatabase& db) { auto& contextObj = db.abi_context(); auto& nodeObj = db.abi_node(); auto const& inputPrims = db.inputs.prims(); // The computation should only be performed when input bundle or prim or prim path changes. // At this moment, unfortunately, there is no way to find out if incoming bundle has changed. // That means we have to recompute all the time. // Extracting bundles is a O(n) operation in worse case. If the number of children in the input bundle // is substantial, then we can get significant performance slow down. // When Dirty IDs interface is in place, this function should be updated to recompute only // when input bundle, or prim path is out of date. // Suggestion: an internal cache - a map of path to child bundle handle could be sufficient. ConstBundleHandle extractedHandle{ ConstBundleHandle::invalidValue() }; if(db.inputs.prim().size() == 0) { // extract child bundle using input prim path std::string const pathStr{ db.inputs.primPath() }; if (PXR_NS::SdfPath::IsValidPathString(pathStr)) { auto primPath = omni::fabric::asInt(PXR_NS::TfToken(pathStr.data())); extractedHandle = extractPrimByPath(contextObj, inputPrims, primPath); } } else { if(db.inputs.prim().size() > 1) db.logWarning("Only one prim target is supported, the rest will be ignored"); extractedHandle = extractPrimByPath(contextObj, inputPrims, db.pathToToken(db.inputs.prim()[0])); } // update outputs BundleType extractedBundle(contextObj, extractedHandle); db.outputs.primBundle() = extractedBundle; return extractedBundle.isValid(); } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
2,684
C++
35.780821
110
0.669151
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrim.cpp
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /* _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ ReadPrim is deprecated and should not be used. First version of ReadPrim outputs 'Single Primitive in a Bundle'(SPiB) + Dynamic Attributes(DA). The successor ReadPrims outputs 'Multiple Primitives in a Bundle'(MPiB) with no dynamic attributes. This operator is kept for backward compatibility. */ // clang-format off #include "UsdPCH.h" // clang-format on #include "OgnReadPrimDatabase.h" #include "PrimCommon.h" #include "ReadPrimCommon.h" #include <omni/kit/commands/ICommandBridge.h> #include <carb/dictionary/DictionaryUtils.h> #include <omni/fabric/FabricUSD.h> #include <omni/kit/PythonInterOpHelper.h> namespace omni { namespace graph { namespace nodes { class OgnReadPrim { std::unordered_set<NameToken> m_added; public: // ---------------------------------------------------------------------------- static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { char const* primNodePath = nodeObj.iNode->getPrimPath(nodeObj); CARB_LOG_WARN("ReadPrim node is deprecated: %s, use ReadPrimAttributes instead", primNodePath); // When inputs:bundle is not an optional input, the outputs need to be cleared when they are disconnected. AttributeObj inputBundleAttribObj = nodeObj.iNode->getAttributeByToken(nodeObj, OgnReadPrimAttributes::inputs::prim.m_token); inputBundleAttribObj.iAttribute->registerValueChangedCallback( inputBundleAttribObj, onInputBundleValueChanged, true); } // ---------------------------------------------------------------------------- static void onInputBundleValueChanged(AttributeObj const& inputBundleAttribObj, void const* userData) { NodeObj nodeObj = inputBundleAttribObj.iAttribute->getNode(inputBundleAttribObj); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); // If the graph is currently disabled then delay the update until the next compute. // Arguably this should be done at the message propagation layer, then this wouldn't be necessary. if (graphObj.iGraph->isDisabled(graphObj)) { return; } // clear the output bundles GraphContextObj context = graphObj.iGraph->getDefaultGraphContext(graphObj); auto outputTokens = { OgnReadPrimAttributes::outputs::primBundle.m_token }; for (auto& outputToken : outputTokens) { BundleHandle outBundle = context.iContext->getOutputBundle( context, nodeObj.nodeContextHandle, outputToken, kAccordingToContextIndex); context.iContext->clearBundleContents(context, outBundle); } } // ---------------------------------------------------------------------------- static PathC getPath(OgnReadPrimDatabase& db) { return readPrimBundle_getPath(db.abi_context(), db.abi_node(), OgnReadPrimAttributes::inputs::prim.m_token, false, omni::fabric::kUninitializedToken, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static bool writeToBundle(OgnReadPrimDatabase& db, PathC inputPath, bool force, pxr::UsdTimeCode const& time) { return readPrimBundle_writeToBundle(db.abi_context(), db.abi_node(), inputPath, db.inputs.attrNamesToImport(), db.outputs.primBundle(), force, db.inputs.computeBoundingBox(), time, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static void clean(OgnReadPrimDatabase& db) { db.outputs.primBundle().clear(); // remove dynamic attributes BundleType empty; updateAttributes(db.abi_context(), db.abi_node(), empty, db.getInstanceIndex()); } // ---------------------------------------------------------------------------- static void updateAttributes(GraphContextObj const& contextObj, NodeObj const& nodeObj, BundleType const& bundle, InstanceIndex instIdx) { OgnReadPrim& state = OgnReadPrimDatabase::sInternalState<OgnReadPrim>(nodeObj); omni::kit::commands::ICommandBridge::ScopedUndoGroup scopedUndoGroup; extractBundle_reflectBundleDynamicAttributes(nodeObj, contextObj, bundle, state.m_added, instIdx); } // ---------------------------------------------------------------------------- static bool compute(OgnReadPrimDatabase& db) { // import by pattern bool inputChanged = false; // bounding box changed if (db.state.computeBoundingBox() != db.inputs.computeBoundingBox()) { db.state.computeBoundingBox() = db.inputs.computeBoundingBox(); inputChanged = true; } // attribute filter changed NameToken const attrNamesToImport = db.inputs.attrNamesToImport(); if (db.state.attrNamesToImport() != attrNamesToImport.token) { db.state.attrNamesToImport() = attrNamesToImport.token; inputChanged = true; } // compute bool result = readPrimBundle_compute<OgnReadPrim>(db, inputChanged); if (!result) return false; // update dynamic attributes BundleType outputBundle(db.abi_context(), db.outputs.primBundle().abi_bundleHandle()); updateAttributes(db.abi_context(), db.abi_node(), outputBundle, db.getInstanceIndex()); return outputBundle.isValid(); } static bool updateNodeVersion(GraphContextObj const& context, NodeObj const& nodeObj, int oldVersion, int newVersion) { if (oldVersion < newVersion) { bool upgraded = false; if (oldVersion < 6) { // backward compatibility: `inputs:attrNamesToImport` // Prior to this version `inputs:attrNamesToImport` attribute did not support wild cards. // The meaning of an empty string was to include all attributes. With the introduction of the wild cards // we need to convert an empty string to "*" in order to include all attributes. static Token const value{ "*" }; if (nodeObj.iNode->getAttributeExists(nodeObj, "inputs:attrNamesToImport")) { AttributeObj attr = nodeObj.iNode->getAttribute(nodeObj, "inputs:attrNamesToImport"); auto roHandle = attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex); Token const* roValue = getDataR<Token const>(context, roHandle); if (roValue && roValue->getString().empty()) { Token* rwValue = getDataW<Token>(context, attr.iAttribute->getAttributeDataHandle(attr, kAccordingToContextIndex)); *rwValue = value; } } else { nodeObj.iNode->createAttribute(nodeObj, "inputs:attrNamesToImport", Type(BaseDataType::eToken), &value, nullptr, kAttributePortType_Input, kExtendedAttributeType_Regular, nullptr); } upgraded = true; } if (oldVersion < 8) { upgraded |= upgradeUsdTimeCodeInput(context, nodeObj); } return upgraded; } return false; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
8,672
C++
41.101942
138
0.559502
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGpuInteropRenderProductEntry.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 "OgnGpuInteropRenderProductEntryDatabase.h" #include <omni/graph/core/NodeTypeRegistrar.h> #include <omni/graph/core/GpuInteropEntryUserData.h> #include <omni/graph/core/iComputeGraph.h> namespace omni { namespace graph { namespace core { // Replaces depreciated GpuInteropRenderProductEntry // Downstream nodes of OgnGpuInteropRenderProductEntry can write Cuda code directly and they will be scheduled on the // Gpu Foundations Rendergraph for Device 0. GpuInteropCudaEntry passes the cuda buffer pointer and // associated metadata for a specific named resource outputted by the Rtx Renderer (such as LdrColor for // final color). This buffer is a read/write buffer, and changes will be passed to consumer of the renderer's // output class OgnGpuInteropRenderProductEntry { public: static bool compute(OgnGpuInteropRenderProductEntryDatabase& db) { GpuInteropRpEntryUserData* userData = static_cast<GpuInteropRpEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node())); if (!userData) return false; db.outputs.simTime() = userData->simTime; db.outputs.hydraTime() = userData->hydraTime; db.outputs.rp() = (uint64_t)userData->rp; db.outputs.gpu() = (uint64_t)userData->gpu; db.outputs.exec() = ExecutionAttributeState::kExecutionAttributeStateEnabled; return true; } static void initializeType(const NodeTypeObj& nodeTypeObj) { OgnGpuInteropRenderProductEntryDatabase::initializeType(nodeTypeObj); } }; REGISTER_OGN_NODE() } } }
2,011
C++
33.689655
135
0.751367
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenameAttr.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 "OgnRenameAttrDatabase.h" #include "TokenUtils.h" #include <algorithm> #include <string> #include <unordered_map> #include <vector> namespace omni { namespace graph { namespace nodes { class OgnRenameAttr { public: // Changes the names of attributes from an input prim for the corresponding output prim. // Attributes not renamed will be copied from the input prim to the output prim without changing the name. static bool compute(OgnRenameAttrDatabase& db) { const auto& inputBundle = db.inputs.data(); auto& outputBundle = db.outputs.data(); // Find all of the attribute names for selection. std::vector<NameToken> inputAttrNames; std::vector<NameToken> outputAttrNames; TokenHelper::splitNames(db.tokenToString(db.inputs.inputAttrNames()), inputAttrNames); TokenHelper::splitNames(db.tokenToString(db.inputs.outputAttrNames()), outputAttrNames); size_t nameCount = std::min(inputAttrNames.size(), outputAttrNames.size()); if (nameCount == 0) { // No renaming, so we can just copy the input data into the output. outputBundle = inputBundle; return true; } // Mismatched name sizes are dealt with going with the minimum number, and reporting this warning if (inputAttrNames.size() != outputAttrNames.size()) { db.logWarning("Input name size %zu != output name size %zu", inputAttrNames.size(), outputAttrNames.size()); // Reduce the size of the name arrays to make them easier to look up later inputAttrNames.resize(nameCount); outputAttrNames.resize(nameCount); } // Zip them together so that iterators can be used to find matches std::unordered_map<NameToken, NameToken> attrNameMap; std::transform(inputAttrNames.begin(), inputAttrNames.end(), outputAttrNames.begin(), std::inserter(attrNameMap, attrNameMap.end()), [](NameToken a, NameToken b) { return std::make_pair(a, b); }); // Start from an empty output prim. outputBundle.clear(); // Loop through the attributes on the input bundle, adding them to the output and renaming if they appear // on the list. for (const auto& input : inputBundle) { CARB_ASSERT(input.isValid()); auto newName = input.name(); // If the attribute's name is in the renaming list then rename it auto itNameFound = attrNameMap.find(input.name()); if (itNameFound != attrNameMap.end()) { newName = itNameFound->second; } outputBundle.insertAttribute(input, newName); } return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
3,297
C++
35.644444
120
0.653321
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRenderPreprocessEntry.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 "OgnRenderPreprocessEntryDatabase.h" #include <omni/graph/core/NodeTypeRegistrar.h> #include <omni/graph/core/GpuInteropEntryUserData.h> #include <omni/graph/core/iComputeGraph.h> namespace omni { namespace graph { namespace core { // OmniGraph nodes executed as a render preprocess need to be connected downstream of an entry point node // in order to be scheduled as part of the render graph. // Scheduling of cuda interop nodes begins with one of these entry nodes, which passes data (e.g. a cuda stream // identifier) to downstream nodes. class OgnRenderPreprocessEntry { public: static bool compute(OgnRenderPreprocessEntryDatabase& db) { CARB_PROFILE_ZONE(1, "OgnRenderPreprocessEntry::compute"); GpuInteropCudaEntryUserData* userData = static_cast<GpuInteropCudaEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node())); if (!userData) return false; db.outputs.stream() = (uint64_t)userData->cudaStream; db.outputs.simTime() = userData->simTime; db.outputs.hydraTime() = userData->hydraTime; return true; } static void initializeType(const NodeTypeObj& nodeTypeObj) { OgnRenderPreprocessEntryDatabase::initializeType(nodeTypeObj); } }; REGISTER_OGN_NODE() } } }
1,730
C++
29.910714
139
0.74104
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnRemoveAttr.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 "OgnRemoveAttrDatabase.h" #include "TokenUtils.h" #include "PrimCommon.h" #include <algorithm> #include <unordered_set> namespace omni { namespace graph { namespace nodes { class OgnRemoveAttr { public: // Copies all attributes from an input prim to the output prim, except for any specified to be removed. static bool compute(OgnRemoveAttrDatabase& db) { auto& inputBundle = db.inputs.data(); auto& outputBundle = db.outputs.data(); outputBundle = inputBundle; // Use pattern matching to find the attribute names. std::vector<NameToken> attributes(outputBundle.attributeCount()); outputBundle.abi_bundleInterface()->getAttributeNames(attributes.data(), attributes.size()); std::vector<NameToken> remove; remove.reserve(outputBundle.attributeCount()); std::string const& attrNamesToRemove = intToToken(db.inputs.attrNamesToRemove()).GetString(); PatternMatcher attrNameMatcher{ attrNamesToRemove }; // allow removing primitive internal attributes if (!db.inputs.allowRemovePrimInternal()) attrNameMatcher.addExcludeTokens(getPrimAdditionalAttrs().names); for (auto attribute : attributes) { if (attrNameMatcher && attrNameMatcher.matches(attribute)) { remove.push_back(attribute); } } if (!remove.empty()) { outputBundle.removeAttributes(remove.size(), remove.data()); } return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
2,042
C++
28.185714
107
0.682174
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGpuInteropCudaEntry.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 "OgnGpuInteropCudaEntryDatabase.h" #include <omni/graph/core/NodeTypeRegistrar.h> #include <omni/graph/core/GpuInteropEntryUserData.h> #include <omni/graph/core/iComputeGraph.h> namespace omni { namespace graph { namespace core { // Replaces depreciated RenderPostprocessEntry // Downstream nodes of OgnGpuInteropCudaEntry can write Cuda code directly and they will be scheduled on the // Gpu Foundations Rendergraph for Device 0. GpuInteropCudaEntry passes the cuda buffer pointer and // associated metadata for a specific named resource outputted by the Rtx Renderer (such as LdrColor for // final color). This buffer is a read/write buffer, and changes will be passed to consumer of the renderer's // output class OgnGpuInteropCudaEntry { public: static bool compute(OgnGpuInteropCudaEntryDatabase& db) { GpuInteropCudaEntryUserData* userData = static_cast<GpuInteropCudaEntryUserData*>(db.abi_node().iNode->getUserData(db.abi_node())); if (!userData) return false; GpuInteropCudaResourceMap& cudaRsrcMap = userData->cudaRsrcMap; std::string sourceName = db.inputs.sourceName(); auto it = cudaRsrcMap.find(sourceName); if (it == cudaRsrcMap.end()) { return false; } GpuInteropCudaResourceData& renderVarData = it->second; db.outputs.cudaMipmappedArray() = (uint64_t)renderVarData.cudaResource; db.outputs.width() = renderVarData.width; db.outputs.height() = renderVarData.height; db.outputs.isBuffer() = renderVarData.isBuffer; db.outputs.bufferSize() = renderVarData.depthOrArraySize; db.outputs.mipCount() = (uint32_t)renderVarData.mipCount; db.outputs.format() = (uint64_t)renderVarData.format; db.outputs.stream() = (uint64_t)userData->cudaStream; db.outputs.simTime() = userData->simTime; db.outputs.hydraTime() = userData->hydraTime; db.outputs.externalTimeOfSimFrame() = userData->externalTimeOfSimFrame; db.outputs.frameId() = userData->frameId; return true; } static void initializeType(const NodeTypeObj& nodeTypeObj) { OgnGpuInteropCudaEntryDatabase::initializeType(nodeTypeObj); } }; REGISTER_OGN_NODE() } } }
2,729
C++
34
139
0.720777
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnEventUpdateTick.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 "OgnEventUpdateTickDatabase.h" namespace omni { namespace graph { namespace core { class OgnEventUpdateTick { public: static bool compute(OgnEventUpdateTickDatabase& db) { // FIXME: temporary incomplete implementation. Always output event id of 0 for now. // This is not useful of course, but does allow the event connenction to trigger. // In time this should become a bundle, to incorporate information about the event // received. db.outputs.event() = 0; return true; } }; REGISTER_OGN_NODE() } } }
1,016
C++
26.486486
92
0.729331
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGraphTarget.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnGraphTargetDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnGraphTarget { public: static size_t computeVectorized(OgnGraphTargetDatabase& db, size_t count) { auto targets = db.getGraphTargets(count); auto paths = db.outputs.primPath.vectorized(count); memcpy(paths.data(), targets.data(), count * sizeof(NameToken)); return count; } }; REGISTER_OGN_NODE() } } }
943
C++
23.205128
77
0.732768
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimMaterial.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <omni/fabric/FabricUSD.h> #include "OgnWritePrimMaterialDatabase.h" using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { class OgnWritePrimMaterial { public: static bool compute(OgnWritePrimMaterialDatabase& db) { // Find our stage const GraphContextObj& context = db.abi_context(); long stageId = context.iContext->getStageId(context); PXR_NS::UsdStagePtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logError("Could not find USD stage %ld", stageId); return false; } PXR_NS::SdfPath sdfPath; if(db.inputs.prim().size() == 0) { const auto& primPath = db.inputs.primPath(); if (!PXR_NS::SdfPath::IsValidPathString(primPath)) { db.logError("Invalid prim path"); return false; } sdfPath = PXR_NS::SdfPath(primPath); } else { if(db.inputs.prim().size() > 1) db.logWarning("Only one prim target is supported, the rest will be ignored"); sdfPath = omni::fabric::toSdfPath(db.inputs.prim()[0]); } PXR_NS::UsdPrim prim = stage->GetPrimAtPath(sdfPath); if (!prim) { db.logError("Could not find USD prim"); return false; } PXR_NS::SdfPath materialSdfPath; if(db.inputs.material().size() == 0) { const auto& materialPath = db.inputs.materialPath(); if (!PXR_NS::SdfPath::IsValidPathString(materialPath)) { db.logError("Invalid material path"); return false; } materialSdfPath = PXR_NS::SdfPath(materialPath); } else { if(db.inputs.material().size() > 1) db.logWarning("Only one material target is supported, the rest will be ignored"); materialSdfPath = omni::fabric::toSdfPath(db.inputs.material()[0]); } PXR_NS::UsdPrim materialPrim = stage->GetPrimAtPath(materialSdfPath); if (!materialPrim) { db.logError("Could not find USD material"); return false; } PXR_NS::UsdShadeMaterialBindingAPI materialBinding(prim); PXR_NS::UsdShadeMaterial material(materialPrim); if (!materialBinding.Bind(material)) { db.logError("Could not bind USD material to USD prim"); return false; } db.outputs.execOut() = kExecutionAttributeStateEnabled; return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
3,245
C++
29.336448
118
0.606163
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimMaterial.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include "OgnReadPrimMaterialDatabase.h" #include <omni/fabric/FabricUSD.h> using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { class OgnReadPrimMaterial { public: static bool compute(OgnReadPrimMaterialDatabase& db) { // Fetch from the target input by default, if it's not set, // use the prim path PXR_NS::SdfPath sdfPath; if (db.inputs.prim.size() == 0) { const auto& primPath = db.inputs.primPath(); if (!PXR_NS::SdfPath::IsValidPathString(primPath)) { db.logError("Invalid prim path"); return false; } sdfPath = PXR_NS::SdfPath(primPath); } else { sdfPath = omni::fabric::toSdfPath(db.inputs.prim()[0]); } // Find our stage const GraphContextObj& context = db.abi_context(); long stageId = context.iContext->getStageId(context); PXR_NS::UsdStagePtr stage = PXR_NS::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId)); if (!stage) { db.logError("Could not find USD stage %ld", stageId); return false; } PXR_NS::UsdPrim prim = stage->GetPrimAtPath(sdfPath); if (!prim) { db.logError("Could not find USD prim at %s", sdfPath.GetText()); return false; } PXR_NS::UsdShadeMaterialBindingAPI materialBinding(prim); PXR_NS::UsdShadeMaterial boundMat = materialBinding.ComputeBoundMaterial(); if (!boundMat) { db.outputs.material() = ""; db.outputs.materialPrim().resize(0); return true; } db.outputs.material() = boundMat.GetPath().GetString().c_str(); db.outputs.materialPrim().resize(1); db.outputs.materialPrim()[0] = omni::fabric::asInt(boundMat.GetPath()); return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
2,539
C++
27.863636
121
0.620323
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnWritePrimAttribute.cpp
// Copyright (c) 2021-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <memory> #include "PrimCommon.h" #include <omni/fabric/FabricUSD.h> #include <omni/usd/UsdContext.h> #include <OgnWritePrimAttributeDatabase.h> using namespace omni::fabric; namespace omni { namespace graph { namespace nodes { // WARNING! // The following code uses low-level ABI functionality and should not be copied for other purposes when such // low level access is not required. Please use the OGN-generated API whenever possible. static const pxr::TfType s_tokenTfType = pxr::SdfValueTypeNames->Token.GetType(); static const TypeC s_tokenType = TypeC(Type(BaseDataType::eToken)); static thread_local bool recursiveSetupGuard = false; class OgnWritePrimAttribute { static void setup(NodeObj const& nodeObj, GraphObj const& graphObj, OgnWritePrimAttributeDatabase& db, size_t offset) { // Check for re-entering setup and avoid. EG When input is being resolved we may get onConnectionTypeResolve() if (recursiveSetupGuard) return; CARB_PROFILE_ZONE(1, "setup"); recursiveSetupGuard = true; std::shared_ptr<nullptr_t> atScopeExit(nullptr, [](auto) { recursiveSetupGuard = false; }); InstanceIndex instanceIndex = db.getInstanceIndex() + offset; db.state.correctlySetup(offset) = false; GraphContextObj context{ graphObj.iGraph->getDefaultGraphContext(graphObj) }; if (context.contextHandle == kInvalidGraphContextHandle) return; auto typeInterface{ carb::getCachedInterface<omni::graph::core::IAttributeType>() }; pxr::UsdAttribute attrib; try { attrib = omni::graph::nodes::findSelectedAttribute(context, nodeObj, instanceIndex); } catch (std::runtime_error const&) { // Ignore errors in this callback - error will be reported at the next compute return; } if (!attrib) { // Couldn't get the indicated attribute for some expected reason return; } // Since we are a sink of data, we can assume that if our inputs:value is connected, it will be resolved by // propagation from upstream. We do not want to resolve/unresolve our inputs:value if we are connected because // this could create a type conflict with the upstream network. So instead we will only resolve/unresolve // when we are disconnected, and otherwise error out if we see a conflict. auto typeName{ attrib ? attrib.GetTypeName().GetAsToken() : pxr::TfToken() }; Type usdAttribType{ typeInterface->typeFromSdfTypeName(typeName.GetText()) }; if (!tryResolveInputAttribute(nodeObj, inputs::value.m_token, usdAttribType)) return; AttributeObj srcData = nodeObj.iNode->getAttributeByToken(nodeObj, inputs::value.m_token); Type srcDataType = srcData.iAttribute->getResolvedType(srcData); TypeC srcDataTypeC(srcDataType); // no need to continue if we are not resolved yet if (srcDataType == Type(BaseDataType::eUnknown)) return; IFabricUsd* iFabricUsd = carb::getCachedInterface<IFabricUsd>(); // Find our stage pxr::UsdStageRefPtr stage; omni::fabric::FabricId fabricId; std::tie(fabricId, stage) = getFabricForNode(context, nodeObj); if (fabricId == omni::fabric::kInvalidFabricId) return; pxr::UsdPrim destPrim{ attrib.GetPrim() }; NameToken destAttribName = asInt(attrib.GetName()); // Add the destination Prim to FC BucketId destPrimBucketId = omni::graph::nodes::addAttribToCache( destPrim, destPrim.GetPath(), destAttribName, iFabricUsd, fabricId, UsdTimeCode::Default()); if (destPrimBucketId == kInvalidBucketId) { OgnWritePrimAttributeDatabase::logError(nodeObj, "Unable to add prim %s to fabric", destPrim.GetPrimPath().GetText()); return; } PathC destPath = asInt(destPrim.GetPrimPath()); // Read the type info of the destination attribute auto iStageReaderWriter = carb::getCachedInterface<omni::fabric::IStageReaderWriter>(); auto stageReaderWriterId = iStageReaderWriter->createOrGetFromFabricId(fabricId); if (iStageReaderWriter->attributeExists(stageReaderWriterId,destPath, destAttribName) == 0) { // Failed to add the attribute - it might not be authored // -------------------------------------------------------------------------------------- // Get PrimVar into fabric by creating it on the prim if (pxr::UsdGeomPrimvar::IsPrimvar(attrib)) { // Primvars have to go through prim var api. Note that we don't set the value here. That is because we // will be subsequently writing into the attribute through Fabric. if (auto primVarAPI = pxr::UsdGeomPrimvarsAPI(destPrim)) { if (pxr::UsdGeomPrimvar primVar = primVarAPI.FindPrimvarWithInheritance(attrib.GetName())) { primVarAPI.CreatePrimvar(attrib.GetName(), primVar.GetTypeName()); } } } else { // -------------------------------------------------------------------------------------- // Get non-primvar into fabric by authoring the attribute with the composed value pxr::VtValue val; if (!attrib.Get(&val)) { OgnWritePrimAttributeDatabase::logError( nodeObj, "Unable to read %s of type %s", attrib.GetPath().GetText(), val.GetTypeName().c_str()); return; } if (!attrib.Set(val)) { OgnWritePrimAttributeDatabase::logError(nodeObj, "Unable to author %s with value of type %s", attrib.GetPath().GetText(), val.GetTypeName().c_str()); return; } } if (omni::graph::nodes::addAttribToCache(destPrim, destPrim.GetPath(), destAttribName, iFabricUsd, fabricId, UsdTimeCode::Default()) == kInvalidBucketId) { OgnWritePrimAttributeDatabase::logError( nodeObj, "Unable to add prim %s to fabric", destPrim.GetPrimPath().GetText()); return; } } TypeC destDataTypeC = TypeC(iStageReaderWriter->getType(stageReaderWriterId,destPath, destAttribName)); if (destDataTypeC == kUnknownType) { OgnWritePrimAttributeDatabase::logError( nodeObj, "Unable to add prim %s to fabric", destPrim.GetPrimPath().GetText()); return; } Type destDataType(destDataTypeC); if (!ogn::areTypesCompatible(srcDataType, destDataType)) { OgnWritePrimAttributeDatabase::logError( nodeObj, "Attribute %s.%s is not compatible with type '%s', please disconnect to change target attribute", destPrim.GetPrimPath().GetText(), toTfToken(destAttribName).GetText(), srcDataType.getTypeName().c_str()); return; } db.state.destPath(offset) = destPath.path; db.state.destPathToken(offset) = asInt(destPrim.GetPrimPath().GetToken()).token; db.state.destAttrib(offset) = destAttribName.token; db.state.correctlySetup(offset) = true; } public: // ---------------------------------------------------------------------------- // Called by OG when our prim attrib changes. We want to catch the case of changing the prim attribute interactively static void onValueChanged(AttributeObj const& attrObj, void const* userData) { // FIXME: Be pedantic about validity checks - this can be run directly by the TfNotice so who knows // when or where this is happening NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) }; if (nodeObj.nodeHandle == kInvalidNodeHandle) return; GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; GraphContextObj contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj); OgnWritePrimAttributeDatabase db(contextObj, nodeObj); setup(nodeObj, graphObj, db, 0); } // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { // We need to check resolution if any of our relevant inputs change static std::array<NameToken, 5> const attribNames{ inputs::name.m_token, inputs::usePath.m_token, inputs::primPath.m_token, inputs::prim.m_token , inputs::value.m_token }; for (auto const& attribName : attribNames) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); } } // ---------------------------------------------------------------------------- static void onConnectionTypeResolve(const NodeObj& nodeObj) { GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; GraphContextObj contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj); OgnWritePrimAttributeDatabase db(contextObj, nodeObj); setup(nodeObj, graphObj, db, 0); } // ---------------------------------------------------------------------------- static bool computeVectorized(OgnWritePrimAttributeDatabase& db, size_t count) { if (!db.inputs.value().resolved()) return true; NodeObj nodeObj = db.abi_node(); GraphContextObj context = db.abi_context(); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); Type type = db.inputs.value().type(); bool gpuValid = context.iAttributeData->gpuValid(db.inputs.value().abi_handle(), context); // for array or GPU attributes, go through the data model to properly handle the copy const bool useDataModel = type.arrayDepth || gpuValid || !db.inputs.value.canVectorize(); auto usePath = db.inputs.usePath.vectorized(count); auto primPath = db.inputs.primPath.vectorized(count); auto name = db.inputs.name.vectorized(count); auto execOut = db.outputs.execOut.vectorized(count); auto usdWriteBack = db.inputs.usdWriteBack.vectorized(count); auto correctlySetup = db.state.correctlySetup.vectorized(count); auto destPathToken = db.state.destPathToken.vectorized(count); auto destAttrib = db.state.destAttrib.vectorized(count); auto destPath = db.state.destPath.vectorized(count); for (size_t idx = 0; idx < count; ++idx) { if (!correctlySetup[idx]) { setup(nodeObj, graphObj, db, idx); } else { auto path = usePath[idx] ? primPath[idx].token : db.pathToToken(db.inputs.prim.firstOrDefault(idx)); if (path != destPathToken[idx] || name[idx] != destAttrib[idx]) setup(nodeObj, graphObj, db, idx); } } if (useDataModel) { for (size_t idx = 0; idx < count; ++idx) { if (correctlySetup[idx]) { copyAttributeData(context, destPath[idx], destAttrib[idx], nodeObj, db.inputs.value(idx).abi_handle(), usdWriteBack[idx]); execOut[idx] = kExecutionAttributeStateEnabled; } } } else { // gather src base pointer uint8_t const* srcData = nullptr; size_t stride = 0; db.inputs.value().rawData(srcData, stride); // retrieve dst pointers std::vector<AttributeDataHandle> dstHandles; dstHandles.reserve(count); for (size_t idx = 0; idx < count; ++idx) { if (correctlySetup[idx]) dstHandles.emplace_back(AttrKey{ destPath[idx], destAttrib[idx] }); else dstHandles.push_back(AttributeDataHandle::invalidHandle()); } std::vector<void*> dstData; dstData.resize(count); { CARB_PROFILE_ZONE(1, "Retrieve Pointers"); context.iAttributeData->getDataW(dstData.data(), context, dstHandles.data(), count); } size_t writeBackCount = 0; for (size_t idx = 0; idx < count; ++idx) { if (correctlySetup[idx]) { void const* const src = srcData + idx * stride; if(dstData[idx]) { memcpy(dstData[idx], src, stride); if (usdWriteBack[idx]) { if (idx != writeBackCount) dstHandles[writeBackCount] = dstHandles[idx]; ++writeBackCount; } execOut[idx] = kExecutionAttributeStateEnabled; } else { db.logError("Target attribute not available"); } } } if (writeBackCount) { CARB_PROFILE_ZONE(1, "RegisterWriteBack"); context.iContext->registerForUSDWriteBacks(context, dstHandles.data(), writeBackCount); } } return true; } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
14,779
C++
39.828729
131
0.574464
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGetGraphTargetId.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 <OgnGetGraphTargetIdDatabase.h> namespace omni::graph::nodes { class OgnGetGraphTargetId { public: static size_t computeVectorized(OgnGetGraphTargetIdDatabase& db, size_t count) { auto targets = db.getGraphTargets(count); auto targetId = db.outputs.targetId.vectorized(count); std::transform(targets.begin(), targets.end(), targetId.begin(), [](auto const& t) { return omni::fabric::hash(t); }); return count; } }; REGISTER_OGN_NODE() }
949
C++
29.64516
92
0.718651
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnGatherByPath.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 <OgnGatherByPathDatabase.h> #include <omni/graph/core/IGatherPrototype.h> #include <carb/flatcache/IPath.h> #include <algorithm> #include <vector> using namespace carb::flatcache; namespace omni { namespace graph { namespace core { class OgnGatherByPath { // The arguments from the last compute call - we want to skip our compute if these haven't changed, and we // haven't heard that our Gather has changed. struct LastComputeState { // copies of input values std::vector<NameToken> primPathTokens; // Used in compute to compare to input tokens bool allAttributes{ false }; std::string attributes; NameToken hydraFastPath{ 0 }; bool shouldWriteBack; bool forceExportToHistory{ false }; // data use by path-changed callback std::vector<PathC> primPaths; // Used in OG callback to compare with given paths PathChangedCallback callback{ nullptr, nullptr }; bool checkResyncAttributes{ false }; // Set to true to be notified for resync children bool gatherDirty{ false }; // Set to true by OG callback const carb::flatcache::IPath * iPath = nullptr; }; public: LastComputeState m_state; // Called by OG when anything changes - which indicates buckets may have been modified static void onPathChanged(const carb::flatcache::PathC* paths, const size_t numPaths, void* userData) { NodeHandle nodeHandle = reinterpret_cast<NodeHandle>(userData); auto& state = OgnGatherByPathDatabase::sm_stateManagerOgnGatherByPath.getState<OgnGatherByPath>(nodeHandle).m_state; // set the dirty flag if we recognize one of the changed prim paths - which will indicate a 'resync' notice // we don't care about attribute values changing const auto& gatheredPaths = state.primPaths; auto iter = std::find_first_of(gatheredPaths.begin(), gatheredPaths.end(), paths, paths + numPaths); state.gatherDirty = (iter != gatheredPaths.end()); if (!state.gatherDirty && state.checkResyncAttributes && state.iPath) { auto& iPath = state.iPath; auto iter = std::find_first_of(gatheredPaths.begin(), gatheredPaths.end(), paths, paths + numPaths, [iPath](const PathC a, const PathC b) { return a == iPath->getParent(b); }); state.gatherDirty = (iter != gatheredPaths.end()); } } // ---------------------------------------------------------------------------- static void initialize(const GraphContextObj& context, const NodeObj& nodeObj) { auto& cppObj = OgnGatherByPathDatabase::sInternalState<OgnGatherByPath>(nodeObj); cppObj.m_state.callback = { &onPathChanged, reinterpret_cast<void*>(nodeObj.nodeHandle) }; nodeObj.iNode->registerPathChangedCallback(nodeObj, cppObj.m_state.callback); } // ---------------------------------------------------------------------------- static void release(const NodeObj& nodeObj) { auto& cppObj = OgnGatherByPathDatabase::sInternalState<OgnGatherByPath>(nodeObj); nodeObj.iNode->deregisterPathChangedCallback(nodeObj, cppObj.m_state.callback); } // ---------------------------------------------------------------------------- static bool compute(OgnGatherByPathDatabase& db) { const omni::graph::core::IGatherPrototype* iGatherPrototype = carb::getCachedInterface<omni::graph::core::IGatherPrototype>(); const IGraphContext& iContext = *db.abi_context().iContext; auto& cppObj = db.internalState<OgnGatherByPath>(); LastComputeState& state = cppObj.m_state; const auto& primPathTokens = db.inputs.primPaths(); bool allAttributes = db.inputs.allAttributes(); const auto& attributes = db.inputs.attributes(); auto hydraFastPathToken = db.inputs.hydraFastPath(); const bool& shouldWriteBack = db.inputs.shouldWriteBack(); bool forceExportToHistory = db.inputs.forceExportToHistory(); if (primPathTokens.empty()) return true; state.checkResyncAttributes = db.inputs.checkResyncAttributes(); state.iPath = db.abi_context().iPath; // We can skip this compute if our state isn't dirty AND none of our inputs have changed if (!state.gatherDirty && (allAttributes == state.allAttributes) && (attributes == state.attributes) && (hydraFastPathToken == state.hydraFastPath) && (primPathTokens.size() == state.primPathTokens.size()) && (shouldWriteBack == state.shouldWriteBack) && (forceExportToHistory == state.forceExportToHistory) && std::equal(primPathTokens.begin(), primPathTokens.end(), state.primPathTokens.begin())) { return true; } // convert the given NameToken[] to PathC[] std::vector<PathC> paths; paths.resize(primPathTokens.size()); std::transform(primPathTokens.begin(), primPathTokens.end(), paths.begin(), [&](const auto& p) { return db.abi_context().iPath->getHandle(db.tokenToString(p)); }); // Save the input args to our per-instance state state.primPaths.resize(paths.size()); state.primPathTokens.resize(paths.size()); std::copy(paths.begin(), paths.end(), state.primPaths.begin()); std::copy(primPathTokens.begin(), primPathTokens.end(), state.primPathTokens.begin()); state.allAttributes = allAttributes; state.attributes = attributes; state.hydraFastPath = hydraFastPathToken; state.shouldWriteBack = shouldWriteBack; state.forceExportToHistory = forceExportToHistory; // tokenize the given list of space-separated attribute names std::vector<NameToken> gatherAttribs; if (!attributes.empty()) { if (allAttributes) { CARB_LOG_ERROR("'attributes' specified, but allAttributes is true"); return false; } std::istringstream iss(attributes); std::string word; while (std::getline(iss, word, ' ')) { if (!word.empty()) gatherAttribs.push_back(db.stringToToken(word.c_str())); } } GatherAddTransformsMode hydraTransformsMode = GatherAddTransformsMode::eNone; if (hydraFastPathToken == db.tokens.Local) hydraTransformsMode = GatherAddTransformsMode::eLocal; else if (hydraFastPathToken == db.tokens.World) hydraTransformsMode = GatherAddTransformsMode::eWorld; // Make the Gather ABI call GatherId gatherId = iGatherPrototype->gatherPaths( db.abi_context(), paths.data(), paths.size(), allAttributes, gatherAttribs.data(), gatherAttribs.size(), hydraTransformsMode, shouldWriteBack, forceExportToHistory); db.outputs.gatherId() = gatherId; // If the gather succeeded, copy the gathered paths into the output if (gatherId != kInvalidGatherId) { size_t gatheredPathsSize{ 0 }; PathC const* gatheredPaths{ nullptr }; size_t repeatedPathsSize{ 0 }; PathBucketIndex const* repeatedPaths{ nullptr }; if (iGatherPrototype->getGatheredPaths(db.abi_context(), gatherId, gatheredPaths, gatheredPathsSize) && iGatherPrototype->getGatheredRepeatedPaths(db.abi_context(), gatherId, repeatedPaths, repeatedPathsSize)) { db.outputs.gatheredPaths().resize(gatheredPathsSize + repeatedPathsSize); std::transform(gatheredPaths, gatheredPaths + gatheredPathsSize, db.outputs.gatheredPaths().begin(), [&db](PathC const& path) { Path pathWrap(path); return db.stringToToken(pathWrap.getText()); }); std::transform(repeatedPaths, repeatedPaths + repeatedPathsSize, db.outputs.gatheredPaths().begin() + gatheredPathsSize, [&db](PathBucketIndex const& pathBucketIndex) { Path pathWrap(std::get<0>(pathBucketIndex)); return db.stringToToken(pathWrap.getText()); }); // clear the state gather dirty flag state.gatherDirty = false; return true; } } db.outputs.gatheredPaths().resize(0); CARB_LOG_ERROR("Could not gather paths"); return false; } }; REGISTER_OGN_NODE() } // namespace core } // namespace graph } // namespace omni
9,303
C++
42.074074
136
0.617865
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/core/OgnReadPrimRelationship.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 <OgnReadPrimRelationshipDatabase.h> #include "PrimCommon.h" namespace omni { namespace graph { namespace nodes { class OgnReadPrimRelationship { public: // ---------------------------------------------------------------------------- // Prefetch prim to fabric static void setup(NodeObj const& nodeObj, GraphObj const& graphObj, OgnReadPrimRelationshipDatabase& db, size_t offset) { db.state.correctlySetup(offset) = false; TargetPath prim = db.inputs.prim.firstOrDefault(offset); NameToken name = db.inputs.name(offset); std::set<omni::fabric::TokenC> attributes = {name.token}; prefetchPrim(graphObj, nodeObj, prim, attributes); db.state.correctlySetup(offset) = true; db.state.prim(offset).resize(1); db.state.prim(offset)[0] = prim; db.state.name(offset) = name; } // ---------------------------------------------------------------------------- // Called by OG when attribute changes static void onValueChanged(AttributeObj const& attrObj, void const* userData) { NodeObj nodeObj{ attrObj.iAttribute->getNode(attrObj) }; if (nodeObj.nodeHandle == kInvalidNodeHandle) return; GraphObj graphObj{ nodeObj.iNode->getGraph(nodeObj) }; if (graphObj.graphHandle == kInvalidGraphHandle) return; GraphContextObj contextObj = graphObj.iGraph->getDefaultGraphContext(graphObj); OgnReadPrimRelationshipDatabase db(contextObj, nodeObj); setup(nodeObj, graphObj, db, 0); } // ---------------------------------------------------------------------------- static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { std::array<NameToken, 2> attribNames{inputs::name.m_token, inputs::prim.m_token}; for (auto const& attribName : attribNames) { AttributeObj attribObj = nodeObj.iNode->getAttributeByToken(nodeObj, attribName); attribObj.iAttribute->registerValueChangedCallback(attribObj, onValueChanged, true); } } // ---------------------------------------------------------------------------- static size_t computeVectorized(OgnReadPrimRelationshipDatabase& db, size_t count) { NodeObj nodeObj = db.abi_node(); GraphContextObj context = db.abi_context(); GraphObj graphObj = nodeObj.iNode->getGraph(nodeObj); auto name = db.inputs.name.vectorized(count); auto correctlySetup = db.state.correctlySetup.vectorized(count); auto nameState = db.state.name.vectorized(count); for (size_t idx = 0; idx < count; ++idx) { TargetPath curPrim = db.inputs.prim.firstOrDefault(idx); if(!correctlySetup[idx] || db.state.prim(idx).size() == 0 || db.state.prim(idx)[0] != curPrim || nameState[idx] != name[idx]) { setup(nodeObj, graphObj, db, idx); } gsl::span<TargetPath> targets = getRelationshipTargets(context, nodeObj, curPrim, name[idx]); db.outputs.value(idx).resize(targets.size()); for(size_t i = 0; i < targets.size(); i++) { db.outputs.value(idx)[i] = targets[i]; } } return count; } }; REGISTER_OGN_NODE() }// namespace nodes }// namespace graph }// namespace omni
4,071
C++
37.415094
123
0.564726
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/usd/OgnIsPrimSelected.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <omni/usd/Selection.h> #include <omni/usd/UsdContext.h> #include <OgnIsPrimSelectedDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnIsPrimSelected { public: static bool compute(OgnIsPrimSelectedDatabase& db) { omni::usd::UsdContext* usdContext = omni::usd::UsdContext::getContext(); NameToken primPathToken = db.inputs.primPath(); bool isSelected {false}; if (primPathToken != carb::flatcache::kUninitializedToken) { char const* primPath = db.abi_context().iToken->getText(primPathToken); if (primPath) isSelected = usdContext->getSelection()->isPrimPathSelected(primPath); } db.outputs.isSelected() = isSelected; return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
1,336
C++
25.215686
86
0.696856
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/usd/OgnReadStageSelection.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // clang-format off #include "UsdPCH.h" // clang-format on #include <omni/usd/Selection.h> #include <omni/usd/UsdContext.h> #include <OgnReadStageSelectionDatabase.h> namespace omni { namespace graph { namespace nodes { class OgnReadStageSelection { public: static bool compute(OgnReadStageSelectionDatabase& db) { omni::usd::UsdContext* usdContext = omni::usd::UsdContext::getContext(); PXR_NS::SdfPathVector selectedPaths = usdContext->getSelection()->getSelectedPrimPathsV2(); ogn::array<NameToken>& selectedPrims = db.outputs.selectedPrims(); selectedPrims.resize(selectedPaths.size()); std::transform(selectedPaths.begin(), selectedPaths.end(), selectedPrims.begin(), [&db](PXR_NS::SdfPath const& path) { std::string const& s = path.GetString(); auto tokenC = db.abi_context().iToken->getHandle(s.c_str()); return tokenC; }); return true; } }; REGISTER_OGN_NODE() } // nodes } // graph } // omni
1,554
C++
28.903846
99
0.655727