file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomGaussian.cpp
// Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnRandomGaussianDatabase.h" #include "random/RandomNodeBase.h" #include <omni/graph/core/ogn/ComputeHelpers.h> namespace omni { namespace graph { namespace nodes { using namespace random; class OgnRandomGaussian : public NodeBase<OgnRandomGaussian, OgnRandomGaussianDatabase> { template <typename T> static bool tryComputeAssumingType(OgnRandomGaussianDatabase& db, size_t count) { if (db.inputs.useLog()) { return ogn::compute::tryComputeWithArrayBroadcasting<T>( db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(), [](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result) { // Generate next random result = asGenerator(genBuffer).nextLogNormal(mean, stdev); }, count); } return ogn::compute::tryComputeWithArrayBroadcasting<T>( db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(), [](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result) { // Generate next random result = asGenerator(genBuffer).nextNormal(mean, stdev); }, count); } template <typename T, size_t N> static bool tryComputeAssumingType(OgnRandomGaussianDatabase& db, size_t count) { if (db.inputs.useLog()) { return ogn::compute::tryComputeWithTupleBroadcasting<N, T>( db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(), [](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result) { // Generate next random result = asGenerator(genBuffer).nextLogNormal(mean, stdev); }, count); } return ogn::compute::tryComputeWithTupleBroadcasting<N, T>( db.state.gen(), db.inputs.mean(), db.inputs.stdev(), db.outputs.random(), [](GenBuffer_t const& genBuffer, T const& mean, T const& stdev, T& result) { // Generate next random result = asGenerator(genBuffer).nextNormal(mean, stdev); }, count); } static bool defaultCompute(OgnRandomGaussianDatabase& db, size_t count) { auto const genBuffers = db.state.gen.vectorized(count); if (genBuffers.size() != count) { db.logWarning("Failed to write to output standard normal distribution (wrong genBuffers size)"); return false; } for (size_t i = 0; i < count; ++i) { auto outPtr = db.outputs.random(i).get<double>(); if (!outPtr) { db.logWarning("Failed to write to output standard normal distribution (null output pointer)"); return false; } *outPtr = asGenerator(genBuffers[i]).nextNormal<double>(0.0, 1.0); } return true; } public: static void initialize(GraphContextObj const& contextObj, NodeObj const& nodeObj) { generateRandomSeed(contextObj, nodeObj, inputs::seed, inputs::useSeed); // HACK: onConnectionTypeResolve is not called the first time, // but by setting the output type, we force it to be called. // // TODO: OGN should really support default inputs for union types! // See https://nvidia-omniverse.atlassian.net/browse/OM-67739 setDefaultOutputType(nodeObj, outputs::random.token()); } static bool onCompute(OgnRandomGaussianDatabase& db, size_t count) { auto const& meanAttr{ db.inputs.mean() }; auto const& stdevAttr{ db.inputs.stdev() }; auto const& outAttr{ db.outputs.random() }; if (!outAttr.resolved()) { // Output type not yet resolved, can't compute db.logWarning("Unsupported input types"); return false; } if (!meanAttr.resolved() && !stdevAttr.resolved()) { // Output using default mean and stdev return defaultCompute(db, count); } // Inputs and outputs are resolved, try all real types auto const outType = outAttr.type(); switch (outType.baseType) // NOLINT(clang-diagnostic-switch-enum) { case BaseDataType::eDouble: switch (outType.componentCount) { case 1: return tryComputeAssumingType<double>(db, count); case 2: return tryComputeAssumingType<double, 2>(db, count); case 3: return tryComputeAssumingType<double, 3>(db, count); case 4: return tryComputeAssumingType<double, 4>(db, count); case 9: return tryComputeAssumingType<double, 9>(db, count); case 16: return tryComputeAssumingType<double, 16>(db, count); default: break; } case BaseDataType::eFloat: switch (outType.componentCount) { case 1: return tryComputeAssumingType<float>(db, count); case 2: return tryComputeAssumingType<float, 2>(db, count); case 3: return tryComputeAssumingType<float, 3>(db, count); case 4: return tryComputeAssumingType<float, 4>(db, count); default: break; } case BaseDataType::eHalf: switch (outType.componentCount) { case 1: return tryComputeAssumingType<pxr::GfHalf>(db, count); case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db, count); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db, count); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db, count); default: break; } default: break; } db.logWarning("Unsupported input types"); return false; } static void onConnectionTypeResolve(NodeObj const& node) { resolveOutputType(node, inputs::mean.token(), inputs::stdev.token(), outputs::random.token()); } }; #undef TRY_CASE REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMultiply.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 <OgnMultiplyDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> namespace omni { namespace graph { namespace nodes { namespace { template<typename T> bool tryComputeAssumingType(OgnMultiplyDatabase& db, size_t count) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](T const& a, T const& b, T& result) { result = a * b; }; return ogn::compute::tryComputeWithArrayBroadcasting<T>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor, count); } else { std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() }; inputArray.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputArray.emplace_back(input()); auto functor = [](const auto& input, auto& result) { result = result * input; }; return ogn::compute::tryComputeInputsWithArrayBroadcasting<T>(inputArray, db.outputs.product(), functor, count); } } template<typename T, size_t N> bool tryComputeAssumingType(OgnMultiplyDatabase& db, size_t count) { auto const& dynamicInputs = db.getDynamicInputs(); if (dynamicInputs.empty()) { auto functor = [](T const& a, T const& b, T& result) { result = a * b; }; return ogn::compute::tryComputeWithTupleBroadcasting<N, T>(db.inputs.a(), db.inputs.b(), db.outputs.product(), functor, count); } else { std::vector<ogn::InputAttribute> inputArray{ db.inputs.a(), db.inputs.b() }; inputArray.reserve(dynamicInputs.size() + 2); for (auto const& input : dynamicInputs) inputArray.emplace_back(input()); auto functor = [](const auto& input, auto& result) { result = result * input; }; return ogn::compute::tryComputeInputsWithTupleBroadcasting<N, T>(inputArray, db.outputs.product(), functor, count); } } } // namespace class OgnMultiply { public: static size_t computeVectorized(OgnMultiplyDatabase& db, size_t count) { auto& productType = db.outputs.product().type(); try { switch (productType.baseType) { case BaseDataType::eDouble: switch (productType.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 (productType.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 (productType.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 (productType.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.logWarning("OgnMultiply: %s", error.what()); } return 0; } static void onConnectionTypeResolve(const NodeObj& node) { auto totalCount = node.iNode->getAttributeCount(node); std::vector<AttributeObj> allAttributes(totalCount); node.iNode->getAttributes(node, allAttributes.data(), totalCount); std::vector<AttributeObj> attributes; std::vector<uint8_t> componentCounts; std::vector<uint8_t> arrayDepths; std::vector<AttributeRole> roles; attributes.reserve(totalCount - 2); componentCounts.reserve(totalCount - 2); arrayDepths.reserve(totalCount - 2); roles.reserve(totalCount - 2); uint8_t maxArrayDepth = 0; uint8_t maxComponentCount = 0; for (auto const& attr : allAttributes) { if (attr.iAttribute->getPortType(attr) == AttributePortType::kAttributePortType_Input) { auto resolvedType = attr.iAttribute->getResolvedType(attr); // if some inputs are not connected stop - the output port resolution is only completed when all inputs // are connected if (resolvedType.baseType == BaseDataType::eUnknown) return; componentCounts.push_back(resolvedType.componentCount); arrayDepths.push_back(resolvedType.arrayDepth); roles.push_back(resolvedType.role); maxComponentCount = std::max(maxComponentCount, resolvedType.componentCount); maxArrayDepth = std::max(maxArrayDepth, resolvedType.arrayDepth); attributes.push_back(attr); } } auto output = node.iNode->getAttributeByToken(node, outputs::product.token()); attributes.push_back(output); // All inputs and the output should have the same tuple count componentCounts.push_back(maxComponentCount); // Allow for a mix of singular and array inputs. If any input is an array, the output must be an array arrayDepths.push_back(maxArrayDepth); // Copy the attribute role from the resolved type to the output type roles.push_back(AttributeRole::eUnknown); node.iNode->resolvePartiallyCoupledAttributes( node, attributes.data(), componentCounts.data(), arrayDepths.data(), roles.data(), attributes.size()); } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnInterpolateTo.ogn
{ "InterpolateTo": { "version": 2, "description": [ "Function which iterpolates one step from a current value to a target value with a given speed.", "Vectors are interpolated component-wise. Interpolation can be applied to decimal types.", "The interpolation provides an eased approach to the target, adjust speed and exponent to tweak the curve.", "The formula is:", "result = current + (target - current) * (1 - clamp(0, speed * deltaSeconds, 1))^exp.", "For quaternions, the node performs a spherical linear interpolation (SLERP) with ", "alpha = (1 - clamp(0, speed * deltaSeconds, 1))^exp" ], "uiName": "Interpolate To", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "current": { "type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"], "description": "The current value" }, "target": { "type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"], "description": "The target value" }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "deltaSeconds": { "type": "double", "description": "The step time for the interpolation (Seconds)", "minimum": 0.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "result": { "type": ["numerics"], "description": "The interpolated result", "uiName": "Result" } }, "tests" : [ { "inputs": { "current": {"type": "float", "value": 0.0}, "target": {"type": "float", "value": 10.0}, "deltaSeconds": 0.1 }, "outputs": {"result": {"type": "float", "value": 1.9}} }, { "inputs": { "current": {"type": "double[3]", "value": [0.0, 1.0, 2.0]}, "target": {"type": "double[3]", "value": [10.0, 11.0, 12.0]}, "deltaSeconds": 0.1 }, "outputs": {"result": {"type": "double[3]", "value": [1.9, 2.9, 3.9]}} }, { "inputs": { "current": {"type": "float[]", "value": [0.0, 1.0, 2.0]}, "target": {"type": "float[]", "value": [10.0, 11.0, 12.0]}, "deltaSeconds": 0.1 }, "outputs": {"result": {"type": "float[]", "value": [1.9, 2.9, 3.9]}} }, { "inputs": { "current": {"type": "double[3][]", "value": [[0.0, 1.0, 2.0],[0.0, 1.0, 2.0]]}, "target": {"type": "double[3][]", "value": [[10.0, 11.0, 12.0], [10.0, 11.0, 12.0]]}, "deltaSeconds": 0.1 }, "outputs": {"result": {"type": "double[3][]", "value": [[1.9, 2.9, 3.9], [1.9, 2.9, 3.9]]}} }, { "inputs": { "current": {"type": "quatd[4]", "value": [0, 0, 0, 1]}, "target": {"type": "quatd[4]", "value": [0.7071068, 0, 0, 0.7071068]}, "deltaSeconds": 0.5, "exponent": 1 }, "outputs": {"result": {"type": "quatd[4]", "value": [0.3826834, 0, 0, 0.9238795]}} }, { "inputs": { "current": {"type": "quatf[4]", "value": [0, 0, 0, 1]}, "target": {"type": "quatf[4]", "value": [0.7071068, 0, 0, 0.7071068]}, "deltaSeconds": 0.5, "exponent": 1 }, "outputs": {"result": {"type": "quatf[4]", "value": [0.3826834, 0, 0, 0.9238795]}} }, { "inputs": { "current": {"type": "float[4]", "value": [0, 0, 0, 1]}, "target": {"type": "float[4]", "value": [0.7071068, 0, 0, 0.7071068]}, "deltaSeconds": 0.5, "exponent": 1 }, "outputs": {"result": {"type": "float[4]", "value": [0.3535534, 0, 0, 0.8535534]}} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSubtract.ogn
{ "Subtract": { "version": 2, "description": [ "Subtracts from the first input the following inputs. The inputs can be of any numeric type." ], "uiName": "Subtract", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["numerics"], "description": "The number B is subtracted from", "uiName": "A" }, "b": { "type": ["numerics"], "description": "The number to subtract from A", "uiName": "B" } }, "outputs": { "difference": { "type": ["numerics"], "description": "Result of A-B", "uiName": "Difference" } }, "tests": [ {"inputs:a": {"type": "double", "value": 1.0}, "inputs:b": {"type": "double", "value": 0.5}, "outputs:difference": {"type": "double", "value": 0.5}}, {"inputs:a": {"type": "float", "value": 1.0}, "inputs:b": {"type": "float", "value": 0.5}, "outputs:difference": {"type": "float", "value": 0.5}}, {"inputs:a": {"type": "half", "value": 1.0}, "inputs:b": {"type": "half", "value": 0.5}, "outputs:difference": {"type": "half", "value": 0.5}}, {"inputs:a": {"type": "int", "value": 10}, "inputs:b": {"type": "int", "value": 6}, "outputs:difference": {"type": "int", "value": 4}}, {"inputs:a": {"type": "int64", "value": 10}, "inputs:b": {"type": "int64", "value": 6}, "outputs:difference": {"type": "int64", "value": 4}}, {"inputs:a": {"type": "uchar", "value": 10}, "inputs:b": {"type": "uchar", "value": 6}, "outputs:difference": {"type": "uchar", "value": 4}}, {"inputs:a": {"type": "uint", "value": 10}, "inputs:b": {"type": "uint", "value": 6}, "outputs:difference": {"type": "uint", "value": 4}}, {"inputs:a": {"type": "uint64", "value": 10}, "inputs:b": {"type": "uint64", "value": 6}, "outputs:difference": {"type": "uint64", "value": 4}}, {"inputs:a": {"type": "float[2]", "value": [1.0, 2.0]}, "inputs:b": {"type": "float[2]", "value": [0.5, 1.0]}, "outputs:difference": {"type": "float[2]", "value": [0.5, 1.0]}}, {"inputs:a": {"type": "float[3]", "value": [1.0, 2.0, 3.0]}, "inputs:b": {"type": "float[3]", "value": [0.5, 1.0, 1.5]}, "outputs:difference": {"type": "float[3]", "value": [0.5, 1.0, 1.5]}}, {"inputs:a": {"type": "float[4]", "value": [1.0, 2.0, 3.0, 4.0]}, "inputs:b": {"type": "float[4]", "value": [0.5, 1.0, 1.5, 2.0]}, "outputs:difference": {"type": "float[4]", "value": [0.5, 1.0, 1.5, 2.0]}}, {"inputs:a": {"type": "float[2]", "value": [2.0, 3.0]}, "inputs:b": {"type": "float", "value": 1.0}, "outputs:difference": {"type": "float[2]", "value": [1.0, 2.0]}}, {"inputs:a": {"type": "float", "value": 1.0}, "inputs:b": {"type": "float[2]", "value": [1.0, 2.0]}, "outputs:difference": {"type": "float[2]", "value": [0.0, -1.0]}}, {"inputs:a": {"type": "float[]", "value": [2.0, 3.0]}, "inputs:b": {"type": "float", "value": 1.0}, "outputs:difference": {"type": "float[]", "value": [1.0, 2.0]}}, {"inputs:a": {"type": "float", "value": 1.0}, "inputs:b": {"type": "float[]", "value": [1.0, 2.0]}, "outputs:difference": {"type": "float[]", "value": [0.0, -1.0]}}, {"inputs:a": {"type": "int64[]", "value": [10]}, "inputs:b": {"type": "int64[]", "value": [5]}, "outputs:difference": {"type": "int64[]", "value": [5]}}, {"inputs:a": {"type": "int64[]", "value": [10, 20]}, "inputs:b": {"type": "int64[]", "value": [5, 10]}, "outputs:difference": {"type": "int64[]", "value": [5, 10]}}, {"inputs:a": {"type": "int64[]", "value": [10, 20, 30]}, "inputs:b": {"type": "int64[]", "value": [5, 10, 15]}, "outputs:difference": {"type": "int64[]", "value": [5, 10, 15]}}, {"inputs:a": {"type": "int64[]", "value": [10, 20, 30, 40]}, "inputs:b": {"type": "int64[]", "value": [5, 10, 15, 20]}, "outputs:difference": {"type": "int64[]", "value": [5, 10, 15, 20]}}, {"inputs:a": {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, "inputs:b": {"type": "int[3]", "value": [5, 10, 15]}, "outputs:difference": {"type": "int[3][]", "value": [[5, 10, 15], [35, 40, 45]]}}, {"inputs:a": {"type": "int[3]", "value": [5, 10, 15]}, "inputs:b": {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, "outputs:difference": {"type": "int[3][]", "value": [[-5, -10, -15], [-35, -40, -45]]}}, {"inputs:a": {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, "inputs:b": {"type": "int[2]", "value": [5, 10]}, "outputs:difference": {"type": "int[2][]", "value": [[5, 10], [25, 30], [45, 50]]}}, {"inputs:a": {"type": "int[2]", "value": [5, 10]}, "inputs:b": {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, "outputs:difference": {"type": "int[2][]", "value": [[-5, -10], [-25, -30], [-45, -50]]}} ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnPartialSum.cpp
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnPartialSumDatabase.h> #include <numeric> class OgnPartialSum { public: static bool compute(OgnPartialSumDatabase& db) { auto inputs = db.inputs.array(); auto outputs = db.outputs.partialSum(); outputs.resize(inputs.size() + 1); outputs[0] = 0; std::partial_sum(inputs.begin(), inputs.end(), outputs.begin() + 1); return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnFloor.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 <OgnFloorDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <cmath> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { template<typename T> bool tryComputeAssumingType(OgnFloorDatabase& db) { auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::floor(a)); }; return ogn::compute::tryComputeWithArrayBroadcasting<T, int>(db.inputs.a(), db.outputs.result(), functor); } template<typename T, size_t N> bool tryComputeAssumingType(OgnFloorDatabase& db) { auto functor = [](auto const& a, auto& result) { result = static_cast<int>(std::floor(a)); }; return ogn::compute::tryComputeWithTupleBroadcasting<N, T, int>(db.inputs.a(), db.outputs.result(), functor); } } // namespace class OgnFloor { public: static bool compute(OgnFloorDatabase& db) { try { auto& aType = db.inputs.a().type(); switch (aType.baseType) { case BaseDataType::eDouble: switch (aType.componentCount) { case 1: return tryComputeAssumingType<double>(db); case 2: return tryComputeAssumingType<double, 2>(db); case 3: return tryComputeAssumingType<double, 3>(db); case 4: return tryComputeAssumingType<double, 4>(db); } case BaseDataType::eFloat: switch (aType.componentCount) { case 1: return tryComputeAssumingType<float>(db); case 2: return tryComputeAssumingType<float, 2>(db); case 3: return tryComputeAssumingType<float, 3>(db); case 4: return tryComputeAssumingType<float, 4>(db); } case BaseDataType::eHalf: switch (aType.componentCount) { case 1: return tryComputeAssumingType<pxr::GfHalf>(db); case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db); } default: break; } throw ogn::compute::InputError("Failed to resolve input types"); } catch (ogn::compute::InputError &error) { db.logWarning("OgnFloor: %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node){ auto a = node.iNode->getAttributeByToken(node, inputs::a.token()); auto result = node.iNode->getAttributeByToken(node, outputs::result.token()); auto valueType = a.iAttribute->getResolvedType(a); if (valueType.baseType != BaseDataType::eUnknown) { Type resultType(BaseDataType::eInt, valueType.componentCount, valueType.arrayDepth); result.iAttribute->setResolvedType(result, resultType); } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnExponent.ogn
{ "Exponent": { "version": 1, "description": [ "Computes the base input raised to the power of the exponent. The result is the same type as the base", "input for floating point types. The result is double for integral values to allow for negative exponents.", "If the input is a vector or matrix, then the node calculates the exponent for each element and output", "a vector or matrix of the same size."], "uiName": "Exponent", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "base": { "type": ["numerics"], "description": "Base value that will be raised to the power of exponent", "uiName": "Base" }, "exponent": { "type": "int", "description": "Power to raise the base value to", "uiName": "Exponent", "default": 2 } }, "outputs": { "result": { "type": ["numerics"], "description": "Result of base raised to exponent", "uiName": "Result" } }, "tests": [ { "inputs:base": {"type": "float", "value": 2.0}, "outputs:result": {"type": "float", "value": 4.0} }, { "inputs:base": {"type": "double", "value": 0.5}, "inputs:exponent": 3, "outputs:result": {"type": "double", "value": 0.125} }, { "inputs:base": {"type": "half[2]", "value": [5.0, 0.5]}, "inputs:exponent": 3, "outputs:result": {"type": "half[2]", "value": [125.0, 0.125]} }, { "inputs:base": {"type": "float[]", "value": [1.0, 3.0]}, "inputs:exponent": 3, "outputs:result": {"type": "float[]", "value": [1.0, 27.0]} }, { "inputs:base": {"type": "float[2][]", "value": [[1.0, 0.3], [0.5, 3.0]]}, "outputs:result": {"type": "float[2][]", "value": [[1.0, 0.09], [0.25, 9.0]]} }, { "inputs:base": {"type": "int", "value": 2147483647}, "inputs:exponent": 0, "outputs:result": {"type": "double", "value": 1.0} }, { "inputs:base": {"type": "int64", "value": 9223372036854775807}, "inputs:exponent": 1, "outputs:result": {"type": "double", "value": 9223372036854775807.0} }, { "inputs:base": {"type": "int", "value": 5}, "inputs:exponent": -1, "outputs:result": {"type": "double", "value": 0.2} }, { "inputs:base": {"type": "float", "value": -2.0}, "outputs:result": {"type": "float", "value": 4.0} }, { "inputs:base": {"type": "float", "value": -2.0}, "inputs:exponent": 3, "outputs:result": {"type": "float", "value": -8.0} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCrossProduct.ogn
{ "CrossProduct": { "version": 1, "description": [ "Compute the cross product of two (arrays of) vectors of the same size", "The cross product of two 3d vectors is a vector perpendicular to both inputs", "If arrays of vectors are provided, the cross-product is computed row-wise between a and b" ], "uiName": "Cross Product", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["vectord[3]", "vectorf[3]", "vectorh[3]", "vectord[3][]", "vectorf[3][]", "vectorh[3][]"], "description": "The first vector in the cross product", "uiName": "A" }, "b": { "type": ["vectord[3]", "vectorf[3]", "vectorh[3]", "vectord[3][]", "vectorf[3][]", "vectorh[3][]"], "description": "The second vector in the cross product", "uiName": "B" } }, "outputs": { "product": { "type": ["vectord[3]", "vectorf[3]", "vectorh[3]", "vectord[3][]", "vectorf[3][]", "vectorh[3][]"], "description": "The resulting product", "uiName": "Product" } }, "tests": [ { "inputs:a": {"type": "half[3]", "value": [1, 2, 3]}, "inputs:b": {"type": "half[3]", "value": [5, 6, 7]}, "outputs:product": {"type": "half[3]", "value": [-4, 8, -4]} }, { "inputs:a": {"type": "float[3]", "value": [1, 2, 3]}, "inputs:b": {"type": "float[3]", "value": [5, 6, 7]}, "outputs:product": {"type": "float[3]", "value": [-4, 8, -4]} }, { "inputs:a": {"type": "double[3]", "value": [1, 2, 3]}, "inputs:b": {"type": "double[3]", "value": [5, 6, 7]}, "outputs:product": {"type": "double[3]", "value": [-4, 8, -4]} }, { "inputs:a": {"type": "double[3][]", "value": [[1, 2, 3], [10.2, 3.5, 7]]}, "inputs:b": {"type": "double[3][]", "value": [[5, 6, 7], [5, 6.1, 4.2]]}, "outputs:product": {"type": "double[3][]", "value": [[-4, 8, -4], [-28, -7.84, 44.72]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSourceIndices.cpp
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnSourceIndicesDatabase.h> class OgnSourceIndices { public: static bool compute(OgnSourceIndicesDatabase& db) { auto inputValues = db.inputs.sourceStartsInTarget(); auto sourceCount = inputValues.size(); auto sourceIndices = db.outputs.sourceIndices(); if (sourceCount <= 1) { sourceIndices.resize(0); return true; } --sourceCount; int32_t targetCount = inputValues[sourceCount]; if (targetCount < 0) { sourceIndices.resize(0); return true; } sourceIndices.resize(targetCount); int32_t i = 0; for (size_t sourcei = 0; sourcei < sourceCount; ++sourcei) { const int32_t sourceEnd = inputValues[sourcei + 1]; while (i < sourceEnd) { sourceIndices[i] = (int32_t)sourcei; ++i; } } return true; } }; REGISTER_OGN_NODE()
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMagnitude.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <OgnMagnitudeDatabase.h> #include <omni/graph/core/ogn/ComputeHelpers.h> #include <carb/logging/Log.h> #include <cmath> #include <type_traits> namespace omni { namespace graph { namespace nodes { // unnamed namespace to avoid multiple declaration when linking namespace { template<typename T> bool tryComputeAssumingType(OgnMagnitudeDatabase& db) { auto functor = [](auto const& input, auto& magnitude) { magnitude = static_cast<T>(std::abs(static_cast<double>(input))); }; return ogn::compute::tryComputeWithArrayBroadcasting<T, T>(db.inputs.input(), db.outputs.magnitude(), functor); } template<> bool tryComputeAssumingType<pxr::GfHalf>(OgnMagnitudeDatabase& db) { auto functor = [](auto const& input, auto& magnitude) { magnitude = static_cast<pxr::GfHalf>(std::abs(static_cast<float>(input))); }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf, pxr::GfHalf>(db.inputs.input(), db.outputs.magnitude(), functor); } template<typename T, size_t N, std::enable_if_t<!std::is_same<T, int>::value && !std::is_same<T, pxr::GfHalf>::value, bool> = true> bool tryComputeAssumingType(OgnMagnitudeDatabase& db) { auto functor = [](auto const& input, auto& magnitude) { double acc = 0.0; for (size_t i = 0; i < N; ++i) { acc += static_cast<double>(input[i]) * static_cast<double>(input[i]); } acc = std::sqrt(acc); magnitude = static_cast<T>(acc); }; return ogn::compute::tryComputeWithArrayBroadcasting<T[N], T>(db.inputs.input(), db.outputs.magnitude(), functor); } template<typename T, size_t N, std::enable_if_t<std::is_same<T, int>::value, bool> = true> bool tryComputeAssumingType(OgnMagnitudeDatabase& db) { auto functor = [](auto const& input, auto& magnitude) { double acc = 0.0; for (size_t i = 0; i < N; ++i) { acc += static_cast<double>(input[i]) * static_cast<double>(input[i]); } acc = std::sqrt(acc); magnitude = acc; }; return ogn::compute::tryComputeWithArrayBroadcasting<int[N], double>(db.inputs.input(), db.outputs.magnitude(), functor); } template<typename T, size_t N, std::enable_if_t<std::is_same<T, pxr::GfHalf>::value, bool> = true> bool tryComputeAssumingType(OgnMagnitudeDatabase& db) { auto functor = [](auto const& input, auto& magnitude) { float acc = 0.0f; for (size_t i = 0; i < N; ++i) { acc += static_cast<float>(input[i]) * static_cast<float>(input[i]); } acc = std::sqrt(acc); magnitude = static_cast<pxr::GfHalf>(acc); }; return ogn::compute::tryComputeWithArrayBroadcasting<pxr::GfHalf[N], pxr::GfHalf>(db.inputs.input(), db.outputs.magnitude(), functor); } } // namespace class OgnMagnitude { public: static bool compute(OgnMagnitudeDatabase& db) { try { auto& type = db.inputs.input().type(); // All possible types excluding ogn::string and bool switch (type.baseType) { case BaseDataType::eDouble: switch (type.componentCount) { case 1: return tryComputeAssumingType<double>(db); case 2: return tryComputeAssumingType<double, 2>(db); case 3: return tryComputeAssumingType<double, 3>(db); case 4: return tryComputeAssumingType<double, 4>(db); // quaternion (XYZW), RGBA, etc case 9: return tryComputeAssumingType<double, 9>(db); // Matrix3f type case 16: return tryComputeAssumingType<double, 16>(db); // Matrix4f type } break; case BaseDataType::eFloat: switch (type.componentCount) { case 1: return tryComputeAssumingType<float>(db); case 2: return tryComputeAssumingType<float, 2>(db); case 3: return tryComputeAssumingType<float, 3>(db); case 4: return tryComputeAssumingType<float, 4>(db); // quaternion (XYZW), RGBA, etc } break; case BaseDataType::eHalf: switch (type.componentCount) { case 1: return tryComputeAssumingType<pxr::GfHalf>(db); case 2: return tryComputeAssumingType<pxr::GfHalf, 2>(db); case 3: return tryComputeAssumingType<pxr::GfHalf, 3>(db); case 4: return tryComputeAssumingType<pxr::GfHalf, 4>(db); // quaternion (XYZW), RGBA, etc } break; case BaseDataType::eInt: switch (type.componentCount) { case 1: return tryComputeAssumingType<int32_t>(db); case 2: return tryComputeAssumingType<int32_t, 2>(db); case 3: return tryComputeAssumingType<int32_t, 3>(db); case 4: return tryComputeAssumingType<int32_t, 4>(db); } break; case BaseDataType::eUInt: switch (type.componentCount) { case 1: return tryComputeAssumingType<uint32_t>(db); } break; case BaseDataType::eInt64: switch (type.componentCount) { case 1: return tryComputeAssumingType<int64_t>(db); } break; case BaseDataType::eUInt64: switch (type.componentCount) { case 1: return tryComputeAssumingType<uint64_t>(db); } break; case BaseDataType::eUChar: switch (type.componentCount) { case 1: return tryComputeAssumingType<unsigned char>(db); } break; default: break; } throw ogn::compute::InputError("Failed to resolve input type"); } catch (ogn::compute::InputError &error) { db.logError("OgnMagnitude: %s", error.what()); } return false; } static void onConnectionTypeResolve(const NodeObj& node) { auto input = node.iNode->getAttributeByToken(node, inputs::input.token()); auto magnitude = node.iNode->getAttributeByToken(node, outputs::magnitude.token()); auto inputType = input.iAttribute->getResolvedType(input); // Require input to be resolved before determining magnitude's type if (inputType.baseType != BaseDataType::eUnknown) { if (inputType.baseType == BaseDataType::eInt && inputType.componentCount > 1) { // int[N] => double auto newType = inputType; newType.baseType = BaseDataType::eDouble; newType.componentCount = 1; magnitude.iAttribute->setResolvedType(magnitude, newType); } else { // T => T // T[N] => T std::array<AttributeObj, 2> attrs { input, magnitude }; std::array<uint8_t, 2> tupleCounts { inputType.componentCount, 1 }; std::array<uint8_t, 2> arrayDepths { inputType.arrayDepth, inputType.arrayDepth }; std::array<AttributeRole, 2> rolesBuf { inputType.role, AttributeRole::eUnknown }; node.iNode->resolvePartiallyCoupledAttributes(node, attrs.data(), tupleCounts.data(), arrayDepths.data(), rolesBuf.data(), attrs.size()); } } } }; REGISTER_OGN_NODE() } // namespace nodes } // namespace graph } // namespace omni // end-compute-helpers
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMatrixMultiply.ogn
{ "MatrixMultiply": { "version": 1, "description": [ "Computes the matrix product of the inputs. Inputs must be compatible. ", "Also accepts tuples (treated as vectors) as inputs. Tuples in input A will be treated as row vectors. ", "Tuples in input B will be treated as column vectors. ", "Arrays of inputs will be computed element-wise with broadcasting if necessary. " ], "uiName": "Matrix Multiply", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["matrices", "matrixd[3][]", "matrixd[4][]", "decimal_tuples", "double[2][]", "double[3][]", "double[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]"], "description": "First matrix or row vector to multiply", "uiName": "A" }, "b": { "type": ["matrices", "matrixd[3][]", "matrixd[4][]", "decimal_tuples", "double[2][]", "double[3][]", "double[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]"], "description": "Second matrix or column vector to multiply", "uiName": "B" } }, "outputs": { "output": { "type": ["matrices", "matrixd[3][]", "matrixd[4][]", "decimal_tuples", "double[2][]", "double[3][]", "double[4][]", "float[2][]", "float[3][]", "float[4][]", "half[2][]", "half[3][]", "half[4][]", "float", "double", "half", "float[]", "double[]", "half[]"], "description": "Product of the two matrices", "uiName": "Product" } }, "tests" : [ { "inputs:a": {"type": "matrixd[3]", "value": [1,2,3, 4,5,6, 7,8,9]}, "inputs:b": {"type": "matrixd[3]", "value": [10,11,12, 13,14,15, 16,17,18]}, "outputs:output": {"type": "matrixd[3]", "value": [84,90,96, 201,216,231, 318,342,366]} }, { "inputs:a": {"type": "matrixd[4]", "value": [1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4]}, "inputs:b": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]}, "outputs:output": {"type": "matrixd[4]", "value": [1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4]} }, { "inputs:a": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]}, "inputs:b": {"type": "double[4]", "value": [1,2,3,4]}, "outputs:output": {"type": "double[4]", "value": [1,2,3,4]} }, { "inputs:a": {"type": "double[4]", "value": [1,2,3,4]}, "inputs:b": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]}, "outputs:output": {"type": "double[4]", "value": [1,2,3,4]} }, { "inputs:a": {"type": "double[4]", "value": [1,2,3,4]}, "inputs:b": {"type": "double[4]", "value": [1,2,3,4]}, "outputs:output": {"type": "double", "value": 30} }, { "inputs:a": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]}, "inputs:b": {"type": "matrixd[4][]", "value": [[1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]]}, "outputs:output": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]} }, { "inputs:a": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]}, "inputs:b": {"type": "matrixd[4]", "value": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]}, "outputs:output": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]} }, { "inputs:a": {"type": "double[4]", "value": [1,2,3,4]}, "inputs:b": {"type": "matrixd[4][]", "value": [[1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]]}, "outputs:output": {"type": "double[4][]", "value": [[1,2,3,4], [1,2,3,4]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTan.ogn
{ "Tan": { "version": 1, "description": [ "Trigonometric operation tangent of one input in degrees." ], "uiName": "Tan", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["decimal_scalers", "double[]", "float[]", "half[]"], "description": "Angle in degrees whose tangent value is to be found" } }, "outputs": { "value": { "type": ["decimal_scalers", "double[]", "float[]", "half[]"], "description": "The tangent value of the input angle in degrees", "uiName": "Result" } }, "tests" : [ { "inputs:value": {"type": "float", "value": 45.0}, "outputs:value": {"type": "float", "value": 1.0} } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLookAtRotation.ogn
{ "GetLookAtRotation": { "version": 1, "description": [ "Computes the rotation angles to align a forward direction vector to a direction vector formed by", " starting at 'start' and pointing at 'target'. The forward vector is the 'default' orientation of", " the asset being rotated, usually +X or +Z" ], "uiName": "Get Look At Rotation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "start": { "type": "pointd[3]", "description": ["The position to look from"] }, "target": { "type": "pointd[3]", "description": ["The position to look at"] }, "forward": { "type": "double[3]", "description": ["The direction vector to be aligned with the look vector"], "default": [0.0, 0.0, 1.0] }, "up": { "type": "double[3]", "description": ["The direction considered to be 'up'. If not specified scene-up will be used."], "optional": true } }, "outputs": { "rotateXYZ": { "type": "double[3]", "description": ["The rotation vector [X, Y, Z]"] }, "orientation": { "type": "quatd[4]", "description": ["The orientation quaternion equivalent to outputs:rotateXYZ"] } }, "tests": [ { "inputs:start": [0.0, 0.0, 0.0], "inputs:target": [100.0, 0.0, 0.0], "inputs:forward": [1.0, 0.0, 0.0], "outputs:rotateXYZ": [0.0, 0.0, 0.0], "outputs:orientation": [0.0, 0.0, 0.0, 1.0] }, { "inputs:start": [0.0, 0.0, 0.0], "inputs:target": [100.0, 0.0, 0.0], "inputs:forward": [0.0, 0.0, 1.0], "outputs:rotateXYZ": [0.0, 90, 0.0], "outputs:orientation": [0.0, 0.70710678, 0.0, 0.70710678] }, { "inputs:start": [0.0, 0.0, 0.0], "inputs:target": [100.0, 0.0, 100.0],"inputs:forward": [1.0, 0.0, 0.0], "outputs:rotateXYZ": [0.0, -45.0, 0.0], "outputs:orientation": [0.0, -0.3826834, 0.0, 0.92387953] }, { "inputs:start": [100.0, 0.0, 100.0], "inputs:target": [200.0, 0.0, 100.0], "inputs:forward": [1.0, 0.0, 0.0], "outputs:rotateXYZ": [0.0, 0.0, 0.0], "outputs:orientation": [0.0, 0.0, 0.0, 1.0] }, { "inputs:start": [100.0, 0.0, -100.0], "inputs:target": [-100.0, 200.0, -300.0], "inputs:forward": [1.0, 0.0, 0.0], "outputs:rotateXYZ": [150.0, 35.26439, 135.0], "outputs:orientation": [0.27984814, 0.88047624, 0.115916896, 0.3647052] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNegate.ogn
{ "Negate": { "version": 1, "description": [ "Computes the result of multiplying a vector, scalar, or array of vectors or scalars by -1.", "The input must not be unsigned." ], "uiName": "Negate", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "input": { "type": ["numerics"], "description": "The vector(s) or scalar(s) to negate" } }, "outputs": { "output": { "type": ["numerics"], "description": "The resulting negated value(s)" } }, "tests" : [ { "inputs:input": {"type": "double", "value": 1.0}, "outputs:output": {"type": "double", "value": -1.0} }, { "inputs:input": {"type": "float[2]", "value": [0.0, 1.0]}, "outputs:output": {"type": "float[2]", "value": [-0.0, -1.0]} }, { "inputs:input": {"type": "half[3]", "value": [-1.0, -0.0, 1.0]}, "outputs:output": {"type": "half[3]", "value": [1.0, 0.0, -1.0]} }, { "inputs:input": {"type": "int[4]", "value": [-1, 0, 1, 2]}, "outputs:output": {"type": "int[4]", "value": [1, 0, -1, -2]} }, { "inputs:input": {"type": "int64[]", "value": [-1, 0, 1, 2]}, "outputs:output": {"type": "int64[]", "value": [1, 0, -1, -2]} }, { "inputs:input": {"type": "double[][2]", "value": [[-1.0, 0.0], [1.0, 2.0]]}, "outputs:output": {"type": "double[][2]", "value": [[1.0, -0.0], [-1.0, -2.0]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnModulo.ogn
{ "Modulo": { "version": 1, "description": [ "Computes the modulo of integer inputs (A % B), which is the remainder of A / B", " If B is zero, the result is zero. If A and B are both non-negative the result is non-negative,", " otherwise the sign of the result is undefined." ], "uiName": "Modulo", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["integral_scalers"], "description": "The dividend of (A % B)", "uiName": "A" }, "b": { "type":["integral_scalers"], "description": "The divisor of (A % B)", "uiName": "B" } }, "outputs": { "result": { "type": ["integral_scalers"], "description": "Modulo (A % B), the remainder of A / B", "uiName": "Result" } }, "tests" : [ { "inputs:a": {"type": "uint64", "value": 4}, "inputs:b": {"type": "uint64", "value": 3}, "outputs:result": {"type": "uint64", "value": 1} }, { "inputs:a": {"type": "int", "value": 4}, "inputs:b": {"type": "int", "value": 0}, "outputs:result": {"type": "int", "value": 0} } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCos.ogn
{ "Cos": { "version": 1, "description": [ "Trigonometric operation cosine of one input in degrees." ], "uiName": "Cosine", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["decimal_scalers", "double[]", "float[]", "half[]"], "description": "Angle in degrees whose cosine value is to be found" } }, "outputs": { "value": { "type": ["decimal_scalers", "double[]", "float[]", "half[]"], "description": "The cosine value of the input angle in degrees", "uiName": "Result" } }, "tests" : [ { "inputs:value": {"type": "float", "value": 45.0}, "outputs:value": {"type": "float", "value": 0.707107} }, { "inputs:value": {"type": "double", "value": 120.0}, "outputs:value": {"type": "double", "value": -0.5} } ] } }
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()
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])
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnSourceIndices.ogn
{ "SourceIndices": { "version": 1, "description": ["Takes an input array of index values in 'sourceStartsInTarget' encoded as the list of ", "index values at which the output array value will be incremented, starting at the second ", "entry, and with the last entry into the array being the desired sized of the output array ", "'sourceIndices'. For example the input [1,2,3,5,6,6] would generate an output array of ", "size 5 (last index) consisting of the values [0,0,2,3,3,3]:\n", " - the first two 0s to fill the output array up to index input[1]=2\n", " - the first two 0s to fill the output array up to index input[1]=2\n", " - the 2 to fill the output array up to index input[2]=3\n", " - the three 3s to fill the output array up to index input[3]=6" ], "metadata" : { "uiName": "Extract Source Index Array" }, "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "sourceStartsInTarget": { "description": "List of index values encoding the increments for the output array values", "type": "int[]", "default": [] } }, "outputs": { "sourceIndices": { "description": "Decoded list of index values as described by the node algorithm", "type": "int[]", "default": [] } }, "tests": [ { "inputs:sourceStartsInTarget": [1, 2, 3, 5, 6, 6], "outputs:sourceIndices": [0, 0, 1, 2, 2, 3] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnAbsolute.ogn
{ "Absolute": { "version": 1, "description": [ "Compute the absolute value of a vector, array of vectors, scalar or array of scalars", "If an array of vectors are passed in, the output will be an array of corresponding absolute values" ], "uiName": "Absolute", "categories": ["math:operator"], "scheduling": ["threadsafe"], "tags": ["absolute"], "inputs": { "input": { "type": ["decimals", "integrals"], "description": "The vector(s) or scalar(s) to take the absolute value of" } }, "outputs": { "absolute": { "type": ["decimals", "integrals"], "description": "The resulting absolute(s)" } }, "tests": [ { "inputs:input": {"type": "double", "value": -10.0}, "outputs:absolute": {"type": "double", "value": 10.0} }, { "inputs:input": {"type": "float", "value": -10.0}, "outputs:absolute": {"type": "float", "value": 10.0} }, { "inputs:input": {"type": "half", "value": -10.0}, "outputs:absolute": {"type": "half", "value": 10.0} }, { "inputs:input": {"type": "int", "value": -10}, "outputs:absolute": {"type": "int", "value": 10} }, { "inputs:input": {"type": "int64", "value": -10}, "outputs:absolute": {"type": "int64", "value": 10} }, { "inputs:input": {"type": "uchar", "value": 10}, "outputs:absolute": {"type": "uchar", "value": 10} }, { "inputs:input": {"type": "uint", "value": 10}, "outputs:absolute": {"type": "uint", "value": 10} }, { "inputs:input": {"type": "uint64", "value": 10}, "outputs:absolute": {"type": "uint64", "value": 10} }, { "inputs:input": {"type": "double[3]", "value": [-1.0, -2.0, -3.0]}, "outputs:absolute": {"type": "double[3]", "value": [1.0, 2.0, 3.0]} }, { "inputs:input": {"type": "float[4]", "value": [-2.0, 2.0, -2.0, 2.0]}, "outputs:absolute": {"type": "float[4]", "value": [2.0, 2.0, 2.0, 2.0]} }, { "inputs:input": {"type": "int[2]", "value": [3, -4]}, "outputs:absolute": {"type": "int[2]", "value": [3, 4]} }, { "inputs:input": {"type": "half[2]", "value": [3.0, -4.0]}, "outputs:absolute": {"type": "half[2]", "value": [3.0, 4.0]} }, { "inputs:input": {"type": "double[]", "value": [-1.0, -2.0, -2.0]}, "outputs:absolute": {"type": "double[]", "value": [1.0, 2.0, 2.0]} }, { "inputs:input": {"type": "float[]", "value": [-2.0, 2.0, -2.0, 2.0]}, "outputs:absolute": {"type": "float[]", "value": [2.0, 2.0, 2.0, 2.0]} }, { "inputs:input": {"type": "half[]", "value": [3.0, -4.0]}, "outputs:absolute": {"type": "half[]", "value": [3.0, 4.0]} }, { "inputs:input": {"type": "int[]", "value": [3, -4]}, "outputs:absolute": {"type": "int[]", "value": [3, 4]} }, { "inputs:input": {"type": "int64[]", "value": [3, -4]}, "outputs:absolute": {"type": "int64[]", "value": [3, 4]} }, { "inputs:input": {"type": "uchar[]", "value": [3, 4]}, "outputs:absolute": {"type": "uchar[]", "value": [3, 4]} }, { "inputs:input": {"type": "uint[]", "value": [3, 4]}, "outputs:absolute": {"type": "uint[]", "value": [3, 4]} }, { "inputs:input": {"type": "uint64[]", "value": [3, 4]}, "outputs:absolute": {"type": "uint64[]", "value": [3, 4]} }, { "inputs:input": {"type": "int[3][]", "value": [[1, -2, -2], [-4, 2, 6], [3, -2, 4], [1, -4, 2]]}, "outputs:absolute": {"type": "int[3][]", "value": [[1, 2, 2], [4, 2, 6], [3, 2, 4], [1, 4, 2]]} }, { "inputs:input": {"type": "double[3][]", "value": [[1.0, -2.0, -2.0], [-4.0, 2.0, 6.0], [3.0, -2.0, 4.0], [1.0, -4.0, 2.0]]}, "outputs:absolute": {"type": "double[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, 4.0, 2.0]]} }, { "inputs:input": {"type": "float[3][]", "value": [[1.0, -2.0, -2.0], [-4.0, 2.0, 6.0], [3.0, -2.0, 4.0], [1.0, -4.0, 2.0]]}, "outputs:absolute": {"type": "float[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, 4.0, 2.0]]} }, { "inputs:input": {"type": "half[3][]", "value": [[1.0, -2.0, -2.0], [-4.0, 2.0, 6.0], [3.0, -2.0, 4.0], [1.0, -4.0, 2.0]]}, "outputs:absolute": {"type": "half[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, 4.0, 2.0]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnRandomGaussian.ogn
{ "RandomGaussian": { "version": 1, "description": [ "Generates a random numeric value using a Gaussian (aka normal) distribution.", "The shape can be controlled with two inputs: mean and standard deviation.", "These inputs can be numbers, vectors, tuples or arrays of these.", "If one input has a higher dimension than the other, ", "then the input with lower dimension will be repeated to match the dimension of the other input (broadcasting). " ], "uiName": "Random Gaussian", "categories": [ "math:operator" ], "scheduling": [ "threadsafe" ], "inputs": { "execIn": { "type": "execution", "description": "The input execution port to output a new random value" }, "seed": { "type": "uint64", "description": "The seed of the random generator.", "uiName": "Seed", "$optional": "Setting optional=true is a workaround to avoid the USD generated tests for checking the default value of 0, since we override the default seed with a random one", "optional": true }, "useSeed": { "type": "bool", "description": "Use the custom seed instead of a random one", "uiName": "Use seed", "default": false }, "isNoise": { "type": "bool", "description": [ "Turn this node into a noise generator function", "For a given seed, it will then always output the same number(s)" ], "uiName": "Is noise function", "default": false, "metadata": { "hidden": "true", "literalOnly": "1" } }, "mean": { "type": [ "decimals" ], "description": [ "The mean of the normal distribution.", "Can be a number, vector, tuple, or array of these.", "The default value is double 0." ], "uiName": "Mean", "optional": true }, "stdev": { "type": [ "decimals" ], "description": [ "The standard deviation of the normal distribution.", "Can be a number, vector, tuple, or array of these.", "The default value is double 1." ], "uiName": "Standard Deviation", "optional": true }, "useLog": { "type": "bool", "description": "Use a log-normal distribution instead", "uiName": "Use log-normal", "default": false } }, "state": { "gen": { "type": "matrixd[3]", "description": "Random number generator internal state (abusing matrix3d because it is large enough)" } }, "outputs": { "random": { "type": [ "decimals" ], "description": "The random Gaussian value that was generated", "uiName": "Random Gaussian", "unvalidated": true }, "execOut": { "type": "execution", "description": "The output execution port" } }, "tests": [ { "$description": "Checks that float 123 is generated", "inputs:useSeed": true, "inputs:seed": 123456789, "inputs:mean": { "type": "float", "value": 123.0 }, "inputs:stdev": { "type": "float", "value": 0.0 }, "inputs:execIn": 1, "outputs:random": { "type": "float", "value": 123.0 }, "outputs:execOut": 1, "inputs:isNoise": true }, { "$description": "Checks double array broadcasting", "inputs:useSeed": true, "inputs:seed": 123456789, "inputs:mean": { "type": "double[]", "value": [ -100, 100 ] }, "inputs:stdev": { "type": "double", "value": 1 }, "inputs:execIn": 1, "outputs:random": { "type": "double[]", "value": [ -98.27423617, 100.04434614 ] }, "outputs:execOut": 1, "inputs:isNoise": true }, { "$description": "Checks half tuple broadcasting", "inputs:useSeed": true, "inputs:seed": 123456789, "inputs:mean": { "type": "half", "value": 0 }, "inputs:stdev": { "type": "half[2]", "value": [ 1, 2 ] }, "inputs:execIn": 1, "outputs:random": { "type": "half[2]", "value": [ 1.7255859, 0.08868408 ] }, "outputs:execOut": 1, "inputs:isNoise": true }, { "$description": "Checks float array tuple broadcasting and log-normal mean", "inputs:useSeed": true, "inputs:seed": 123456789, "inputs:mean": { "type": "float[2][]", "value": [ [ 1, 2 ], [ 3, 4 ] ] }, "inputs:stdev": { "type": "float", "value": 0 }, "inputs:useLog": true, "inputs:execIn": 1, "outputs:random": { "type": "float[2][]", "value": [ [ 1, 2 ], [ 3, 4 ] ] }, "outputs:execOut": 1, "inputs:isNoise": true }, { "$description": "Checks log-normal stdev", "inputs:useSeed": true, "inputs:seed": 123456789, "inputs:mean": { "type": "float", "value": 100 }, "inputs:stdev": { "type": "float[]", "value": [ 1, 1, 1, 1, 1 ] }, "inputs:useLog": true, "inputs:execIn": 1, "outputs:random": { "type": "float[]", "value": [ 101.735756, 100.03935, 99.89501, 100.42319, 99.54652 ] }, "outputs:execOut": 1, "inputs:isNoise": true }, { "$description": "Checks that the default input values are used", "inputs:useSeed": true, "inputs:seed": 9302349107990861236, "inputs:execIn": 1, "outputs:random": { "type": "double", "value": 0.6957887336760361 }, "outputs:execOut": 1, "inputs:isNoise": true } ] } }
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()
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
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()
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIncrement.ogn
{ "Increment": { "version": 1, "description": [ "Add a double argument to any type (element-wise). This includes simple values, tuples, arrays,", "and arrays of tuples. ", "The output type is always the same as the type of input:value. ", "For example: tuple + double results a tuple. ", "Chopping is used for approximation. For example: 4 + 3.2 will result 7. ", "The default increment value is 1.0. " ], "uiName": "Increment", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["numerics"], "description": "The operand that to be increased", "uiName": "Value" }, "increment": { "type": "double", "description": "The number added to the first operand", "uiName": "Increment amount", "default": 1.0 } }, "outputs": { "result": { "type": ["numerics"], "description": "Result of the increment", "uiName": "Result" } }, "tests": [ { "inputs:value": {"type": "float[2]", "value": [1.0, 2.0]}, "inputs:increment": 0.5, "outputs:result": {"type": "float[2]", "value": [ 1.5, 2.5 ] } }, { "inputs:value": {"type": "int64", "value": 10}, "inputs:increment": 1.2, "outputs:result": {"type": "int64", "value": 11} }, { "inputs:value": {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, "inputs:increment": 5.4, "outputs:result": {"type": "double[2][]", "value": [[ 15.4, 10.4 ],[ 6.4, 6.4 ]]} }, { "inputs:value": {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, "inputs:increment": 5, "outputs:result": {"type": "double[2][]", "value": [[15, 10], [6, 6]]} }, { "inputs:value": {"type": "double", "value": 2.22045e-16}, "outputs:result": {"type": "double", "value": 1.000000000000000222045} } ] } }
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
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnATan2.ogn
{ "ATan2": { "version": 1, "description": "Outputs the arc tangent of a/b in degrees", "language": "python", "categories": ["math:operator"], "uiName": "Atan2", "inputs": { "a": { "type": ["decimal_scalers"], "description": "Input A" }, "b": { "type": ["decimal_scalers"], "description": "Input B" } }, "outputs": { "result": { "type": ["decimal_scalers"], "description": "The result of ATan2(A,B)", "uiName": "Result" } }, "tests" : [ { "inputs:a": {"type": "float", "value": 5.0}, "inputs:b": {"type": "float", "value": 3.0}, "outputs:result": {"type": "float", "value": 59.0362434679} }, { "inputs:a": {"type": "double", "value": 70.0}, "inputs:b": {"type": "double", "value": 10.0}, "outputs:result": {"type": "double", "value": 81.8698976458} } ] } }
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(); } } }
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
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
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
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
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnGetLocationAtDistanceOnCurve.ogn
{ "GetLocationAtDistanceOnCurve": { "version": 1, "description": [ "DEPRECATED: Use GetLocationAtDistanceOnCurve2" ], "uiName": "Get Locations At Distances On Curve", "categories": ["internal"], "metadata": {"hidden": "true"}, "scheduling": ["threadsafe"], "inputs": { "curve": { "type": "pointd[3][]", "description": "The curve to be examined", "uiName": "Curve" }, "distance": { "type": "double[]", "description": "The distances along the curve, wrapped to the range 0-1.0", "uiName": "Distances" }, "forwardAxis": { "type": "token", "description": ["The direction vector from which the returned rotation is relative, one of X, Y, Z"], "uiName": "Forward", "default": "X" }, "upAxis": { "type": "token", "description": ["The world Up vector, the curve should be in a plane perpendicular with this - one of X, Y, Z"], "uiName": "Up", "default": "Y" } }, "outputs": { "location": { "type": "pointd[3][]", "description": "Locations", "uiName": "Locations on curve at the given distances in world space" }, "rotateXYZ": { "type": "vectord[3][]", "description": "Rotations", "uiName": "World space rotations of the curve at the given distances, may not be smooth for some curves" }, "orientation": { "type": "quatf[4][]", "description": "Orientations", "uiName": "World space orientations of the curve at the given distances, may not be smooth for some curves" } }, "tokens": [ "x", "y", "z", "X", "Y", "Z" ], "tests": [ {"inputs:curve": [[1, 2, 3]], "inputs:distance": [0.5], "outputs:location": [[1, 2, 3]]}, {"inputs:curve": [[0, 0, 0], [0, 0, 1]], "inputs:distance": [0.75, 0], "inputs:forwardAxis": "X", "inputs:upAxis": "Y", "outputs:location": [[0, 0, 0.5], [0, 0, 0]], "outputs:rotateXYZ": [[0, 90, 0], [0, -90, 0]]} ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnEase.ogn
{ "Ease": { "version": 2, "description": [ "Easing function which iterpolates between a start and end value.", "Vectors are eased component-wise. The easing functions can be applied to decimal types.", "Linear: Interpolates between start and finish at a fixed rate.", "EaseIn: Starts slowly and ends fast according to an exponential, the slope is determined by the 'exponent' input.", "EaseOut: Same as EaseIn, but starts fast and ends slow", "EaseInOut: Combines EaseIn and EaseOut", "SinIn: Starts slowly and ends fast according to a sinusoidal curve", "SinOut: Same as SinIn, but starts fast and ends slow", "SinInOut: Combines SinIn and SinOut" ], "uiName": "Easing Function", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "start": { "type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"], "description": "The start value" }, "end": { "type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"], "description": "The end value" }, "alpha": { "type": ["float", "float[]"], "description": "The normalized time (0 - 1.0). Values outside this range will be clamped" }, "blendExponent": { "type": "int", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). ", "This only applies to the Ease* functions"], "minimum": 1, "maximum": 10, "default": 2 }, "easeFunc": { "type": "token", "description": "The easing function to apply (EaseIn, EaseOut, EaseInOut, Linear, SinIn, SinOut, SinInOut)", "uiName": "Operation", "default": "EaseInOut", "metadata": { "allowedTokens": ["EaseIn", "EaseOut", "EaseInOut", "Linear", "SinIn", "SinOut", "SinInOut"] } } }, "outputs": { "result": { "type": ["decimal_scalers", "decimal_tuples", "decimal_arrays"], "description": "The eased result of the function applied to value", "uiName": "Result" } }, "tests" : [ { "inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 0.5}, "outputs:result": {"type": "float", "value": 5} }, { "inputs:start": {"type": "float[]", "value": [0, 1]}, "inputs:end": {"type": "float[]", "value": [10, 11]}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]}, "outputs:result": {"type": "float[]", "value": [5, 7]} }, { "inputs:start": {"type": "float[]", "value": [0, 0]}, "inputs:end": {"type": "float", "value": 10}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]}, "outputs:result": {"type": "float[]", "value": [5, 6]} }, { "inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]}, "outputs:result": {"type": "float[]", "value": [5, 6]} }, { "inputs:start": {"type": "float[2]", "value": [0,0]}, "inputs:end": {"type": "float[2]", "value": [10,10]}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.6]}, "outputs:result": {"type": "float[2][]", "value": [[5, 5],[6,6]]} }, { "inputs:start": {"type": "float[2][]", "value": [[0, 0], [10, 10]]}, "inputs:end": {"type": "float[2]", "value": [10, 20]}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float[]", "value": [0.5, 0.5]}, "outputs:result": {"type": "float[2][]", "value": [[5, 10],[10,15]]} }, { "inputs:start": {"type": "double", "value": 0.0}, "inputs:end": {"type": "double", "value": 10.0}, "inputs:easeFunc": "EaseInOut", "inputs:alpha": {"type": "float", "value": 0.25}, "outputs:result": {"type": "double", "value": 1.25} }, { "inputs:start": {"type": "double", "value": 0.0}, "inputs:end": {"type": "double", "value": 10.0}, "inputs:easeFunc": "SinOut", "inputs:alpha": {"type": "float", "value": 0.75}, "outputs:result": {"type": "double", "value": 9.238795} }, { "inputs:start": {"type": "float[2]", "value": [0, 1]}, "inputs:end": {"type": "float[2]", "value": [10.0, 11.0]}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 0.5}, "outputs:result": {"type": "float[2]", "value": [5.0, 6.0]} }, { "inputs:start": {"type": "half[3]", "value": [0, 1, 2]}, "inputs:end": {"type": "half[3]", "value": [10.0, 11.0, 12.0]}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 0.5}, "outputs:result": {"type": "half[3]", "value": [5.0, 6.0, 7.0]} }, { "inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": 1.524}, "outputs:result": {"type": "float", "value": 10} }, { "inputs:start": {"type": "float", "value": 0}, "inputs:end": {"type": "float", "value": 10}, "inputs:easeFunc": "Linear", "inputs:alpha": {"type": "float", "value": -20}, "outputs:result": {"type": "float", "value": 0} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnNoise.ogn
{ "Noise": { "version": 1, "description": [ "Sample values from a Perlin noise field.\n", "The noise field for any given seed is static: the same input position will always", "give the same result. This is useful in many areas, such as texturing and animation,", "where repeatability is essential. If you want a result that varies then you will need", "to vary either the position or the seed. For example, connecting the 'frame' output of", "an OnTick node to position will provide a noise result which varies from frame to frame.", "Perlin noise is locally smooth, meaning that small changes in the sample position will", "produce small changes in the resulting noise. Varying the seed value will produce a more", "chaotic result.\n", "Another characteristic of Perlin noise is that it is zero at the corners of each cell in", "the field. In practical terms this means that integral positions, such as 5.0 in a", "one-dimensional field or (3.0, -1.0) in a two-dimensional field, will return a result", "of 0.0. Thus, if the source of your sample positions provides only integral values then all of", "your results will be zero. To avoid this try offsetting your position values by a fractional", "amount, such as 0.5." ], "uiName": "Noise", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "seed": { "type": "uint", "description": [ "Seed for generating the noise field." ], "default": 0 }, "position": { "type": [ "float", "float[]", "float[2]", "float[2][]", "float[3]", "float[3][]", "float[4]", "float[4][]" ], "description": [ "Position(s) within the noise field to be sampled. For a given seed, the same position ", "will always return the same noise value." ] } }, "outputs": { "result": { "type": [ "float", "float[]" ], "description": "Value at the selected position(s) in the noise field." } }, "tests": [ { "inputs:seed": 5, "inputs:position": {"type": "float", "value": 1.4}, "outputs:result": {"type": "float", "value": 0.03438323736190796} }, { "inputs:seed": 5, "inputs:position": {"type": "float", "value": -1.4}, "outputs:result": {"type": "float", "value": -0.03764888644218445} }, { "inputs:seed": 23, "inputs:position": {"type": "float", "value": 1.4}, "outputs:result": {"type": "float", "value": -0.1955927014350891} }, { "inputs:seed": 5, "inputs:position": {"type": "float[2]", "value": [1.7, -0.4]}, "outputs:result": {"type": "float", "value": -0.10021606087684631} }, { "inputs:seed": 5, "inputs:position": {"type": "float[2]", "value": [-0.4, 1.7]}, "outputs:result": {"type": "float", "value": -0.4338015019893646} }, { "inputs:seed": 5, "inputs:position": {"type": "float[3]", "value": [1.4, -0.8, 0.5]}, "outputs:result": {"type": "float", "value": -0.14821206033229828} }, { "inputs:seed": 5, "inputs:position": {"type": "float[3]", "value": [1.5, -0.8, 0.5]}, "outputs:result": {"type": "float", "value": -0.11368121206760406} }, { "inputs:seed": 5, "inputs:position": {"type": "float[3]", "value": [1.4, -0.9, 0.5]}, "outputs:result": {"type": "float", "value": -0.16395819187164307} }, { "inputs:seed": 5, "inputs:position": {"type": "float[3]", "value": [1.4, -0.8, 0.8]}, "outputs:result": {"type": "float", "value": 0.00016325712203979492} }, { "inputs:seed": 5, "inputs:position": {"type": "float[3]", "value": [1.5, -0.9, 0.8]}, "outputs:result": {"type": "float", "value": -0.03829096257686615} }, { "inputs:seed": 5, "inputs:position": {"type": "float[3]", "value": [2.5, -0.9, 0.8]}, "outputs:result": {"type": "float", "value": 0.034046247601509094} }, { "inputs:seed": 5, "inputs:position": {"type": "float[4]", "value": [2.5, -0.9, 0.8, 0.0]}, "outputs:result": {"type": "float", "value": -0.009762797504663467} }, { "inputs:seed": 5, "inputs:position": {"type": "float[4]", "value": [2.5, -0.9, 0.8, 0.1]}, "outputs:result": {"type": "float", "value": -0.07352154701948166} }, { "inputs:seed": 6, "inputs:position": {"type": "float[4]", "value": [2.5, -0.9, 0.8, 0.1]}, "outputs:result": {"type": "float", "value": 0.2615857422351837} }, { "inputs:seed": 5, "inputs:position": {"type": "float[]", "value": [-1.4]}, "outputs:result": {"type": "float[]", "value": [-0.03764889]} }, { "inputs:seed": 5, "inputs:position": {"type": "float[]", "value": [0.5, -1.4]}, "outputs:result": {"type": "float[]", "value": [0.18699697, -0.03764889]} }, { "inputs:seed": 5, "inputs:position": { "type": "float[2][]", "value": [[1.5, -0.8]] }, "outputs:result": {"type": "float[]", "value": [0.16450586915016174] } }, { "inputs:seed": 5, "inputs:position": { "type": "float[2][]", "value": [[1.5, -0.8], [2.5, -0.9]] }, "outputs:result": {"type": "float[]", "value": [0.16450587, 0.08753645] } }, { "inputs:seed": 5, "inputs:position": { "type": "float[3][]", "value": [[1.5, -0.8, 0.5]] }, "outputs:result": {"type": "float[]", "value": [-0.11368121206760406] } }, { "inputs:seed": 5, "inputs:position": { "type": "float[3][]", "value": [[1.5, -0.8, 0.5], [1.4, -0.8, 0.5]] }, "outputs:result": {"type": "float[]", "value": [-0.11368121206760406, -0.14821206033229828] } }, { "inputs:seed": 5, "inputs:position": { "type": "float[3][]", "value": [[2.5, -0.9, 0.8], [1.5, -0.8, 0.5], [1.4, -0.8, 0.5]] }, "outputs:result": {"type": "float[]", "value": [0.034046247601509094, -0.11368121206760406, -0.14821206033229828] } }, { "inputs:seed": 5, "inputs:position": { "type": "float[4][]", "value": [[2.5, -0.9, 0.8, 0.0], [2.5, -0.9, 0.8, 0.1]] }, "outputs:result": {"type": "float[]", "value": [-0.009762797504663467, -0.07352154701948166] } } ] } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnIsZero.ogn
{ "IsZero": { "version": 1, "description": [ "Outputs a boolean indicating if all of the input values are zero within a specified tolerance." ], "uiName": "Is Zero", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "value": { "type": ["numerics"], "description": "Value(s) to check for zero.", "uiName": "Value" }, "tolerance": { "type": "double", "description": [ "How close the value must be to 0 to be considered \"zero\"." ], "uiName": "Tolerance", "minimum": 0.0 } }, "outputs": { "result": { "type": "bool", "description": [ "If 'value' is a scalar then 'result' will be true if 'value' is zero. If 'value' is non-scalar", "(array, tuple, matrix, etc) then 'result' will be true if all of its elements/components are zero." ], "uiName": "Result" } }, "tests" : [ { "inputs:value": {"type": "int", "value": 6}, "outputs:result": false }, { "inputs:value": {"type": "int", "value": -3}, "outputs:result": false }, { "inputs:value": {"type": "int", "value": 0}, "outputs:result": true }, { "inputs:value": {"type": "float", "value": 42.5}, "outputs:result": false }, { "inputs:value": {"type": "float", "value": -7.1}, "outputs:result": false }, { "inputs:value": {"type": "float", "value": 0.0}, "outputs:result": true }, { "inputs:value": {"type": "float", "value": 0.01}, "outputs:result": false }, { "inputs:value": {"type": "float", "value": -0.01}, "outputs:result": false }, { "inputs:value": {"type": "float", "value": 42.5}, "inputs:tolerance": 0.1, "outputs:result": false }, { "inputs:value": {"type": "float", "value": -7.1}, "inputs:tolerance": 0.1, "outputs:result": false }, { "inputs:value": {"type": "float", "value": 0.0}, "inputs:tolerance": 0.1, "outputs:result": true }, { "inputs:value": {"type": "float", "value": 0.01}, "inputs:tolerance": 0.1, "outputs:result": true }, { "inputs:value": {"type": "float", "value": -0.01}, "inputs:tolerance": 0.1, "outputs:result": true }, { "inputs:value": {"type": "int", "value": 6}, "inputs:tolerance": 0.1, "outputs:result": false }, { "inputs:value": {"type": "int", "value": -3}, "inputs:tolerance": 0.1, "outputs:result": false }, { "inputs:value": {"type": "int", "value": 0}, "inputs:tolerance": 0.1, "outputs:result": true }, { "inputs:value": {"type": "int", "value": 6}, "inputs:tolerance": 10.0, "outputs:result": true }, { "inputs:value": {"type": "int", "value": -3}, "inputs:tolerance": 10.0, "outputs:result": true }, { "inputs:value": {"type": "int", "value": 0}, "inputs:tolerance": 10.0, "outputs:result": true }, { "inputs:value": {"type": "int[2]", "value": [ 0, 0 ]}, "outputs:result": true }, { "inputs:value": {"type": "int[2]", "value": [ 0, 3 ]}, "outputs:result": false }, { "inputs:value": {"type": "int[2]", "value": [ 3, 0 ]}, "outputs:result": false }, { "inputs:value": {"type": "int[2]", "value": [ 3, 5 ]}, "outputs:result": false }, { "inputs:value": {"type": "float[3]", "value": [1.7, 0.05, -4.3]}, "inputs:tolerance": 0.1, "outputs:result": false }, { "inputs:value": {"type": "float[3]", "value": [0.02, 0.05, -0.03]}, "inputs:tolerance": 0.1, "outputs:result": true }, { "inputs:value": {"type": "float[3][]", "value": [ [1.7, 0.05, -4.3], [0.02, 0.05, -0.03] ]}, "inputs:tolerance": 0.1, "outputs:result": false }, { "inputs:value": {"type": "float[3][]", "value": [ [0.0, 0.0, 0.0], [0.02, 0.05, -0.03] ]}, "inputs:tolerance": 0.1, "outputs:result": true } ] } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnTrig.ogn
{ "Trig": { "version": 1, "description": [ "Trigonometric operation of one input in degrees.", "Supported operations are:\n", "SIN, COS, TAN, ARCSIN, ARCCOS, ARCTAN, DEGREES, RADIANS" ], "uiName": "Trigonometric Operation", "categories": ["math:operator", "math:conversion"], "scheduling": ["threadsafe"], "metadata": {"hidden": "true"}, "inputs": { "a": { "type": ["decimal_scalers"], "description": "Input to the function" }, "operation": { "type": "token", "description": "The operation to perform", "uiName": "Operation", "default": "SIN", "metadata": { "allowedTokens": ["SIN","COS","TAN","ARCSIN","ARCCOS", "ARCTAN", "DEGREES","RADIANS"] } } }, "outputs": { "result": { "type": ["decimal_scalers"], "description": "The result of the function", "uiName": "Result" } }, "tests" : [ { "inputs:a": {"type": "float", "value": 120.0}, "inputs:operation": "COS", "outputs:result": {"type": "float", "value": -0.5} }, { "inputs:a": {"type": "double", "value": -57.2958}, "inputs:operation": "RADIANS", "outputs:result": {"type": "double", "value": -1.0} }, { "inputs:a": {"type": "double", "value": -1.0}, "inputs:operation": "ARCCOS", "outputs:result": {"type": "double", "value": 180.0} }, { "inputs:a": {"type": "float", "value": 45.0}, "inputs:operation": "SIN", "outputs:result": {"type": "float", "value": 0.707107} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnCeil.ogn
{ "Ceil": { "version": 1, "description": [ "Computes the ceil of the given decimal number a, which is the smallest integral value greater than a" ], "uiName": "Ceiling", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["decimals"], "description": "The decimal number", "uiName": "A" } }, "outputs": { "result": { "type": ["int", "integral_tuples", "int[]", "int[2][]", "int[3][]", "int[4][]"], "description": "The ceil of the input a", "uiName": "Result" } }, "tests" : [ { "inputs:a": {"type": "float", "value": 4.1}, "outputs:result": 5 }, { "inputs:a": {"type": "half", "value": -4.9}, "outputs:result": -4 }, { "inputs:a": {"type": "double[3]", "value": [1.3, 2.4, -3.7]}, "outputs:result": [2, 3, -3] }, { "inputs:a": {"type": "double[]", "value": [1.3, 2.4, -3.7, 4.5]}, "outputs:result": [2, 3, -3, 5] } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnMagnitude.ogn
{ "Magnitude": { "version": 1, "description": [ "Compute the magnitude of a vector, array of vectors, or a scalar", "If a scalar is passed in, the absolute value will be returned", "If an array of vectors are passed in, the output will be an array of corresponding magnitudes" ], "uiName": "Magnitude", "categories": ["math:operator"], "scheduling": ["threadsafe"], "tags": ["absolute"], "inputs": { "input": { "type": ["decimals", "integrals"], "description": "The vector(s) or scalar to take the magnitude of" } }, "outputs": { "magnitude": { "type": ["decimals", "integrals"], "description": "The resulting magnitude(s)" } }, "tests": [ { "inputs:input": {"type": "double", "value": -10.0}, "outputs:magnitude": {"type": "double", "value": 10.0} }, { "inputs:input": {"type": "float", "value": -10.0}, "outputs:magnitude": {"type": "float", "value": 10.0} }, { "inputs:input": {"type": "half", "value": -10.0}, "outputs:magnitude": {"type": "half", "value": 10.0} }, { "inputs:input": {"type": "int", "value": -10}, "outputs:magnitude": {"type": "int", "value": 10} }, { "inputs:input": {"type": "int64", "value": -10}, "outputs:magnitude": {"type": "int64", "value": 10} }, { "inputs:input": {"type": "uchar", "value": 10}, "outputs:magnitude": {"type": "uchar", "value": 10} }, { "inputs:input": {"type": "uint", "value": 10}, "outputs:magnitude": {"type": "uint", "value": 10} }, { "inputs:input": {"type": "uint64", "value": 10}, "outputs:magnitude": {"type": "uint64", "value": 10} }, { "inputs:input": {"type": "int[2]", "value": [3, -4]}, "outputs:magnitude": {"type": "double", "value": 5.0} }, { "inputs:input": {"type": "double[3]", "value": [1.0, 2.0, 2.0]}, "outputs:magnitude": {"type": "double", "value": 3.0} }, { "inputs:input": {"type": "float[4]", "value": [-2.0, 2.0, -2.0, 2.0]}, "outputs:magnitude": {"type": "float", "value": 4.0} }, { "inputs:input": {"type": "half[2]", "value": [3.0, -4.0]}, "outputs:magnitude": {"type": "half", "value": 5.0} }, { "inputs:input": {"type": "double[]", "value": [1.0, 2.0, 2.0]}, "outputs:magnitude": {"type": "double[]", "value": [1.0, 2.0, 2.0]} }, { "inputs:input": {"type": "float[]", "value": [-2.0, 2.0, -2.0, 2.0]}, "outputs:magnitude": {"type": "float[]", "value": [2.0, 2.0, 2.0, 2.0]} }, { "inputs:input": {"type": "half[]", "value": [3.0, -4.0]}, "outputs:magnitude": {"type": "half[]", "value": [3.0, 4.0]} }, { "inputs:input": {"type": "int[]", "value": [3, -4]}, "outputs:magnitude": {"type": "int[]", "value": [3, 4]} }, { "inputs:input": {"type": "int64[]", "value": [3, -4]}, "outputs:magnitude": {"type": "int64[]", "value": [3, 4]} }, { "inputs:input": {"type": "uchar[]", "value": [3, 4]}, "outputs:magnitude": {"type": "uchar[]", "value": [3, 4]} }, { "inputs:input": {"type": "uint[]", "value": [3, 4]}, "outputs:magnitude": {"type": "uint[]", "value": [3, 4]} }, { "inputs:input": {"type": "uint64[]", "value": [3, 4]}, "outputs:magnitude": {"type": "uint64[]", "value": [3, 4]} }, { "inputs:input": {"type": "int[3][]", "value": [[1, 2, 2], [4, 2, 6], [3, 2, 4], [1, -4, 2]]}, "outputs:magnitude": {"type": "double[]", "value": [3.0, 7.483314773547883, 5.385164807134504, 4.58257569495584]} }, { "inputs:input": {"type": "double[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, -4.0, 2.0]]}, "outputs:magnitude": {"type": "double[]", "value": [3.0, 7.483314773547883, 5.385164807134504, 4.58257569495584]} }, { "inputs:input": {"type": "float[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, -4.0, 2.0]]}, "outputs:magnitude": {"type": "float[]", "value": [3.0, 7.483315, 5.3851647, 4.582576]} }, { "inputs:input": {"type": "half[3][]", "value": [[1.0, 2.0, 2.0], [4.0, 2.0, 6.0], [3.0, 2.0, 4.0], [1.0, -4.0, 2.0]]}, "outputs:magnitude": {"type": "half[]", "value": [3.0, 7.484375, 5.3867188, 4.5820312]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnPartialSum.ogn
{ "PartialSum": { "description": ["Compute the partial sums of the input integer array named 'array' and put the result in ", "an output integer array named 'partialSum'. A partial sum is the sum of all of the elements ", "up to but not including a certain point in an array, so output element 0 is always 0, ", "element 1 is array[0], element 2 is array[0] + array[1], etc." ], "metadata" : { "uiName": "Compute Integer Array Partial Sums" }, "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "array": { "description": "List of integers whose partial sum is to be computed", "type": "int[]", "default": [] } }, "outputs": { "partialSum": { "description": "Array whose nth value equals the nth partial sum of the input 'array'", "type": "int[]", "default": [] } }, "tests": [ { "inputs:array": [1, 2, 3, 4, 5], "outputs:partialSum": [0, 1, 3, 6, 10, 15] } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadKeyboardState.ogn
{ "ReadKeyboardState": { "description": "Reads the current state of the keyboard", "version": 1, "uiName": "Read Keyboard State", "categories": ["input:keyboard"], "scheduling": ["threadsafe"], "inputs": { "key": { "type": "token", "description": "The key to check the state of", "uiName": "Key", "default": "A", "metadata": { "displayGroup": "parameters", "allowedTokens": [ "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", "Apostrophe", "Backslash", "Backspace", "CapsLock", "Comma", "Del", "Down", "End", "Enter", "Equal", "Escape", "F1", "F10", "F11", "F12", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "GraveAccent", "Home", "Insert", "Key0", "Key1", "Key2", "Key3", "Key4", "Key5", "Key6", "Key7", "Key8", "Key9", "Left", "LeftAlt", "LeftBracket", "LeftControl", "LeftShift", "LeftSuper", "Menu", "Minus", "NumLock", "Numpad0", "Numpad1", "Numpad2", "Numpad3", "Numpad4", "Numpad5", "Numpad6", "Numpad7", "Numpad8", "Numpad9", "NumpadAdd", "NumpadDel", "NumpadDivide", "NumpadEnter", "NumpadEqual", "NumpadMultiply", "NumpadSubtract", "PageDown", "PageUp", "Pause", "Period", "PrintScreen", "Right", "RightAlt", "RightBracket", "RightControl", "RightShift", "RightSuper", "ScrollLock", "Semicolon", "Slash", "Space", "Tab", "Up"] } } }, "outputs": { "isPressed": { "type": "bool", "description": "True if the key is currently pressed, false otherwise" }, "shiftOut": { "type": "bool", "description": "True if Shift is held", "uiName": "Shift" }, "altOut": { "type": "bool", "description": "True if Alt is held", "uiName": "Alt" }, "ctrlOut": { "type": "bool", "description": "True if Ctrl is held", "uiName": "Ctrl" } } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/io/OgnReadGamepadState.ogn
{ "ReadGamepadState": { "description": "Reads the current state of the gamepad", "version": 1, "uiName": "Read Gamepad State", "categories": ["input:gamepad"], "scheduling": ["threadsafe"], "inputs": { "gamepadId": { "type": "uint", "description": "Gamepad id number starting from 0", "uiName": "Gamepad ID", "default": 0 }, "gamepadElement": { "type": "token", "description": "The gamepad element to check the state of", "uiName": "Element", "default": "Left Stick X Axis", "metadata": { "displayGroup": "parameters", "allowedTokens": { "LeftStickXAxis": "Left Stick X Axis", "LeftStickYAxis": "Left Stick Y Axis", "RightStickXAxis": "Right Stick X Axis", "RightStickYAxis": "Right Stick Y Axis", "LeftTrigger": "Left Trigger", "RightTrigger": "Right Trigger", "FaceButtonBottom": "Face Button Bottom", "FaceButtonRight": "Face Button Right", "FaceButtonLeft": "Face Button Left", "FaceButtonTop": "Face Button Top", "LeftShoulder": "Left Shoulder", "RightShoulder": "Right Shoulder", "SpecialLeft": "Special Left", "SpecialRight": "Special Right", "LeftStickButton": "Left Stick Button", "RightStickButton": "Right Stick Button", "DpadUp": "D-Pad Up", "DpadRight": "D-Pad Right", "DpadDown": "D-Pad Down", "DpadLeft": "D-Pad Left" } } }, "deadzone": { "type": "float", "description": "Threshold from [0, 1] that the value must pass for it to be registered as input", "uiName": "Deadzone", "default": 0.1, "minimum": 0.0, "maximum": 1.0 } }, "outputs": { "isPressed": { "type": "bool", "description": "True if the gamepad element is currently pressed, false otherwise" }, "value": { "type": "float", "description": "Value of how much the gamepad element is being pressed. [0, 1] for buttons [-1, 1] for stick and trigger" } } } }
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() } } }
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
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() } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimDirectionVector.ogn
{ "GetPrimDirectionVector": { "version": 2, "description": [ "Given a prim, find its direction vectors (up vector, forward vector, right vector, etc.)" ], "uiName": "Get Prim Direction Vector", "scheduling": ["usd-read", "threadsafe"], "categories": ["sceneGraph"], "inputs": { "primPath": { "type": "token", "description": "The path of the input prim - this attribute is used when 'usePath' is true", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "usePath": { "type": "bool", "default": true, "description": "When true, it will use the 'primPath' attribute as the path to the prim, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "prim": { "type": "target", "description": "The connection to the input prim - this attribute is used when 'usePath' is false", "optional": true } }, "outputs": { "upVector": { "type": "double[3]", "description": "The up vector of the prim", "uiName": "Up Vector" }, "downVector": { "type": "double[3]", "description": "The down vector of the prim", "uiName": "Down Vector" }, "forwardVector": { "type": "double[3]", "description": "The forward vector of the prim", "uiName": "Forward Vector" }, "backwardVector": { "type": "double[3]", "description": "The backward vector of the prim", "uiName": "Backward Vector" }, "rightVector": { "type": "double[3]", "description": "The right vector of the prim", "uiName": "Right Vector" }, "leftVector": { "type": "double[3]", "description": "The left vector of the prim", "uiName": "Left Vector" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTransformVector.ogn
{ "TransformVector": { "version": 1, "description": [ "Applies a transformation matrix to a row vector, returning the result. returns vector * matrix", "If the vector is one dimension smaller than the matrix (eg a 4x4 matrix and a 3d vector), ", "The last component of the vector will be treated as a 1. The result is then projected back to a 3-vector. ", "Supports mixed array inputs, eg a single matrix and an array of vectors." ], "uiName": "Transform Vector", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]", "matrixd[3]", "matrixd[3][]"], "uiName": "Matrix", "description": "The transformation matrix to be applied" }, "vector": { "type": ["vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]"], "uiName": "Vector", "description": "The row vector(s) to be translated" } }, "outputs": { "result": { "type": ["vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]"], "uiName": "Result", "description": "The transformed row vector(s)" } }, "tests" : [ { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]}, "vector": {"type": "vectord[3]", "value":[1, 2, 3]}}, "outputs:result": {"type":"vectord[3]", "value":[81, 32, 3]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1], [1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]] }, "vector": {"type": "vectorf[3][]", "value": [[1, 2, 3], [1, 2, 3]]}}, "outputs:result": {"type":"vectorf[3][]", "value" : [[81, 32, 3], [81, 32, 3]]} }, { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]}, "vector": {"type": "vectorf[3][]", "value": [[1, 2, 3], [1, 2, 3]]}}, "outputs:result": {"type":"vectorf[3][]", "value" : [[81, 32, 3], [81, 32, 3]]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1], [1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]] }, "vector": {"type": "vectorf[3]", "value": [1, 2, 3]}}, "outputs:result": {"type":"vectorf[3][]", "value" : [[81, 32, 3], [81, 32, 3]]} } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToLocation.ogn
{ "TranslateToLocation": { "version": 2, "description": [ "Perform a smooth translation maneuver, translating a prim to a desired point given a speed and easing factor" ], "uiName": "Translate To Location", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "prim": { "type": "target", "description": "The prim to be translated", "optional": true }, "usePath": { "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "primPath": { "type": "path", "description": "The source prim to be transformed, used when 'usePath' is true", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "target": { "type": "vectord[3]", "description": "The desired local position" }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Translation.ogn
{ "GetMatrix4Translation": { "version": 1, "description": [ "Gets the translation of the given matrix4d value which represents a linear transformation.", "Returns a vector3" ], "uiName": "Get Translation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The matrix to be modified" } }, "outputs": { "translation": { "type": ["vectord[3]", "vectord[3][]"], "uiName": "Translation", "description": [ "The translation from the transformation matrix" ] } }, "tests" : [ { "inputs:matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1]}, "outputs:translation": {"type": "vectord[3]", "value":[50,0,0]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,3,0, 0,1,0,1, 0,0,1,0, 50,0,0,1], [1.0,0,0,3, 0,1,0,1, 0,0,1,0, 1,100,4,1]] } }, "outputs:translation": {"type":"vectord[3][]", "value": [[50,0,0], [1,100,4]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToOrientation.ogn
{ "RotateToOrientation": { "version": 2, "description": [ "Perform a smooth rotation maneuver, rotating a prim to a desired orientation given a speed and easing factor" ], "uiName": "Rotate To Orientation", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "prim": { "type": "target", "description": "The prim to be rotated", "optional": true }, "usePath": { "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "primPath": { "type": "path", "description": "The source prim to be transformed, used when 'usePath' is true", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "target": { "type": "vectord[3]", "description": "The desired orientation as euler angles (XYZ) in local space", "uiName": "Target Orientation" }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTransform.ogn
{ "MoveToTransform": { "version": 2, "description": [ "Perform a transformation maneuver, moving a prim to a target transformation given a speed and easing factor.", "Transformation, Rotation, and Scale from a 4x4 transformation matrix will be applied", "Note: The Prim must have xform:orient in transform stack in order to interpolate rotations" ], "uiName": "Move to Transform", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "prim": { "type": "target", "description": "The prim to be transformed", "optional": true }, "usePath": { "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "primPath": { "type": "path", "description": "The source prim to be transformed, used when 'usePath' is true", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "target": { "type": "matrixd[4]", "description": "The desired local transform", "uiName": "Target Transform" }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateToTarget.ogn
{ "RotateToTarget": { "version": 2, "description": [ "This node smoothly rotates a prim object to match a target prim object given a speed and easing factor. ", "At the end of the maneuver, the source prim will have the rotation as the target prim.\n", "Note: The Prim must have xform:orient in transform stack in order to interpolate rotations" ], "uiName": "Rotate To Target", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "sourcePrim": { "type": "target", "description": "The source prim to be transformed", "optional": true }, "useSourcePath": { "type": "bool", "default": false, "description": "When true, the 'sourcePrimPath' attribute is used, otherwise it will read the connection at the 'sourcePrim' attribute" }, "sourcePrimPath": { "type": "path", "description": "The source prim to be transformed, used when 'useSourcePath' is true", "optional": true }, "targetPrim": { "type": "target", "description": "The destination prim. The target's rotation will be matched by the sourcePrim", "optional": true }, "useTargetPath": { "type": "bool", "default": false, "description": "When true, the 'targetPrimPath' attribute is used, otherwise it will read the connection at the 'targetPrim' attribute" }, "targetPrimPath": { "type": "path", "description": "The destination prim. The target's rotation will be matched by the sourcePrim, used when 'useTargetPath' is true", "optional": true }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
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
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
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Quaternion.ogn
{ "GetMatrix4Quaternion": { "version": 1, "description": [ "Gets the rotation of the given matrix4d value which represents a linear transformation.", "Returns a quaternion" ], "uiName": "Get Rotation Quaternion", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The transformation matrix" } }, "outputs": { "quaternion": { "type": ["quatd[4]", "quatd[4][]"], "description": "quaternion representing the orientation of the matrix transformation" } }, "tests" : [ { "inputs:matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]}, "outputs:quaternion": {"type":"quatd[4]", "value": [0.38268481, 0, 0, 0.9238804]} }, { "inputs:matrix": {"type":"matrixd[4][]", "value": [[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1]] }, "outputs:quaternion": {"type":"quatd[4][]", "value": [[0.38268481, 0, 0, 0.9238804], [0.38268481, 0, 0, 0.9238804]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Translation.ogn
{ "SetMatrix4Translation": { "version": 1, "description": [ "Sets the translation of the given matrix4d value which represents a linear transformation.", "Does not modify the orientation (row 0-2) of the matrix." ], "uiName": "Set Translation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The matrix to be modified" }, "translation": { "type": ["vectord[3]", "vectord[3][]"], "uiName": "Translation", "description": [ "The translation that the matrix will apply" ] } }, "outputs": { "matrix": { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The updated matrix" } }, "tests" : [ { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]}, "translation": {"type": "vectord[3]", "value":[1, 2, 3]}}, "outputs:matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,1,0,0, 10,10,1,0, 1,2,3,1]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1.0,10,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1], [1.0,15,0,0, 0,1,0,0, 0,0,1,0, 100,0,0,1]] }, "translation": {"type": "vectord[3][]", "value": [[45, 10, 10], [3, 2, 1]]}}, "outputs:matrix": {"type":"matrixd[4][]", "value" : [ [1.0,10,0,0, 0,1,0,0, 0,0,1,0, 45,10,10,1], [1.0,15,0,0, 0,1,0,0, 0,0,1,0, 3,2,1,1]]} } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransform.ogn
{ "MakeTransform": { "version": 1, "description": "Make a transformation matrix that performs a translation, rotation (in euler angles), and scale in that order", "uiName": "Make Transformation Matrix from TRS", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "translation": { "type": "vectord[3]", "description": "the desired translation as a vector", "default": [0, 0, 0] }, "rotationXYZ": { "type": "vectord[3]", "description": "The desired orientation in euler angles (XYZ)", "default": [0, 0, 0] }, "scale": { "type": "vectord[3]", "description": "The desired scaling factor about the X, Y, and Z axis respectively", "default": [1, 1, 1] } }, "outputs": { "transform": { "type": "matrixd[4]", "description": "the resulting transformation matrix" } }, "tests": [ { "inputs:rotationXYZ": [0, 0, 0], "inputs:translation": [0, 0, 0], "outputs:transform": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }, { "inputs:rotationXYZ": [0, 0, 0], "inputs:translation": [1, 2, 3], "outputs:transform": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1] }, { "inputs:rotationXYZ": [20, 0, 30], "inputs:translation": [1, -2, 3], "outputs:transform": [ 8.66025404e-01, 5.00000000e-01, 4.16333634e-17, 0.00000000e+00, -4.69846310e-01, 8.13797681e-01, 3.42020143e-01, 0.00000000e+00, 1.71010072e-01,-2.96198133e-01, 9.39692621e-01, 0.00000000e+00, 1.00000000e+00,-2.00000000e+00, 3.00000000e+00, 1.00000000e+00] }, { "inputs:scale": [10, 5, 2], "outputs:transform": [10, 0, 0, 0, 0, 5, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1] }, { "inputs:translation": [1, -2, 3], "inputs:rotationXYZ": [20, 0, 30], "inputs:scale": [10, 5, 2], "outputs:transform": [ 8.66025404e+00, 5.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.34923155e+00, 4.06898841e+00, 1.71010072e+00, 0.00000000e+00, 3.42020140e-01,-5.92396270e-01, 1.87938524e+00, 0.00000000e+00, 1.00000000e+00,-2.00000000e+00, 3.00000000e+00, 1.00000000e+00] } ] } }
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() } } }
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() } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetMatrix4Rotation.ogn
{ "GetMatrix4Rotation": { "version": 1, "description": [ "Gets the rotation of the given matrix4d value which represents a linear transformation.", "Returns euler angles (XYZ)" ], "uiName": "Get Rotation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The transformation matrix" } }, "outputs": { "rotation": { "type": ["vectord[3]", "vectord[3][]"], "description": "vector representing the rotation component of the transformation (XYZ)" } }, "tests" : [ { "inputs:matrix": {"type":"matrixd[4]", "value":[1,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]}, "outputs:rotation": {"type":"vectord[3]", "value": [45, 0, 0]} }, { "inputs:matrix": {"type":"matrixd[4][]", "value": [[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1]] }, "outputs:rotation": {"type":"vectord[3][]", "value": [[45, 0, 0], [45, 0, 0]] } } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnRotateVector.ogn
{ "RotateVector": { "version": 1, "description": [ "Rotates a 3d direction vector by a specified rotation.", "Accepts 3x3 matrices, 4x4 matrices, euler angles (XYZ), or quaternions", "For 4x4 matrices, the transformation information in the matrix is ignored and the vector is treated as ", "a 4-component vector where the fourth component is zero. The result is then projected back to a 3-vector. ", "Supports mixed array inputs, eg a single quaternion and an array of vectors." ], "uiName": "Rotate Vector", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "rotation" : { "type": ["matrixd[4]", "matrixd[4][]", "matrixd[3]", "matrixd[3][]", "vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]", "quatd[4]", "quatd[4][]", "quatf[4]", "quatf[4][]", "quath[4]", "quath[4][]"], "uiName": "Rotation", "description": "The rotation to be applied" }, "vector": { "type": ["vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]"], "uiName": "Vector", "description": "The row vector(s) to be rotated" } }, "outputs": { "result": { "type": ["vectord[3]", "vectord[3][]", "vectorf[3]", "vectorf[3][]", "vectorh[3]", "vectorh[3][]"], "uiName": "Result", "description": "The transformed row vector(s)" } }, "tests" : [ { "inputs": { "rotation": {"type":"matrixd[4]", "value":[1,0,0,0, 0,1,0,0, 10,10,1,0, 50,0,0,1]}, "vector": {"type": "vectord[3]", "value":[1, 2, 3]}}, "outputs:result": {"type":"vectord[3]", "value":[31, 32, 3]} }, { "inputs": { "rotation": {"type":"matrixd[3]", "value":[1,0,0, 0,0,1, 0,-1,0]}, "vector": {"type": "vectorf[3]", "value":[0, 0, 1]}}, "outputs:result": {"type":"vectorf[3]", "value":[0, -1, 0]} }, { "inputs": { "rotation": {"type":"vectord[3]", "value":[90, 0, 0]}, "vector": {"type": "vectord[3]", "value":[0, 0, 1]}}, "outputs:result": {"type":"vectord[3]", "value":[0, -1, 0]} }, { "inputs": { "rotation": {"type":"quatf[4]", "value":[0.7071068, 0, 0, 0.7071068]}, "vector": {"type": "vectorf[3]", "value":[0, 0, 1]}}, "outputs:result": {"type":"vectorf[3]", "value":[0, -1, 0]} }, { "inputs": { "rotation": {"type":"vectorf[3][]", "value":[[0, 90, 0], [90, 0, 0], [90, 90, 0]]}, "vector": {"type": "vectorf[3]", "value": [0, 0, 1]}}, "outputs:result": {"type":"vectorf[3][]", "value" : [[1, 0, 0], [0, -1, 0], [0, -1, 0]]} }, { "inputs": { "rotation": {"type":"vectord[3]", "value":[90, 90, 0]}, "vector": {"type": "vectord[3][]", "value": [[0, 0, 1], [0, 1, 0], [1, 0, 0]]}}, "outputs:result": {"type":"vectord[3][]", "value" : [[0, -1, 0], [1, 0, 0], [0, 0, -1]]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnTranslateToTarget.ogn
{ "TranslateToTarget": { "version": 2, "description": [ "This node smoothly translates a prim object to a target prim object given a speed and easing factor. ", "At the end of the maneuver, the source prim will have the same translation as the target prim" ], "uiName": "Translate To Target", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "sourcePrim": { "type": "target", "description": "The source prim to be transformed", "optional": true }, "useSourcePath": { "type": "bool", "default": false, "description": "When true, the 'sourcePrimPath' attribute is used, otherwise it will read the connection at the 'sourcePrim' attribute" }, "sourcePrimPath": { "type": "path", "description": "The source prim to be transformed, used when 'useSourcePath' is true", "optional": true }, "targetPrim": { "type": "bundle", "description": "The destination prim. The target's translation will be matched by the sourcePrim", "optional": true }, "useTargetPath": { "type": "bool", "default": false, "description": "When true, the 'targetPrimPath' attribute is used, otherwise it will read the connection at the 'targetPrim' attribute" }, "targetPrimPath": { "type": "path", "description": "The destination prim. The target's translation will be matched by the sourcePrim, used when 'useTargetPath' is true", "optional": true }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
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() } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Rotation.ogn
{ "SetMatrix4Rotation": { "version": 1, "description": [ "Sets the rotation of the given matrix4d value which represents a linear transformation.", "Does not modify the translation (row 3) of the matrix." ], "uiName": "Set Rotation", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The matrix to be modified" }, "fixedRotationAxis": { "type": "token", "description": ["The axis of the given rotation"], "default": "Y", "metadata": { "allowedTokens": ["X", "Y", "Z"] } }, "rotationAngle": { "type": ["double", "double[]"], "uiName": "Rotation", "description": [ "The rotation in degrees that the matrix will apply about the given rotationAxis." ] } }, "outputs": { "matrix": { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The updated matrix" } }, "tests" : [ { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1]}, "fixedRotationAxis": "X", "rotationAngle": {"type": "double", "value":45}}, "outputs:matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1], [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 100,0,0,1]] }, "fixedRotationAxis": "X", "rotationAngle": {"type": "double[]", "value": [45, 45]}}, "outputs:matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1] ]} } ] } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMakeTransformLookAt.ogn
{ "MakeTransformLookAt": { "version": 1, "description": [ "Make a transformation matrix from eye, center world-space position and an up vector.", "Forward vector is negative Z direction computed from eye-center and normalized.", "Up is positive Y direction. Right is the positive X direction." ], "uiName": "Make Transformation Matrix Look At", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "eye": { "type": "vectord[3]", "description": "The desired look at position in world-space", "default": [1, 0, 0] }, "center": { "type": "vectord[3]", "description": "The desired center position in world-space", "default": [0, 0, 0] }, "up": { "type": "vectord[3]", "description": "The desired up vector", "default": [0, 1, 0] } }, "outputs": { "transform": { "type": "matrixd[4]", "description": "The resulting transformation matrix" } }, "tests": [ { "inputs:eye": [1, 0, 0], "inputs:center": [0, 0, 1], "inputs:up": [0, 1, 0], "outputs:transform": [ 0.70710678, 0, -0.70710678, 0, 0, 1, 0, 0, 0.70710678, 0, 0.70710678, 0, -0.70710678, 0, -0.70710678, 1 ] }, { "inputs:eye": [1, 0, 0], "inputs:center": [0, 0, 0], "inputs:up": [0, 1, 0], "outputs:transform": [ 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ] } ] } }
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
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnSetMatrix4Quaternion.ogn
{ "SetMatrix4Quaternion": { "version": 1, "description": [ "Sets the rotation of the given matrix4d value which represents a linear transformation.", "Does not modify the translation (row 3) of the matrix." ], "uiName": "Set Rotation Quaternion", "categories": ["math:operator"], "scheduling": ["threadsafe"], "inputs": { "matrix" : { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The matrix to be modified" }, "quaternion": { "type": ["quatd[4]", "quatd[4][]"], "uiName": "Quaternion", "description": [ "The quaternion the matrix will apply about the given rotationAxis." ] } }, "outputs": { "matrix": { "type": ["matrixd[4]", "matrixd[4][]"], "description": "The updated matrix" } }, "tests" : [ { "inputs": { "matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1]}, "quaternion": {"type": "quatd[4]", "value": [0.3826834, 0, 0, 0.9238795]}}, "outputs:matrix": {"type":"matrixd[4]", "value":[1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1]} }, { "inputs": { "matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 50,0,0,1], [1.0,0,0,0, 0,1,0,0, 0,0,1,0, 100,0,0,1]] }, "quaternion": {"type": "quatd[4][]", "value": [[0.3826834, 0, 0, 0.9238795], [0.3826834, 0, 0, 0.9238795]]}}, "outputs:matrix": {"type":"matrixd[4][]", "value":[ [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 50,0,0,1], [1.0,0,0,0, 0,0.70711,0.70711,0, 0,-0.70711,0.70711,0, 100,0,0,1] ]} } ] } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnGetPrimLocalToWorldTransform.ogn
{ "GetPrimLocalToWorldTransform": { "version": 2, "description": ["Given a path to a prim on the current USD stage, return the the transformation matrix.", " that transforms a vector from the local frame to the global frame " ], "uiName": "Get Prim Local to World Transform", "scheduling": ["usd-read", "threadsafe"], "categories": ["sceneGraph"], "inputs": { "primPath": { "type": "token", "description": "The path of the prim used as the local coordinate system when 'usePath' is true" }, "usePath": { "type": "bool", "default": true, "description": "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "prim": { "type": "target", "description": "The prim used as the local coordinate system when 'usePath' is false", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" } }, "outputs": { "localToWorldTransform": { "type": "matrixd[4]", "description": "the local to world transformation matrix for the prim" } } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnScaleToSize.ogn
{ "ScaleToSize": { "version": 2, "description": [ "Perform a smooth scaling maneuver, scaling a prim to a desired size tuple given a speed and easing factor" ], "uiName": "Scale To Size", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "prim": { "type": "target", "description": "The prim to be scaled", "optional": true }, "usePath": { "type": "bool", "default": false, "description": "When true, the 'primPath' attribute is used, otherwise it will read the connection at the 'prim' attribute", "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "primPath": { "type": "path", "description": "The source prim to be transformed, used when 'usePath' is true", "optional": true, "deprecated": "Use prim input with a GetPrimsAtPath node instead" }, "target": { "type": "vectord[3]", "description": "The desired local scale" }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/transformation/OgnMoveToTarget.ogn
{ "MoveToTarget": { "version": 2, "description": [ "This node smoothly translates, rotates, and scales a prim object to a target prim object given a speed and easing factor. ", "At the end of the maneuver, the source prim will have the translation, rotation, and scale of the target prim.\n", "Note: The Prim must have xform:orient in transform stack in order to interpolate rotations" ], "uiName": "Move To Target", "categories": ["sceneGraph"], "scheduling": ["usd-write", "threadsafe"], "inputs": { "execIn": { "type": "execution", "description": "The input execution", "uiName": "Execute In" }, "stop": { "type": "execution", "description": "Stops the maneuver", "uiName": "Stop" }, "sourcePrim": { "type": "target", "description": "The source prim to be transformed", "optional": true }, "useSourcePath": { "type": "bool", "default": false, "description": "When true, the 'sourcePrimPath' attribute is used, otherwise it will read the connection at the 'sourcePrim' attribute" }, "sourcePrimPath": { "type": "path", "description": "The source prim to be transformed, used when 'useSourcePath' is true", "optional": true }, "targetPrim": { "type": "target", "description": "The destination prim. The target's translation, rotation, and scale will be matched by the sourcePrim", "optional": true }, "useTargetPath": { "type": "bool", "default": false, "description": "When true, the 'targetPrimPath' attribute is used, otherwise it will read the connection at the 'targetPrim' attribute" }, "targetPrimPath": { "type": "path", "description": "The destination prim. The target's translation, rotation, and scale will be matched by the sourcePrim, used when 'useTargetPath' is true", "optional": true }, "speed": { "type": "double", "description": "The peak speed of approach (Units / Second)", "minimum": 0.0, "default": 1.0 }, "exponent": { "type": "float", "description": ["The blend exponent, which is the degree of the ease curve", " (1 = linear, 2 = quadratic, 3 = cubic, etc). "], "minimum": 1.0, "maximum": 10.0, "default": 2.0 } }, "outputs": { "finished": { "type": "execution", "description": "The output execution, sent one the maneuver is completed", "uiName": "Finished" } } } }
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() } } }
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNor.ogn
{ "BooleanNor": { "version": 2, "description": [ "Boolean NOR on two or more inputs.", "If the inputs are arrays, NOR operations will be performed pair-wise. The input sizes 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." ], "uiName": "Boolean NOR", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["bool", "bool[]"], "description": "Input A: bool or bool array." }, "b": { "type": ["bool", "bool[]"], "description": "Input B: bool or bool array." } }, "outputs": { "result": { "type": ["bool", "bool[]"], "description": "The result of the boolean NOR - an array of booleans if either input is an array, otherwise a boolean.", "uiName": "Result" } }, "tests": [ { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool", "value": true}, "outputs:result": false }, { "inputs:a": {"type": "bool[]", "value": [false, false, true, true]}, "inputs:b": {"type": "bool[]", "value": [false, true, false, true]}, "outputs:result": [true, false, false, false] }, { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool[]", "value": [false, true]}, "outputs:result": [true, false] }, { "inputs:a": {"type": "bool[]", "value": [false, true]}, "inputs:b": {"type": "bool", "value": false}, "outputs:result": [true, false] } ] } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNot.ogn
{ "BooleanNot": { "description": "Inverts a bool or bool array", "version": 1, "categories": ["math:condition"], "scheduling": ["threadsafe"], "uiName": "Boolean Not", "inputs": { "valueIn": { "type": ["bool", "bool[]"], "description": "bool or bool array to invert" } }, "outputs": { "valueOut": { "type": ["bool", "bool[]"], "description": "inverted bool or bool array" } }, "tests": [ { "inputs:valueIn": {"type": "bool", "value": true}, "outputs:valueOut": false }, { "inputs:valueIn": {"type": "bool", "value": false}, "outputs:valueOut": true }, { "inputs:valueIn": {"type": "bool[]", "value": [true, false, true, false]}, "outputs:valueOut": [false, true, false, true] } ] } }
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() } } }
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
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnNand.ogn
{ "BooleanNand": { "version": 2, "description": [ "Boolean NAND on two or more inputs.", "If the inputs are arrays, NAND operations will be performed pair-wise. The input sizes 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." ], "uiName": "Boolean NAND", "categories": ["math:condition"], "scheduling": ["threadsafe"], "inputs": { "a": { "type": ["bool", "bool[]"], "description": "Input A: bool or bool array." }, "b": { "type": ["bool", "bool[]"], "description": "Input B: bool or bool array." } }, "outputs": { "result": { "type": ["bool", "bool[]"], "description": "The result of the boolean NAND - an array of booleans if either input is an array, otherwise a boolean.", "uiName": "Result" } }, "tests": [ { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool", "value": true}, "outputs:result": true }, { "inputs:a": {"type": "bool[]", "value": [false, false, true, true]}, "inputs:b": {"type": "bool[]", "value": [false, true, false, true]}, "outputs:result": [true, true, true, false] }, { "inputs:a": {"type": "bool", "value": false}, "inputs:b": {"type": "bool[]", "value": [false, true]}, "outputs:result": [true, true] }, { "inputs:a": {"type": "bool[]", "value": [false, true]}, "inputs:b": {"type": "bool", "value": false}, "outputs:result": [true, true] } ] } }