file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/include/omni/core/Platform.h | // Copyright (c) 2020-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.
//
//! @file
//! @brief Helper macros to detect the current platform.
#pragma once
#include "../../carb/Defines.h"
//! Set to `1` if compiling a Windows build. Set to `0` otherwise. This symbol will
//! always be defined even when not on a Windows build. It can thus be used to pass
//! as parameters or in if-statements to modify behavior based on the platform.
#define OMNI_PLATFORM_WINDOWS CARB_PLATFORM_WINDOWS
//! Set to `1` if compiling a Linux build. Set to `0` otherwise. This symbol will
//! always be defined even when not on a Linux build. It can thus be used to pass
//! as parameters or in if-statements to modify behavior based on the platform.
#define OMNI_PLATFORM_LINUX CARB_PLATFORM_LINUX
//! Set to `1` if compiling a MacOS build. Set to `0` otherwise. This symbol will
//! always be defined even when not on a MacOS build. It can thus be used to pass
//! as parameters or in if-statements to modify behavior based on the platform.
#define OMNI_PLATFORM_MACOS CARB_PLATFORM_MACOS
/** @copydoc CARB_POSIX */
#define OMNI_POSIX CARB_POSIX
#if OMNI_PLATFORM_LINUX || OMNI_PLATFORM_MACOS || defined(DOXYGEN_BUILD)
//! Triggers a breakpoint. If no debugger is attached, the program terminates.
# define OMNI_BREAK_POINT() ::raise(SIGTRAP)
#elif OMNI_PLATFORM_WINDOWS
//! Triggers a breakpoint. If no debugger is attached, the program terminates.
# define OMNI_BREAK_POINT() ::__debugbreak()
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
| 1,906 | C | 44.404761 | 85 | 0.747639 |
omniverse-code/kit/include/omni/core/Interface.h | // 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.
//
//! @file
//! @brief Helper functions for collecting module information.
#pragma once
#include "../../carb/Interface.h"
//! Used to declare the interface description for an ONI object's API layer.
//!
//! @param[in] name The fully qualified name of the interface (as a string literal)
//! that contains this call. This call must be made from the class
//! scope for the interface's API layer.
//!
//! @note This does not need to be called directly if the `omni.bind` tool is being used
//! to generate the API layer for an interface. The `omni.bind` tool will insert
//! this call automatically.
#define OMNI_PLUGIN_INTERFACE(name) \
/** \
* Returns information about this interface. Auto-generated by OMNI_PLUGIN_INTERFACE(). \
* @returns The carb::InterfaceDesc struct with information about this interface. \
*/ \
static carb::InterfaceDesc getInterfaceDesc() \
{ \
return carb::InterfaceDesc{ name, { 1, 0 } }; \
}
| 2,069 | C | 61.727271 | 120 | 0.490092 |
omniverse-code/kit/include/omni/core/BuiltIn.h | // 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.
//
//! @file
//!
//! @brief Header file for Omni built-in interfaces.
#pragma once
#include "Api.h"
//! Used by omniGetBuiltInWithoutAcquire() to specify the desired interface.
//!
//! @warning Do not use omniGetBuiltInWithoutAcquire() directly. Instead use the referenced inline function for the
//! desired OmniBuiltIn enum value.
enum class OmniBuiltIn
{
//! Returns a reference to ITypeFactory. Use omniGetTypeFactoryWithoutAcquire() inline function.
eITypeFactory,
//! Returns a reference to ILog. Use omniGetLogWithoutAcquire() inline function.
eILog,
//! Returns a reference to IStructuredLog. Use omniGetStructuredLogWithoutAcquire() inline function.
eIStructuredLog,
};
//! Returns a built-in interface based on the given parameter.
//!
//! @warning This function should not be used. Instead, use the specific inline function for the desired OmniBuiltIn.
OMNI_API void* omniGetBuiltInWithoutAcquire(OmniBuiltIn);
| 1,383 | C | 36.405404 | 117 | 0.770065 |
omniverse-code/kit/include/omni/core/ResultError.h | // 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.
//
//! @file
//!
//! @brief Helpers related reporting errors from @ref omni::core::Result.
#pragma once
#include "../../carb/extras/Debugging.h"
#include "Assert.h"
#include "IObject.h"
#include <stdexcept>
#include <string>
namespace omni
{
namespace core
{
//! Given a @ref Result code, returns a human readable interpretation of the
//! code.
//!
//! A valid pointer is always returned. The returned pointer is valid for the
//! lifetime of the module from which the function was called.
inline const char* resultToString(Result result)
{
#ifndef DOXYGEN_BUILD
# define OMNI_RESULT_CODE_GEN_RESULT_TO_STRING_CASE(symbol_, snek_symbol_, message_) \
case kResult##symbol_: \
return message_;
#endif
switch (result)
{
OMNI_RESULT_CODE_LIST(OMNI_RESULT_CODE_GEN_RESULT_TO_STRING_CASE)
default:
return "unknown error";
}
#undef OMNI_RESULT_CODE_GEN_RESULT_TO_STRING_CASE
}
//! Exception object that encapsulates a @ref Result along with a customizable
//! message.
class ResultError : public std::exception
{
public:
//! Constructor.
ResultError(Result result) : m_result{ result }
{
}
//! Constructor with custom messages.
ResultError(Result result, std::string msg) : m_result{ result }, m_msg(std::move(msg))
{
}
//! Returns a human readable description of the error.
virtual const char* what() const noexcept override
{
if (m_msg.empty())
{
return resultToString(m_result);
}
else
{
return m_msg.c_str();
}
}
//! Return the result code that describes the error.
Result getResult() const noexcept
{
return m_result;
}
private:
Result m_result;
std::string m_msg;
};
} // namespace core
} // namespace omni
#if CARB_DEBUG && !defined(DOXYGEN_BUILD)
# define OMNI_RETURN_ERROR(e_) \
carb::extras::debuggerBreak(); \
return e_;
#else
//! Helper macro used to return a @ref omni::core::Result. When in debug mode
//! and attached to a debugger, this macro will cause a debugger break. Useful
//! for determining the origin of an error.
# define OMNI_RETURN_ERROR(e_) return e_
#endif
//! Helper macro to catch exceptions and return them as @ref omni::core::Result
//! codes. Useful when writing ABI code.
#define OMNI_CATCH_ABI_EXCEPTION() \
catch (const omni::core::ResultError& e_) \
{ \
OMNI_RETURN_ERROR(e_.getResult()); \
} \
catch (...) \
{ \
OMNI_RETURN_ERROR(omni::core::kResultFail); \
}
//! Helper macro to convert a @ref omni::core::Result to a @ref
//! omni::core::ResultError exception. Useful when authoring API code. Used
//! heavily by *omni.bind*.
#define OMNI_THROW_IF_FAILED(expr_) \
do \
{ \
omni::core::Result result_ = (expr_); \
if (OMNI_FAILED(result_)) \
{ \
throw omni::core::ResultError{ result_ }; \
} \
} while (0)
//! Helper macro to return an appropriate @ref omni::core::Result when the given
//! argument is @c nullptr. Useful when authoring ABI code.
//!
//! Note, use of this macro should be rare since *omni.bind* will check for @c
//! nullptr arguments in the generated API code.
#define OMNI_RETURN_IF_ARG_NULL(expr_) \
do \
{ \
if (nullptr == expr_) \
{ \
OMNI_RETURN_ERROR(omni::core::kResultInvalidArgument); \
} \
} while (0)
//! Helper macro to throw a @ref omni::core::ResultError exception if a function argument is
//! @c nullptr. Used heavily by *omni.bind*.
#define OMNI_THROW_IF_ARG_NULL(ptr_) \
do \
{ \
if (!ptr_) \
{ \
auto constexpr const msg_ = __FILE__ ":" CARB_STRINGIFY(__LINE__) /*": " CARB_PRETTY_FUNCTION*/ \
": argument '" #ptr_ "' must not be nullptr"; \
throw omni::core::ResultError(omni::core::kResultInvalidArgument, msg_); \
} \
} while (0)
| 7,587 | C | 48.594771 | 120 | 0.368657 |
omniverse-code/kit/include/omni/core/IWeakObject.h | // 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.
//
//! @file IWeakObject.h
//!
//! @brief Defines @ref omni::core::IWeakObject.
#pragma once
#include <carb/cpp/Atomic.h> // atomic_ref
#include <carb/detail/DeferredLoad.h>
#include <omni/core/Api.h> // OMNI_API
#include <omni/core/Assert.h>
#include <omni/core/IObject.h>
#include <limits>
namespace omni
{
namespace core
{
class IWeakObject;
class IWeakObject_abi;
class IWeakObjectControlBlock;
class IWeakObjectControlBlock_abi;
//! Control block to maintain weak and strong reference counts for an object.
//!
//! The @ref IWeakObject interface supports the notion of "weak pointers". Unlike "strong pointers" (e.g. @ref
//! ObjectPtr) weak pointers do not affect the pointee's reference count. While this sounds like a raw pointer (and
//! possibly a bad idea), the magic of a weak pointer is that if the pointee's reference count goes to zero, the weak
//! pointer updates its internal pointer to `nullptr`.
//!
//! @ref IWeakObjectControlBlock is an ABI-safe object used to store a pointer to both the object and the object's
//! reference count (i.e. the "strong count"). This object additionally stores a "weak count", which is a count of
//! objects pointing to the @ref IWeakObjectControlBlock.
//!
//! Both @ref WeakPtr and @ref IWeakObject affect the "weak count".
//!
//! Only @ref ObjectPtr will affect the "strong count".
//!
//! Direct usage of this object should be avoided. See @ref WeakPtr to learn how weak pointers are used in practice.
//!
//! **Advanced: Design Considerations**
//!
//! The design of ONI's weak pointers takes three main design considerations into account:
//!
//! - The user API should work similar to <a href="https://en.cppreference.com/w/cpp/memory/weak_ptr">std::weak_ptr</a>.
//!
//! - Enabling weak pointer support for an object should should not tank performance in hot code paths.
//!
//! - Weak pointers must be able to point to object's whose DLL has been unloaded from memory.
//!
//! Above, the final point has a strong affect on the implementation of weak pointers. In particular, this object (i.e.
//! @ref IWeakObjectControlBlock). Consider:
//!
//! - For a virtual function to be called successfully, the code implementing the virtual function must still be loaded.
//!
//! - An @ref IWeakObjectControlBlock may outlive the DLL that created the object to which it points.
//!
//! Rather than exposing a raw struct with the weak and strong counts (and associated inline code to manipulate them),
//! this interface is used to hide both the counts and the manipulation logic. However, this introduces virtual
//! functions, which could potentially be unloaded. To address the unloading problem, *carb.dll* provides
//! `omni::core::getOrCreateWeakObjectControlBlock()`. This C-ABI returns an implementation of @ref
//! IWeakObjectControlBlock implemented within *carb.dll*. This effectively avoids the DLL unloading problem, since
//! *carb.dll* is considered a core dependency that cannot be unloaded and therefore the virtual function
//! implementations for @ref IWeakObjectControlBlock will always be loaded.
class IWeakObjectControlBlock_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.core.IWeakObjectControlBlock")>
{
protected:
//! Returns a pointer to the object pointed to by this control block. May return `nullptr`.
//!
//! If the object pointed to by this control block has a strong reference count of zero, `nullptr` is returned.
//! Otherwise, @ref IObject::acquire() is called on the object before being returned.
//!
//! @thread_safety This method is thread safe.
virtual IObject* getObject_abi() noexcept = 0;
};
//! Interface defining a contract for objects which support "weak"/non-owning references.
//!
//! This interface works tightly with @ref WeakPtr to implement weak pointers. Users of weak pointers should focus on
//! @ref WeakPtr rather than this interface, as this interface is an implementation detail of the weak pointer ABI.
//!
//! Developers wishing to add weak pointer support to their objects must implement this interface, which is a
//! non-trivial task. A default implementation is provided in @ref ImplementsWeak.
class IWeakObject_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.core.IWeakObject")>
{
protected:
//! Returns a control block containing reference count information needed for the implementation of weak pointers.
//!
//! Users of weak pointers must never call this method. Rather, they should focus on exclusively using @ref
//! WeakPtr.
//!
//! Implementers of this method are encouraged to use the implementation found in @ref omni::core::ImplementsWeak.
//!
//! The returns pointer is never `nullptr`.
//!
//! The returned pointer will have @ref IObject::acquire() called on it before being returned.
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("not_null") IWeakObjectControlBlock* getWeakObjectControlBlock_abi() noexcept = 0;
};
} // namespace core
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/core/IWeakObject.gen.h>
namespace omni
{
namespace core
{
//! @copydoc omni::core::IWeakObjectControlBlock_abi
class IWeakObjectControlBlock : public omni::core::Generated<omni::core::IWeakObjectControlBlock_abi>
{
};
//! @copydoc omni::core::IWeakObject_abi
class IWeakObject : public omni::core::Generated<omni::core::IWeakObject_abi>
{
};
//! Weak pointer to ONI objects much like <a href="https://en.cppreference.com/w/cpp/memory/weak_ptr">std::weak_ptr</a>.
//!
//! The @ref IWeakObject interface support the notion of "weak pointers". Unlike "strong pointers" (e.g. @ref
//! ObjectPtr) weak pointers do not affect the pointee's reference count. While this sounds like a raw pointer (and
//! possibly a bad idea), the magic of a weak pointer is that if the pointee's reference count goes to zero, the weak
//! pointer updates its internal pointer to `nullptr`.
//!
//! Below are several practical use cases of weak pointers.
//!
//! **Breaking Reference Count Cycles**
//!
//! A reference count cycle happens when an object "A" contains an @ref ObjectPtr to object "B". At this same time,
//! object "B" holds an @ref ObjectPtr to object "A". Since each object increments the other's reference count, neither
//! is every destructed. To break this cycle, one of the objects can hold a @ref WeakPtr to the other object.
//!
//! **Pointing to Objects Whose Code May Be Unloaded From Memory**
//!
//! Carbonite supports the notion of plugins that can be loaded, unloaded, and reloaded at runtime. Often code from DLL
//! *X* holds an @ref ObjectPtr to code from DLL *Y*. If the user unloads *Y*, and DLL *X* still wishes to use *Y*, the
//! application is likely to crash when DLL *X* attempts to access the unloaded code.
//!
//! Instead of storing an @ref ObjectPtr, a @ref WeakPtr can be used instead. When DLL *X* wants to access the code in
//! DLL *Y*, @ref WeakPtr::getObjectPtr() is called, which converts the @ref WeakPtr into an @ref ObjectPtr. Here, if
//! the underlying object's strong reference count is zero, the returned @ref ObjectPtr will point to `nullptr`. DLL
//! *X* simply must check if the @ref ObjectPtr points to `nullptr` before using the pointer.
//!
//! Above, we make the assumption that DLL *Y* will either:
//!
//! - Refuse to unload as long as an object it produced has a non-zero strong reference count.
//!
//! - Will cleanup all external @ref ObjectPtr objects that hold a reference to an object produced by the DLL. One way
//! to implement this is for the plugin to allow callbacks to be registered with it that will be invoked when the DLL
//! is about to unloaded.
//!
//! **Usage**
//!
//! Weak pointers should be used as follows:
//!
#ifdef CARB_DOC_BUILD
//! @snippet "source/tests/test.unit/omni.core/TestWeakPtr.cpp" carb-docs-weakptr-example-use
#endif
template <typename T>
class WeakPtr
{
public:
//! Allow implicit conversion from nullptr to an WeakPtr.
WeakPtr(std::nullptr_t = nullptr) noexcept
{
}
//! Strong pointer to weak pointer conversion.
WeakPtr(const omni::core::ObjectPtr<T>& strong) noexcept
{
if (strong)
{
m_ref = strong->getWeakObjectControlBlock();
}
}
//! Raw pointer to weak pointer conversion.
WeakPtr(T* strong) noexcept
{
if (strong)
{
m_ref = strong->getWeakObjectControlBlock();
}
}
//! Copy constructor.
WeakPtr(const WeakPtr& other) noexcept = default;
//! Move constructor.
WeakPtr(WeakPtr&& other) noexcept = default;
~WeakPtr() noexcept = default;
//! Assignment operator.
//!
//! @thread_safety This method is not thread safe.
WeakPtr& operator=(const WeakPtr& other) noexcept = default;
//! Move assignment operator.
//!
//! @thread_safety This method is not thread safe.
WeakPtr& operator=(WeakPtr&& other) noexcept = default;
//! Returns an @ref omni::core::ObjectPtr to the object to which this weak pointer is pointing.
//!
//! The returned object will point to `nullptr` if there are no "strong" references to the underlying object.
//! Otherwise, if a non-`nullptr` pointer is returned, the object will live at least as long as the returned @ref
//! omni::core::ObjectPtr.
//!
//! To understand how/when to use weak pointers and this method, consult the class documentation for @ref
//! omni::core::WeakPtr.
//!
//! Equivalent to @ref WeakPtr::lock().
//!
//! @thread_safety This method is not thread safe.
omni::core::ObjectPtr<T> getObjectPtr() const noexcept
{
if (m_ref)
{
return m_ref->getObject().template as<T>();
}
return nullptr;
}
//! Returns an @ref omni::core::ObjectPtr to the object to which this weak pointer is pointing.
//!
//! The returned object will point to `nullptr` if there are no "strong" references to the underlying object.
//! Otherwise, if a non-`nullptr` pointer is returned, the object will live at least as long as the returned @ref
//! omni::core::ObjectPtr.
//!
//! To understand how/when to use weak pointers and this method, consult the class documentation for @ref
//! omni::core::WeakPtr.
//!
//! Equivalent to @ref WeakPtr::getObjectPtr().
//!
//! @thread_safety This method is not thread safe.
omni::core::ObjectPtr<T> lock() const noexcept
{
if (m_ref)
{
return m_ref->getObject().template as<T>();
}
return nullptr;
}
private:
ObjectPtr<IWeakObjectControlBlock> m_ref;
};
#ifndef DOXYGEN_BUILD
namespace detail
{
enum class WeakObjectControlBlockOp
{
eIncrementStrong = 0,
eDecrementStrong = 1,
eDecrementWeak = 2,
eGetStrongCount = 3, // for testing
eGetWeakCount = 4, // for testing
eHasControlBlock = 5, // for testing
};
} // namespace detail
#endif // DOXYGEN_BUILD
} // namespace core
} // namespace omni
// carb.dll C-ABI to hide the implementation details of a weak object's control block. see IWeakObject's class docs for
// motivation.
#ifndef DOXYGEN_BUILD
# if CARB_REQUIRE_LINKED
OMNI_API omni::core::IWeakObjectControlBlock* omniWeakObjectGetOrCreateControlBlock(omni::core::IObject* obj,
uintptr_t* refCountOrEncodedPtr);
OMNI_API uint32_t omniWeakObjectControlBlockOp(uintptr_t* refCountOrEncodedPtr, omni::core::WeakObjectControlBlockOp op);
# else
OMNI_API omni::core::IWeakObjectControlBlock* omniWeakObjectGetOrCreateControlBlock(omni::core::IObject* obj,
uintptr_t* refCountOrEncodedPtr)
CARB_ATTRIBUTE(weak);
OMNI_API uint32_t omniWeakObjectControlBlockOp(uintptr_t* refCountOrEncodedPtr,
omni::core::detail::WeakObjectControlBlockOp op) CARB_ATTRIBUTE(weak);
# endif
#endif // DOXYGEN_BUILD
namespace omni
{
namespace core
{
#ifndef DOXYGEN_BUILD
namespace detail
{
CARB_DETAIL_DEFINE_DEFERRED_LOAD(loadWeakObjectGetOrCreateControlBlock,
omniWeakObjectGetOrCreateControlBlock,
(omni::core::IWeakObjectControlBlock * (*)(omni::core::IObject*, uintptr_t*)));
//! Returns an implementation of @ref omni::core::IWeakObjectControlBlock provided by *carb.dll*.
//!
//! This method is an implementation detail and should not directly be called by users.
//!
//! The provided parameter, @p refCountOrPtr, is a pointer that points to a value. That value can represent either:
//!
//! - An object's reference count (i.e. strong count).
//!
//! - An **encoded** pointer to an @ref omni::core::IWeakObjectControlBlock object.
//!
//! The purpose of this function is to determine if the value is either a reference count or an encoded pointer to the
//! control block. If it is a reference count, an @ref omni::core::IWeakObjectControlBlock is allocated and the value
//! is updated to point to this new block. If the value is already an encoded pointer to a control block, the control
//! block's weak reference count is incremented (i.e. @ref omni::core::IObject::acquire() is called on the *control
//! block*).
//!
//! In both cases, a pointer to the control block is returned. It is up to the caller to ensure @ref
//! omni::core::IObject::release() is called on the returned pointer once the object is no longer in use.
//!
//! See @ref omni::core::IWeakObjectControlBlock for motivation as to why this function is needed.
//!
//! See @ref omni::core::WeakPtr and @ref omni::core::ImplementsWeak to understand how to use weak pointers and how to
//! enable weak pointer support in your objects.
//!
//! @thread_safety All operations on the given value are thread safe.
inline omni::core::IWeakObjectControlBlock* getOrCreateWeakObjectControlBlock(omni::core::IObject* obj,
uintptr_t* refCountOrEncodedPtr)
{
auto impl = detail::loadWeakObjectGetOrCreateControlBlock();
OMNI_ASSERT(impl);
return impl(obj, refCountOrEncodedPtr);
}
CARB_DETAIL_DEFINE_DEFERRED_LOAD(loadWeakObjectControlBlockOp,
omniWeakObjectControlBlockOp,
(uint32_t(*)(uintptr_t*, WeakObjectControlBlockOp)));
//! Increments the strong count of an object that is implemented with @ref omni::core::ImplementsWeak.
//!
//! This method is an implementation detail and should not directly be called by users.
//!
//! The provided parameter, @p refCountOrPtr, is a pointer that points to a value. That value can represent either:
//!
//! - An object's reference count (i.e. strong count).
//!
//! - An **encoded** pointer to an @ref omni::core::IWeakObjectControlBlock object.
//!
//! This method determines which of the above cases is true and atomically increments the strong count.
//!
//! See @ref omni::core::IWeakObjectControlBlock for motivation as to why this function is needed.
//!
//! See @ref omni::core::WeakPtr and @ref omni::core::ImplementsWeak to understand how to use weak pointers and how to
//! enable weak pointer support in your objects.
//!
//! @thread_safety All operations on the given value are thread safe.
inline uint32_t incrementWeakObjectStrongCount(uintptr_t* refCountOrEncodedPtr)
{
auto impl = detail::loadWeakObjectControlBlockOp();
OMNI_ASSERT(impl);
return impl(refCountOrEncodedPtr, WeakObjectControlBlockOp::eIncrementStrong);
}
//! Decrements the strong count of an object that is implemented with @ref omni::core::ImplementsWeak.
//!
//! This method is an implementation detail and should not directly be called by users.
//!
//! The provided parameter, @p refCountOrPtr, is a pointer that points to a value. That value can represent either:
//!
//! - An object's reference count (i.e. strong count).
//!
//! - An **encoded** pointer to an @ref omni::core::IWeakObjectControlBlock object.
//!
//! This method determines which of the above cases is true and atomically decrements the strong count.
//!
//! See @ref omni::core::IWeakObjectControlBlock for motivation as to why this function is needed.
//!
//! See @ref omni::core::WeakPtr and @ref omni::core::ImplementsWeak to understand how to use weak pointers and how to
//! enable weak pointer support in your objects.
//!
//! @thread_safety All operations on the given value are thread safe.
inline uint32_t decrementWeakObjectStrongCount(uintptr_t* refCountOrEncodedPtr)
{
auto impl = detail::loadWeakObjectControlBlockOp();
OMNI_ASSERT(impl);
return impl(refCountOrEncodedPtr, WeakObjectControlBlockOp::eDecrementStrong);
}
//! Decrements the weak count of an object that is implemented with @ref omni::core::ImplementsWeak.
//!
//! This method is an implementation detail and should not directly be called by users.
//!
//! The provided parameter, @p refCountOrPtr, is a pointer that points to a value. That value can represent either:
//!
//! - An object's reference count (i.e. strong count).
//!
//! - An **encoded** pointer to an @ref omni::core::IWeakObjectControlBlock object.
//!
//! This method determines which of the above cases is true and atomically decrements the weak count.
//!
//! See @ref omni::core::IWeakObjectControlBlock for motivation as to why this function is needed.
//!
//! See @ref omni::core::WeakPtr and @ref omni::core::ImplementsWeak to understand how to use weak pointers and how to
//! enable weak pointer support in your objects.
//!
//! @thread_safety All operations on the given value are thread safe.
inline void decrementWeakObjectWeakCount(uintptr_t* refCountOrEncodedPtr)
{
auto impl = detail::loadWeakObjectControlBlockOp();
OMNI_ASSERT(impl);
(void)impl(refCountOrEncodedPtr, WeakObjectControlBlockOp::eDecrementWeak);
}
//! Returns the strong count of an object that is implemented with @ref omni::core::ImplementsWeak.
//!
//! This method is an implementation detail and should not directly be called by users.
//!
//! The provided parameter, @p refCountOrPtr, is a pointer that points to a value. That value can represent either:
//!
//! - An object's reference count (i.e. strong count).
//!
//! - An **encoded** pointer to an @ref omni::core::IWeakObjectControlBlock object.
//!
//! This method determines which of the above cases is true and returns the strong count.
//!
//! See @ref omni::core::IWeakObjectControlBlock for motivation as to why this function is needed.
//!
//! See @ref omni::core::WeakPtr and @ref omni::core::ImplementsWeak to understand how to use weak pointers and how to
//! enable weak pointer support in your objects.
//!
//! @thread_safety All operations on the given value are thread safe.
inline uint32_t getWeakObjectStrongCount(uintptr_t* refCountOrEncodedPtr)
{
auto impl = detail::loadWeakObjectControlBlockOp();
OMNI_ASSERT(impl);
return impl(refCountOrEncodedPtr, WeakObjectControlBlockOp::eGetStrongCount);
}
//! Returns the weak count of an object that is implemented with @ref omni::core::ImplementsWeak.
//!
//! This method is an implementation detail and should not directly be called by users.
//!
//! The provided parameter, @p refCountOrPtr, is a pointer that points to a value. That value can represent either:
//!
//! - An object's reference count (i.e. strong count).
//!
//! - An **encoded** pointer to an @ref omni::core::IWeakObjectControlBlock object.
//!
//! This method determines which of the above cases is true and returns the weak count.
//!
//! See @ref omni::core::IWeakObjectControlBlock for motivation as to why this function is needed.
//!
//! See @ref omni::core::WeakPtr and @ref omni::core::ImplementsWeak to understand how to use weak pointers and how to
//! enable weak pointer support in your objects.
//!
//! @thread_safety All operations on the given value are thread safe.
inline uint32_t getWeakObjectWeakCount(uintptr_t* refCountOrEncodedPtr)
{
auto impl = detail::loadWeakObjectControlBlockOp();
OMNI_ASSERT(impl);
return impl(refCountOrEncodedPtr, WeakObjectControlBlockOp::eGetWeakCount);
}
//! Returns the `true` on object that is implemented with @ref omni::core::ImplementsWeak has had a weak pointer
//! attached to it.
//!
//! This method is an implementation detail and should not directly be called by users.
//!
//! The provided parameter, @p refCountOrPtr, is a pointer that points to a value. That value can represent either:
//!
//! - An object's reference count (i.e. strong count).
//!
//! - An **encoded** pointer to an @ref omni::core::IWeakObjectControlBlock object.
//!
//! This method determines which of the above cases is true and return true if the value points to a control block.
//!
//! See @ref omni::core::IWeakObjectControlBlock for motivation as to why this function is needed.
//!
//! See @ref omni::core::WeakPtr and @ref omni::core::ImplementsWeak to understand how to use weak pointers and how to
//! enable weak pointer support in your objects.
//!
//! @thread_safety All operations on the given value are thread safe.
inline bool hasWeakObjectControlBlock(uintptr_t* refCountOrEncodedPtr)
{
auto impl = detail::loadWeakObjectControlBlockOp();
OMNI_ASSERT(impl);
return (0 != impl(refCountOrEncodedPtr, WeakObjectControlBlockOp::eHasControlBlock));
}
} // namespace detail
#endif // DOXYGEN_BUILD
//! Helper template for implementing one or more interfaces that support weak pointers.
//!
//! This class has similar functionality as @ref Implements but adds support for @ref IWeakObject.
//!
//! As an example, consider the following interface:
//!
#ifdef CARB_DOC_BUILD
//! @snippet "source/tests/test.unit/omni.core/TestWeakPtr.cpp" carb-docs-weakptr-example-interface
#endif
//!
//! Note that the interface inherits from @ref IWeakObject rather than @ref IObject.
//!
//! To implement the interface above, @ref ImplementsWeak (i.e. this class) can be used as follows:
//!
#ifdef CARB_DOC_BUILD
//! @snippet "source/tests/test.unit/omni.core/TestWeakPtr.cpp" carb-docs-weakptr-example-class
#endif
template <typename T, typename... Rest>
struct ImplementsWeak : public ImplementsCast<T, Rest...>
{
public:
//! @copydoc omni::core::IObject::acquire.
inline void acquire() noexcept
{
// note: this implementation is needed to disambiguate which `cast` to call when using multiple inheritance. it
// has zero-overhead.
static_cast<T*>(this)->acquire();
}
//! @copydoc omni::core::IObject::release.
inline void release() noexcept
{
// note: this implementation is needed to disambiguate which `cast` to call when using multiple inheritance. it
// has zero-overhead.
static_cast<T*>(this)->release();
}
//! @copydoc omni::core::IWeakObject::getWeakObjectControlBlock_abi.
inline ObjectPtr<IWeakObjectControlBlock> getWeakObjectControlBlock() noexcept
{
// note: this implementation is needed to disambiguate which `getWeakObjectControlBlock` to call when using
// multiple inheritance. it has zero-overhead.
return static_cast<T*>(this)->getWeakObjectControlBlock();
}
protected:
//! Destructor
virtual ~ImplementsWeak() noexcept
{
// decrementWeakObjectWeakCount() will no-op if a control block has not been created
omni::core::detail::decrementWeakObjectWeakCount(&m_refCountOrPtr);
}
//! @copydoc omni::core::IObject::acquire.
virtual void acquire_abi() noexcept override
{
omni::core::detail::incrementWeakObjectStrongCount(&m_refCountOrPtr);
}
//! @copydoc omni::core::IObject::release.
virtual void release_abi() noexcept override
{
if (0 == omni::core::detail::decrementWeakObjectStrongCount(&m_refCountOrPtr))
{
delete this;
}
}
//! @copydoc omni::core::IWeakObject::getWeakObjectControlBlock
virtual IWeakObjectControlBlock* getWeakObjectControlBlock_abi() noexcept override
{
return omni::core::detail::getOrCreateWeakObjectControlBlock(static_cast<T*>(this), &m_refCountOrPtr);
}
#ifndef DOXYGEN_BUILD
//! Return the strong reference count. Should only be used for testing and debugging.
uint32_t _getStrongCount() noexcept
{
return omni::core::detail::getWeakObjectStrongCount(&m_refCountOrPtr);
}
//! Return `true` if a weak object control block has been created for this object. Should only be used for testing
//! and debugging.
bool _hasWeakObjectControlBlock() noexcept
{
return omni::core::detail::hasWeakObjectControlBlock(&m_refCountOrPtr);
}
#endif
private:
// by default, this value stores the reference count of the object.
//
// however, when getWeakObjectControlBlock_abi() is called, this memory is repurposed to store a pointer to an
// IWeakObjectControlBlock. it's the IWeakObjectControlBlock that will store both a strong and weak reference count
// for this object.
//
// the pointer to the IWeakObjectControlBlock count is "encoded" so that we can easily determine if this memory is a
// reference count or a pointer to an IWeakObjectControlBlock.
//
// the encoding of this pointer is an implementation detail and not exposed to the user.
//
// this value should be treated as opaque.
uintptr_t m_refCountOrPtr{ 1 };
};
} // namespace core
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/core/IWeakObject.gen.h>
| 26,155 | C | 41.25525 | 121 | 0.709195 |
omniverse-code/kit/include/omni/core/VariadicMacroUtils.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
// this macro can be used to count the number of arguments, returning a user defined value for each count.
//
// some examples as to what you can do with this:
//
// - return the argument count
//
// - return 1 if the count is even, and 0 if the count is odd.
//
// - return "one", "two", "three", etc. based on the argument count
//
// note, if the argument list is empty, this macro counts the argument list as 1. in short, this macro cannot detect an
// empty list.
//
// to call the macro, pass the argument list along with a reversed list of a mapping from the count to the desired
// value. for example, to return the argument count:
//
// #define COUNT(...)
// OMNI_VA_GET_ARG_64(__VA_ARGS__, 63, 62, 61, 60,
// 59, 58, 57, 56, 55, 54, 53, 52, 51, 50,
// 49, 48, 47, 46, 45, 44, 43, 42, 41, 40,
// 39, 38, 37, 36, 35, 34, 33, 32, 31, 30,
// 29, 28, 27, 26, 25, 24, 23, 22, 21, 20,
// 19, 18, 17, 16, 15, 14, 13, 12, 11, 10,
// 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define OMNI_VA_GET_ARG_64(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \
_21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, \
_39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, \
_57, _58, _59, _60, _61, _62, _63, N, ...) \
N
// needed in by MSVC's preprocessor to evaluate __VA_ARGS__. harmless on other compilers.
#define OMNI_VA_EXPAND(x_) x_
// returns 1 if the argument list has fewer than two arguments (i.e. 1 or empty). otherwise returns 0.
#define OMNI_VA_IS_FEWER_THAN_TWO(...) \
OMNI_VA_EXPAND(OMNI_VA_GET_ARG_64(__VA_ARGS__, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 /* one or 0 */, 1))
// counts the number of given arguments. due to the design of the pre-processor, if 0 arguments are given, a count of 1
// is incorrectly returned.
#define OMNI_VA_COUNT(...) \
OMNI_VA_EXPAND(OMNI_VA_GET_ARG_64(__VA_ARGS__, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, \
46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, \
26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 20, 9, 8, 7, 6, \
5, 4, 3, 2, 1, 0))
// returns the first argument. if the argument list is empty, nothing is returned.
//
// ("a", "b", "c") -> "a"
#define OMNI_VA_FIRST(...) OMNI_VA_FIRST_(OMNI_VA_IS_FEWER_THAN_TWO(__VA_ARGS__), __VA_ARGS__)
#define OMNI_VA_FIRST_(is_fewer_than_two_, ...) OMNI_VA_FIRST__(is_fewer_than_two_, __VA_ARGS__)
#define OMNI_VA_FIRST__(is_fewer_than_two_, ...) OMNI_VA_FIRST__##is_fewer_than_two_(__VA_ARGS__)
#define OMNI_VA_FIRST__0(...) OMNI_VA_EXPAND(OMNI_VA_FIRST___(__VA_ARGS__))
#define OMNI_VA_FIRST__1(...) __VA_ARGS__
#define OMNI_VA_FIRST___(first, ...) first
// removes the first argument from the argument list, returning the remaining arguments.
//
// if any arguments are returned a comma is prepended to the list.
//
// if no arguments are returned, no comma is added.
//
// ("a", "b", "c") -> , "b", "c"
// () ->
#define OMNI_VA_COMMA_WITHOUT_FIRST(...) \
OMNI_VA_COMMA_WITHOUT_FIRST_(OMNI_VA_IS_FEWER_THAN_TWO(__VA_ARGS__), __VA_ARGS__)
#define OMNI_VA_COMMA_WITHOUT_FIRST_(is_fewer_than_two_, ...) \
OMNI_VA_COMMA_WITHOUT_FIRST__(is_fewer_than_two_, __VA_ARGS__)
#define OMNI_VA_COMMA_WITHOUT_FIRST__(is_fewer_than_two_, ...) \
OMNI_VA_COMMA_WITHOUT_FIRST__##is_fewer_than_two_(__VA_ARGS__)
#define OMNI_VA_COMMA_WITHOUT_FIRST__0(...) OMNI_VA_EXPAND(OMNI_VA_COMMA_WITHOUT_FIRST___(__VA_ARGS__))
#define OMNI_VA_COMMA_WITHOUT_FIRST__1(...)
#define OMNI_VA_COMMA_WITHOUT_FIRST___(first, ...) , __VA_ARGS__
// returns the first argument from the argument list. if the given list is empty, an empty string is returned.
//
// ("a", "b", "c") -> "a"
// () -> ""
#define OMNI_VA_FIRST_OR_EMPTY_STRING(...) \
OMNI_VA_FIRST_OR_EMPTY_STRING_(OMNI_VA_IS_FEWER_THAN_TWO(__VA_ARGS__), __VA_ARGS__)
#define OMNI_VA_FIRST_OR_EMPTY_STRING_(is_fewer_than_two_, ...) \
OMNI_VA_FIRST_OR_EMPTY_STRING__(is_fewer_than_two_, __VA_ARGS__)
#define OMNI_VA_FIRST_OR_EMPTY_STRING__(is_fewer_than_two_, ...) \
OMNI_VA_FIRST_OR_EMPTY_STRING__##is_fewer_than_two_(__VA_ARGS__)
#define OMNI_VA_FIRST_OR_EMPTY_STRING__0(...) OMNI_VA_EXPAND(OMNI_VA_FIRST_OR_EMPTY_STRING___(__VA_ARGS__))
#define OMNI_VA_FIRST_OR_EMPTY_STRING__1(...) " " __VA_ARGS__
#define OMNI_VA_FIRST_OR_EMPTY_STRING___(first, ...) first
| 5,949 | C | 58.499999 | 120 | 0.518911 |
omniverse-code/kit/include/omni/core/OmniAttr.h | // Copyright (c) 2020-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.
//
//! @file
//!
//! @brief Helpers related to define interfaces and interface attributes.
#pragma once
#include <type_traits>
#ifdef OMNI_BIND
// OMNI_ATTR("enum,prefix=eState") --> __attribute__((annotate("omni_attr:enum,prefix=eState")))
# define OMNI_ATTR(attrs_) __attribute__((annotate("omni_attr:" attrs_)))
#else
//! Provides additional contextual information to the 'omni.bind' code generation tool. This information is used to
//! generated efficient bindings to the interface.
//!
//! For example, if an ABI method accepts a const pointer than cannot be null, the method will be bound to an API layer
//! method that accepts a C++ reference.
//!
//! See @rstdoc{../../../../docs/omni.bind/omni.bind} for an overview of `OMNI_ATTR` and the <i>omni.bind</i> tool.
# define OMNI_ATTR(p0_)
#endif
//! Macro to access generated API of an interface.
#define OMNI_GENERATED_API(iface_) omni::core::Generated<iface_##_abi>
//! Used in cases when defined interface provides an overload for a function from generated API.
//!
//! In those situations generated API becomes unavailable and member function from generated API
//! has to be introduced explicitly:
//!
//! @code{.cpp}
//! OMNI_DEFINE_INTERFACE_API(omni::windowing::IWindow)
//! {
//! public:
//! OMNI_USE_FROM_GENERATED_API(omni::windowing::IWindow, overloadedFunction)
//!
//! void overloadedFunction(int overloadedArg)
//! {
//! }
//! };
//! @endcode
//!
#define OMNI_USE_FROM_GENERATED_API(iface_, func_) using OMNI_GENERATED_API(iface_)::func_;
//! Used to forward declare an interface.
//!
//! The given class name must not include namespaces. Rather, this macro must be invoked within the proper namespace.
//!
//! When _defining_ an interface in a header file, either @ref OMNI_DECLARE_INTERFACE() or @ref
//! OMNI_DEFINE_INTERFACE_API() should be invoked.
#define OMNI_DECLARE_INTERFACE(iface_) \
class iface_##_abi; \
/** \
Typedef for API wrapper of iface_##_abi \
@see omni::core::Api, iface_##_abi \
*/ \
using iface_ = omni::core::Api<iface_##_abi>;
//! Used to extend the <i>omni.bind</i> generated API layer.
//!
//! This macro handles the `class` line of a C++ class. Use this macro in the following manner:
//!
//! @code{.cpp}
//! OMNI_DEFINE_INTERFACE_API(omni::windowing::IWindow)
//! {
//! public:
//! inline ObjectPtr<input::IKeyboardOnEventConsumer> getConsumer() noexcept
//! { /* ... */ }
//! };
//! @endcode
#define OMNI_DEFINE_INTERFACE_API(iface_) \
/** \
* Implements the generated API layer for iface_ \
*/ \
template <> \
class omni::core::Api<iface_##_abi> : public OMNI_GENERATED_API(iface_)
//! @def OMNI_BIND_INCLUDE_INTERFACE_DECL
//!
//! By defining this macro before including a header generated by *omni.bind*, only the declaration of any generated
//! boiler-plate code is included.
//!
//! @see OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! @def OMNI_BIND_INCLUDE_INTERFACE_IMPL
//!
//! By defining this macro before including a header generated by *omni.bind*, only the implementations of any
//! generated boiler-plate code is included.
//!
//! @see OMNI_BIND_INCLUDE_INTERFACE_DECL
namespace carb
{
template <typename T>
class ObjectPtr; // forward declaration needed by ObjectParam
}
namespace omni
{
namespace core
{
//! Templated class to store generated code from the <i>omni.bind</i> code generator.
//!
//! See @ref omni::core::Api for how this class is used.
template <typename T>
class Generated : public T
{
};
//! The API layer of an Omniverse interface.
//!
//! This template is the main construct used by users to interact with Omniverse interfaces.
//!
//! This template inherits from the @ref omni::core::Generated template which in turn inherits from another @ref
//! omni::core::Api template instantiation. Eventually, we'll find that the root base class is @ref IObject_abi. For
//! example, @ref omni::log::ILog has the following inheritance chain:
//!
//! Api<omni::log::ILog_abi> // interface author bindings for ILog
//! Generated<omni::log::ILog_abi> // omni.bind (generated) bindings for ILog
//! omni::log::ILog_abi // raw ABI (defined by author)
//! Api<omni::core::IObject_abi> // hand-written bindings to IObject
//! Generated<omni::core::IObject_abi> // omni.bind (generated) bindings for IObject
//! omni::core::IObject_abi // raw ABI
//!
//! where:
//!
//! @code{.cpp}
//! namespace omni::log
//! {
//! using ILog = Api<omni::log::ILog_abi>;
//! }
//! @endcode
//!
//! Each point in the inheritance chain serves a different component in the system:
//!
//! - The `_abi` layer defines the raw ABI. The `_abi` object's methods define how the interface can be used across DLL
//! boundaries. Defining a stable ABI is the primary goal of Omniverse interfaces. In practice, methods in the ABI
//! have many restrictions. See @oni_overview for details.
//!
//! - The @ref Generated template gives the <i>omni.bind</i> code generation tool a place to create a template
//! specialization that defines boiler-plate methods that make using the ABI easier. Again, see @oni_overview for
//! details.
//!
//! - The @ref Api template gives the interface author a place to create wrappers (via specialization) to make using the
//! interface easier. Since the @ref Api layer inherits from the @ref Generated layer, specializing the the @ref Api
//! layer allows interface authors to augment the boiler-plate code generated by <i>omni.bind</i>. Interfaces authors
//! should use the @ref OMNI_DEFINE_INTERFACE_API() macro to specialize the @ref Api layer.
//!
//! Expected usage is:
//!
//! @code{.cpp}
//! // forward declare the interface. this sets up the Api<> typedef.
//! OMNI_DECLARE_INTERFACE(foo::IMyInteface);
//!
//! namespace foo {
//! class IMyInterface_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("foo.IMyInterface")>
//! {
//! protected:
//! void myMethod_abi(uint32_t x) noexcept = 0;
//! // ...
//! };
//! } // namespace foo
//!
//! // include code generated by the omni.bind tool.
//! // this include should be outside of any namespace {} blocks
//! #include "IMyInterface.gen.h"
//!
//! // use OMNI_DEFINE_INTERFACE_API() to add hand-written API wrappers
//! // this macro should be invoked outside of any namespace {} blocks
//! OMNI_DEFINE_INTERFACE(foo::IMyInterface_abi)
//! {
//! void myReallyCoolMethod() { /* inline code here */ }
//! // ...
//! };
//! @endcode
template <typename T>
class Api : public Generated<T>
{
};
template <typename T>
class ObjectPtr; // forward declaration needed by ObjectParam
//! Helper object used by <i>omni.bind</i> to ease, at zero cost, the acceptance of raw and smart pointers to methods
//! that wish to accept a raw pointer.
//!
//! This object should never be used outside of <i>omni.bind</i>.
template <typename T>
class ObjectParam
{
public:
//! Accept a smart pointer of different type.
template <typename Y>
ObjectParam(const ObjectPtr<Y>& o, typename std::enable_if_t<std::is_base_of<T, Y>::value>* = nullptr) noexcept
: m_ptr{ o.get() }
{
}
//! Accept a Carbonite smart pointer of different type.
template <typename Y>
ObjectParam(const carb::ObjectPtr<Y>& o) noexcept : m_ptr{ o.get() }
{
}
//! Accept a raw pointer.
ObjectParam(T* o) noexcept : m_ptr{ o }
{
}
//! Arrow operator.
T* operator->() const noexcept
{
return m_ptr;
}
//! Access raw pointer.
T* get() const noexcept
{
return m_ptr;
}
//! Returns true if the wrapped pointer is not `nullptr`.
explicit operator bool() const noexcept
{
return m_ptr != nullptr;
}
private:
T* m_ptr;
};
} // namespace core
} // namespace omni
| 9,454 | C | 36.971887 | 120 | 0.590438 |
omniverse-code/kit/include/omni/core/ModuleExports.h | // Copyright (c) 2020-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.
//
//! @file
//!
//! @brief Helpers for defining a plugin's @ref omni::core::ModuleExports table.
#pragma once
#include "IObject.h"
#include "../../carb/Interface.h"
#include <algorithm>
#include <cstring>
#include <type_traits>
namespace omni
{
namespace log
{
class ILog;
}
namespace structuredlog
{
class IStructuredLog;
//! Registration function to install a schema with the structured logging system.
//!
//! @param[in] log A pointer to the global singleton structured logging system to install
//! the schema in.
//! @returns `true` if the schema is successfully installed or was already installed.
//! @returns `false` if the schema could not be installed. This may be caused by a lack of
//! available memory, or too many events have been registered in the system.
using SchemaAddFn = bool (*)(IStructuredLog* log);
} // namespace structuredlog
namespace core
{
//! Unique type name for @ref omni::core::ModuleExportEntryOnModuleLoad.
constexpr const char* const kModuleExportEntryTypeOnModuleLoad = "omniOnModuleLoad";
//! Unique type name for @ref omni::core::ModuleExportEntryOnModuleStarted.
constexpr const char* const kModuleExportEntryTypeOnModuleStarted = "omniOnModuleStarted";
//! Unique type name for @ref omni::core::ModuleExportEntryOnModuleCanUnload.
constexpr const char* const kModuleExportEntryTypeOnModuleCanUnload = "omniOnModuleCanUnload";
//! Unique type name for @ref omni::core::ModuleExportEntryOnModuleUnload.
constexpr const char* const kModuleExportEntryTypeOnModuleUnload = "omniOnModuleUnload";
//! Unique type name for @ref omni::core::ModuleExportEntryITypeFactory.
constexpr const char* const kModuleExportEntryTypeITypeFactory = "omniITypeFactory";
//! Unique type name for @ref omni::core::ModuleExportEntryILog.
constexpr const char* const kModuleExportEntryTypeILog = "omniILog";
//! Unique type name for @ref omni::core::ModuleExportEntryLogChannel.
constexpr const char* const kModuleExportEntryTypeLogChannel = "omniLogChannel";
//! Unique type name for @ref omni::core::ModuleExportEntryIStructuredLog.
constexpr const char* const kModuleExportEntryTypeIStructuredLog = "omniIStructuredLog";
//! Unique type name for @ref omni::core::ModuleExportEntrySchema.
constexpr const char* const kModuleExportEntryTypeSchema = "omniSchema";
//! Unique type name for @ref omni::core::ModuleExportEntryCarbClientName.
constexpr const char* const kModuleExportEntryTypeCarbClientName = "carbClientName";
//! Unique type name for @ref omni::core::ModuleExportEntryCarbFramework.
constexpr const char* const kModuleExportEntryTypeCarbFramework = "carbFramework";
//! Unique type name for @ref omni::core::ModuleExportEntryCarbIAssert.
constexpr const char* const kModuleExportEntryTypeCarbIAssert = "carbIAssert";
//! Unique type name for @ref omni::core::ModuleExportEntryCarbILogging.
constexpr const char* const kModuleExportEntryTypeCarbILogging = "carbILogging";
//! Unique type name for @ref omni::core::ModuleExportEntryCarbIProfiler.
constexpr const char* const kModuleExportEntryTypeCarbIProfiler = "carbIProfiler";
//! Unique type name for @ref omni::core::ModuleExportEntryCarbIL10n.
constexpr const char* const kModuleExportEntryTypeCarbIL10n = "carbIL10n";
//! Unique type name for @ref omni::core::ModuleExportEntryGetModuleDependencies.
constexpr const char* const kModuleExportEntryTypeGetModuleDependencies = "omniGetModuleDependecies";
//! Per @ref omni::core::ModuleExportEntry flags.
using ModuleExportEntryFlag = uint32_t;
constexpr ModuleExportEntryFlag fModuleExportEntryFlagNone = 0; //!< No flags.
//! Fail module load if entry could not be populated.
constexpr ModuleExportEntryFlag fModuleExportEntryFlagRequired = (1 << 0);
//! Helper macro for defining an entry (i.e. @ref omni::core::ModuleExportEntry) in the export table (i.e. @ref
//! omni::core::ModuleExports).
//!
//! Implementation detail. Not intended for use outside of omni/core/ModuleExports.h.
#define OMNI_MODULE_EXPORT_ENTRY_BEGIN(name_) \
struct name_ \
{ \
/** <b>Unique</b> type name describing the entry. */ \
const char* type; \
/** Special flags for the entry (ex: required). */ \
ModuleExportEntryFlag flags; \
/** Size of the entry in bytes (including the header). */ \
uint32_t byteCount; \
\
/** Constructor */ \
name_(const char* t, ModuleExportEntryFlag f) \
{ \
type = t; \
flags = f; \
byteCount = sizeof(*this); \
};
//! Helper macro for defining an entry in the export table.
//!
//! Implementation detail. Not intended for use outside of omni/core/ModuleExports.h.
#define OMNI_MODULE_EXPORT_ENTRY_END(name_) \
} \
; \
CARB_ASSERT_INTEROP_SAFE(name_);
//! Define an entry in @ref omni::core::ModuleExports.
//!
//! Use @ref OMNI_MODULE_EXPORT_ENTRY_BEGIN and @ref OMNI_MODULE_EXPORT_ENTRY_END to define an new entry type.
//!
//! Each entry type must have a unique @p type (which is a `string`).
//!
//! @ref OMNI_MODULE_EXPORT_ENTRY_BEGIN defines the header of the entry. Note, the use of macros vs. inheritance is to
//! ensure the resulting entry is @rstref{ABI-safe <abi-compatibility>} (e.g. passes @ref CARB_ASSERT_INTEROP_SAFE)
//! since these entries will be passed across DLL boundaries.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntry)
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntry)
static_assert(sizeof(ModuleExportEntry) == (8 + sizeof(void*)), "unexpected ModuleExportEntry size");
struct InterfaceImplementation;
//! Called to load interface implementation registration information.
//!
//! This function is called @ref omni::core::ModuleGetExportsFn.
//!
//! This function will never be called concurrently with any other function in the module.
//!
//! The module author can assume that the module's static initialization has occurred by the time this function is
//! called.
//!
//! The author should perform any implementation initialization in this function and return @ref kResultSuccess. If
//! initialization fails, an error message should be logged (via @ref OMNI_LOG_ERROR) and an appropriate error code
//! should be returned.
//!
//! Due to potential race conditions, the module will not have access to the @ref omni::core::ITypeFactory during this
//! call but will have access to the logging and profiling systems. If @ref omni::core::ITypeFactory access is needed
//! during initialization, lazy initialization is suggested (i.e. perform initialization during the first call to
//! `createFn`).
//!
//! The memory pointed to by @p *out must remain valid until the next call to this function.
using OnModuleLoadFn = Result(const InterfaceImplementation** out, uint32_t* outCount);
//! @ref omni::core::ModuleExports entry to register a function to advertise the interface implementations available in
//! the plugin.
//!
//! Use the helper @ref OMNI_MODULE_ON_MODULE_LOAD to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryOnModuleLoad)
OnModuleLoadFn* onModuleLoad; //!< Module's unload function.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryOnModuleLoad)
//! Registers the plugin's function who is responsible for advertising the available interface implementations in the
//! plugin.
//!
//! @param exp_ The @ref omni::core::ModuleExports table in which the entry should be added.
//!
//! @param fn_ The plugin's @ref omni::core::OnModuleLoadFn who is responsible for advertising the plugin's interface
//! implementations.
#define OMNI_MODULE_ON_MODULE_LOAD(exp_, fn_) OMNI_RETURN_IF_FAILED(exp_->addOnModuleLoad(fn_))
//! This function will be called after the module is fully registered. It is called after @ref
//! omni::core::OnModuleLoadFn successfully returns.
//!
//! This function will not be called again until after @ref OnModuleUnloadFn has completed and the module has been fully
//! unloaded and reloaded.
//!
//! The owning @ref omni::core::ITypeFactory can be safely accessed in this function.
//!
//! A interface implementation's `createFn` can be called concurrently with this function.
//!
//! An interface implementation's `createFn` can be called before this function is called, as such:
//!
//! - Move critical module initialization to @ref omni::core::OnModuleLoadFn.
//!
//! - If some initialization cannot be performed in @ref omni::core::OnModuleLoadFn (due to @ref
//! omni::core::ITypeFactory not being accessible), perform lazy initialization in `createFn` (in a thread-safe
//! manner).
using OnModuleStartedFn = void();
//! @ref omni::core::ModuleExports entry to register a function to be called after the plugin has loaded.
//!
//! Use the helper @ref OMNI_MODULE_ON_MODULE_STARTED to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryOnModuleStarted)
OnModuleStartedFn* onModuleStarted; //!< Module function to call once the module is loaded.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryOnModuleStarted)
//! Registers the plugin's function that will be called once the plugin is loaded. See
//! @ref omni::core::OnModuleStartedFn for threading consideration with this function.
//!
//! @param exp_ The @ref omni::core::ModuleExports table in which the entry should be added.
//!
//! @param fn_ The plugin's @ref omni::core::OnModuleStartedFn to be called after the plugin is loaded.
#define OMNI_MODULE_ON_MODULE_STARTED(exp_, fn_) OMNI_RETURN_IF_FAILED(exp_->addOnModuleStarted(fn_))
//! Called to determine if the module can be unloaded.
//!
//! Return `true` if it is safe to unload the module. It is up to the module to determine what "safe" means, though in
//! general, it is expected that "safe" means that none of the objects created from the module's `createFn`'s are still
//! alive.
//!
//! This function will never be called while another thread is calling one of this module's `createFn` functions, during
//! @ref omni::core::OnModuleLoadFn, or during @ref omni::core::OnModuleStartedFn.
//!
//! @ref omni::core::OnModuleCanUnloadFn <u>must not</u> access the owning @ref omni::core::ITypeFactory. @ref
//! omni::core::ITypeFactory is unable to prevent this, thus, if @ref omni::core::OnModuleCanUnloadFn does access @ref
//! omni::core::ITypeFactory (either directly or indirectly) there are no safety guards in place and undefined behavior
//! will result.
//!
//! If the module returns `true` from this function, @ref omni::core::OnModuleUnloadFn will be called. If `false` is
//! returned, @ref omni::core::OnModuleUnloadFn will not be called.
//!
//! If this function returns `false`, it may be called again. If `true` is returned, the module will be unloaded and
//! this function will not be called until the module is loaded again (if ever).
using OnModuleCanUnloadFn = bool();
//! @ref omni::core::ModuleExports entry to register a function to determine if the module can be unloaded.
//!
//! Use the helper @ref OMNI_MODULE_ON_MODULE_CAN_UNLOAD to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryOnModuleCanUnload)
OnModuleCanUnloadFn* onModuleCanUnload; //!< Module function to call to see if the module can be unloaded.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryOnModuleCanUnload)
//! Registers the plugin's function that determines if the plugin can be unloaded. See @ref
//! omni::core::OnModuleCanUnloadFn for details.
//!
//! @param exp_ The @ref omni::core::ModuleExports table in which the entry should be added.
//!
//! @param fn_ The plugin's @ref omni::core::OnModuleCanUnloadFn to be called after the plugin is loaded.
#define OMNI_MODULE_ON_MODULE_CAN_UNLOAD(exp_, fn_) OMNI_RETURN_IF_FAILED(exp_->addOnModuleCanUnload(fn_))
//! Called when the module is about to be unloaded.
//!
//! This function is called after @ref OnModuleCanUnloadFn returns `true`.
//!
//! The module is expected to clean-up any external references to code within the module. For example, unregistering
//! asset types.
//!
//! Any registered implementations from this module will have already been unregistered by the time this function is
//! called.
//!
//! This function must never fail.
//!
//! It is safe to access the owning @ref omni::core::ITypeFactory.
//!
//! Attempting to load the module within @ref OnModuleLoadFn may result in deadlock. It is safe for other threads to
//! attempt the load the module during @ref OnModuleUnloadFn, however, it is not safe for @ref OnModuleUnloadFn to
//! attempt to load the module.
//!
//! No other module functions will be called while this function is active.
//!
//! @ref omni::core::ITypeFactory implements the following unload pseudo-code:
//!
//! @code{.cpp}
//! if (module->canUnload()) {
//! factory->unregisterModuleTypes(module);
//! module->onUnload();
//! os->unloadDll(module);
//! }
//! @endcode
using OnModuleUnloadFn = void();
//! @ref omni::core::ModuleExports entry to register a function to be called when the plugin is unloaded.
//!
//! Use the helper @ref OMNI_MODULE_ON_MODULE_UNLOAD to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryOnModuleUnload)
OnModuleUnloadFn* onModuleUnload; //!< Module function to call to clean-up the module during unload.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryOnModuleUnload)
//! Registers the plugin's function who is responsible for cleaning up the plugin when the plugin is being unloaded.
//!
//! @param exp_ The @ref omni::core::ModuleExports table in which the entry should be added.
//!
//! @param fn_ The plugin's @ref omni::core::OnModuleUnloadFn who is responsible for cleaning up the plugin.
#define OMNI_MODULE_ON_MODULE_UNLOAD(exp_, fn_) OMNI_RETURN_IF_FAILED(exp_->addOnModuleUnload(fn_))
//! Forward declaration for omni::core::ITypeFactory.
OMNI_DECLARE_INTERFACE(ITypeFactory)
//! @ref omni::core::ModuleExports entry to access @ref omni::core::ITypeFactory.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryITypeFactory)
ITypeFactory** typeFactory; //!< Pointer to the module's type factory pointer.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryITypeFactory)
//! @ref omni::core::ModuleExports entry to access @ref omni::log::ILog.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryILog)
log::ILog** log; //!< Pointer to the module's log pointer.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryILog)
//! @ref omni::core::ModuleExports entry to add a logging channel.
//!
//! Use the helper @ref OMNI_MODULE_ADD_LOG_CHANNEL to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryLogChannel)
const char* name; //!< Name of the channel.
int32_t* level; //!< Pointer to module memory where the channel's logging level is stored.
const char* description; //!< Description of the channel (for humans).
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryLogChannel)
//! Adds a log channel to the logging system. The channel will be removed when the module is unloaded.
//!
//! @p name_ and @p level_ must not be `nullptr`.
//!
//! The given pointers must remain valid for the lifetime of the module.
//!
//! Rather than calling this macro, use @ref OMNI_LOG_ADD_CHANNEL to both declare a channel and add it to the @ref
//! omni::core::ModuleExports table.
//!
//! @param exp_ The @ref omni::core::ModuleExports table in which the entry should be added.
//!
//! @param name_ The name of the channel. Must not be `nullptr`.
//!
//! @param level_ Pointer to plugin memory where the logging system can store the channel's logging threshold. Shouldn't
//! be `nullptr`.
//!
//! @param description_ Description of the channel. Useful for debugging and UIs. Must not be `nullptr`.
#define OMNI_MODULE_ADD_LOG_CHANNEL(exp_, name_, level_, description_) \
OMNI_RETURN_IF_FAILED(exp_->addLogChannel(name_, level_, description_))
//! @ref omni::core::ModuleExports entry to interop with @ref g_carbClientName.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryCarbClientName)
const char* clientName; //!< The client name
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryCarbClientName)
//! Requires that the owning @ref omni::core::ITypeFactory provides a Carbonite client name: @ref g_carbClientName.
//!
//! By default, the owning @ref omni::core::ITypeFactory will try to populate the module's @ref g_carbClientName, but
//! will silently fail if it cannot. This macro tells the @ref omni::core::ITypeFactory to fail the module's load.
#define OMNI_MODULE_REQUIRE_CARB_CLIENT_NAME(exp_) \
OMNI_RETURN_IF_FAILED(out->requireExport(omni::core::kModuleExportEntryTypeCarbClientName))
//! @ref omni::core::ModuleExports entry to access @ref omni::structuredlog::IStructuredLog.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryIStructuredLog)
omni::structuredlog::IStructuredLog** structuredLog; //!< Pointer to module structured log pointer.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryIStructuredLog)
//! @ref omni::core::ModuleExports entry to add a new structured logging schema to be registered.
//!
//! Use the helper @ref OMNI_MODULE_ADD_STRUCTURED_LOG_SCHEMA() to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntrySchema)
omni::structuredlog::SchemaAddFn schemaAddFn; //!< the schema registration function to run after core startup.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntrySchema)
//! adds a new schema to be registered after core startup.
//!
//! @p fn_ must not be `nullptr`.
//!
//! This does not need to be called directly. All the schemas included in a module will be
//! implicitly added by @ref OMNI_MODULE_SET_EXPORTS().
//!
//! @param exp_ The @ref omni::core::ModuleExports table in which the schema should be added.
//! @param fn_ The schema registration function that will be stored. This will be executed
//! once the core's startup has completed. This must not be nullptr.
#define OMNI_MODULE_ADD_STRUCTURED_LOG_SCHEMA(exp_, fn_) OMNI_RETURN_IF_FAILED(exp_->addStructuredLogSchema(fn_))
} // namespace core
} // namespace omni
namespace carb
{
struct Framework;
namespace assert
{
struct IAssert;
} // namespace assert
namespace logging
{
struct ILogging;
} // namespace logging
namespace profiler
{
struct IProfiler;
} // namespace profiler
namespace l10n
{
struct IL10n;
struct LanguageTable;
struct LanguageIdentifier;
} // namespace l10n
} // namespace carb
namespace omni
{
namespace core
{
#ifndef DOXYGEN_BUILD
namespace detail
{
//! Carbonite logging callback.
using CarbLogFn = void (*)(const char* source,
int32_t level,
const char* fileName,
const char* functionName,
int lineNumber,
const char* fmt,
...);
//! Carbonite logging threshold callback.
using CarbLogLevelFn = void(int32_t);
//! Carbonite localization callback.
using CarbLocalizeStringFn = const char*(CARB_ABI*)(const carb::l10n::LanguageTable* table,
uint64_t id,
const carb::l10n::LanguageIdentifier* language);
} // namespace detail
#endif
//! @ref omni::core::ModuleExports entry to interop with @ref carb::Framework.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryCarbFramework)
carb::Framework** framework; //!< Pointer to the module's @ref g_carbFramework pointer.
carb::Version version; //!< Version of the @ref carb::Framework the module expects.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryCarbFramework)
//! Requires that the owning @ref omni::core::ITypeFactory provides a Carbonite @ref carb::Framework @ref
//! g_carbFramework.
//!
//! By default, the owning @ref omni::core::ITypeFactory will try to populate the module's @ref g_carbFramework, but
//! will silently fail if it cannot. This macro tells the @ref omni::core::ITypeFactory to fail the module's load.
#define OMNI_MODULE_REQUIRE_CARB_FRAMEWORK(exp_) \
OMNI_RETURN_IF_FAILED(out->requireExport(omni::core::kModuleExportEntryTypeCarbFramework))
//! @ref omni::core::ModuleExports entry to interop with @ref carb::assert::IAssert.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryCarbIAssert)
carb::assert::IAssert** assert; //!< Pointer to the module's @ref g_carbAssert pointer.
carb::InterfaceDesc interfaceDesc; //!< Required version of @ref carb::assert::IAssert.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryCarbIAssert)
//! Requires that the owning @ref omni::core::ITypeFactory provides a Carbonite @ref carb::assert::IAssert @ref
//! g_carbAssert.
//!
//! By default, the owning @ref omni::core::ITypeFactory will try to populate the module's @ref g_carbAssert, but will
//! silently fail if it cannot. This macro tells the @ref omni::core::ITypeFactory to fail the module's load.
#define OMNI_MODULE_REQUIRE_CARB_IASSERT(exp_) \
OMNI_RETURN_IF_FAILED(out->requireExport(omni::core::kModuleExportEntryTypeCarbIAssert))
//! @ref omni::core::ModuleExports entry to interop with @ref carb::logging::ILogging.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryCarbILogging)
carb::logging::ILogging** logging; //!< Pointer to the module's @ref g_carbLogging pointer.
detail::CarbLogFn* logFn; //!< Pointer to the module's @ref g_carbLogFn function pointer.
detail::CarbLogLevelFn* logLevelFn; //!< Pointer to a module function which can set the log level.
int32_t* logLevel; //!< Pointer to module memory where the logging threshold is stored.
carb::InterfaceDesc interfaceDesc; //!< Required version of @ref carb::logging::ILogging.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryCarbILogging)
//! Requires that the owning @ref omni::core::ITypeFactory provides a Carbonite @ref carb::logging::ILogging @ref
//! g_carbLogging.
//!
//! By default, the owning @ref omni::core::ITypeFactory will try to populate the module's @ref g_carbLogging, but will
//! silently fail if it cannot. This macro tells the @ref omni::core::ITypeFactory to fail the module's load.
#define OMNI_MODULE_REQUIRE_CARB_ILOGGING(exp_) \
OMNI_RETURN_IF_FAILED(out->requireExport(omni::core::kModuleExportEntryTypeCarbILogging))
//! @ref omni::core::ModuleExports entry to interop with @ref carb::profiler::IProfiler.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryCarbIProfiler)
carb::profiler::IProfiler** profiler; //!< Pointer to the module's @ref g_carbProfiler.
carb::InterfaceDesc interfaceDesc; //!< Required version of @ref carb::profiler::IProfiler.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryCarbIProfiler)
//! Requires that the owning @ref omni::core::ITypeFactory provides a Carbonite @ref carb::profiler::IProfiler @ref
//! g_carbProfiler.
//!
//! By default, the owning @ref omni::core::ITypeFactory will try to populate the module's @ref g_carbProfiler, but will
//! silently fail if it cannot. This macro tells the @ref omni::core::ITypeFactory to fail the module's load.
#define OMNI_MODULE_REQUIRE_CARB_IPROFILER(exp_) \
OMNI_RETURN_IF_FAILED(out->requireExport(omni::core::kModuleExportEntryTypeCarbIProfiler))
//! @ref omni::core::ModuleExports entry to interop with @ref carb::l10n::IL10n.
//!
//! Use the helper @ref OMNI_MODULE_SET_EXPORTS to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryCarbIL10n)
carb::l10n::IL10n** localization; //!< Pointer to the module's @ref g_carbLocalization.
detail::CarbLocalizeStringFn* localizationFn; //!< Pointer to the module's @ref g_localizationFn function pointer.
carb::InterfaceDesc interfaceDesc; //!< Required version of @ref carb::l10n::IL10n.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryCarbIL10n)
//! Called to get dependencies from the module.
using GetModuleDependenciesFn = Result(carb::InterfaceDesc** out, size_t* outCount);
//! @ref omni::core::ModuleExports entry to register a function to advertise the interface implementations available in
//! the plugin.
//!
//! Use the helper @ref OMNI_MODULE_GET_MODULE_DEPENDENCIES to add this entry.
OMNI_MODULE_EXPORT_ENTRY_BEGIN(ModuleExportEntryGetModuleDependencies)
GetModuleDependenciesFn* getModuleDependencies; //!< Module's dependencies information function.
OMNI_MODULE_EXPORT_ENTRY_END(ModuleExportEntryGetModuleDependencies)
//! Registers the function responsible for advertising the plugin's interface dependencies.
//!
//! @param exp_ The @ref omni::core::ModuleExports table in which the entry should be added.
//!
//! @param fn_ The plugin's @ref omni::core::GetModuleDependenciesFn responsible for advertising
//! plugin's interface dependencies.
#define OMNI_MODULE_GET_MODULE_DEPENDENCIES(exp_, fn_) OMNI_RETURN_IF_FAILED(exp_->addGetModuleDependencies(fn_))
//! Requires that the owning @ref omni::core::ITypeFactory provides a Carbonite @ref carb::l10n::IL10n @ref
//! g_carbLocalization.
//!
//! By default, the owning @ref omni::core::ITypeFactory will try to populate the module's @ref g_carbLocalization, but
//! will silently fail if it cannot. This macro tells the @ref omni::core::ITypeFactory to fail the module's load.
#define OMNI_MODULE_REQUIRE_CARB_IL10N(exp_) \
OMNI_RETURN_IF_FAILED(out->requireExport(omni::core::kModuleExportEntryTypeCarbIL10n))
//! Magic number for sanity checking of @ref omni::core::ModuleExports.
constexpr uint16_t kModuleExportsMagic = 0x766e; // { 'n', 'v' }
//! Binary layout of @ref omni::core::ModuleExports. This should be incremented if the fields in @ref
//! omni::core::ModuleExports change.
//!
//! Great care must be taken when changing this version, as it may prevent existing modules from loading without
//! recompilation.
constexpr uint16_t kModuleExportsVersion = 1;
//! Entities exported by a module for both use and population by @ref omni::core::ITypeFactory.
//!
//! Rather than a fixed data structure to communicate which functions a DLL exports, Omniverse modules use a data driven
//! approach to convey both what functionality the module brings to the table and the needs of the module in order to
//! operate correctly.
//!
//! The data members in this structure, while public, should be treated as opaque. Hiding the data members (i.e. making
//! them private) would violate C++11's "standard layout" requirements, thus making this struct not
//! @rstref{ABI safe <abi-compatibility>}.
//!
//! Avoid calling methods of this struct directly. Rather call the helper macros. For example, call @ref
//! OMNI_MODULE_ON_MODULE_LOAD() rather than @ref ModuleExports::addOnModuleLoad(). Calling the former allows future
//! implementations leeway to make your awesome-futuristic interface compatible with older <i>carb.dll</i>'s.
//!
//! Unless otherwise noted, pointers provided to this object are expected to be valid for the lifetime of the module.
//!
//!@see @oni_overview for an overview of plugin loading (explicit module loading).
struct ModuleExports
{
//! Magic number. Used for sanity checking. Should be kModuleExportsMagic.
uint16_t magic;
//! Version of this structure. Changing this will break most modules.
//!
//! Version 1 of this structure defines a key/value database of module capabilities and requirements.
//!
//! Adding or removing a key from this database does not warrant a version bump. Rather a version bump is required
//! if:
//!
//! - Any field in this struct change its meaning.
//! - Fields are removed from this struct (hint: never remove a field, rather, deprecate it).
//!
//! The "keys" in the key/value pairs are designed such that a "key" has a known value. A "key"'s meaning can never
//! change. If a change is desired, a new key is created.
uint16_t version;
//! Size of this structure. Here the size is `sizeof(ModuleExports)` + any extra space allocated at the end of this
//! struct for @ref ModuleExportEntry's.
uint32_t byteCount;
//! Pointer to the first byte of the first @ref ModuleExportEntry.
uint8_t* exportsBegin;
//! Pointer to the byte after the end of the last @ref ModuleExportEntry. The module is expected to update this
//! field.
uint8_t* exportsEnd;
//! Returns @ref kResultSuccess if the given version is supported, an error otherwise.
//!
//! This method is called from the module.
Result checkVersion(uint16_t moduleMagic, uint16_t moduleVersion)
{
// we can't log here, since we're to early in the module load process for logging to be available. pass back the
// magic number and version we were expecting so omni::core::ITypeFactory can print an appropriate message if
// the checks below fail.
std::swap(magic, moduleMagic);
std::swap(version, moduleVersion);
if (magic != moduleMagic)
{
return kResultVersionParseError;
}
if (version != moduleVersion)
{
return kResultVersionCheckFailure;
}
return kResultSuccess;
}
//! Adds the given export entry. Return `false` if there is not enough space.
Result add(const ModuleExportEntry* entry)
{
uint32_t neededSize = uint32_t(exportsEnd - exportsBegin) + sizeof(ModuleExports) + entry->byteCount;
if (neededSize > byteCount)
{
return kResultInsufficientBuffer;
}
std::memcpy(exportsEnd, entry, entry->byteCount);
exportsEnd += entry->byteCount;
return kResultSuccess;
}
//! Returns a pointer to the first entry of the given type. Return `nullptr` if no such entry exists.
ModuleExportEntry* find(const char* type)
{
if (!type)
{
return nullptr;
}
uint8_t* p = exportsBegin;
while (p < exportsEnd)
{
auto entry = reinterpret_cast<ModuleExportEntry*>(p);
if (0 == strcmp(type, entry->type))
{
return entry;
}
p += entry->byteCount;
}
return nullptr;
}
//! Finds the first entry of the given type and sets it as "required". Returns an error if no such entry could be
//! found.
Result requireExport(const char* type)
{
auto entry = find(type);
if (entry)
{
entry->flags |= fModuleExportEntryFlagRequired;
return kResultSuccess;
}
return kResultNotFound;
}
//! See @ref OMNI_MODULE_ON_MODULE_LOAD.
Result addOnModuleLoad(OnModuleLoadFn* fn, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryOnModuleLoad entry{ kModuleExportEntryTypeOnModuleLoad, flags };
entry.onModuleLoad = fn;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_ON_MODULE_STARTED.
Result addOnModuleStarted(OnModuleStartedFn* fn, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryOnModuleStarted entry{ kModuleExportEntryTypeOnModuleStarted, flags };
entry.onModuleStarted = fn;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_ON_MODULE_CAN_UNLOAD.
Result addOnModuleCanUnload(OnModuleCanUnloadFn* fn, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryOnModuleCanUnload entry{ kModuleExportEntryTypeOnModuleCanUnload, flags };
entry.onModuleCanUnload = fn;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_ON_MODULE_UNLOAD.
Result addOnModuleUnload(OnModuleUnloadFn* fn, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryOnModuleUnload entry{ kModuleExportEntryTypeOnModuleUnload, flags };
entry.onModuleUnload = fn;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addITypeFactory(ITypeFactory** typeFactory, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryITypeFactory entry{ kModuleExportEntryTypeITypeFactory, flags };
entry.typeFactory = typeFactory;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addILog(log::ILog** log, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryILog entry{ kModuleExportEntryTypeILog, flags };
entry.log = log;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_LOG_ADD_CHANNEL.
Result addLogChannel(const char* channelName,
int32_t* level,
const char* description,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryLogChannel entry{ kModuleExportEntryTypeLogChannel, flags };
entry.name = channelName;
entry.level = level;
entry.description = description;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addIStructuredLog(omni::structuredlog::IStructuredLog** strucLog,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryIStructuredLog entry{ kModuleExportEntryTypeIStructuredLog, flags };
entry.structuredLog = strucLog;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_ADD_STRUCTURED_LOG_SCHEMA().
Result addStructuredLogSchema(omni::structuredlog::SchemaAddFn fn,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntrySchema entry{ kModuleExportEntryTypeSchema, flags };
entry.schemaAddFn = fn;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addCarbClientName(const char* clientName, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryCarbClientName entry{ kModuleExportEntryTypeCarbClientName, flags };
entry.clientName = clientName;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addCarbFramework(carb::Framework** carbFramework,
const carb::Version& ver,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryCarbFramework entry{ kModuleExportEntryTypeCarbFramework, flags };
entry.framework = carbFramework;
entry.version = ver;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addCarbIAssert(carb::assert::IAssert** assert,
const carb::InterfaceDesc& interfaceDesc,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryCarbIAssert entry{ kModuleExportEntryTypeCarbIAssert, flags };
entry.assert = assert;
entry.interfaceDesc = interfaceDesc;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addCarbILogging(carb::logging::ILogging** logging,
detail::CarbLogFn* logFn,
detail::CarbLogLevelFn* logLevelFn,
int32_t* logLevel,
const carb::InterfaceDesc& interfaceDesc,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryCarbILogging entry{ kModuleExportEntryTypeCarbILogging, flags };
entry.logging = logging;
entry.logFn = logFn;
entry.logLevelFn = logLevelFn;
entry.logLevel = logLevel;
entry.interfaceDesc = interfaceDesc;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addCarbIProfiler(carb::profiler::IProfiler** profiler,
const carb::InterfaceDesc& interfaceDesc,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryCarbIProfiler entry{ kModuleExportEntryTypeCarbIProfiler, flags };
entry.profiler = profiler;
entry.interfaceDesc = interfaceDesc;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_SET_EXPORTS.
Result addCarbIL10n(carb::l10n::IL10n** localization,
detail::CarbLocalizeStringFn* localizationFn,
const carb::InterfaceDesc& interfaceDesc,
ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryCarbIL10n entry{ kModuleExportEntryTypeCarbIL10n, flags };
entry.localization = localization;
entry.localizationFn = localizationFn;
entry.interfaceDesc = interfaceDesc;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
//! See @ref OMNI_MODULE_GET_MODULE_DEPENDENCIES.
Result addGetModuleDependencies(GetModuleDependenciesFn* fn, ModuleExportEntryFlag flags = fModuleExportEntryFlagNone)
{
ModuleExportEntryGetModuleDependencies entry{ kModuleExportEntryTypeGetModuleDependencies, flags };
entry.getModuleDependencies = fn;
return add(reinterpret_cast<ModuleExportEntry*>(&entry));
}
};
CARB_ASSERT_INTEROP_SAFE(ModuleExports);
static_assert(sizeof(ModuleExports) == (8 + (2 * sizeof(void*))),
"unexpected ModuleExports size. do not change ModuleExports?");
//! Type of @ref kModuleGetExportsName. See @ref omniModuleGetExports.
using ModuleGetExportsFn = Result(ModuleExports* out);
//! Name of the module's exported function that is of type @ref omni::core::ModuleGetExportsFn. See @ref
//! omniModuleGetExports.
constexpr const char* const kModuleGetExportsName = "omniModuleGetExports";
} // namespace core
} // namespace omni
#ifdef DOXYGEN_BUILD
//! @brief Main entry point into a module. Returns the list of capabilities and requirements for the module.
//!
//! This is the first function called in a module by @ref omni::core::ITypeFactory. Information is passed between the
//! module and the @ref omni::core::ITypeFactory via @ref omni::core::ModuleExports.
//!
//! @ref omni::core::ModuleExports is an @rstref{ABI-safe <abi-compatibility>} table used to store the module's
//! requirements. For example, the module may require that the Carbonite @ref carb::Framework is present.
//!
//! This table is also used to communicate capabilities of the module. For example, the module is able to denote which
//! logging channels it wishes to register.
//!
//! See @oni_overview for more details on how this function is used.
omni::core::Result omniModuleGetExports(omni::core::ModuleExports* out);
#endif
| 41,927 | C | 47.193103 | 122 | 0.684666 |
omniverse-code/kit/include/omni/core/ITypeFactory.gen.h | // Copyright (c) 2020-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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/OmniAttr.h>
#include <omni/core/Interface.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <utility>
#include <type_traits>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! A mapping from type id's to implementations.
//!
//! This object maps type id's to concrete implementations. The type id's can represent interface ids or implementation
//! ids.
//!
//! Register types with registerInterfaceImplementationsFromModule() and registerInterfaceImplementations().
//!
//! Instantiate types with omni::core::createType(). This is the primary way Omniverse applications are able to
//! instantiate concrete implementations of @rstref{ABI-safe <abi-compatibility>} interfaces. See
//! omni::core::createType() for a helpful wrapper around omni::core::ITypeFactory::createType().
//!
//! In practice, there will be a single ITypeFactory active in the process space (accessible via
//! omniGetTypeFactoryWithoutAcquire()). However, @ref omni::core::ITypeFactory is not inherently a singleton, and as
//! such multiple instantiations of the interface may exists. This can be used to create private type trees.
//!
//! Unless otherwise noted, all methods in this interface are thread safe.
template <>
class omni::core::Generated<omni::core::ITypeFactory_abi> : public omni::core::ITypeFactory_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::core::ITypeFactory")
//! Instantiates a concrete type.
//!
//! The given type id can be an interface or implementation id.
//!
//! If the id is an interface id, the following rules are followed:
//!
//! - If the application specified a default implementation, that implementation will be instantiated.
//!
//! - Otherwise, the first registered implementation of the interface is instantiated. If multiple versions of the
//! implementation exist, the highest version is picked.
//!
//! - implVersion must be 0 since interfaces are not versioned (only implementations are versioned). If implVersion
//! is not 0, nullptr is returned.
//!
//! - If a default module name was provided by the app, the rules above will only be applied to implementations from
//! the specified default module.
//!
//! If the id is an implementation id, the followings rules apply:
//!
//! - If version is 0, the highest version of the implementation is returned.
//!
//! - If version is not 0, the returned object is the specified version of the implementation. If such a version
//! does not exists, nullptr is returned. If multiple implementations exists with the same version, the
//! implementation registered first is instantiated.
//!
//! In both cases above, if moduleName given, the rules above are followed by only looking at implementations from
//! the specified module. If no match is found, nullptr is returned.
//!
//! If moduleName has not been loaded, it will be loaded and its implementations registered.
//!
//! If moduleName is nullptr, the rules above are applied across all loaded modules.
//!
//! This method is thread safe.
omni::core::ObjectPtr<omni::core::IObject> createType(omni::core::TypeId id,
const char* moduleName,
uint32_t implVersion) noexcept;
//! Registers types from the given module.
//!
//! If the module is currently loaded, it will not be reloaded and kResultSuccess is returned.
//!
//! Modules (e.g. .dll or .so) may contain one or many implementations of one or many interfaces. When registering a
//! module with the type factory, a function, whose name is described by 'kModuleGetExportsName', is found and
//! invoked. Let's assume the exported function name is "omniModuleGetExports".
//!
//! "omniModuleGetExports" returns a key/value database of the module's capabilities and the module's requirements.
//! Some things to note about this database:
//!
//! - The module's requirements can be marked as optional.
//!
//! - The module's capabilities can be ignored by ITypeFactory.
//!
//! These properties allow ITypeFactory and the module to find an intersection of desired functionality in a data
//! driven manner. If one party's required needs are not met, the module fails to load (e.g. an appropriate
//! omni::core::Result is returned).
//!
//! It is expected the module has entries in the key/value database describing the functions ITypeFactory should
//! call during the loading process. The most important of these entries is the one defined by
//! OMNI_MODULE_ON_MODULE_LOAD(), which points to the function ITypeFactory should call to get a list of
//! implementations in the module. ITypeFactory invokes exports from the module in the following pattern:
//!
//! .--------------------------------------------------------------------------------------------------------------.
//! | -> Time -> |
//! |--------------------------------------------------------------------------------------------------------------|
//! | omniModuleGetExports | onLoad (req.) | onStarted (optional) | onCanUnload (optional) | onUnload (optional) |
//! | | | impl1->createFn | | |
//! | | | impl2->createFn | | |
//! | | | impl1->createFn | | |
//! \--------------------------------------------------------------------------------------------------------------/
//!
//! Above, functions in the same column can be called concurrently. It's up to the module to make sure such call
//! patterns are thread safe within the module.
//!
//! onCanUnload and createFn can be called multiple times. All other functions are called once during the lifecycle
//! of a module.
//!
//! \see omni/core/ModuleExports.h.
//! \see onModuleLoadFn
//! \see onModuleStartedFn
//! \see onModuleCanUnloadFn
//! \see onModuleUnloadFn
//!
//!
//! The module can be explicitly unloaded with unregisterInterfaceImplementationsFromModule().
//!
//! Upon destruction of this ITypeFactory, unregisterInterfaceImplementationsFromModule is called for each loaded
//! module. If the ITypeFactory destructor's call to unregisterInterfaceImplementationsFromModule fails to safely
//! unload a module (via the module's onModuleCanUnload and onModuleUnload), an attempt will be made to
//! forcefully/unsafely unload the module.
//!
//! The given module name must not be nullptr.
//!
//! This method is thread safe. Modules can be loaded in parallel.
//!
//! \returns Returns kResultSuccess if the module is loaded (either due to this function or a previous call).
//! Otherwise, an error is returned.
omni::core::Result registerInterfaceImplementationsFromModule(const char* moduleName,
omni::core::TypeFactoryLoadFlags flags) noexcept;
//! Unregisters all types registered from the given module.
//!
//! Unregistering a module may fail if the module does not belief it can safely be unloaded. This is determined by
//! OMNI_MODULE_ON_MODULE_CAN_UNLOAD().
//!
//! If unregistration does succeed, the given module will be unloaded from the process space.
//!
//! Upon destruction of this ITypeFactory, unregisterInterfaceImplementationsFromModule is called for each loaded
//! module. If the ITypeFactory destructor's call to unregisterInterfaceImplementationsFromModule fails to safely
//! unload a module (via the module's onModuleCanUnload and onModuleUnload), an attempt will be made to
//! forcefully/unsafely unload the module.
//!
//! The given module name must not be nullptr.
//!
//! This method is thread safe.
//!
//! \returns Returns kResultSuccess if the module wasn't already loaded or if this method successfully unloaded the
//! module. Return an error code otherwise.
omni::core::Result unregisterInterfaceImplementationsFromModule(const char* moduleName) noexcept;
//! Register the list of types.
//!
//! Needed data from the "implementations" list is copied by this method.
//!
//! This method is thread safe.
void registerInterfaceImplementations(const omni::core::InterfaceImplementation* implementations,
uint32_t implementationsCount,
omni::core::TypeFactoryLoadFlags flags) noexcept;
//! Maps a type id back to its type name.
//!
//! The memory returned is valid for the lifetime of ITypeFactory
//!
//! Returns nullptr if id has never been registered. Types that have been registered, and then unregistered, will
//! still have a valid string returned from this method.
//!
//! This method is thread safe.
const char* getTypeIdName(omni::core::TypeId id) noexcept;
//! Sets the implementation matching constraints for the given interface id.
//!
//! See omni::core::ITypeFactory_abi::createType_abi() for how these constraints are used.
//!
//! moduleName can be nullptr.
//!
//! if implVersion is 0 and implId is an implementation id, the implementation with the highest version is chosen.
//!
//! This method is thread safe.
void setInterfaceDefaults(omni::core::TypeId interfaceId,
omni::core::TypeId implId,
const char* moduleName,
uint32_t implVersion) noexcept;
//! Returns the implementation matching constraints for the given interface id.
//!
//! See omni::core::ITypeFactory_abi::createType_abi() for how these constraints are used.
//!
//! If the given output implementation id pointer (outImplid) is not nullptr, it will be populated with the default
//! implementation id instantiated when the interface requested to be created.
//!
//! If the given output implementation version pointer (outImplVersion) is not nullptr, it will be populated with
//! the default implementation version instantiated when the interface is requested to be created.
//!
//! If the output module name pointer (outModuleName) is not nullptr, it will be populated with the name of the
//! module searched when trying to find an implementation of the interface. If there is no current default module
//! name, the output module name will be populated with the empty string. If the output module name's buffer size is
//! insufficient to store the null terminated module name, kResultBufferInsufficient is returned and the module
//! name's buffer size is updated with the needed buffer size.
//!
//! If the output module name is nullptr, the output module name buffer size (inOutModuleNameCount) will be
//! populated with the size of the buffer needed to store the module name.
//!
//! The output module name buffer size pointer (inOutModuleNameCount) must not be nullptr.
//!
//! If the given interface id is not found, kResultNotFound is returned and the output implementation id (outImplId)
//! and version (outImplVersion), if defined, are set to 0. Additionally, the output module name (outModuleName),
//! if defined, is set to the empty string.
//!
//! If kResultInsufficientBuffer and kResultNotFound are both flagged internally, kResultNotFound is returned.
//!
//! See omni::core::getInterfaceDefaults() for a C++ wrapper to this method.
//!
//! This method is thread safe.
omni::core::Result getInterfaceDefaults(omni::core::TypeId interfaceId,
omni::core::TypeId* outImplId,
char* outModuleName,
uint32_t* inOutModuleNameCount,
uint32_t* outImplVersion) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::ObjectPtr<omni::core::IObject> omni::core::Generated<omni::core::ITypeFactory_abi>::createType(
omni::core::TypeId id, const char* moduleName, uint32_t implVersion) noexcept
{
return omni::core::steal(createType_abi(id, moduleName, implVersion));
}
inline omni::core::Result omni::core::Generated<omni::core::ITypeFactory_abi>::registerInterfaceImplementationsFromModule(
const char* moduleName, omni::core::TypeFactoryLoadFlags flags) noexcept
{
return registerInterfaceImplementationsFromModule_abi(moduleName, flags);
}
inline omni::core::Result omni::core::Generated<omni::core::ITypeFactory_abi>::unregisterInterfaceImplementationsFromModule(
const char* moduleName) noexcept
{
return unregisterInterfaceImplementationsFromModule_abi(moduleName);
}
inline void omni::core::Generated<omni::core::ITypeFactory_abi>::registerInterfaceImplementations(
const omni::core::InterfaceImplementation* implementations,
uint32_t implementationsCount,
omni::core::TypeFactoryLoadFlags flags) noexcept
{
registerInterfaceImplementations_abi(implementations, implementationsCount, flags);
}
inline const char* omni::core::Generated<omni::core::ITypeFactory_abi>::getTypeIdName(omni::core::TypeId id) noexcept
{
return getTypeIdName_abi(id);
}
inline void omni::core::Generated<omni::core::ITypeFactory_abi>::setInterfaceDefaults(omni::core::TypeId interfaceId,
omni::core::TypeId implId,
const char* moduleName,
uint32_t implVersion) noexcept
{
setInterfaceDefaults_abi(interfaceId, implId, moduleName, implVersion);
}
inline omni::core::Result omni::core::Generated<omni::core::ITypeFactory_abi>::getInterfaceDefaults(
omni::core::TypeId interfaceId,
omni::core::TypeId* outImplId,
char* outModuleName,
uint32_t* inOutModuleNameCount,
uint32_t* outImplVersion) noexcept
{
return getInterfaceDefaults_abi(interfaceId, outImplId, outModuleName, inOutModuleNameCount, outImplVersion);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
static_assert(std::is_standard_layout<omni::core::InterfaceImplementation>::value,
"omni::core::InterfaceImplementation must be standard layout to be used in ONI ABI");
| 15,587 | C | 51.484848 | 124 | 0.651376 |
omniverse-code/kit/include/omni/core/Omni.h | // Copyright (c) 2020-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.
//
//! @file
//!
//! @brief Main header for the Omniverse core.
#pragma once
#include "../../carb/extras/Library.h"
#include "../../carb/PluginInitializers.h"
#include "Api.h"
#include "BuiltIn.h"
#include "ITypeFactory.h"
#include "../log/ILog.h"
#include "../structuredlog/IStructuredLog.h"
//! Returns the module's name (e.g. "c:/foo/omni-glfw.dll"). The pointer returned is valid for the lifetime of the
//! module.
//!
//! The returned path will be delimited by '/' on all platforms.
OMNI_API const char* omniGetModuleFilename();
//! Returns the module's directory name (e.g. "c:/foo" for "c:/foo/omni-glfw.dll"). The pointer returned is valid for
//! the lifetime of the module.
//!
//! The returned path will be delimited by '/' on all platforms.
OMNI_API const char* omniGetModuleDirectory();
#if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD)
//! Defines global symbols intended to be used to statically analyze whether a given plugin
//! is a debug or release build. In a debug build, the `g_carbIsDebugConfig` symbol will
//! be present. In a release build, the `g_carbIsReleaseConfig` symbol will be present.
//! These symbols are not intended to be used at runtime, but rather to be able to determine
//! the build configuration without having to load up the module in a process first.
//!
//! These symbols are only present on non-Windows builds. They can be found with a command
//! line similar to this:
//! `nm <modulePath> | grep g_carbIsDebugConfig` or
//! `nm <modulePath> | grep g_carbIsReleaseConfig`
//!
//! On Windows, each module's "properties" window will list "(Debug)" in the "Product Name"
//! field of the "Details" tab for debug builds.
# define OMNI_MODULE_GLOBALS_BUILD_CONFIG_SYMBOLS()
#else
# if CARB_DEBUG
# define OMNI_MODULE_GLOBALS_BUILD_CONFIG_SYMBOLS() CARB_HIDDEN int g_carbIsDebugConfig = 1
# else
# define OMNI_MODULE_GLOBALS_BUILD_CONFIG_SYMBOLS() CARB_HIDDEN int g_carbIsReleaseConfig = 1
# endif
#endif
//! Defines functions centered around determining the current module's disk location.
//!
//! Internal macro to reduce code duplication. Do not directly use.
#define OMNI_MODULE_DEFINE_LOCATION_FUNCTIONS() \
OMNI_API const char* omniGetModuleFilename() \
{ \
static std::string s_omniModuleFilename = carb::extras::getLibraryFilename((void*)(omniGetModuleFilename)); \
return s_omniModuleFilename.c_str(); \
} \
OMNI_API const char* omniGetModuleDirectory() \
{ \
static std::string s_omniModuleDirectory = carb::extras::getLibraryDirectory((void*)(omniGetModuleDirectory)); \
return s_omniModuleDirectory.c_str(); \
}
//! Defines default implementations of global omni functions for a module.
//!
//! Internal macro to reduce code duplication. Do not directly use. Use @ref OMNI_MODULE_GLOBALS().
#define OMNI_MODULE_DEFINE_OMNI_FUNCTIONS() \
namespace \
{ \
::omni::core::ITypeFactory* s_omniTypeFactory = nullptr; \
::omni::log::ILog* s_omniLog = nullptr; \
::omni::structuredlog::IStructuredLog* s_omniStructuredLog = nullptr; \
} \
OMNI_MODULE_DEFINE_LOCATION_FUNCTIONS() \
OMNI_MODULE_GLOBALS_BUILD_CONFIG_SYMBOLS(); \
OMNI_API void* omniGetBuiltInWithoutAcquire(OmniBuiltIn type) \
{ \
switch (type) \
{ \
case ::OmniBuiltIn::eITypeFactory: \
return s_omniTypeFactory; \
case ::OmniBuiltIn::eILog: \
return s_omniLog; \
case ::OmniBuiltIn::eIStructuredLog: \
return s_omniStructuredLog; \
default: \
return nullptr; \
} \
}
//! Type of the `omniCarbStartup` function that is generated by \ref OMNI_MODULE_DEFINE_CARB_FUNCTIONS
using OmniCarbStartupFn = const char* (*)(carb::Framework*);
//! Type of the `omniCarbShutdown` function that is generated by \ref OMNI_MODULE_DEFINE_CARB_FUNCTIONS
using OmniCarbShutdownFn = void (*)();
//! Defines default implementations of global Carbonite functions for an Omni module.
//!
//! Internal macro to reduce code duplication. Do not directly use. Use @ref OMNI_MODULE_GLOBALS().
#define OMNI_MODULE_DEFINE_CARB_FUNCTIONS() \
OMNI_EXPORT const char* omniCarbStartup(carb::Framework* framework) \
{ \
g_carbFramework = framework; \
carb::pluginInitialize(); \
return g_carbClientName; \
} \
OMNI_EXPORT void omniCarbShutdown() \
{ \
carb::pluginDeinitialize(); \
}
//! Implementation detail. Do not directly use. Use @ref OMNI_GLOBALS_ADD_DEFAULT_CHANNEL.
#define OMNI_GLOBALS_ADD_DEFAULT_CHANNEL_1(chan_, name_, desc_) OMNI_LOG_ADD_CHANNEL(chan_, name_, desc_)
//! Adds the @p name_ as the default logging channel.
//!
//! It's unlikely user code will have to use this, as code like @ref CARB_GLOBALS_EX call this macro on behalf of most
//! clients.
#define OMNI_GLOBALS_ADD_DEFAULT_CHANNEL(name_, desc_) \
OMNI_GLOBALS_ADD_DEFAULT_CHANNEL_1(OMNI_LOG_DEFAULT_CHANNEL, name_, desc_)
//! Helper macro to declare globals needed by modules (i.e. plugins).
//!
//! Use with @ref OMNI_MODULE_SET_EXPORTS_WITHOUT_CARB().
//!
//! This macro is like @ref OMNI_MODULE_GLOBALS() but disables the interop between Carbonite interfaces and ONI. This
//! macro is useful if you never plan on accessing Carbonite interfaces within your module.
#define OMNI_MODULE_GLOBALS_WITHOUT_CARB(name_, desc_) \
OMNI_MODULE_DEFINE_OMNI_FUNCTIONS() \
OMNI_GLOBALS_ADD_DEFAULT_CHANNEL(name_, desc_)
//! Helper macro to declare globals needed by modules (i.e. plugins).
//!
//! Use with @ref OMNI_MODULE_SET_EXPORTS().
#define OMNI_MODULE_GLOBALS(name_, desc_) \
OMNI_MODULE_DEFINE_OMNI_FUNCTIONS() \
OMNI_MODULE_DEFINE_CARB_FUNCTIONS() \
CARB_GLOBALS_EX(name_, desc_)
//! Helper macro to set known export fields in @ref omniModuleGetExports().
//!
//! Use this macro in conjunction with @ref OMNI_MODULE_GLOBALS_WITHOUT_CARB().
#define OMNI_MODULE_SET_EXPORTS_WITHOUT_CARB(out_) \
do \
{ \
OMNI_RETURN_IF_FAILED(out_->checkVersion(omni::core::kModuleExportsMagic, omni::core::kModuleExportsVersion)); \
OMNI_RETURN_IF_FAILED(out_->addITypeFactory(&s_omniTypeFactory)); \
OMNI_RETURN_IF_FAILED(out_->addILog(&s_omniLog)); \
OMNI_RETURN_IF_FAILED(out_->addIStructuredLog(&s_omniStructuredLog)); \
for (auto channel = omni::log::getModuleLogChannels(); channel; channel = channel->next) \
{ \
OMNI_MODULE_ADD_LOG_CHANNEL(out_, channel->name, &channel->level, channel->description); \
} \
for (auto& schema : omni::structuredlog::getModuleSchemas()) \
{ \
OMNI_MODULE_ADD_STRUCTURED_LOG_SCHEMA(out_, schema); \
} \
} while (0)
//! Helper macro to set known export fields in @ref omniModuleGetExports().
//!
//! Use this macro in conjunction with @ref OMNI_MODULE_GLOBALS().
#define OMNI_MODULE_SET_EXPORTS(out_) \
OMNI_MODULE_SET_EXPORTS_WITHOUT_CARB(out_); \
OMNI_MODULE_SET_CARB_EXPORTS(out_)
//! Helper macro to set known export fields in @ref omniModuleGetExports() related to Carbonite.
//!
//! Internal macro to reduce code duplication. Do not directly use. Use @ref OMNI_MODULE_SET_EXPORTS().
#define OMNI_MODULE_SET_CARB_EXPORTS(out_) \
OMNI_RETURN_IF_FAILED(out_->addCarbClientName(g_carbClientName)); \
OMNI_RETURN_IF_FAILED(out_->addCarbFramework(&g_carbFramework, carb::kFrameworkVersion)); \
OMNI_RETURN_IF_FAILED(out_->addCarbIAssert(&g_carbAssert, carb::assert::IAssert::getInterfaceDesc())); \
OMNI_RETURN_IF_FAILED(out_->addCarbILogging(&g_carbLogging, &g_carbLogFn, \
[](int32_t logLevel) { g_carbLogLevel = logLevel; }, &g_carbLogLevel, \
carb::logging::ILogging::getInterfaceDesc())); \
OMNI_RETURN_IF_FAILED(out_->addCarbIProfiler(&g_carbProfiler, carb::profiler::IProfiler::getInterfaceDesc())); \
OMNI_RETURN_IF_FAILED( \
out_->addCarbIL10n(&g_carbLocalization, &g_localizationFn, carb::l10n::IL10n::getInterfaceDesc()))
//! Helper macro to declare globals needed my the omni library when using the omni library in an application.
//!
//! \note Either this macro, or \ref CARB_GLOBALS, or \ref CARB_GLOBALS_EX must be specified in the global namespace
//! in exactly one compilation unit for a Carbonite Application.
//!
//! See @ref OMNI_CORE_INIT().
//! @param clientName The name of the client application. Must be unique with respect to any plugins loaded. Also is the
//! name of the default log channel.
//! @param clientDescription A description to use for the default log channel.
#define OMNI_APP_GLOBALS(clientName, clientDescription) CARB_GLOBALS_EX(clientName, clientDescription)
//! Helper macro to startup the Carbonite framework and Omni type factory.
//!
//! See @ref OMNI_CORE_INIT().
#define OMNI_CORE_START(args_) \
omniCoreStart(args_); \
omni::log::addModulesChannels(); \
omni::structuredlog::addModulesSchemas(); \
carb::detail::registerAtexitHandler()
//! Helper macro to shutdown the Carbonite framework and Omni type factory.
//!
//! See @ref OMNI_CORE_INIT().
#define OMNI_CORE_STOP() \
omni::log::removeModulesChannels(); \
omniCoreStop()
//! Helper macro to shutdown the Carbonite framework and Omni type factory, for script bindings.
//!
//! See @ref OMNI_CORE_INIT().
#define OMNI_CORE_STOP_FOR_BINDINGS() \
omni::log::removeModulesChannels(); \
omniCoreStopForBindings()
//! Version of @ref OmniCoreStartArgs struct passed to @ref omniCoreStart.
//!
//! The version should be incremented only when removing/rearranging fields in @ref OmniCoreStartArgs. Adding fields
//! that default to `nullptr` or `0` (from the reserved space) is allowed without incrementing the version.
constexpr uint16_t kOmniCoreStartArgsVersion = 1;
//! Base type for the Omni core startup flags.
using OmniCoreStartFlags = uint32_t;
//! Flag to indicate that ILog usage should be disabled on startup instead of creating the
//! internal version or expecting that the caller to provide an implementation of the ILog
//! interface that has already been instantiated.
constexpr OmniCoreStartFlags fStartFlagDisableILog = 0x00000001;
//! Flag to indicate that IStructuredLog usage should be disabled on startup instead of
//! creating the internal version or expecting that the caller to provide an implementation
//! of the IStructuredLog interface that has already been instantiated.
constexpr OmniCoreStartFlags fStartFlagDisableIStructuredLog = 0x00000002;
//! Arguments passed to omniCoreStart().
class OmniCoreStartArgs
{
public:
//! Version of this structure. The version should be incremented only when removing/rearranging fields. Adding
//! fields (from the reserved space) is allowed without increment the version.
//!
//! This fields value should always be set to @ref kOmniCoreStartArgsVersion.
uint16_t version;
//! Size of this structure.
uint16_t byteCount;
//! flags to control the behavior of the Omni core startup.
OmniCoreStartFlags flags;
//! The type factory that will be returned by omniGetTypeFactoryWithoutAcquire().
//!
//! omniCoreStart will call acquire() on the given type factory.
//!
//! If the given parameter is nullptr, omniCreateTypeFactory() will be called.
omni::core::ITypeFactory* typeFactory;
//! The log that will be returned by omniGetLogWithoutAcquire().
//!
//! omniCoreStart will call acquire() on the given log.
//!
//! If the given parameter is nullptr, omniCreateLog() will be called.
omni::log::ILog* log;
//! The structured log object that will be returned by omniGetStructuredLogWithoutAcquire().
//!
//! omniCoreStart will call acquire on the given structured log object.
//!
//! If the given parameter is nullptr, the default implementation object will be used instead.
omni::structuredlog::IStructuredLog* structuredLog;
//! When adding fields, decrement this reserved space. Be mindful of alignment (explicitly add padding fields if
//! needed).
void* reserved[12];
//! Default constructor.
OmniCoreStartArgs()
{
std::memset(this, 0, sizeof(*this));
version = kOmniCoreStartArgsVersion;
byteCount = sizeof(*this);
}
//! Constructor which accepts default implementations for the core.
OmniCoreStartArgs(omni::core::ITypeFactory* factory_,
omni::log::ILog* log_ = nullptr,
omni::structuredlog::IStructuredLog* strucLog_ = nullptr)
: OmniCoreStartArgs()
{
typeFactory = factory_;
log = log_;
structuredLog = strucLog_;
}
};
CARB_ASSERT_INTEROP_SAFE(OmniCoreStartArgs);
static_assert((8 + 15 * sizeof(void*)) == sizeof(OmniCoreStartArgs), "OmniCoreStartArgs has an unexpected size");
//! Initializes the omni core library's internal data structures.
//!
//! nullptr is accepted, in which case the default behavior described in OmniCoreStartArgs is applied.
//!
//! See @ref OMNI_CORE_INIT().
OMNI_API void omniCoreStart(const OmniCoreStartArgs* args);
//! Tears down the omni core library's internal data structures.
//!
//! See @ref OMNI_CORE_INIT().
OMNI_API void omniCoreStop();
//! Tears down the omni core library's internal data structures for script bindings.
//!
//! See @ref OMNI_CORE_INIT().
OMNI_API void omniCoreStopForBindings();
//! Releases the structured log pointer.
//!
//! This should be called before unloading plugins so that the structured log plugin properly shuts down.
OMNI_API void omniReleaseStructuredLog();
#include "../../carb/ClientUtils.h"
| 20,232 | C | 60.126888 | 120 | 0.490905 |
omniverse-code/kit/include/omni/core/Types.gen.h | // Copyright (c) 2020-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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/OmniAttr.h>
#include <omni/core/Interface.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <utility>
#include <type_traits>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
static_assert(std::is_standard_layout<omni::core::UInt2>::value,
"omni::core::UInt2 must be standard layout to be used in ONI ABI");
static_assert(std::is_standard_layout<omni::core::Int2>::value,
"omni::core::Int2 must be standard layout to be used in ONI ABI");
static_assert(std::is_standard_layout<omni::core::Float2>::value,
"omni::core::Float2 must be standard layout to be used in ONI ABI");
| 1,374 | C | 32.536585 | 82 | 0.721252 |
omniverse-code/kit/include/omni/usd/UsdTypes.h | // Copyright (c) 2018-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.
//
#pragma once
#include <omni/kit/KitTypes.h>
#include <functional>
namespace omni
{
namespace usd
{
typedef uint64_t SubscriptionId;
/**
* Defines the USD state types.
*/
enum class StageState
{
eClosed, ///! USD is closed/unopened.
eOpening, ///! USD is opening.
eOpened, ///! USD is opened.
eClosing ///! USD is closing.
};
/**
* Defines the usd event types.
*/
enum class StageEventType
{
eSaved, ///! USD file saved.
eSaveFailed, ///! Failed to save USD.
eOpening, ///! USD stage is opening.
eOpened, ///! USD stage is opened successfully.
eOpenFailed, ///! USD stage failed to open.
eClosing, ///! USD stage is about to close. This is a good opportunity to shutdown anything depends on USD stage.
eClosed, ///! USD stage is fully closed.
eSelectionChanged, ///! USD Prim selection has changed.
eAssetsLoaded, ///! Current batch of async asset loading has been completed.
eAssetsLoadAborted, ///! Current batch of async asset loading has been aborted.
eGizmoTrackingChanged, ///! Started or stopped tracking (hovering) on a gizmo
eMdlParamLoaded, ///! MDL parameter is loaded for a MDL UsdShadeShader.
eSettingsLoaded, /// Stage settings have loaded
eSettingsSaving, /// Stage settings are being saved
eOmniGraphStartPlay, /// OmniGraph play has started
eOmniGraphStopPlay, /// OmniGraph play has stopped
eSimulationStartPlay, /// Simulation play has started
eSimulationStopPlay, /// Simulation play has stopped
eAnimationStartPlay, /// Animation playback has started
eAnimationStopPlay, /// Animation playback has stopped
eDirtyStateChanged, /// Dirty state of USD stage has changed. Dirty state means if it has unsaved changes or not.
eAssetsLoading, ///! A new batch of async asset loading has started.
eActiveLightsCountChanged, ///! Number of active lights in the scene has changed. This signal should be triggered
/// every time a scene has been loaded or number of lights has been changed. A few
/// features, for instance view lighting mode, need to detect when a number of active
/// lights becomes zero / become non-zero.
eHierarchyChanged, ///! USD stage hierarchy has changed.
eHydraGeoStreamingStarted, ///! Fabric Scene Delegate sends this when starting to stream rprims.
eHydraGeoStreamingStopped, ///! Fabric Scene Delegate sends this when stopping to stream rprims.
eHydraGeoStreamingStoppedNotEnoughMem, ///! Fabric Scene Delegate sends this when geometry streaming stops loading more geometry because of insufficient device memory
eHydraGeoStreamingStoppedAtLimit, ///! Fabric Scene Delegate sends this when stopping to stream rprims because of the limit set by the user.
eSaving, ///! Saving is in progress
};
enum class StageRenderingEventType
{
eNewFrame, ///! New frame available for Viewport, params are ViewportHandle, FrameNo, RenderResults
/// Frames complete for a single hydra engine render() invocation.
/// Payload is {
/// render_results: [ { viewport_handle: ViewportHandle, product: HydraRenderProduct*, subframe_count: int32_t } ],
/// average_frame_time_ns: float,
/// swh_frame_number: uint64_t,
/// }
eHydraEngineFramesComplete,
/// Frames added to the GPU queue for a single hydra engine.
/// This event signifies that the frame is scheduled for GPU rendering and has not been rendered yet.
/// The payload structure is the same as eHydraEngineFramesComplete.
eHydraEngineFramesAdded,
};
using OnStageResultFn = std::function<void(bool result, const char* err)>;
using OnLayersSavedResultFn =
std::function<void(bool result, const char* err, const std::vector<std::string>& savedLayers)>;
using OnPickingCompleteFn = std::function<void(const char* path, const carb::Double3* worldPos)>;
}
}
| 4,375 | C | 45.063157 | 170 | 0.716571 |
omniverse-code/kit/include/omni/usd/UsdUtils.h | // 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.
//
#pragma once
#ifndef USD_UTILS_INCLUDES
# error "Please include UtilsIncludes.h before including this header or in pre-compiled header."
#endif
#include "PathUtils.h"
#include <omni/kit/SettingsUtils.h>
#include <carb/InterfaceUtils.h>
#include <carb/datasource/IDataSource.h>
#include <carb/extras/Path.h>
#include <carb/extras/StringUtils.h>
#include <carb/filesystem/IFileSystem.h>
#include <carb/logging/Log.h>
#include <carb/omniclient/OmniClientUtils.h>
#include <carb/profiler/Profile.h>
#include <carb/settings/ISettings.h>
#include <functional>
#include <regex>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
inline bool GfIsClose(const pxr::GfQuatd& val1, const pxr::GfQuatd& val2, double tolerance)
{
bool result1 = pxr::GfIsClose(val1.GetReal(), val2.GetReal(), tolerance) &&
GfIsClose(val1.GetImaginary(), val2.GetImaginary(), tolerance);
bool result2 = GfIsClose(val1.GetReal(), -val2.GetReal(), tolerance) &&
GfIsClose(val1.GetImaginary(), -val2.GetImaginary(), tolerance);
return result1 || result2;
}
PXR_NAMESPACE_CLOSE_SCOPE
namespace omni
{
namespace usd
{
static constexpr char kAuthorOldMdlSchemaSettingPath[] = "/omni.kit.plugin/authorOldMdlSchema";
static constexpr char kCreateXformForTypelessReferenceSettingPath[] = "/omni.kit.plugin/createXformForTypelessReference";
static constexpr char kCreateExplicitRefForNoneDefaultPrimSettingPath[] =
"/omni.kit.plugin/createExplicitRefForNoneDefaultPrim";
static constexpr char kAuthorXformsWithFastUpdatesSettingPath[] = "/omni.kit.plugin/authorXformsWithFastUpdates";
static constexpr char kDefaultRotationOrderSettingPath[] =
PERSISTENT_SETTINGS_PREFIX "/app/primCreation/DefaultRotationOrder";
static constexpr char kDefaultXforOpTypeSettingPath[] = PERSISTENT_SETTINGS_PREFIX "/app/primCreation/DefaultXformOpType";
/**
* Defines a helper class to perform various USD operations.
*
* Because different project might want to include USD headers differently (Kit uses pre-compiled header for USD
* includes), UsdUtils.h doesn't include any USD headers. Users are responsible for including the correct headers.
*/
class UsdUtils
{
public:
/**
* Defines a helper class to do scoped layer editing. It sets scoped edit target and layer editing permission.
*/
class ScopedLayerEdit
{
public:
ScopedLayerEdit(pxr::UsdStageWeakPtr stage, const pxr::SdfLayerHandle& layer)
: m_usdEditCtx(stage, layer), m_layer(layer)
{
m_wasLayerEditable = m_layer->PermissionToEdit();
m_layer->SetPermissionToEdit(true);
CARB_ASSERT(m_layer->PermissionToEdit());
}
~ScopedLayerEdit()
{
m_layer->SetPermissionToEdit(m_wasLayerEditable);
}
private:
pxr::UsdEditContext m_usdEditCtx;
pxr::SdfLayerHandle m_layer;
bool m_wasLayerEditable;
};
/**
* Helper base class to subscribe to pxr::TfNotice
*/
template <typename T>
class UsdNoticeListener : public pxr::TfWeakBase
{
public:
virtual ~UsdNoticeListener()
{
revokeListener();
}
void registerListener()
{
// To avoid leak
revokeListener();
m_usdNoticeListenerKey =
pxr::TfNotice::Register(pxr::TfCreateWeakPtr(this), &UsdNoticeListener::handleNotice);
}
void revokeListener()
{
if (m_usdNoticeListenerKey.IsValid())
{
pxr::TfNotice::Revoke(m_usdNoticeListenerKey);
}
}
virtual void handleNotice(const T& objectsChanged) = 0;
private:
pxr::TfNotice::Key m_usdNoticeListenerKey;
};
using OnCreateFn = std::function<pxr::UsdPrim(pxr::UsdStageWeakPtr stage, const pxr::SdfPath& path)>;
/**
* Checks if a UsdGeomXformable instance is time sampled.
*
* @param xform The UsdGeomXformable to be checked.
* @return True if the xform is timesampled.
*/
static bool isTimeSampled(const pxr::UsdGeomXformable& xform)
{
// Iterate every xformOps check if any of them is timesampled.
// Don't call xform.GetTimeSamples() since this function will perform a very low efficient timesamples union for
// all xformOps.
// Also xform.TransformsMightBeTimeVarying() is not fit here since it will return true only one of
// the xformOp's numTimesamples > 1.
bool resetXformStack = false;
auto xformOps = xform.GetOrderedXformOps(&resetXformStack);
for (auto xformOp : xformOps)
{
if (xformOp.GetNumTimeSamples() > 0)
{
return true;
}
}
return false;
}
/**
* Checks if a UsdGeomXformable has timeSample on Key time
* TODO: currently imgizmo can only handle matrix, which brings that we need to set translate/rotation/scale have
* same key times But this is not correct, need to be fixed.
* @param xform The UsdGeomXformable to be checked.
* @param timeCode The timeCode to be checked on xform.
* @return True if the xform is timesampled on key timeCode.
*/
static bool hasTimeSample(const pxr::UsdGeomXformable& xform, pxr::UsdTimeCode timeCode)
{
if (timeCode.IsDefault())
return false;
bool resetXformStack = false;
auto xformOps = xform.GetOrderedXformOps(&resetXformStack);
for (auto xformOp : xformOps)
{
if (hasTimeSample(xformOp.GetAttr(), timeCode))
{
return true;
}
}
return false;
}
/**
* Checks if a UsdAttribute instance is time sampled.
*
* @param attribute The UsdAttribute to be checked.
* @return True if the attribute is timesampled.
*/
static bool isTimeSampled(const pxr::UsdAttribute& attribute)
{
return attribute.GetNumTimeSamples() > 0;
}
/**
* Checks if a UsdAttribute instance has time sample on key timeCode
*
* @param attribute The UsdAttribute to be checked.
* @param timeCode The timeCode to be checked.
* @return True if the attribute has timesampled on key timeCode.
*/
static bool hasTimeSample(const pxr::UsdAttribute& attribute, pxr::UsdTimeCode timeCode)
{
if (timeCode.IsDefault())
return false;
std::vector<double> times;
if (attribute.GetTimeSamples(×))
{
double timeCodeValue = timeCode.GetValue();
if (round(timeCodeValue) != timeCode.GetValue())
{
CARB_LOG_WARN("Error : Try to identify attribute %s has time sample on a fractinal key frame %f",
attribute.GetPath().GetText(), timeCodeValue);
return false;
}
return std::find(times.begin(), times.end(), timeCodeValue) != times.end();
}
return false;
}
/**
* Gets current UsdTimeCode of given stage.
*
* @param stage The stage to get time code from.
* @param isTimeSampled If the property is timesampled.
* @param time Current timecode.
* @return Current timecode of the stage.
*/
static pxr::UsdTimeCode getUsdTimeCode(pxr::UsdStageWeakPtr stage, bool isTimeSampled, pxr::UsdTimeCode time)
{
return isTimeSampled ? time : pxr::UsdTimeCode::Default();
}
/**
* Removes a prim from stage.
*
* @param prim The prim instance to be removed.
* @return True if prim is removed successfully.
*/
static bool removePrim(pxr::UsdPrim& prim)
{
auto stage = prim.GetStage();
bool ret = false;
if (checkAncestral(prim))
{
CARB_LOG_ERROR("Cannot remove ancestral prim %s", prim.GetPath().GetText());
return false;
}
pxr::SdfChangeBlock changeBlock;
if (stage->HasDefaultPrim() && stage->GetDefaultPrim() == prim)
{
stage->ClearDefaultPrim();
}
auto layerStack = stage->GetLayerStack();
std::set<pxr::SdfLayerHandle> layerSet(layerStack.begin(), layerStack.end());
auto primStack = prim.GetPrimStack();
for (auto&& primSpec : primStack)
{
auto layer = primSpec->GetLayer();
// Only remove from layers in the stage
if (layerSet.find(layer) == layerSet.end() || primSpec->GetPath() != prim.GetPath())
{
continue;
}
pxr::SdfBatchNamespaceEdit nsEdits;
nsEdits.Add(pxr::SdfNamespaceEdit::Remove(primSpec->GetPath()));
ret |= layer->Apply(nsEdits);
}
return ret;
}
/**
* Removes a prim from layer
*
* @param prim The prim instance to be removed.
* @param layer Layer from which to remove prim
* @return True if prim is removed successfully.
*/
static bool removePrimFromLayer(pxr::UsdPrim& prim, pxr::SdfLayerHandle layer)
{
auto stage = prim.GetStage();
if (checkAncestral(prim))
{
CARB_LOG_ERROR("Cannot remove ancestral prim %s", prim.GetPath().GetText());
return false;
}
pxr::SdfChangeBlock changeBlock;
if (stage->HasDefaultPrim() && stage->GetDefaultPrim() == prim)
{
stage->ClearDefaultPrim();
}
auto primSpec = layer->GetPrimAtPath(prim.GetPath());
auto parent = primSpec->GetNameParent();
if (!parent)
{
parent = layer->GetPseudoRoot();
}
return parent->RemoveNameChild(primSpec);
}
/**
* Copies a prim in the stage.
*
* @param prim The prim to be copied.
* @param tarPath The target path of copied prim, or nullptr if you want a auto generated path (e.g. "foo" ->
* "foo_2").
* @param defOrRefOnly True to only copy the layer that defines or references the Prim. False copy deltas on all
* layers. @p defOrRefOnly has no effect if @p combineAllLayers is true.
* @param combineAllLayers True to combine deltas on all layers and make a consolidated copy on current edit layer.
* False to copy each delta on their own layer.
* @return The copied prim. Call IsValid on the return value to check if copy is successful.
*/
static PXR_NS::UsdPrim copyPrim(PXR_NS::UsdPrim& prim, const char* tarPath, bool defOrRefOnly, bool combineAllLayers)
{
PXR_NS::UsdPrim ret;
auto stage = prim.GetStage();
std::string tarPathStr;
if (tarPath)
{
tarPathStr = tarPath;
}
else
{
tarPathStr = findNextNoneExisitingNodePath(stage, prim.GetPath().GetString(), false);
}
PXR_NS::SdfPath srcPath(prim.GetPath());
PXR_NS::SdfPath dstPath(tarPathStr);
if (!combineAllLayers)
{
PXR_NS::SdfChangeBlock changeBlock;
auto layers = prim.GetStage()->GetLayerStack();
for (const auto& layer : layers)
{
auto oldPrimSpec = layer->GetPrimAtPath(srcPath);
if (oldPrimSpec)
{
PXR_NS::SdfLayerHandle dstLayer = layer;
if (!defOrRefOnly)
{
dstLayer = stage->GetEditTarget().GetLayer();
}
if (defOrRefOnly || (!defOrRefOnly && oldPrimSpec->HasReferences()) ||
oldPrimSpec->GetSpecifier() == PXR_NS::SdfSpecifier::SdfSpecifierDef)
{
PXR_NS::SdfCreatePrimInLayer(dstLayer, dstPath);
PXR_NS::SdfCopySpec(layer, srcPath, dstLayer, dstPath);
if (!defOrRefOnly)
{
break;
}
}
}
}
}
else // Combine all prim spec from all visible layers and copy to current edit target
{
auto editTargetLayerHandle = stage->GetEditTarget().GetLayer();
// Make a temporary stage to hold the Prim to copy, and flatten it later
auto flattenStage = PXR_NS::UsdStage::CreateInMemory();
PXR_NS::SdfPrimSpecHandleVector primSpecs;
// If the prim is introduced by its ancestor, its primSpec might now exist in current stage (if no "over" is
// made to it) we need to copy from its primStack
if (checkAncestral(prim))
{
primSpecs = prim.GetPrimStack();
}
else
{
for (auto& layer : prim.GetStage()->GetLayerStack())
{
auto primSpec = layer->GetPrimAtPath(prim.GetPath());
if (primSpec)
{
primSpecs.push_back(primSpec);
}
}
}
for (const auto& primSpec : primSpecs)
{
auto srcLayer = primSpec->GetLayer();
PXR_NS::SdfLayerRefPtr dstLayer = nullptr;
if (srcLayer->IsAnonymous())
{
// If src layer is Anonymous, all relative path has been converted to absolute path.
dstLayer = PXR_NS::SdfLayer::CreateAnonymous();
}
else
{
// If src layer is not Anonymous, we need to create a layer at the same parent dir so
// relative path can be resolved.
carb::extras::Path layerPath(srcLayer->GetRealPath());
size_t counter = 0;
while (!dstLayer)
{
std::string tempFileName = layerPath.getParent() / layerPath.getStem() +
std::to_string(counter++) + layerPath.getExtension();
// Make sure we create a none-exist temp layer
if (PXR_NS::SdfLayer::FindOrOpen(tempFileName))
{
continue;
}
auto format = PXR_NS::SdfFileFormat::FindByExtension(layerPath.getExtension());
// Use PXR_NS::SdfLayer::New instead of PXR_NS::SdfLayer::CreateNew so no file is created
dstLayer = PXR_NS::SdfLayer::New(format, tempFileName);
}
}
PXR_NS::SdfCreatePrimInLayer(dstLayer, srcPath);
PXR_NS::SdfCopySpec(srcLayer, primSpec->GetPath(), dstLayer, srcPath);
flattenStage->GetRootLayer()->InsertSubLayerPath(dstLayer->GetIdentifier());
}
auto flattenLayer = flattenStage->Flatten();
PXR_NS::SdfCopySpec(flattenLayer, srcPath, editTargetLayerHandle, dstPath);
}
prim = stage->GetPrimAtPath(dstPath);
return prim;
}
/**
* Resolve all prim path reference to use new path. This is mainly used to remapping
* prim path reference after structure change of original prim.
* @param layer Layer to resolve.
* @param oldPath Old prim path.
* @param newPath New prim path that all old prim path references will be resolved to.
*/
static void resolvePrimPathReferences(const PXR_NS::SdfLayerRefPtr& layer,
const PXR_NS::SdfPath& oldPath, const PXR_NS::SdfPath& newPath)
{
static auto updatePrimPathRef = [](const PXR_NS::SdfPrimSpecHandle& primSpec, const PXR_NS::SdfPath& oldPath, const PXR_NS::SdfPath& newPath)
{
auto modifyItemEditsCallback = [&oldPath, &newPath](const PXR_NS::SdfPath& path)
{
return path.ReplacePrefix(oldPath, newPath);
};
auto modifyItemReferencesCallback = [&oldPath, &newPath](const PXR_NS::SdfReference& reference)
{
PXR_NS::SdfPath primPath;
if (reference.GetAssetPath().empty())
{
primPath = reference.GetPrimPath().ReplacePrefix(oldPath, newPath);
}
else
{
primPath = reference.GetPrimPath();
}
return PXR_NS::SdfReference(
reference.GetAssetPath(),
primPath,
reference.GetLayerOffset(),
reference.GetCustomData()
);
};
// Update relationships
for (const auto& relationship : primSpec->GetRelationships())
{
relationship->GetTargetPathList().ModifyItemEdits(modifyItemEditsCallback);
}
// Update connections
for (const auto& attribute : primSpec->GetAttributes())
{
attribute->GetConnectionPathList().ModifyItemEdits(modifyItemEditsCallback);
}
primSpec->GetReferenceList().ModifyItemEdits(modifyItemReferencesCallback);
};
auto onPrimSpecPath = [&layer, &oldPath, &newPath](const PXR_NS::SdfPath& primPath)
{
if (primPath.IsPropertyPath() || primPath == PXR_NS::SdfPath::AbsoluteRootPath())
{
return;
}
auto primSpec = layer->GetPrimAtPath(primPath);
if (primSpec)
{
updatePrimPathRef(primSpec, oldPath, newPath);
}
};
layer->Traverse(PXR_NS::SdfPath::AbsoluteRootPath(), onPrimSpecPath);
}
/**
* Moves a prim to a new path.
*
* @param prim The prim to be moved.
* @param newPath The new path to move prim to.
* @param supportNamespaceEdit false if (omni::usd::UsdContext::getContext()->isStageLive() &&
* strncmp(realPath.c_str(), "omniverse:", 10) == 0 && pxr::SdfFileFormat::GetFileExtension(realPath) != "usdov")
* @return True if Prim is moved successfully.
*/
static bool movePrim(pxr::UsdPrim& prim, const char* newPath, bool supportNamespaceEdit)
{
if (!prim)
{
return false;
}
if (checkAncestral(prim))
{
CARB_LOG_ERROR("Cannot remove ancestral prim %s", prim.GetPath().GetText());
return false;
}
auto stage = prim.GetStage();
const char* oldPath = prim.GetPath().GetText();
// If src and target path are the same, don't move.
if (strcmp(newPath, oldPath) == 0)
{
return false;
}
bool wasDefaultPrim = stage->GetDefaultPrim() == prim;
auto newPathStr = findNextNoneExisitingNodePath(prim.GetStage(), newPath, false);
if (!pxr::SdfPath::IsValidPathString(newPathStr))
{
return false;
}
pxr::SdfPath newSdfPath(newPathStr);
pxr::TfToken newName = newSdfPath.GetNameToken();
pxr::SdfPath newParentPath = newSdfPath.GetParentPath();
pxr::SdfPath oldSdfPath = prim.GetPath();
pxr::TfToken oldName = prim.GetName();
pxr::SdfPath oldParentPath = prim.GetParent().GetPath();
auto layerStack = stage->GetLayerStack();
std::set<pxr::SdfLayerHandle> layerSet(layerStack.begin(), layerStack.end());
auto primStack = prim.GetPrimStack();
for (auto&& primSpec : primStack)
{
bool useNamespaceEdit = true;
auto layer = primSpec->GetLayer();
// Only remove from layers in the stage
if (layerSet.find(layer) == layerSet.end())
{
continue;
}
if (!supportNamespaceEdit)
{
CARB_LOG_WARN(
"Current USD format doesn't support NamespaceEdit to move/rename prim, fallback to copy/delete");
useNamespaceEdit = false;
}
if (useNamespaceEdit)
{
pxr::SdfBatchNamespaceEdit nsEdits;
if (oldParentPath == newParentPath)
{
CARB_LOG_INFO("Rename %s to %s", oldSdfPath.GetText(),
(oldSdfPath.GetParentPath().AppendChild(newName)).GetText());
nsEdits.Add(pxr::SdfNamespaceEdit::Rename(oldSdfPath, newName));
}
else
{
// SdfNamespaceEdit::Reparent somehow doesn't work for move without renaming
CARB_LOG_INFO("Move %s to %s", oldSdfPath.GetText(), (newParentPath.AppendChild(newName)).GetText());
nsEdits.Add(pxr::SdfNamespaceEdit::ReparentAndRename(
primSpec->GetPath(), newParentPath, newName, pxr::SdfNamespaceEdit::AtEnd));
}
layer->Apply(nsEdits);
}
else
{
if (pxr::SdfCreatePrimInLayer(layer, newSdfPath))
{
if (pxr::SdfCopySpec(layer, oldSdfPath, layer, newSdfPath))
{
pxr::SdfBatchNamespaceEdit nsEdits;
nsEdits.Add(pxr::SdfNamespaceEdit::Remove(oldSdfPath));
layer->Apply(nsEdits);
}
}
}
auto newPrim = layer->GetPrimAtPath(newSdfPath);
if (newPrim)
{
// Fixup connections and relationships
resolvePrimPathReferences(layer, prim.GetPrimPath(), newSdfPath);
}
}
auto newPrim = stage->GetPrimAtPath(newSdfPath);
if (newPrim)
{
// Restore defaultPrim state
if (wasDefaultPrim && newPrim.GetParent() == stage->GetPseudoRoot())
{
stage->SetDefaultPrim(newPrim);
}
}
return newPrim.IsValid();
}
/**
* Creates a prim on given stage.
*
* @param stage The stage to create prim on.
* @param path The path to create prim at.
* @param onCreateFn The creating function for the prim.
* @param prependDefaultPrimPath Whether to prepend defaultPrim path to Prim path. True to put the prim under
* defaultPrim path.
* @return The created prim. Call IsValid on the return value to check if creation is successful.
*/
static pxr::UsdPrim createPrim(pxr::UsdStageWeakPtr stage,
const char* path,
OnCreateFn onCreateFn,
bool prependDefaultPrimPath = true)
{
std::string newPath = findNextNoneExisitingNodePath(stage, path, prependDefaultPrimPath);
return onCreateFn(stage, pxr::SdfPath(newPath));
}
/**
* Creates a prim on given stage.
*
* @param stage The stage to create prim on.
* @param path The path to create prim at.
* @param typeName The type name of the prim.
* @param prependDefaultPrimPath Whether to prepend defaultPrim path to Prim path. True to put the prim under
* defaultPrim path.
* @return The created prim. Call IsValid on the return value to check if creation is successful.
*/
static pxr::UsdPrim createPrim(pxr::UsdStageWeakPtr stage,
const char* path,
const char* typeName,
bool prependDefaultPrimPath = true)
{
std::string newPath = findNextNoneExisitingNodePath(stage, path, prependDefaultPrimPath);
return stage->DefinePrim(pxr::SdfPath(newPath), pxr::TfToken(typeName));
}
/**
* Returns if a prim exists at given path.
*
* @param stage The stage to check prim existence.
* @param path The prim path
* @param prependDefaultPrimPath Whether to check under defaultPrim path or stage root.
*/
static bool hasPrimAtPath(pxr::UsdStageWeakPtr stage, std::string path, bool prependDefaultPrimPath = true)
{
if (prependDefaultPrimPath && stage->HasDefaultPrim())
{
path = stage->GetDefaultPrim().GetPath().GetString() + path;
}
return stage->GetPrimAtPath(pxr::SdfPath(path)).IsValid();
}
/**
* Gets if a prim is visible.
*
* @param prim The prim to get visibility from.
* @param prim The visibility of the prim's parent.
* @param time Current timecode.
* @return True if prim is visible.
*/
static bool isPrimVisible(const pxr::UsdPrim& prim, pxr::UsdTimeCode time = pxr::UsdTimeCode::Default())
{
pxr::UsdGeomImageable imageable(prim);
auto visibilityAttr = imageable.GetVisibilityAttr();
auto visibility = imageable.ComputeVisibility(time);
return visibility != pxr::UsdGeomTokens->invisible;
}
/**
* Sets the visibility on a prim.
*
* @param prim The prim to set visibility.
* @param visible True to make a prim visible. False to hide it.
* @param time Current timecode.
*/
static void setPrimVisibility(pxr::UsdPrim prim, bool visible, pxr::UsdTimeCode time = pxr::UsdTimeCode::Default())
{
pxr::UsdGeomImageable imageable(prim);
auto visibilityAttr = imageable.GetVisibilityAttr();
visibilityAttr.Set(visible ? pxr::UsdGeomTokens->inherited : pxr::UsdGeomTokens->invisible, time);
}
/**
* Gets if prim have transforms at key time_code.
*
* @param The prim to check transform sequence.
* @param time Current timecode.
* @return if prim has transform at time_code
*/
// TODO : Need more tweak on each kinds of transformop after timesample authoring support all kinds of transformop
static bool getPrimHasTransformAtKey(const pxr::UsdPrim& prim,
pxr::UsdTimeCode time_code = pxr::UsdTimeCode::Default())
{
pxr::UsdGeomXformable xform(prim);
bool resetXFormStack;
auto xformOps = xform.GetOrderedXformOps(&resetXFormStack);
if (time_code.IsDefault())
{
return false;
}
for (auto xformOp : xformOps)
{
std::vector<double> times;
if (xformOp.GetTimeSamples(×))
{
if (std::find(times.begin(), times.end(), time_code.GetValue()) != times.end())
{
return true;
}
}
}
return false;
}
/**
* Gets local transform matrix of a prim.
*
* @param prim The prim to get local transform matrix from.
* @param time Current timecode.
* @return The local transform matrix.
*/
static pxr::GfMatrix4d getLocalTransformMatrix(const pxr::UsdPrim& prim,
pxr::UsdTimeCode time = pxr::UsdTimeCode::Default())
{
bool resetXformStack = false;
pxr::UsdGeomXformable xform(prim);
pxr::GfMatrix4d mat;
xform.GetLocalTransformation(&mat, &resetXformStack, time);
return mat;
}
/**
* Gets GfRotation from XformOp that is UsdGeomXformOp::TypeOrient.
* It is caller's responsibility to pass the xformOp with correct type.
*
* @param xformOp The UsdGeomXformOp to get rotation from. It must be of type UsdGeomXformOp::TypeOrient.
* @param time The timecode to get value from.
* @return GfRotation of the xformOp. The value is set to identity if failed to fetch from xformOp (mismatched type or undefined value).
*/
template <typename QuatT>
static PXR_NS::GfRotation getRotationFromXformOpOrient(const PXR_NS::UsdGeomXformOp& xformOp,
const PXR_NS::UsdTimeCode& time)
{
QuatT quat;
if (xformOp.Get<QuatT>(&quat, time))
{
return PXR_NS::GfRotation(quat);
}
return PXR_NS::GfRotation({ 1, 0, 0 }, 0);
}
/**
* Gets local transform if applied in scale, rotation, translation order.
*
* Depending on the xformOpOrder of the prim, the returned value may not be identical to the final local
* transform. Only use this function on simple SRT xformOpOrder or matrix.
*
* @param prim The prim to get local transform matrix from.
* @param time translation to be written to.
* @param time rotation euler angle (in degree) to be written to.
* @param time rotation order to be written to.
* @param time scale to be written to.
* @param time Current timecode.
* @return true if operation succeed.
*/
static bool getLocalTransformSRT(const PXR_NS::UsdPrim& prim,
PXR_NS::GfVec3d& translation,
PXR_NS::GfVec3d& rotation,
PXR_NS::GfVec3i& rotationOrder,
PXR_NS::GfVec3d &scale, PXR_NS::UsdTimeCode time = pxr::UsdTimeCode::Default())
{
using namespace PXR_NS;
bool resetXformStack = false;
pxr::UsdGeomXformable xform(prim);
std::vector<UsdGeomXformOp> extraXformOps;
std::vector<UsdGeomXformOp> orderedXformOps = xform.GetOrderedXformOps(&resetXformStack);
bool seenScale = false;
uint32_t seenRotation = 0; // use a counter here, because euler angle can show up as individual xformOp.
bool seenAxes[3] = { false, false, false };
bool seenTranslation = false;
// default values
scale.Set(1.0, 1.0, 1.0);
rotation.Set(0.0, 0.0, 0.0);
rotationOrder.Set(-1, -1, -1); // placeholder
translation.Set(0.0, 0.0, 0.0);
for (auto it = orderedXformOps.rbegin(); it != orderedXformOps.rend(); ++it)
{
const UsdGeomXformOp& xformOp = *it;
if (xformOp.IsInverseOp())
{
continue;
}
// A.B.temp solution to unblock a showstopper for supporting unitsResolve suffix xformOp stacks
// for preop we need still full matrix computation for post op we can reconstruct at the end
static const TfToken kUnitsResolve = TfToken("unitsResolve");
if (xformOp.HasSuffix(kUnitsResolve))
{
if (xformOp == orderedXformOps[0])
{
GfMatrix4d mtx;
bool resetXformStack;
xform.GetLocalTransformation(&mtx, &resetXformStack, time);
pxr::GfMatrix4d rotMat(1.0);
pxr::GfMatrix4d scaleOrientMatUnused, perspMatUnused;
mtx.Factor(&scaleOrientMatUnused, &scale, &rotMat, &translation, &perspMatUnused);
// By default decompose as XYZ order (make it an option?)
GfVec3d decompRot =
rotMat.ExtractRotation().Decompose(GfVec3d::ZAxis(), GfVec3d::YAxis(), GfVec3d::XAxis());
rotation = { decompRot[2], decompRot[1], decompRot[0] };
rotationOrder = { 0, 1, 2 };
return true;
}
else
{
extraXformOps.push_back(xformOp);
}
continue;
}
const UsdGeomXformOp::Type opType = xformOp.GetOpType();
const UsdGeomXformOp::Precision precision = xformOp.GetPrecision();
if (opType == UsdGeomXformOp::TypeTransform)
{
seenScale = true;
seenRotation = 3;
seenTranslation = true;
GfMatrix4d mtx = xformOp.GetOpTransform(time);
pxr::GfMatrix4d rotMat(1.0);
pxr::GfMatrix4d scaleOrientMatUnused, perspMatUnused;
mtx.Factor(&scaleOrientMatUnused, &scale, &rotMat, &translation, &perspMatUnused);
// By default decompose as XYZ order (make it an option?)
GfVec3d decompRot =
rotMat.ExtractRotation().Decompose(GfVec3d::ZAxis(), GfVec3d::YAxis(), GfVec3d::XAxis());
rotation = { decompRot[2], decompRot[1], decompRot[0] };
rotationOrder = { 0, 1, 2 };
break;
}
if (!seenScale)
{
if (opType == UsdGeomXformOp::TypeScale)
{
if (seenRotation || seenTranslation)
{
CARB_LOG_WARN("Incompatible xformOpOrder, rotation or translation applied before scale.");
}
seenScale = true;
xformOp.GetAs<>(&scale, time);
}
}
if (seenRotation != 3)
{
if (opType >= UsdGeomXformOp::TypeRotateXYZ && opType <= UsdGeomXformOp::TypeRotateZYX)
{
if (seenTranslation || seenRotation != 0)
{
CARB_LOG_WARN("Incompatible xformOpOrder, translation applied before rotation or too many rotation ops.");
}
seenRotation = 3;
xformOp.GetAs<>(&rotation, time);
static const GfVec3i kRotationOrder[] = {
{ 0, 1, 2 }, // XYZ
{ 0, 2, 1 }, // XZY
{ 1, 0, 2 }, // YXZ
{ 1, 2, 0 }, // YZX
{ 2, 0, 1 }, // ZXY
{ 2, 1, 0 }, // ZYX
};
rotationOrder = kRotationOrder[opType - UsdGeomXformOp::TypeRotateXYZ];
}
else if (opType >= UsdGeomXformOp::TypeRotateX && opType <= UsdGeomXformOp::TypeRotateZ)
{
if (seenTranslation || seenRotation > 3)
{
CARB_LOG_WARN("Incompatible xformOpOrder, too many single axis rotation ops.");
}
// Set rotation order based on individual axis order
rotationOrder[seenRotation++] = opType - UsdGeomXformOp::TypeRotateX;
seenAxes[opType - UsdGeomXformOp::TypeRotateX] = true;
double angle = 0.0;
xformOp.GetAs<>(&angle, time);
rotation[opType - UsdGeomXformOp::TypeRotateX] = angle;
}
else if (opType == UsdGeomXformOp::TypeOrient)
{
if (seenTranslation || seenRotation != 0)
{
CARB_LOG_WARN("Incompatible xformOpOrder, translation applied before rotation or too many rotation ops.");
}
seenRotation = 3;
GfRotation rot;
// GetAs cannot convert between Quath, Quatf and Quatd
switch (precision)
{
case PXR_NS::UsdGeomXformOp::PrecisionHalf:
{
rot = getRotationFromXformOpOrient<GfQuath>(xformOp, time);
break;
}
case PXR_NS::UsdGeomXformOp::PrecisionFloat:
{
rot = getRotationFromXformOpOrient<GfQuatf>(xformOp, time);
break;
}
case PXR_NS::UsdGeomXformOp::PrecisionDouble:
{
rot = getRotationFromXformOpOrient<GfQuatd>(xformOp, time);
break;
}
default:
break;
}
// By default decompose as XYZ order (make it an option?)
GfVec3d decompRot = rot.Decompose(GfVec3d::ZAxis(), GfVec3d::YAxis(), GfVec3d::XAxis());
rotation = { decompRot[2], decompRot[1], decompRot[0] };
rotationOrder = { 0, 1, 2 };
}
}
if (!seenTranslation)
{
// Do not get translation from pivot
if (opType == UsdGeomXformOp::TypeTranslate && !xformOp.HasSuffix(PXR_NS::TfToken("pivot")))
{
seenTranslation = true;
xformOp.GetAs<>(&translation, time);
}
}
}
if (seenRotation == 0)
{
// If we did not see any rotation op, get it from the preferences
static const std::unordered_map<std::string, PXR_NS::GfVec3i> s_orderMap{
{ "XYZ", { 0, 1, 2 } }, { "XZY", { 0, 2, 1 } }, { "YXZ", { 1, 0, 2 } },
{ "YZX", { 1, 2, 0 } }, { "ZXY", { 2, 0, 1 } }, { "ZYX", { 2, 1, 0 } },
};
PXR_NS::GfVec3i preferredDefaultRotationOrder = { 0, 1, 2 }; // fallback
const char* orderStr =
carb::getCachedInterface<carb::settings::ISettings>()->getStringBuffer(kDefaultRotationOrderSettingPath);
const auto orderEntry = s_orderMap.find(orderStr);
if (orderEntry != s_orderMap.end())
{
preferredDefaultRotationOrder = orderEntry->second;
}
rotationOrder = preferredDefaultRotationOrder;
seenRotation = 3;
}
else
{
// Assign rotation order to missing rotation ops after existing rotation ops
for (size_t i = 0; i < 3; i++)
{
int32_t& order = rotationOrder[i];
if (order == -1)
{
for (int32_t j = 0; j < 3; j++)
{
if (!seenAxes[j])
{
order = j;
seenAxes[j] = true;
break;
}
}
}
}
}
// A.B. this is a known transformation, we have a rotateX + -90 and scale
// we can just add the X euler rotation and swap the scale Y, Z axis, this should represent the additonal transformation
if (!extraXformOps.empty())
{
for (const UsdGeomXformOp& extraOp : extraXformOps)
{
if (extraOp.GetOpType() == UsdGeomXformOp::Type::TypeScale)
{
PXR_NS::GfVec3d scaleValue;
extraOp.GetAs<>(&scaleValue, time);
scale = PXR_NS::GfCompMult(scale, scaleValue);
}
else if (extraOp.GetOpType() == UsdGeomXformOp::Type::TypeRotateX)
{
double rotValue;
extraOp.GetAs<>(&rotValue, time);
if (PXR_NS::GfIsClose(abs(rotValue), 90.0, 0.01))
{
rotation[0] = rotation[0] + rotValue;
std::swap(scale[1], scale[2]);
}
else
{
CARB_LOG_WARN(
"UnitsResolve rotateX supports only +-90 degree on prim: %s", prim.GetPrimPath().GetText());
}
}
}
}
return true;
}
/**
* Gets the inversed pivot transform matrix of a prim.
*
* @param prim The prim to get inversed pivot transform matrix from.
* @param time Current timecode.
* @return The inversed pivot transform matrix. If prim has no pivot, identity matrix will be returned.
*/
static pxr::GfMatrix4d getLocalTransformPivotInv(const pxr::UsdPrim& prim,
pxr::UsdTimeCode time = pxr::UsdTimeCode::Default())
{
pxr::UsdGeomXformable xform(prim);
bool resetXFormStack;
auto xformOps = xform.GetOrderedXformOps(&resetXFormStack);
// potential pivot inv node
if (xformOps.size())
{
auto pivotOpInv = xformOps.back();
if (pivotOpInv.GetOpType() == pxr::UsdGeomXformOp::Type::TypeTranslate &&
pivotOpInv.HasSuffix(pxr::TfToken("pivot")) && pivotOpInv.IsInverseOp())
{
return pivotOpInv.GetOpTransform(time);
}
}
// return an identity matrix if no pivot is found
return pxr::GfMatrix4d(1.f);
}
/**
* Gets world transform matrix of a prim.
*
* @param prim The prim to get world transform matrix from.
* @param time Current timecode.
* @return The world transform matrix.
*/
static pxr::GfMatrix4d getWorldTransformMatrix(const pxr::UsdPrim& prim,
pxr::UsdTimeCode time = pxr::UsdTimeCode::Default())
{
pxr::UsdGeomXformable xform(prim);
return xform.ComputeLocalToWorldTransform(time);
}
/**
* Given a target local transform matrix for a prim, determine what value to set just
* the transformOp when other xformOps are present.
*
* @param prim The prim in question
* @param mtx The desired final transform matrix for the prim including all ops
* @param foundTransformOp returns true if there is a transform xformOp
*/
static pxr::GfMatrix4d findInnerTransform(pxr::UsdPrim prim,
const pxr::GfMatrix4d& mtx,
bool& foundTransformOp,
pxr::UsdTimeCode timecode = pxr::UsdTimeCode::Default(),
bool skipEqualSetForTimeSample = false)
{
pxr::UsdGeomXformable xform(prim);
bool resetXFormStack;
auto xformOps = xform.GetOrderedXformOps(&resetXFormStack);
foundTransformOp = false;
bool foundOtherOps = false;
pxr::GfMatrix4d preTransform = pxr::GfMatrix4d(1.);
pxr::GfMatrix4d postTransform = pxr::GfMatrix4d(1.);
for (auto xformOp : xformOps)
{
if (!foundTransformOp && xformOp.GetOpType() == pxr::UsdGeomXformOp::TypeTransform)
{
foundTransformOp = true;
}
else
{
bool isInverseOp = false;
pxr::UsdGeomXformOp op(xformOp.GetAttr(), isInverseOp);
if (op)
{
static const PXR_NS::TfToken kPivotSuffix("pivot");
if (op.HasSuffix(kPivotSuffix))
{
continue;
}
// possibly check for identity and skip multiplication
auto opTransform = op.GetOpTransform(timecode);
if (foundTransformOp)
{
preTransform = opTransform * preTransform;
}
else
{
postTransform = opTransform * postTransform;
}
foundOtherOps = true;
}
}
}
if (foundTransformOp && foundOtherOps)
{
return preTransform.GetInverse() * mtx * postTransform.GetInverse();
}
return mtx;
}
/**
* Sets local transform matrix of a prim.
*
* @param prim The prim to set local transform matrix to.
* @param mtx The local transform matrix.
*/
static bool setLocalTransformMatrix(pxr::UsdPrim prim,
const pxr::GfMatrix4d& mtxIn,
pxr::UsdTimeCode timecode = pxr::UsdTimeCode::Default(),
bool skipEqualSetForTimeSample = false,
std::unique_ptr<PXR_NS::SdfChangeBlock>* parentChangeBlock = nullptr)
{
// If prim is defined in session layer, we author in session layer.
std::unique_ptr<PXR_NS::UsdEditContext> editCtx;
auto mightDefOnSessionLayer = getLayerIfDefOnSessionOrItsSublayers(prim.GetStage(), prim.GetPath());
if (mightDefOnSessionLayer)
{
editCtx = std::make_unique<PXR_NS::UsdEditContext>(prim.GetStage(), mightDefOnSessionLayer);
}
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
bool fastUpdates = settings->getAsBool(kAuthorXformsWithFastUpdatesSettingPath);
std::unique_ptr<PXR_NS::SdfChangeBlock> localChangeBlock;
std::unique_ptr<PXR_NS::SdfChangeBlock>& changeBlock =
(parentChangeBlock != nullptr) ? *parentChangeBlock : localChangeBlock;
if (!changeBlock.get())
{
// https://github.com/PixarAnimationStudios/USD/commit/5e38b2aac0693fcf441a607165346e42cd625b59
// fastUpdates have long been deprecated, and will be removed from the API
// in nv-usd 22.05, as they not conflict with the "enabled" parameter
// added by Pixar in USD v22.03
changeBlock.reset(new PXR_NS::SdfChangeBlock());
}
pxr::UsdGeomXformable xform(prim);
bool resetXFormStack;
auto xformOps = xform.GetOrderedXformOps(&resetXFormStack);
PXR_NS::VtTokenArray xformOpOrders;
xform.GetXformOpOrderAttr().Get(&xformOpOrders);
bool foundTransformOp = false;
PXR_NS::UsdGeomXformOp transformOp;
bool success = true;
pxr::GfMatrix4d mtx = mtxIn;
const pxr::GfMatrix4d innerMtx =
findInnerTransform(prim, mtx, foundTransformOp, timecode, skipEqualSetForTimeSample);
for (auto xformOp : xformOps)
{
// Found transform op, trying to set its value
if (xformOp.GetOpType() == pxr::UsdGeomXformOp::TypeTransform)
{
foundTransformOp = true;
success &= UsdUtils::setAttribute(xformOp.GetAttr(), innerMtx, timecode, skipEqualSetForTimeSample);
}
}
// If transformOp is not found, make individual xformOp or reuse old ones.
if (!foundTransformOp)
{
// A.B.temp solution to unblock a showstopper for supporting unitsResolve suffix xformOp stacks
static const PXR_NS::TfToken kUnitsResolve = PXR_NS::TfToken("unitsResolve");
bool preTransformStack = false;
std::vector<PXR_NS::UsdGeomXformOp> extraXformOps;
for (auto& xformOp : xformOps)
{
if (xformOp.HasSuffix(kUnitsResolve))
{
extraXformOps.push_back(xformOp);
if (xformOp == xformOps[0])
{
preTransformStack = true;
}
}
}
// A.B.temp solution to unblock a showstopper for supporting unitsResolve suffix xformOp stacks
// reconstruct the values back after modifying the incoming transform
if (!extraXformOps.empty())
{
PXR_NS::GfMatrix4d extraTransform(1.0);
for (auto& extraOp : extraXformOps)
{
extraTransform *= extraOp.GetOpTransform(timecode);
}
const PXR_NS::GfMatrix4d extraTransformInv = extraTransform.GetInverse();
if (preTransformStack)
{
mtx = mtx * extraTransformInv;
}
else
{
mtx = extraTransformInv * mtx;
}
}
pxr::GfVec3d translation;
pxr::GfMatrix4d rotMat(1.0);
pxr::GfVec3d doubleScale(1.0);
pxr::GfMatrix4d scaleOrientMatUnused, perspMatUnused;
mtx.Factor(&scaleOrientMatUnused, &doubleScale, &rotMat, &translation, &perspMatUnused);
rotMat.Orthonormalize(false);
pxr::GfRotation rotation = rotMat.ExtractRotation();
// Don't use UsdGeomXformCommonAPI. It can only manipulate a very limited subset of xformOpOrder
// combinations Do it manually as non-destructively as possible
pxr::UsdGeomXformOp xformOp;
std::vector<pxr::UsdGeomXformOp> newXformOps;
if (!extraXformOps.empty() && preTransformStack)
{
for (auto& copyXformOp : extraXformOps)
{
newXformOps.push_back(copyXformOp);
}
}
auto findOrAdd = [&xformOps, &xformOpOrders, &xform, &changeBlock, &fastUpdates](
pxr::UsdGeomXformOp::Type xformOpType, pxr::UsdGeomXformOp& outXformOp,
bool createIfNotExist, pxr::UsdGeomXformOp::Precision& precision,
pxr::TfToken const& opSuffix = pxr::TfToken()) {
for (auto xformOp : xformOps)
{
if (xformOp.GetOpType() == xformOpType)
{
// To differentiate translate and translate:pivot
const pxr::TfToken expectedOpName = pxr::UsdGeomXformOp::GetOpName(xformOpType, opSuffix);
const pxr::TfToken opName = xformOp.GetOpName();
if (opName == expectedOpName)
{
precision = xformOp.GetPrecision();
outXformOp = xformOp;
return true;
}
}
}
if (createIfNotExist)
{
// It is not safe to create new xformOps inside of SdfChangeBlocks, since
// new attribute creation via anything above Sdf API requires the PcpCache
// to be up to date. Flush the current change block before creating
// the new xformOp.
changeBlock.reset(nullptr);
if (std::find(xformOpOrders.begin(), xformOpOrders.end(),
pxr::UsdGeomXformOp::GetOpName(xformOpType, opSuffix)) == xformOpOrders.end())
outXformOp = xform.AddXformOp(xformOpType, precision, opSuffix);
else
{
// Sometimes XformOp attributes and XformOpOrder don't match. GetOrderedXformOps() considers both XformOp attributes and XformOpOrder. But AddXformOp() considers only XformOpOrder. So we need to fix it here.
auto opAttr = xform.GetPrim().CreateAttribute(
pxr::UsdGeomXformOp::GetOpName(xformOpType, opSuffix),
pxr::UsdGeomXformOp::GetValueTypeName(xformOpType, precision), false);
outXformOp = pxr::UsdGeomXformOp(opAttr);
}
// Create a new change block to batch the subsequent authoring operations
// where possible.
changeBlock.reset(new PXR_NS::SdfChangeBlock());
// Creation may have failed for a variety of reasons (including instanceable=True)
return static_cast<bool>(outXformOp);
}
return false;
};
auto getFirstRotateOpType = [&xformOps](pxr::UsdGeomXformOp::Precision& precision) {
for (auto xformOp : xformOps)
{
if (xformOp.GetOpType() >= pxr::UsdGeomXformOp::Type::TypeRotateX &&
xformOp.GetOpType() <= pxr::UsdGeomXformOp::Type::TypeOrient &&
!xformOp.HasSuffix(kUnitsResolve))
{
precision = xformOp.GetPrecision();
return xformOp.GetOpType();
}
}
return pxr::UsdGeomXformOp::Type::TypeInvalid;
};
auto decomposeAndSetValue = [&rotation, &findOrAdd, &newXformOps](
pxr::UsdGeomXformOp::Type rotationType, const pxr::GfVec3d& axis0,
const pxr::GfVec3d& axis1, const pxr::GfVec3d& axis2, size_t xIndex,
size_t yIndex, size_t zIndex, pxr::UsdGeomXformOp::Precision precision,
pxr::UsdTimeCode timecode, bool skipEqualSetForTimeSample) {
bool ret = false;
pxr::GfVec3d angles = rotation.Decompose(axis0, axis1, axis2);
pxr::GfVec3d rotate = { angles[xIndex], angles[yIndex], angles[zIndex] };
pxr::UsdGeomXformOp xformOp;
if (findOrAdd(rotationType, xformOp, true, precision))
{
ret = setValueWithPrecision<pxr::GfVec3h, pxr::GfVec3f, pxr::GfVec3d, pxr::GfVec3d>(
xformOp, rotate, timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
return ret;
};
// Set translation
pxr::UsdGeomXformOp::Precision precision = pxr::UsdGeomXformOp::PrecisionDouble;
if (findOrAdd(pxr::UsdGeomXformOp::TypeTranslate, xformOp, true, precision))
{
success &= setValueWithPrecision<pxr::GfVec3h, pxr::GfVec3f, pxr::GfVec3d, pxr::GfVec3d>(
xformOp, translation, timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
// Set pivot
static const pxr::TfToken kPivot = pxr::TfToken("pivot");
precision = pxr::UsdGeomXformOp::PrecisionFloat;
pxr::UsdGeomXformOp pivotOp;
pxr::UsdGeomXformOp pivotOpInv;
pxr::GfVec3d pivotValue(0., 0., 0.);
const bool hasPivot =
findOrAdd(pxr::UsdGeomXformOp::TypeTranslate, pivotOp, false, precision, kPivot);
if (hasPivot)
{
newXformOps.push_back(pivotOp);
for (size_t k = xformOps.size(); k--;)
{
if (xformOps[k].IsInverseOp() && xformOps[k].HasSuffix(kPivot))
{
pivotOpInv = xformOps[k];
break;
}
}
}
// Set rotation
precision = pxr::UsdGeomXformOp::PrecisionFloat;
auto firstRotateOpType = getFirstRotateOpType(precision);
if (firstRotateOpType == pxr::UsdGeomXformOp::TypeInvalid)
{
static const std::unordered_map<std::string, PXR_NS::UsdGeomXformOp::Type> s_typeMap{
{ "XYZ", PXR_NS::UsdGeomXformOp::TypeRotateXYZ }, { "XZY", PXR_NS::UsdGeomXformOp::TypeRotateXZY },
{ "YXZ", PXR_NS::UsdGeomXformOp::TypeRotateYXZ }, { "YZX", PXR_NS::UsdGeomXformOp::TypeRotateYZX },
{ "ZXY", PXR_NS::UsdGeomXformOp::TypeRotateZXY }, { "ZYX", PXR_NS::UsdGeomXformOp::TypeRotateZYX },
};
firstRotateOpType = PXR_NS::UsdGeomXformOp::TypeRotateXYZ; // fallback
const char* orderStr = carb::getCachedInterface<carb::settings::ISettings>()->getStringBuffer(
kDefaultRotationOrderSettingPath);
const auto orderEntry = s_typeMap.find(orderStr);
if (orderEntry != s_typeMap.end())
{
firstRotateOpType = orderEntry->second;
}
}
switch (firstRotateOpType)
{
case pxr::UsdGeomXformOp::TypeRotateX:
case pxr::UsdGeomXformOp::TypeRotateY:
case pxr::UsdGeomXformOp::TypeRotateZ:
{
pxr::GfVec3d angles =
rotation.Decompose(pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis());
pxr::GfVec3d rotateZYX = { angles[2], angles[1], angles[0] };
if (findOrAdd(pxr::UsdGeomXformOp::TypeRotateZ, xformOp, true, precision))
{
success &= setValueWithPrecision<pxr::GfHalf, float, double, double>(
xformOp, rotateZYX[2], timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
if (findOrAdd(pxr::UsdGeomXformOp::TypeRotateY, xformOp, true, precision))
{
success &= setValueWithPrecision<pxr::GfHalf, float, double, double>(
xformOp, rotateZYX[1], timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
if (findOrAdd(pxr::UsdGeomXformOp::TypeRotateX, xformOp, true, precision))
{
success &= setValueWithPrecision<pxr::GfHalf, float, double, double>(
xformOp, rotateZYX[0], timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
break;
}
case pxr::UsdGeomXformOp::TypeRotateZYX:
success &= decomposeAndSetValue(firstRotateOpType, pxr::GfVec3d::XAxis(), pxr::GfVec3d::YAxis(),
pxr::GfVec3d::ZAxis(), 0, 1, 2, precision, timecode,
skipEqualSetForTimeSample);
break;
case pxr::UsdGeomXformOp::TypeRotateXZY:
success &= decomposeAndSetValue(firstRotateOpType, pxr::GfVec3d::YAxis(), pxr::GfVec3d::ZAxis(),
pxr::GfVec3d::XAxis(), 2, 0, 1, precision, timecode,
skipEqualSetForTimeSample);
break;
case pxr::UsdGeomXformOp::TypeRotateYXZ:
success &= decomposeAndSetValue(firstRotateOpType, pxr::GfVec3d::ZAxis(), pxr::GfVec3d::XAxis(),
pxr::GfVec3d::YAxis(), 1, 2, 0, precision, timecode,
skipEqualSetForTimeSample);
break;
case pxr::UsdGeomXformOp::TypeRotateYZX:
success &= decomposeAndSetValue(firstRotateOpType, pxr::GfVec3d::XAxis(), pxr::GfVec3d::ZAxis(),
pxr::GfVec3d::YAxis(), 0, 2, 1, precision, timecode,
skipEqualSetForTimeSample);
break;
case pxr::UsdGeomXformOp::TypeRotateZXY:
success &= decomposeAndSetValue(firstRotateOpType, pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis(),
pxr::GfVec3d::ZAxis(), 1, 0, 2, precision, timecode,
skipEqualSetForTimeSample);
break;
case pxr::UsdGeomXformOp::TypeOrient:
if (findOrAdd(pxr::UsdGeomXformOp::TypeOrient, xformOp, false, precision))
{
success &= setValueWithPrecision<pxr::GfQuath, pxr::GfQuatf, pxr::GfQuatd, pxr::GfQuatd>(
xformOp, rotation.GetQuat(), timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
break;
case pxr::UsdGeomXformOp::TypeRotateXYZ:
default:
success &= decomposeAndSetValue(pxr::UsdGeomXformOp::TypeRotateXYZ, pxr::GfVec3d::ZAxis(),
pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis(), 2, 1, 0, precision,
timecode, skipEqualSetForTimeSample);
break;
}
// Set scale
precision = pxr::UsdGeomXformOp::PrecisionFloat;
if (findOrAdd(pxr::UsdGeomXformOp::TypeScale, xformOp, true, precision))
{
success &= setValueWithPrecision<pxr::GfVec3h, pxr::GfVec3f, pxr::GfVec3d, pxr::GfVec3d>(
xformOp, doubleScale, timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
// Set extra ops from units resolve
if (!extraXformOps.empty() && !preTransformStack)
{
for (auto& copyXformOp : extraXformOps)
{
newXformOps.push_back(copyXformOp);
}
}
// Set inverse pivot
if (hasPivot && pivotOpInv)
{
// Assume the last xformOps is the pivot
newXformOps.push_back(pivotOpInv);
}
success &= xform.SetXformOpOrder(newXformOps, resetXFormStack);
}
return success;
}
static PXR_NS::GfMatrix4d constructTransformMatrixFromSRT(const PXR_NS::GfVec3d& translation,
const PXR_NS::GfVec3d& rotationEuler,
const PXR_NS::GfVec3i& rotationOrder,
const PXR_NS::GfVec3d& scale)
{
using namespace PXR_NS;
GfMatrix4d transMtx, rotMtx, scaleMtx;
transMtx.SetTranslate(translation);
static const GfVec3d kAxes[] = { GfVec3d::XAxis(), GfVec3d::YAxis(), GfVec3d::ZAxis() };
GfRotation rotation = GfRotation(kAxes[rotationOrder[0]], rotationEuler[rotationOrder[0]]) *
GfRotation(kAxes[rotationOrder[1]], rotationEuler[rotationOrder[1]]) *
GfRotation(kAxes[rotationOrder[2]], rotationEuler[rotationOrder[2]]);
rotMtx.SetRotate(rotation);
scaleMtx.SetScale(scale);
return scaleMtx * rotMtx * transMtx;
}
/**
* Sets local transform matrix of a prim.
*
* @param prim The prim to set local transform matrix to.
* @param mtx The local transform matrix.
*/
static bool setLocalTransformSRT(PXR_NS::UsdPrim prim,
const PXR_NS::GfVec3d& translationIn,
const PXR_NS::GfVec3d& rotationEulerIn,
const PXR_NS::GfVec3i& rotationOrder,
const PXR_NS::GfVec3d& scaleIn,
PXR_NS::UsdTimeCode timecode = PXR_NS::UsdTimeCode::Default(),
bool skipEqualSetForTimeSample = false,
std::unique_ptr<PXR_NS::SdfChangeBlock>* parentChangeBlock = nullptr)
{
using namespace PXR_NS;
// If prim is defined in session layer, we author in session layer.
std::unique_ptr<PXR_NS::UsdEditContext> editCtx;
auto mightDefOnSessionLayer = getLayerIfDefOnSessionOrItsSublayers(prim.GetStage(), prim.GetPath());
if (mightDefOnSessionLayer)
{
editCtx = std::make_unique<PXR_NS::UsdEditContext>(prim.GetStage(), mightDefOnSessionLayer);
}
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
bool fastUpdates = settings->getAsBool(kAuthorXformsWithFastUpdatesSettingPath);
std::unique_ptr<SdfChangeBlock> localChangeBlock;
std::unique_ptr<SdfChangeBlock>& changeBlock =
(parentChangeBlock != nullptr) ? *parentChangeBlock : localChangeBlock;
if (!changeBlock.get())
{
changeBlock.reset(new SdfChangeBlock());
}
UsdGeomXformable xform(prim);
bool resetXFormStack;
auto xformOps = xform.GetOrderedXformOps(&resetXFormStack);
PXR_NS::VtTokenArray xformOpOrders;
xform.GetXformOpOrderAttr().Get(&xformOpOrders);
bool foundTransformOp = false;
UsdGeomXformOp transformOp;
bool success = true;
PXR_NS::GfVec3d translation = translationIn;
PXR_NS::GfVec3d rotationEuler = rotationEulerIn;
PXR_NS::GfVec3d scale = scaleIn;
// A.B.temp solution to unblock a showstopper for supporting unitsResolve suffix xformOp stacks
static const TfToken kUnitsResolve = TfToken("unitsResolve");
bool preTransformStack = false;
std::vector<UsdGeomXformOp> extraXformOps;
for (auto& xformOp : xformOps)
{
// Found transform op, trying to set its value
if (xformOp.GetOpType() == UsdGeomXformOp::TypeTransform)
{
foundTransformOp = true;
transformOp = xformOp;
}
else if (xformOp.HasSuffix(kUnitsResolve))
{
extraXformOps.push_back(xformOp);
if (xformOp == xformOps[0])
{
preTransformStack = true;
}
}
}
// A.B.temp solution to unblock a showstopper for supporting unitsResolve suffix xformOp stacks
// reconstruct the values back after modifying the incoming transform
if (!extraXformOps.empty() && !foundTransformOp)
{
if (preTransformStack)
{
GfMatrix4d mtx = constructTransformMatrixFromSRT(translation, rotationEuler, rotationOrder, scale);
GfMatrix4d extraTransform(1.0);
for (auto& extraOp : extraXformOps)
{
extraTransform *= extraOp.GetOpTransform(timecode);
}
const GfMatrix4d extraTransformInv = extraTransform.GetInverse();
mtx = mtx * extraTransformInv;
PXR_NS::GfVec3d translationNew;
PXR_NS::GfVec3d rotationNew;
PXR_NS::GfMatrix4d rotMat(1.0);
PXR_NS::GfVec3d scaleNew(1.0);
PXR_NS::GfMatrix4d scaleOrientMatUnused, perspMatUnused;
mtx.Factor(
&scaleOrientMatUnused, &scaleNew, &rotMat, &translationNew, &perspMatUnused);
static const PXR_NS::GfVec3d kAxis[] = { PXR_NS::GfVec3d::XAxis(), PXR_NS::GfVec3d::YAxis(),
PXR_NS::GfVec3d::ZAxis() };
auto decompRot = rotMat.ExtractRotation().Decompose(
kAxis[rotationOrder[2]], kAxis[rotationOrder[1]], kAxis[rotationOrder[0]]);
PXR_NS::GfVec3i indexOrder;
for (int32_t i = 0; i < 3; i++)
{
indexOrder[rotationOrder[i]] = 2 - i;
}
rotationNew[0] = decompRot[indexOrder[0]];
rotationNew[1] = decompRot[indexOrder[1]];
rotationNew[2] = decompRot[indexOrder[2]];
translation = translationNew;
rotationEuler = rotationNew;
scale = scaleNew;
}
else
{
// Post transform, we should know what to do
for (const UsdGeomXformOp& extraOp : extraXformOps)
{
if (extraOp.GetOpType() == UsdGeomXformOp::Type::TypeScale)
{
PXR_NS::GfVec3d scaleValue;
extraOp.GetAs<>(&scaleValue, timecode);
scale = PXR_NS::GfCompDiv(scale, scaleValue);
}
else if (extraOp.GetOpType() == UsdGeomXformOp::Type::TypeRotateX)
{
double rotValue;
extraOp.GetAs<>(&rotValue, timecode);
if (PXR_NS::GfIsClose(abs(rotValue), 90.0, 0.01))
{
rotationEuler[0] = rotationEuler[0] - rotValue;
std::swap(scale[1], scale[2]);
}
else
{
CARB_LOG_WARN(
"UnitsResolve rotateX supports only +-90 degree on prim: %s", prim.GetPrimPath().GetText());
}
}
}
}
}
// If transformOp is not found, make individual xformOp or reuse old ones.
if (!foundTransformOp)
{
// Don't use UsdGeomXformCommonAPI. It can only manipulate a very limited subset of xformOpOrder
// combinations Do it manually as non-destructively as possible
UsdGeomXformOp xformOp;
std::vector<UsdGeomXformOp> newXformOps;
newXformOps.reserve(5); // SRT + pivot and pivot inv
if (!extraXformOps.empty() && preTransformStack)
{
for (auto& copyXformOp : extraXformOps)
{
newXformOps.push_back(copyXformOp);
}
}
auto findOrAdd = [&xformOps, &xformOpOrders, &xform, &changeBlock, &fastUpdates](
UsdGeomXformOp::Type xformOpType, UsdGeomXformOp& outXformOp, bool createIfNotExist,
UsdGeomXformOp::Precision& precision, TfToken const& opSuffix = TfToken()) {
TfToken expectedOpName = UsdGeomXformOp::GetOpName(xformOpType, opSuffix);
for (auto& xformOp : xformOps)
{
if (xformOp.GetOpType() == xformOpType)
{
// To differentiate translate and translate:pivot
TfToken opName = xformOp.GetOpName();
if (opName == expectedOpName)
{
precision = xformOp.GetPrecision();
outXformOp = xformOp;
return true;
}
}
}
if (createIfNotExist)
{
// It is not safe to create new xformOps inside of SdfChangeBlocks, since
// new attribute creation via anything above Sdf API requires the PcpCache
// to be up to date. Flush the current change block before creating
// the new xformOp.
changeBlock.reset(nullptr);
if (std::find(xformOpOrders.begin(), xformOpOrders.end(), expectedOpName) == xformOpOrders.end())
{
outXformOp = xform.AddXformOp(xformOpType, precision, opSuffix);
}
else
{
// Sometimes XformOp attributes and XformOpOrder don't match. GetOrderedXformOps() considers
// both XformOp attributes and XformOpOrder. But AddXformOp() considers only XformOpOrder. So we
// need to fix it here.
auto opAttr = xform.GetPrim().CreateAttribute(
expectedOpName, UsdGeomXformOp::GetValueTypeName(xformOpType, precision), false);
outXformOp = UsdGeomXformOp(opAttr);
}
// Create a new change block to batch the subsequent authoring operations
// where possible.
changeBlock.reset(new SdfChangeBlock());
// Creation may have failed for a variety of reasons (including instanceable=True)
return static_cast<bool>(outXformOp);
}
return false;
};
auto getFirstRotateOpType = [&xformOps](UsdGeomXformOp::Precision& precision) {
for (auto& xformOp : xformOps)
{
if (xformOp.GetOpType() >= UsdGeomXformOp::Type::TypeRotateX &&
xformOp.GetOpType() <= UsdGeomXformOp::Type::TypeOrient &&
!xformOp.HasSuffix(kUnitsResolve))
{
precision = xformOp.GetPrecision();
return xformOp.GetOpType();
}
}
return UsdGeomXformOp::Type::TypeInvalid;
};
auto setEulerValue = [&rotationEuler, &findOrAdd, &newXformOps](
UsdGeomXformOp::Type rotationType, UsdGeomXformOp::Precision precision,
UsdTimeCode timecode, bool skipEqualSetForTimeSample) {
bool ret = false;
UsdGeomXformOp xformOp;
if (findOrAdd(rotationType, xformOp, true, precision))
{
ret = setValueWithPrecision<GfVec3h, GfVec3f, GfVec3d, GfVec3d>(
xformOp, rotationEuler, timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
return ret;
};
// Set translation
UsdGeomXformOp::Precision precision = UsdGeomXformOp::PrecisionDouble;
if (findOrAdd(UsdGeomXformOp::TypeTranslate, xformOp, true, precision))
{
success &= setValueWithPrecision<GfVec3h, GfVec3f, GfVec3d, GfVec3d>(
xformOp, translation, timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
// Set pivot
precision = UsdGeomXformOp::PrecisionFloat;
UsdGeomXformOp pivotOp;
static const TfToken kPivot = TfToken("pivot");
const bool hasPivot = findOrAdd(UsdGeomXformOp::TypeTranslate, pivotOp, false, precision, kPivot);
UsdGeomXformOp pivotOpInv;
if (hasPivot)
{
newXformOps.push_back(pivotOp);
for (size_t k = xformOps.size();k--;)
{
if (xformOps[k].IsInverseOp() && xformOps[k].HasSuffix(kPivot))
{
pivotOpInv = xformOps[k];
break;
}
}
}
// Set rotation
precision = UsdGeomXformOp::PrecisionFloat;
auto firstRotateOpType = getFirstRotateOpType(precision);
struct HashFn
{
size_t operator()(const GfVec3i& vec) const
{
return hash_value(vec);
}
};
static const std::unordered_map<GfVec3i, UsdGeomXformOp::Type, HashFn> kRotationOrderToTypeMap{
{ { 0, 1, 2 }, UsdGeomXformOp::TypeRotateXYZ }, { { 0, 2, 1 }, UsdGeomXformOp::TypeRotateXZY },
{ { 1, 0, 2 }, UsdGeomXformOp::TypeRotateYXZ }, { { 1, 2, 0 }, UsdGeomXformOp::TypeRotateYZX },
{ { 2, 0, 1 }, UsdGeomXformOp::TypeRotateZXY }, { { 2, 1, 0 }, UsdGeomXformOp::TypeRotateZYX },
};
if (firstRotateOpType == UsdGeomXformOp::TypeInvalid)
{
const char* defaultOpXformType =
carb::getCachedInterface<carb::settings::ISettings>()->getStringBuffer(kDefaultXforOpTypeSettingPath);
if (defaultOpXformType &&
strncmp(defaultOpXformType, "Scale, Orient, Translate", sizeof("Scale, Orient, Translate") - 1) == 0)
{
firstRotateOpType = UsdGeomXformOp::TypeOrient;
}
else
{
// TODO what if default_xform_ops == "Transform" ?
// If no rotation was defined on the prim, use rotationOrder as default
const auto orderEntry = kRotationOrderToTypeMap.find(rotationOrder);
if (orderEntry != kRotationOrderToTypeMap.end())
{
firstRotateOpType = orderEntry->second;
}
}
}
switch (firstRotateOpType)
{
case UsdGeomXformOp::TypeRotateX:
case UsdGeomXformOp::TypeRotateY:
case UsdGeomXformOp::TypeRotateZ:
{
// Add in reverse order
for (int32_t i = 2; i >= 0; i--)
{
size_t axis = rotationOrder[i];
if (findOrAdd(static_cast<UsdGeomXformOp::Type>(UsdGeomXformOp::TypeRotateX + axis), xformOp, true,
precision))
{
success &= setValueWithPrecision<GfHalf, float, double, double>(
xformOp, rotationEuler[axis], timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
}
break;
}
case UsdGeomXformOp::TypeRotateXYZ:
case UsdGeomXformOp::TypeRotateXZY:
case UsdGeomXformOp::TypeRotateYXZ:
case UsdGeomXformOp::TypeRotateYZX:
case UsdGeomXformOp::TypeRotateZXY:
case UsdGeomXformOp::TypeRotateZYX:
{
UsdGeomXformOp::Type providedRotationOrder = firstRotateOpType;
const auto orderEntry = kRotationOrderToTypeMap.find(rotationOrder);
if (orderEntry != kRotationOrderToTypeMap.end())
{
providedRotationOrder = orderEntry->second;
}
if (providedRotationOrder != firstRotateOpType)
{
CARB_LOG_WARN(
"Existing rotation order on prim %s is different than desired (%d, %d, %d), overriding...",
prim.GetPrimPath().GetText(), rotationOrder[0], rotationOrder[1], rotationOrder[2]);
}
success &= setEulerValue(providedRotationOrder, precision, timecode, skipEqualSetForTimeSample);
break;
}
case UsdGeomXformOp::TypeOrient:
if (findOrAdd(UsdGeomXformOp::TypeOrient, xformOp, true, precision))
{
static const GfVec3d kAxes[] = { GfVec3d::XAxis(), GfVec3d::YAxis(), GfVec3d::ZAxis() };
GfRotation rotation = GfRotation(kAxes[rotationOrder[0]], rotationEuler[rotationOrder[0]]) *
GfRotation(kAxes[rotationOrder[1]], rotationEuler[rotationOrder[1]]) *
GfRotation(kAxes[rotationOrder[2]], rotationEuler[rotationOrder[2]]);
success &= setValueWithPrecision<GfQuath, GfQuatf, GfQuatd, GfQuatd>(
xformOp, rotation.GetQuat(), timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
break;
default:
CARB_LOG_ERROR("Failed to determine rotation order");
}
// Set scale
precision = UsdGeomXformOp::PrecisionFloat;
if (findOrAdd(UsdGeomXformOp::TypeScale, xformOp, true, precision))
{
success &= setValueWithPrecision<GfVec3h, GfVec3f, GfVec3d, GfVec3d>(
xformOp, scale, timecode, skipEqualSetForTimeSample);
newXformOps.push_back(xformOp);
}
// Set extra ops from units resolve
if (!extraXformOps.empty() && !preTransformStack)
{
for (auto& copyXformOp : extraXformOps)
{
newXformOps.push_back(copyXformOp);
}
}
// Set inverse pivot
if (hasPivot && pivotOpInv)
{
newXformOps.push_back(pivotOpInv);
}
success &= xform.SetXformOpOrder(newXformOps, resetXFormStack);
}
else
{
const GfMatrix4d mtx = constructTransformMatrixFromSRT(translation, rotationEuler, rotationOrder, scale);
const GfMatrix4d innerMtx =
findInnerTransform(prim, mtx, foundTransformOp, timecode, skipEqualSetForTimeSample);
success &= UsdUtils::setAttribute(transformOp.GetAttr(), innerMtx, timecode, skipEqualSetForTimeSample);
}
return success;
}
/**
* Sets local transform of a prim from its world transform matrix.
*
* @param prim The prim to set local transform matrix to.
* @param time Current timecode.
* @param mtx The world transform matrix.
*/
static bool setLocalTransformFromWorldTransformMatrix(pxr::UsdPrim prim,
const pxr::GfMatrix4d& mtx,
pxr::UsdTimeCode timeCode = pxr::UsdTimeCode::Default(),
bool skipEqualSetForTimeSample = false)
{
pxr::GfMatrix4d parentToWorldMat = pxr::UsdGeomXformable(prim).ComputeParentToWorldTransform(timeCode);
pxr::GfMatrix4d worldToParentMat = parentToWorldMat.GetInverse();
return UsdUtils::setLocalTransformMatrix(prim, mtx * worldToParentMat, timeCode, skipEqualSetForTimeSample);
}
/**
* Creates a reference prim from external USD asset.
*
* @param stage The stage to create reference prim on.
* @param refUrl The URL of the reference asset.
* @param primPath The path to create the reference prim at.
* @param warningMsg Output warning message during the process.
* @param prependDefaultPrimPath Whether to check under defaultPrim path or stage root.
*/
static pxr::UsdPrim createExternalRefNodeAtPath(pxr::UsdStageWeakPtr stage,
const char* refUrl,
const char* primPath,
std::string& warningMsg,
bool prependDefaultPrimPath = true,
bool adjustLayerOffset = true)
{
pxr::UsdPrim prim;
std::string newPrimPath = findNextNoneExisitingNodePath(stage, primPath, prependDefaultPrimPath);
std::string refUrlStr(refUrl);
std::replace(refUrlStr.begin(), refUrlStr.end(), '\\', '/');
std::string relativeUrl = refUrlStr;
if (!makePathRelativeToLayer(stage->GetEditTarget().GetLayer(), relativeUrl))
{
#if CARB_PLATFORM_LINUX
// makePathRelativeToLayer returns false, it is a absolute path.
auto omniclient = carb::getCachedInterface<carb::omniclient::IOmniClient>();
carb::omniclient::OmniClientUrlPtr url(omniclient, relativeUrl.c_str());
if (!url->scheme || url->scheme[0] == '\0')
{
relativeUrl = carb::omniclient::makeFileUrl(omniclient, relativeUrl.c_str());
}
#endif
}
carb::settings::ISettings* settings = carb::getFramework()->acquireInterface<carb::settings::ISettings>();
bool xformForTypelessRef = settings->getAsBool(kCreateXformForTypelessReferenceSettingPath);
bool explictRefForNoneDefaultPrim = settings->getAsBool(kCreateExplicitRefForNoneDefaultPrimSettingPath);
pxr::UsdStageRefPtr refStage = pxr::UsdStage::Open(refUrl, pxr::UsdStage::InitialLoadSet::LoadNone);
if (refStage)
{
PXR_NS::SdfLayerOffset layerOffset;
if (adjustLayerOffset)
layerOffset.SetScale(stage->GetTimeCodesPerSecond() / refStage->GetTimeCodesPerSecond());
if (refStage->HasDefaultPrim() && refStage->GetDefaultPrim())
{
auto defaultPrim = refStage->GetDefaultPrim();
const std::string& typeName = defaultPrim.GetTypeName().GetString();
if (typeName.empty() && xformForTypelessRef)
{
warningMsg =
"The defaultPrim of this USD is typeless. Overriding it to Xform. Do not rely on this behavior, it will be removed at anytime.";
// If the defaultPrim is typeless,
// define a root Xfrom node for the external refs so it can be moved around
prim = pxr::UsdGeomXform::Define(stage, pxr::SdfPath(newPrimPath)).GetPrim();
}
else
{
prim = stage->DefinePrim(pxr::SdfPath(newPrimPath));
}
if (prim)
{
// If has DefaultPrim, reference it directly.
auto ref = prim.GetReferences();
ref.AddReference(relativeUrl, layerOffset);
}
}
else if (explictRefForNoneDefaultPrim)
{
if (refStage->HasDefaultPrim() && !refStage->GetDefaultPrim())
{
warningMsg =
"The USD file has a defaultPrim but references an invalid prim, creating explicit reference for each root-level object. Do not rely on this behavior, it will be removed at anytime.";
}
else if (!refStage->HasDefaultPrim())
{
warningMsg =
"There's no defaultPrim in this USD file, creating explicit reference for each root-level object. Do not rely on this behavior, it will be removed at anytime.";
}
// Define a root Xfrom node for the external refs
prim = pxr::UsdGeomXform::Define(stage, pxr::SdfPath(newPrimPath)).GetPrim();
// If has no defaultPrim, reference each root level Prim individually.
auto refRoot = refStage->GetPseudoRoot();
auto refRootDirectChildren = refRoot.GetAllChildren();
// iterate through all root level children and create reference for them
for (const auto& child : refRootDirectChildren)
{
std::string newPath = newPrimPath + child.GetPrimPath().GetString();
auto subPrim = stage->DefinePrim(pxr::SdfPath(newPath));
if (subPrim)
{
auto ref = subPrim.GetReferences();
ref.AddReference(relativeUrl, child.GetPrimPath(), layerOffset);
}
else
{
CARB_LOG_WARN("Failed to import %s from %s", child.GetPrimPath().GetText(), refUrl);
}
}
}
if (prim)
{
// Get the timeline of the referenced stage and extend current stage timeline if needed.
double refStartTimeCode = refStage->GetStartTimeCode();
double refEndTimeCode = refStage->GetEndTimeCode();
double refTimeCodePerSecond = refStage->GetTimeCodesPerSecond();
double startTimeCode = stage->GetStartTimeCode();
double endTimeCode = stage->GetEndTimeCode();
double timeCodePerSecond = stage->GetTimeCodesPerSecond();
if (refStartTimeCode < startTimeCode)
{
UsdUtils::ScopedLayerEdit scopedLayerEdit(stage, stage->GetRootLayer());
stage->SetStartTimeCode(refStartTimeCode);
}
if (refEndTimeCode > endTimeCode)
{
UsdUtils::ScopedLayerEdit scopedLayerEdit(stage, stage->GetRootLayer());
stage->SetEndTimeCode(refEndTimeCode);
}
// Also warn if fps of referenced
if (refTimeCodePerSecond != timeCodePerSecond)
{
warningMsg =
"Referenced USD file TimeCodesPerSecond does not match current USD file TimeCodesPerSecond.";
}
}
}
if (!prim)
{
warningMsg = std::string("Could not create reference from ") + refUrl;
}
return prim;
}
/**
* Gets the enclosing model of given prim.
*
* @param prim The prim to get enclosing model from.
* @return The enclosing model of given prim.
*/
static pxr::UsdPrim getEnclosingModelPrim(pxr::UsdPrim prim)
{
// Code partially ported from USD\pxr\usdImaging\lib\usdviewq\common.py
while (prim)
{
pxr::UsdModelAPI modelApi(prim);
pxr::TfToken kind;
modelApi.GetKind(&kind);
if (pxr::KindRegistry::IsA(kind, pxr::KindTokens->model))
{
break;
}
prim = prim.GetParent();
}
return prim;
}
/**
* Takes an absolute path and makes it relative to a layer.
*
* @param layer The layer to make path relative to.
* @param path The absolute path to be converted in place.
* @return true if the conversion is successful, false if failed to make relative path (possible reasons: layer is
* in-memory only, layer and path have different protocol (omni: vs file:), layer and path are on different Window
* drive etc.).
*/
static bool makePathRelativeToLayer(pxr::SdfLayerHandle layer, std::string& path)
{
if (layer->IsAnonymous() || PXR_NS::SdfLayer::IsAnonymousLayerIdentifier(path))
{
return false;
}
std::string realPath = layer->GetRealPath();
std::string externRefPathRelative;
if (makeRelativePathTo(path, realPath, externRefPathRelative))
{
path = externRefPathRelative;
return true;
}
else
{
CARB_LOG_INFO("Cannot make '%s' relative to '%s'", path.c_str(), realPath.c_str());
}
return false;
}
/**
* Removes a property from all layer specs.
*
* @param stage The stage to remove property.
* @param primPath The parent prim path of the property to be removed.
* @param propertyName Name of the property to be removed.
* @return true if property has been removed from at least one layer.
*/
static bool removeProperty(pxr::UsdStageWeakPtr stage, const pxr::SdfPath& primPath, const pxr::TfToken& propertyName)
{
bool ret = false;
auto layerStack = stage->GetLayerStack();
for (auto&& layer : layerStack)
{
auto primSpec = layer->GetPrimAtPath(primPath);
if (primSpec)
{
auto propertySpec = layer->GetPropertyAtPath(primPath.AppendProperty(propertyName));
if (propertySpec)
{
primSpec->RemoveProperty(propertySpec);
ret |= true;
}
}
}
return ret;
}
/**
* Gets the attribute value.
*
* @tparam T the data type of the attribute.
* @param attribute The attribute to get value from.
* @param time Current timecode.
* @return the value of the attribute.
*/
template <class T>
static T getAttribute(pxr::UsdAttribute& attribute, pxr::UsdTimeCode time)
{
T val;
attribute.Get(&val, time);
return val;
}
/**
* Gets the attribute array value.
*
* @tparam T The data type of the attribute array.
* @param attribute The attribute to get value from.
* @param out the value of the attribute.
* @return True if the out value is valid.
*/
template <typename T>
static bool getAttributeArray(pxr::UsdAttribute& attribute, pxr::VtArray<T>& out, pxr::UsdTimeCode time)
{
pxr::VtValue arrayDataValue;
attribute.Get(&arrayDataValue, time);
if (arrayDataValue.GetArraySize())
{
out = arrayDataValue.Get<pxr::VtArray<T>>();
return true;
}
return false;
}
/**
* enum to show effective timesamples in layerstacks based on current authoring layer
*/
enum class TimeSamplesOnLayer
{
eNoTimeSamples,
eOnCurrentLayer,
eOnStrongerLayer,
eOnWeakerLayer
};
/**
* check if attribute has efficient timesample and
* these data are on currentlayer/strongerlayer/weakerlayer
* @tparam Stage Current Working Stage.
* @param attribute The attribute to check.
*/
static TimeSamplesOnLayer getAttributeEffectiveTimeSampleLayerInfo(const pxr::UsdStage& stage,
const pxr::UsdAttribute& attr,
pxr::SdfLayerRefPtr* outLayer = nullptr)
{
if (attr.GetNumTimeSamples() == 0)
return TimeSamplesOnLayer::eNoTimeSamples;
auto authoringLayer = stage.GetEditTarget().GetLayer();
bool isOnStrongerLayer = true;
const pxr::PcpLayerStackPtr& nodeLayers = attr.GetResolveInfo().GetNode().GetLayerStack();
const pxr::SdfLayerRefPtrVector& layerStack = nodeLayers->GetLayers();
for (auto layer : layerStack)
{
auto attrSpec = layer->GetAttributeAtPath(attr.GetPath());
if (attrSpec && attrSpec->GetTimeSampleMap().size() > 0)
{
if (outLayer)
{
*outLayer = layer;
}
if (layer == authoringLayer)
{
return TimeSamplesOnLayer::eOnCurrentLayer;
}
else if (isOnStrongerLayer)
{
return TimeSamplesOnLayer::eOnStrongerLayer;
}
else
{
return TimeSamplesOnLayer::eOnWeakerLayer;
}
}
else
{
if (layer == authoringLayer)
{
isOnStrongerLayer = false;
}
}
}
return TimeSamplesOnLayer::eNoTimeSamples;
}
/**
* Copy TimeSample From Waker Layer.
*
* @param Stage Current Working Stage.
* @param attribute The attribute to check.
*/
static void copyTimeSamplesFromWeakerLayer(pxr::UsdStage& stage, const pxr::UsdAttribute& attr)
{
pxr::SdfLayerRefPtr outLayer;
if (getAttributeEffectiveTimeSampleLayerInfo(stage, attr, &outLayer) == TimeSamplesOnLayer::eOnWeakerLayer)
{
pxr::SdfTimeSampleMap timesamples;
if (attr.GetMetadata(pxr::TfToken("timeSamples"), ×amples))
{
attr.SetMetadata(pxr::TfToken("timeSamples"), timesamples);
}
}
}
/**
* Sets attribute value.
*
* @tparam T The data type of the attribute.
* @param attribute The attribute to set value to.
* @param val The value to set.
* @param autoTargetSessionLayer whether the edit target should auto switch to session layer.
* @return true if set is successfully.
*/
template <class ValueType>
static bool setAttribute(const pxr::UsdAttribute& attribute,
const ValueType& val,
pxr::UsdTimeCode timeCode = pxr::UsdTimeCode::Default(),
bool skipEqualSetForTimeSample = false,
bool autoTargetSessionLayer = true)
{
PXR_NS::UsdTimeCode setTimeCode = timeCode;
if (!isTimeSampled(attribute))
{
setTimeCode = PXR_NS::UsdTimeCode::Default();
}
// This is here to prevent the TransformGizmo from writing a translation, rotation and scale on every
// key where it sets a value. At some point we should revisit the gizmo to simplify the logic, and
// start setting only the transform value the user intends.
if (skipEqualSetForTimeSample)
{
if (!setTimeCode.IsDefault() && !hasTimeSample(attribute, setTimeCode))
{
ValueType value;
bool result = attribute.Get(&value, timeCode);
if (result && PXR_NS::GfIsClose(value, val, 1e-6))
{
return false;
}
}
}
// if the prim is defined on session layer, or the attribute itself is on session layer, switch EditTarget to session layer instead
std::unique_ptr<PXR_NS::UsdEditContext> editCtx;
auto stage = attribute.GetStage();
if (autoTargetSessionLayer)
{
// check first if the attribute is on session layer
auto sessionOrSubLayer = getLayerIfSpecOnSessionOrItsSublayers(stage, attribute.GetPath());
if (!sessionOrSubLayer)
{
// if attribute doesn't exist, fallback to prim "def" (but not "over")
sessionOrSubLayer = getLayerIfDefOnSessionOrItsSublayers(stage, attribute.GetPrim().GetPath());
}
if (sessionOrSubLayer)
{
editCtx = std::make_unique<PXR_NS::UsdEditContext>(stage, sessionOrSubLayer);
}
}
if (!setTimeCode.IsDefault())
{
copyTimeSamplesFromWeakerLayer(*stage, attribute);
}
return attribute.Set(val, setTimeCode);
}
static bool getDefaultPrimName(const pxr::UsdStageRefPtr stage, std::string& defaultPrimName)
{
if (stage && stage->HasDefaultPrim())
{
defaultPrimName = stage->GetDefaultPrim().GetName();
return true;
}
return false;
}
static pxr::UsdStageRefPtr getUsdStageFromId(long int stageId)
{
return pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
}
static bool isSameDriveOrProtocol(const std::string& path1, const std::string& path2)
{
auto absolutePathArray = tokenizePath(path1);
auto anchorPathArray = tokenizePath(path2);
if (absolutePathArray.size() > 0 && anchorPathArray.size() > 0)
{
const std::string& protocolOrDrivePath = absolutePathArray.front();
const std::string& protocolOrDriveAnchor = anchorPathArray.front();
return isSameDriveOrProtocolInternal(protocolOrDrivePath, protocolOrDriveAnchor);
}
return false;
}
static std::string findNextNoneExisitingNodePath(pxr::UsdStageWeakPtr stage,
std::string path,
bool prependDefaultPrimPath)
{
uint64_t dupSuffix = 2;
pxr::UsdPrim oldPrim;
std::string newPrimPath;
// Do not support dot in the path
std::replace(path.begin(), path.end(), '.', '_');
// Do not support Prim names begin with a number in any part of the path
// Add a "_" in front of any section that starts with number. e.g. /1foo/2bar/baz -> /_1foor/_2bar/baz
static const std::regex kNodeNameStartsWithNumber(
"(\\/)([0-9])", std::regex_constants::icase | std::regex_constants::optimize);
path = std::regex_replace(path, kNodeNameStartsWithNumber, "/_$2");
if (prependDefaultPrimPath && stage->HasDefaultPrim())
{
auto defaultPrim = stage->GetDefaultPrim();
if (defaultPrim)
{
path = stage->GetDefaultPrim().GetPath().GetString() + path;
}
}
std::string oldPrimTestPath = path;
// Find out if the path already has a dup suffix number
static const std::regex kNodeNameEndsWithUnderscoreNumber(
"(_)([0-9]+)$", std::regex_constants::icase | std::regex_constants::optimize);
std::smatch m;
if (std::regex_search(path, m, kNodeNameEndsWithUnderscoreNumber))
{
std::string dupSuffixStr = m[m.size() - 1];
dupSuffix = std::strtoul(dupSuffixStr.c_str(), nullptr, 0);
path = m.prefix();
}
for (;;)
{
// If the node already exists, append a "_n" to the end
oldPrim = stage->GetPrimAtPath(pxr::SdfPath(oldPrimTestPath));
if (oldPrim.IsValid())
{
oldPrimTestPath = std::string(path) + "_" + std::to_string(dupSuffix++);
}
else
{
newPrimPath = oldPrimTestPath;
break;
}
}
return newPrimPath;
}
static PXR_NS::SdfPathVector fromStringArray(const char** stringArray, size_t count)
{
PXR_NS::SdfPathVector sdfPaths(count);
for (size_t i = 0; i < count; i++)
{
sdfPaths[i] = PXR_NS::SdfPath(stringArray[i]);
}
return sdfPaths;
}
static PXR_NS::SdfPathVector fromStringArray(const std::vector<std::string>& stringArray)
{
PXR_NS::SdfPathVector sdfPaths(stringArray.size());
for (size_t i = 0; i < stringArray.size(); i++)
{
sdfPaths[i] = PXR_NS::SdfPath(stringArray[i]);
}
return sdfPaths;
}
static std::vector<std::string> toStringArray(const PXR_NS::SdfPathVector& paths)
{
std::vector<std::string> stringArray(paths.size());
for (size_t i = 0; i < paths.size(); i++)
{
stringArray[i] = paths[i].GetString();
}
return stringArray;
}
/**
* Finds if the given path (prim/attribute/property/object/etc) has a spec on session layer or its sublayers.
*
* @param stage of the prim.
* @param path The path to be checked for spec.
* @param predicate additional predicate to be called if spec is found on the layer.
*
* @return the layer that has spec at given path, or nullptr if not found.
*/
static PXR_NS::SdfLayerRefPtr getLayerIfSpecOnSessionOrItsSublayers(
PXR_NS::UsdStageRefPtr stage,
const PXR_NS::SdfPath& path,
const std::function<bool(PXR_NS::SdfSpecHandle)>& predicate = nullptr)
{
auto sessionLayer = stage->GetSessionLayer();
auto hasSpec = [&path, &predicate](PXR_NS::SdfLayerRefPtr layer)
{
auto spec = layer->GetObjectAtPath(path);
return spec && (!predicate || predicate(spec));
};
if (hasSpec(sessionLayer))
{
return sessionLayer;
}
auto sublayerPaths = sessionLayer->GetSubLayerPaths();
for (auto const& path : sublayerPaths)
{
auto layer = PXR_NS::SdfLayer::Find(path);
if (layer)
{
if (hasSpec(layer))
{
return layer;
}
}
}
return nullptr;
}
/**
* Finds if the given *prim* path has a "def" *primSpec* on session layer or its sublayers.
* If you want to find attributeSpec use @ref getLayerIfSpecOnSessionOrItsSublayers instead.
*
* @stage stage of the prim.
* @param path The path to be checked for "def" primSpec.
*
* @return the layer that has "def" prim spec, or nullptr if not found.
*/
static PXR_NS::SdfLayerRefPtr getLayerIfDefOnSessionOrItsSublayers(PXR_NS::UsdStageRefPtr stage,
const PXR_NS::SdfPath& path)
{
return getLayerIfSpecOnSessionOrItsSublayers(
stage, path,
[](PXR_NS::SdfSpecHandle spec)
{
auto primSpec = PXR_NS::SdfSpecStatic_cast<PXR_NS::SdfPrimSpecHandle>(spec);
return primSpec && PXR_NS::SdfIsDefiningSpecifier(primSpec->GetSpecifier());
});
}
private:
static std::list<std::string> tokenizePath(std::string path)
{
std::list<std::string> result;
for (;;)
{
size_t pos = path.find_first_of('/');
if (pos == std::string::npos)
{
if (!path.empty())
{
result.push_back(path);
}
break;
}
else
{
std::string token = path.substr(0, pos);
if (!token.empty())
{
result.push_back(token);
}
path = path.substr(pos + 1);
}
}
return result;
}
static bool isSameDriveOrProtocolInternal(const std::string& protocol1, const std::string& protocol2)
{
// If E: or omni:
if (protocol1.length() && protocol2.length() && protocol1.back() == ':' && protocol2.back() == ':')
{
if (protocol1.length() == protocol2.length())
{
#if CARB_PLATFORM_WINDOWS
constexpr auto strncasecmp = _strnicmp;
#endif
if (strncasecmp(protocol1.c_str(), protocol2.c_str(), protocol1.length()) == 0)
{
return true;
}
}
}
return false;
}
static bool makeRelativePathTo(const std::string& absolutePath, const std::string& anchor, std::string& relativePath)
{
auto omniclient = carb::getCachedInterface<carb::omniclient::IOmniClient>();
if (omniclient)
{
std::string result;
relativePath = carb::omniclient::makeRelativeUrl(omniclient, anchor.c_str(), absolutePath.c_str());
#if CARB_PLATFORM_WINDOWS
carb::omniclient::OmniClientUrlPtr clientUrl(omniclient, relativePath.c_str());
if (!clientUrl->scheme || strcmp(clientUrl->scheme, "omniverse") != 0) // omniverse path can have '\'
{
std::replace(relativePath.begin(), relativePath.end(), '\\', '/');
}
#endif
return relativePath != absolutePath;
}
return false;
}
static bool checkAncestralNode(const pxr::PcpNodeRef& node)
{
bool isAncestral = node.IsDueToAncestor();
if (!isAncestral)
{
using namespace pxr;
TF_FOR_ALL(childIt, node.GetChildrenRange())
{
isAncestral |= checkAncestralNode(*childIt);
if (isAncestral)
{
break;
}
}
}
return isAncestral;
}
static bool checkAncestral(const pxr::UsdPrim& prim)
{
return checkAncestralNode(prim.GetPrimIndex().GetRootNode());
}
template <class HalfType, class FloatType, class DoubleType, class ValueType>
static bool setValueWithPrecision(pxr::UsdGeomXformOp& xformOp,
const ValueType& value,
pxr::UsdTimeCode timeCode = pxr::UsdTimeCode::Default(),
bool skipEqualSetForTimeSample = false)
{
switch (xformOp.GetPrecision())
{
case pxr::UsdGeomXformOp::PrecisionHalf:
return UsdUtils::setAttribute(
xformOp.GetAttr(), HalfType(FloatType(value)), timeCode, skipEqualSetForTimeSample);
case pxr::UsdGeomXformOp::PrecisionFloat:
return UsdUtils::setAttribute(xformOp.GetAttr(), FloatType(value), timeCode, skipEqualSetForTimeSample);
case pxr::UsdGeomXformOp::PrecisionDouble:
return UsdUtils::setAttribute(xformOp.GetAttr(), DoubleType(value), timeCode, skipEqualSetForTimeSample);
}
return false;
}
};
/**
* Gets the string attribute value.
*
* @param attribute The attribute to get value from.
* @param time Current timecode.
* @return the value of the attribute.
*/
template <> // Define it out of class body to avoid "Explicit specialization in non-namespace scope" error.
inline std::string UsdUtils::getAttribute(pxr::UsdAttribute& attribute, pxr::UsdTimeCode time)
{
pxr::VtValue val;
attribute.Get(&val, time);
if (attribute.GetTypeName() == pxr::SdfValueTypeNames->String)
{
return val.Get<std::string>();
}
else if (attribute.GetTypeName() == pxr::SdfValueTypeNames->Asset)
{
auto path = val.Get<pxr::SdfAssetPath>();
return path.GetAssetPath();
}
return "";
}
}
}
| 109,776 | C | 39.478245 | 231 | 0.542022 |
omniverse-code/kit/include/omni/usd/IStageAudio.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/events/IEvents.h>
#include <carb/audio/IAudioPlayback.h>
#include <carb/audio/IAudioUtils.h>
#include <omni/usd/Api.h>
#include <limits.h>
namespace omni
{
namespace usd
{
namespace audio
{
class AudioManager;
/** base type for a streamer handle value. This uniquely identifies a single streamer
* that has been created in the audio manager. A value of this type can be
* @ref kInvalidStreamerId to indicate an invalid handle.
*/
using StreamerId = size_t;
/** an invalid handle value for a streamer. This can be returned from createCaptureStreamer(). */
constexpr StreamerId kInvalidStreamerId = (size_t)(SIZE_MAX);
/** The status of a sound's asset's loading. */
enum class AssetLoadStatus
{
eDone, /**< Asset has finished loading */
eInProgress, /**< Asset loading is in progress */
eFailed, /**< Asset has failed to load */
eNotRegistered, /**< Prim was not registered from hydra yet. */
eNoAssetPath, /**< No asset path has been set for the prim. No load has been queued. */
};
/** The default value to be used for a setting. */
enum class FeatureDefault
{
eOn, /**< The setting is enabled when a value is not explicitly set. */
eOff, /**< The setting is disabled when a value is not explicitly set. */
eForceOn, /**< The setting is always enabled.
* This is intended to allow users to override all sounds in
* a scene to test what a specific feature does. */
eForceOff, /**< The setting is always disabled.
* This is intended to allow users to override all sounds in
* a scene to test what a specific feature does. */
};
/** Names for the various change notification events that can be sent on the event
* stream from UsdAudioContext::getMetadataChangeStream().
*/
enum class EventType
{
/** An event type that is sent from UsdAudioContext::getMetadataChangeStream().
* This indicates that the audio metadata has changed for the current stage.
* This is also sent when a new stage is loaded.
*/
eMetadataChange = 1,
/** An event type that is sent from UsdAudioContext::getMetadataChangeStream().
* This indicates that the stage's listener state has changed and any property
* windows should be updated. This change may include a new listener being
* added to the stage or an existing listener being removed from the stage.
*/
eListenerListChange,
/** An event type that is sent from UsdAudioContext::getMetadataChangeStream().
* This indicates that the active listener in the stage has changed and any
* property windows displaying it should be updated.
*/
eActiveListenerChange,
/** The context object has been created and is now valid. It can be retrieved with a call to
* getPlaybackContext().
*/
eContextCreated,
/** The context object will be destroyed soon. External callers that hold the context object
* should invalidate their pointer and avoid using it further.
*/
eContextWillBeDestroyed,
/** The context object has been destroyed. External calls that held the context object should
* already no longer be using this object. This is just a notification that the object
* destruction has been completed.
*/
eContextDestroyed,
};
/** The method that will be used to calculate the length of a sound prim. */
enum class SoundLengthType
{
/** The length of time the sound is estimated to play for in the stage once
* it's triggered.
* This will be the lesser of the difference between the sound's start and
* end times (if an end time is set on the prim) or the length of the
* actual sound itself (including `mediaOffsetStart`, `mediaOffsetEnd`
* and `timeScale`), multiplied by loop count.
* Note that timeScale is taken into account when calculating the play time
* of an asset.
* For sounds that are set to loop infinitely, this will be a very large
* number (on the scale of 100 days).
*/
ePlayLength,
/** The length of the sound.
* This doesn't include the sound's start time, end time or loop count.
* This is calculated using `mediaOffsetStart` and `mediaOffsetEnd` if those
* are set; otherwise, this just returns the sound asset's length.
* `timeScale` will also affect the length of the sound in this case.
*/
eSoundLength,
/** The length of the underlying sound asset, ignoring any USD parameters. */
eAssetLength
};
/** A pure virtual class for streaming audio data from an @ref AudioManager. */
class Streamer
{
public:
/** A callback for when a stream opens.
* @param[inout] format The format of the stream.
* This format can be edited to whatever is needed by the
* callback and the audio engine will convert the data to
* the desired format.
* @param[inout] context The user-specified context.
* @returns `true` if the stream was initialized successfully.
* @returns `false` if the stream should be abandoned.
*/
virtual bool open(carb::audio::SoundFormat* format) noexcept = 0;
/** A callback for when a stream closes.
* @param[inout] context The user-specified context.
*/
virtual void close() noexcept = 0;
/** A callback that receives audio data.
* @param[in] data The buffer of audio data.
* @param[in] bytes The number of bytes of data specified in @p data.
* This buffer is only valid until the callback returns.
* @param[inout] context The user-specified context.
* @note This callback is sent from the audio engine's thread, so this callback
* must do minimal work and return to avoid stalling the audio engine.
* Any callback that wants to do something expensive, such as rendering
* an image or performing a FFT should use the callback to copy data to
* a buffer, then process that buffer in a separate thread.
* @note It's not possible to change the rate at which data is received.
* Because Kit plays audio to a physical device, that device must be
* allowed to control the data rate to avoid underruns/overruns.
*/
virtual void writeData(const void* data, size_t bytes) noexcept = 0;
};
/** A descriptor for drawWaveform(). */
struct AudioImageDesc
{
/** Flags that alter the drawing style. */
carb::audio::AudioImageFlags flags;
/** This specifies which audio channel from @ref sound will be rendered.
* This is ignored when @ref fAudioImageMultiChannel or @ref fAudioImageSplitChannels
* is set on @ref flags.
*/
size_t channel;
/** The buffer that holds the image data.
* The image format is RGBA8888.
* This must be @ref height * @ref pitch bytes long.
* This may not be nullptr.
*/
void* image;
/** The width of the image in pixels. */
size_t width;
/** The width of the image buffer in bytes.
* This can be set to 0 to use 4 * @ref width as the pitch.
* This may be used for applications such as writing a subimage or an
* image that needs some specific alignment.
*/
size_t pitch;
/** The height of the image in pixels. */
size_t height;
/** The background color to write to the image in normalized RGBA color.
* The alpha channel in this color is not used to blend this color with
* the existing data in @ref image; use @ref fAudioImageNoClear if you
* want to render on top of an existing image.
* This value is ignored when @ref fAudioImageNoClear is set on @ref flags.
*/
carb::Float4 background;
/** The colors to use for the image in normalized RGBA colors.
* If @ref carb::audio::fAudioImageMultiChannel or @ref
* carb::audio::fAudioImageSplitChannels are set, each element in this
* array maps to each channel in the output audio data; otherwise, element
* 0 is used as the color for the single channel.
*/
carb::Float4 colors[carb::audio::kMaxChannels];
};
/** The IStageAudio interface.
* This was previously a Carbonite interface, but it was changed to a regular
* C interface due to linking issues related to the USD shared lib.
* This may return to being a Carbonite interface eventually.
* @{
*/
/** Get the default audio manager.
* @returns The default audio manager.
* This is equivalent to calling UsdContext::getContext()->getAudioManager(),
* except that you don't have to include UsdContext.h in your module.
* At the time of writing, UsdContext.h pulls in the USD headers, which
* causes conflicts with pybind11 modules.
* @returns nullptr if audio is disabled.
* @returns nullptr if the UsdContext couldn't be retrieved for whatever reason.
*/
OMNI_USD_API AudioManager* getDefaultAudioManager();
/** Retrieve the audio playback context for an audio manager.
*
* @param[in] mgr The audio manager to retrieve the playback context from. This may
* not be `nullptr`. This can be the audio manager object returned
* from getDefaultAudioManager().
* @returns The audio playback context that the requested audio manager is using.
*
* @remarks This retrieves the audio playback context object for the requested
* audio manager object. This can be used by external callers to play
* their own sounds on the same context that the main USD stage does.
*
* Notifications about the creation and destruction of the context object
* can be received by subscribing to the event stream returned by
* getMetadataChangeStream(). The interesting events in this case will be
* the @a EventType::eContext* events. Note that the context is only ever
* created when the given audio manager is first created. This means that
* most callers would not be subscribed to the event stream by that point.
* This is normally acceptable since the same context is reused from one
* stage to the next. The more important notification will be the
* @ref EventType::eContextWillBeDestroyed event. When this is received, the
* context object should be considered invalidated and all future operations
* on it stopped. The playback context object is typically only destroyed
* during shutdown when the audio manager is unloading.
*/
OMNI_USD_API carb::audio::Context* getPlaybackContext(AudioManager* mgr);
/** Retrieves the total number of registered sound objects in the USD stage.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
*
* @return the total number of sounds in the stage. This will be one larger than
* the highest valid index of sound prims in the current USD stage.
*
* @note Sounds that have not had their asset loaded yet (or their asset failed
* to load) will not show up in the sound count unless they've been passed
* to an IStageAudio function.
*/
OMNI_USD_API size_t getSoundCount(AudioManager* mgr);
/** Immediately plays the requested USD stage sound if it is loaded.
*
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to sound prim to play.
* @return no return value.
*
* @remarks This plays a single non-looping instance of a USD stage sound immediately. The
* sound must have already been loaded. If the sound resource was missing or
* couldn't be loaded, this call will simply be ignored. This will return
* immediately after scheduling the sound to play. It will never block for the
* duration of the sound playback. This sound may be prematurely stopped with
* stopSound().
*
* @note This operation is always thread safe.
*
* @note The loopCount parameter of the prim parameter is ignored in this call.
* This functionality will be added in a future revision.
*
* @note If the sound at path @p path is playing when this is called, the
* previous playing instance will continue playing.
* The previously playing instance will no longer receive updates when
* the USD prim at path @p path is changed.
* The only way to stop this previously playing instance is for it to
* end on its own or for the timeline to stop.
* In the future, this function may stop the previously playing instance.
* For cases where playing the same sound repeatedly in a fire-and-forget
* fashion is desired, use spawnVoice().
*
* @note The playing sound will stop when the timeline is stopped.
* This behavior may change in the future.
*
* @note OmniSound prims that are scheduled to play in an animation should not also
* be played with playSound(), since it may prevent them from playing
* when they are scheduled to play.
*/
OMNI_USD_API void playSound(AudioManager* mgr, const char* path);
/** Queries whether a sound object is currently playing.
*
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to sound prim to query the playing state for.
* @return true if the sound object is currently playing.
* @return false if the sound has either finished playing or has not been played yet.
*
* @remarks This queries whether a sound is currently playing. If this fails, that may mean
* that the sound ended naturally on its own or it was explicitly stopped. Note
* that this may continue to return true for a short period after a sound has been
* stopped with stopSound() or stopAllSounds(). This period may be up to 10
* milliseconds.
*
* @note This only checks the most recently playing instance of a sound,
* if multiple simultaneous sounds have been spawned with playSound().
*/
OMNI_USD_API bool isSoundPlaying(AudioManager* mgr, const char* path);
/** Immediately schedules the stop of the playback of a sound.
*
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to sound prim to stop playback for.
*
* @remarks This stops the playback of an active sound. If the sound was not playing or had
* already naturally stopped on its own, this call is ignored.
*
* @note This only stops the most recently played instance of a sound, if
* multiple overlapping instances of a sound were played with playSound().
*/
OMNI_USD_API void stopSound(AudioManager* mgr, const char* path);
/** Retrieves length of a sound in seconds (if known).
*
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to sound prim to retrieve the length for.
* @return the play length of the sound in seconds if the asset is loaded and the length
* can be calculated.
* @return 0.0 if the sound asset is not available yet or the length could not be properly
* calculated.
*
* @remarks This calculates the length of a USD stage sound in seconds. This will be the
* lesser of the difference between the sound's start and end times (if an end time
* is set on the prim) or the length of the actual sound asset itself (if not
* looping). In either case, this will be the amount of time that the sound would
* be expected to play for if it were triggered. For sounds that are set to loop,
* the returned time will include all scheduled loop iterations. For sounds that
* are set to loop infinitely, this will be a very large number (on the scale of
* 100 days).
* This is equivalent to calling getSoundLengthEx() with `type` set to `ePlayLength`.
*/
OMNI_USD_API double getSoundLength(AudioManager* mgr, const char* path);
/** Retrieves length of a sound in seconds (if known).
*
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to sound prim to retrieve the length for.
* @param[in] type The type of calculation to perform.
* @return The play length of the sound in seconds if the asset is loaded and the length
* can be calculated.
* @return 0.0 if the sound asset is not available yet or the length could not be properly
* calculated.
*/
OMNI_USD_API double getSoundLengthEx(AudioManager* mgr, const char* path, SoundLengthType type);
/** Stops all currently playing USD stage sounds.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
*
* @return no return value.
*
* @remarks This stops all currently playing stage sounds. Any sounds that have been
* queued for playback will be stopped. UI sounds will not be affected. This
* is intended to be used to reset the sound playback system when an animation
* sequence is stopped. This will be automatically called internally whenever
* the animation sequence is stopped or it loops.
*/
OMNI_USD_API void stopAllSounds(AudioManager* mgr);
/** Immediately plays the requested USD stage sound as a new @ref carb::audio::Voice if it is loaded.
*
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to sound prim to spawn a voice from.
*
* @returns The new voice that was spawned.
* This returns a handle, so there is no need to free the result; the
* pointer can be discarded.
* This voice's settings are only a snapshot of the sound prim that
* they were based off. Updates to these parameters will have to be
* performed on the returned voice through the IAudioPlayback interface.
* @returns nullptr if a new voice could not be spawned.
*
* @remarks This begins playing the requested sound as a new @ref carb::audio::Voice.
* The sound must have already been loaded or nullptr will be returned.
* The spawned voice plays the sound asynchronously for the lifetime
* of the voice.
* This is intended for cases where the behavior of playSound() is too
* limiting.
*
* @note This operation is always thread safe.
*
* @note stopAllSounds() and stopSound() do not affect the playing voices
* spawned from this call.
*
* @note Unlike playSound(), the loopCount parameter of the prim is used, so
* the voice must be explicitly stopped if the voice is infinitely
* looping.
*
* @note Unlike playSound(), these voice handles are managed separately from
* the voice handles of the timeline, so spawning a voice from a sound
* that will play on the timeline shouldn't affect that sound's timeline
* playback.
* Stopping the timeline will also not stop these playing voices.
*/
OMNI_USD_API carb::audio::Voice* spawnVoice(AudioManager* mgr, const char* path);
/** Queries whether the asset of an individual sound has been fully loaded.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to sound prim to retrieve the status of.
* @return AssetLoadStatus::eInProgress if the asset is in the process of loading.
* @return AssetLoadStatus::eDone if the asset has finished loading and is ready
* for immediate playback.
* @return AssetLoadStatus::eFailed if the asset has failed to load.
* @return AssetLoadStatus::eFailed if the audio manager has not loaded.
* @return AssetLoadStatus.NotRegistered if the sound prim has not been
* registered with the audio manager yet. This happens when the
* hydra renderer hasn't started creating the prims yet.
*/
OMNI_USD_API AssetLoadStatus getSoundAssetStatus(AudioManager* mgr, const char* path);
/** Bind a callback for when assets are loaded.
* @param[in] mgr The AudioManager instance that this function acts upon.
* @param[in] path The path to sound prim to bind a callback to.
* @param[in] callback The callback to fire once a load has occurred.
* The parameter passed to this callback is @p callbackContext.
* @param[in] callbackContext The context parameter to pass to @p callback.
*
* @returns true if the callback was bound successfully.
* @returns true if the callback was executed immediately.
* @returns false if the prim path passed corresponds to a prim that's not
* of type `OmniSound`.
* @returns false if the prim path passed did not correspond to any prim.
* @returns false if an unexpected error prevents the callback from occurring.
*
* @remarks This will fire the callback when the sound's asset is loaded or
* immediately if the asset was already loaded. The callback will
* only fire once.
*/
OMNI_USD_API bool subscribeToAssetLoad(AudioManager* mgr, const char* path, void (*callback)(void*), void* callbackContext);
/** Change the active Listener prim in the scene.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] path The path to the Listener prim to set.
* This can be nullptr to leave the active camera as the
* active listener.
* @returns true if the prim at @p path was set as the active prim.
* @returns false if the prim at @p path was not registered with hydra.
* This can occur if hydra has not informed the audio manager about
* its existence yet.
*/
OMNI_USD_API bool setActiveListener(AudioManager* mgr, const char* path);
/** Get the active Listener prim in the scene.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns The path to the active listener if one is set.
* @returns nullptr if no active listener is set, which means the active camera
* is being used as the listener.
*/
OMNI_USD_API const char* getActiveListener(AudioManager* mgr);
/** Retrieves the total number of listener prims in the current stage.
*
* @param[in] mgr The stage audio manager instance that this function acts upon. This
* must not be nullptr.
* @returns The total number of listener prims in the current stage. Note that this will
* reflect the total number of listener prims that have been registered with the
* audio manager. This will not necessarily always match with the number of
* listener prims that USD knows about from one moment to the next. There may be
* a small delay between when a prim is added or removed and when the audio manager
* is notified of that change.
*/
OMNI_USD_API size_t getListenerCount(AudioManager* mgr);
/** Retrieves the SDF path of an indexed listener prim in the current stage.
*
* @param[in] mgr The stage audio manager instance that this function acts upon. This
* must not be `nullptr`.
* @param[in] index The zero based index of the listener prim to retrieve the SDF path for.
* This should be between 0 and one less than the most recent return value
* from getListenerCount().
* @param[out] sdfPath Receives the SDF path of the requested listener prim. This may not be
* `nullptr`.
* @param[in] maxLen The maximum number of characters including the terminating null that can
* fit in @p sdfPath.
* @returns `true` if the path of the requested listener prim is successfully returned. Returns
* `false` otherwise.
*/
OMNI_USD_API bool getListenerByIndex(AudioManager* mgr, size_t index, char* sdfPath, size_t maxLen);
/** Set the default value for whether doppler calculations are enabled for the current USD Stage.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The value to set this as.
* The default value of this is @ref FeatureDefault::eOff.
* This is the default because Doppler effect's implementation
* is still experimental. The default will be switched to
* @ref FeatureDefault::eOn when the feature is stabilized.
* @remarks This will append the USD Stage metadata to add this new scene setting.
*/
OMNI_USD_API void setDopplerDefault(AudioManager* mgr, FeatureDefault value = FeatureDefault::eOff);
/** Get the default value for whether doppler calculations are enabled for the current USD Stage.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns The default value for whether doppler calculations are enabled for the current USD Stage.
*/
OMNI_USD_API FeatureDefault getDopplerDefault(AudioManager* mgr);
/** Set the default value for whether distance delayed audio is enable for the current USD Stage.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The value to set this as.
* The default value of this is @ref FeatureDefault::eOff.
* This is the default because distance delay can have a very
* confusing effect if worldUnitScale hasn't been set correctly.
* @remarks This will append the USD Stage metadata to add this new scene setting.
*/
OMNI_USD_API void setDistanceDelayDefault(AudioManager* mgr, FeatureDefault value = FeatureDefault::eOff);
/** Set the default value for whether distance delayed audio is enable for the current USD Stage.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns The default value for whether distance delayed audio is enable for the current USD Stage.
*/
OMNI_USD_API FeatureDefault getDistanceDelayDefault(AudioManager* mgr);
/** Set the default value for whether interaural delay is enabled for the current USD Stage.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The value to set this as.
* The default value of this is @ref FeatureDefault::eOff.
* This feature is currently not implemented.
* @remarks This will append the USD Stage metadata to add this new scene setting.
*/
OMNI_USD_API void setInterauralDelayDefault(AudioManager* mgr, FeatureDefault value = FeatureDefault::eOff);
/** Get the default value for whether interaural delay is enabled for the current USD Stage.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns the default value for whether interaural delay is enabled for the current USD Stage.
*/
OMNI_USD_API FeatureDefault getInterauralDelayDefault(AudioManager* mgr);
/** The minimum number of sounds in a scene that can be played concurrently.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The new value for the number of concurrent voices.
*
* @remarks In a scene where `concurrentVoice` is set to `N` and `N + 1`
* sounds are played concurrently, Omniverse Kit will choose to not
* play the `N+1`th sound to the audio device and just track it as a
* 'virtual' voice.
* The voices chosen to become 'virtual' will be the lowest priority
* or silent. A 'virtual' voice should begin playing again as soon
* as one of the `N` playing voices has finished.
*/
OMNI_USD_API void setConcurrentVoices(AudioManager* mgr, int32_t value = 64);
/** Gets the minimum number of sounds in a scene that can be played concurrently.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns the minimum number of sounds in a scene that can be played concurrently.
*/
OMNI_USD_API int32_t getConcurrentVoices(AudioManager* mgr);
/** Sets the speed of sound in the medium surrounding the listener (typically air).
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The new value for the speed of sound.
*
* @remarks This is measured in meters per second.
* This would typically be adjusted when doing an underwater scene.
* The speed of sound in dry air at sea level is approximately 340.0m/s.
*
*/
OMNI_USD_API void setSpeedOfSound(AudioManager* mgr, double value = carb::audio::kDefaultSpeedOfSound);
/** Gets the speed of sound in the medium surrounding the listener (typically air).
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns The speed of sound in the medium surrounding the listener.
*/
OMNI_USD_API double getSpeedOfSound(AudioManager* mgr);
/** Sets a scaler that can exaggerate or lessen the Doppler effect.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The new value for the doppler scale.
*
* @remarks Setting this above 1.0 will exaggerate the Doppler effect.
* Setting this below 1.0 will lessen the Doppler effect.
* Negative values and zero are not allowed.
* Doppler effects alter the pitch of a sound based on its relative
* velocity to the listener.
*/
OMNI_USD_API void setDopplerScale(AudioManager* mgr, double value = 1.0);
/** Gets a scaler for the doppler effect.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns The scaler for the doppler effect.
*/
OMNI_USD_API double getDopplerScale(AudioManager* mgr);
/** Sets a Limit on the maximum Doppler pitch shift that can be applied to a playing voice.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The new value for the doppler limit.
*
* @remarks Since Omniverse Kit does not handle supersonic spatial audio, a
* maximum frequency shift must be set for prims that move toward the
* listener at or faster than the speed of sound. This is mostly
* useful for handling edge cases such as teleporting an object far
* away while it's playing a sound.
*/
OMNI_USD_API void setDopplerLimit(AudioManager* mgr, double value = 2.0);
/** Gets a Limit on the maximum Doppler pitch shift that can be applied to a playing voice.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns The Limit on the maximum Doppler pitch shift that can be applied to a playing voice.
*/
OMNI_USD_API double getDopplerLimit(AudioManager* mgr);
/** This sets the timescale modifier for all spatial voices.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] value The new value for the spatial timescale.
*
* @remarks Each spatial OmniSound prim multiplies its timeScale attribute by this value.
* For example, setting this to 0.5 will play all spatial sounds at
* half speed and setting this to 2.0 will play all non-spatial
* sounds at double speed.
* This affects delay times for the distance delay effect.
* Altering the playback speed of a sound will affect the pitch of the sound.
* The limits of this setting under Omniverse Kit are [1/1024, 1024].
* This feature is intended to allow time-dilation to be performed with the
* sound effects in the scene without affecting non-spatial elements like
* the background music.
*/
OMNI_USD_API void setSpatialTimeScale(AudioManager* mgr, double value = 1.0);
/** This gets the timescale modifier for all spatial voices.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns The timescale modifier for all spatial voices.
*/
OMNI_USD_API double getSpatialTimeScale(AudioManager* mgr);
/** The timescale modifier for all non-spatial voices.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be ptr.
* @param[in] value The new value for the non-spatial timescale.
*
* @remarks Each prim multiplies its timeScale attribute by this value.
* For example, setting this to 0.5 will play all non-spatial sounds
* at half speed and setting this to 2.0 will play all non-spatial
* sounds at double speed.
* Altering the playback speed of a sound will affect the pitch of the sound.
* The limits of this setting under Omniverse Kit are [1/1024, 1024].
*/
OMNI_USD_API void setNonSpatialTimeScale(AudioManager* mgr, double value = 1.0);
/** The timescale modifier for all non-spatial voices.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be ptr.
* @returns The timescale modifier for all non-spatial voices.
*/
OMNI_USD_API double getNonSpatialTimeScale(AudioManager* mgr);
/** Test whether the Hydra audio plugin is accessible.
* @returns This returns true if the plugin could load.
* @returns This returns false if the plugin failed to load or doesn't exist.
* @remarks This is intended to allow the tests to check whether the Hydra audio
* plugin is still working.
*/
OMNI_USD_API bool testHydraPlugin();
/** Switch to use a new device for for audio output.
*
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be ptr.
* @param[in] deviceName the name or GUID of the device to set as active. This must
* exactly match the name or GUID of one of the devices attached
* to the system at the time. If the given name or GUID doesn't
* match one of the connected devices, the default device will be
* used instead. This may be set to nullptr or an empty string
* to use the system's default device.
* @returns no return value.
*
* @remarks This sets the device that the audio manager will use for its output. If the
* requested device cannot be used for any reason, the default output device will
* be used instead. The device may change the final output format. If a streamer
* is attached to the previous output, its stream will be closed before opening
* a new stream on the new device. Even if the new device name matches the current
* device's name, the device will still be changed and any stream reset.
*
* @note If multiple devices attached to the system have the same name, the one that is
* chosen may be undefined. This can be a common issue with certain devices showing
* up in the system as simply "Speakers". Using the device's GUID instead will allow
* a specific device to be used instead, even its name exactly matches that of another
* device.
*/
OMNI_USD_API void setDevice(AudioManager* mgr, const char* deviceName);
/** creates a new capture streamer.
*
* @param[in] mgr the audio manager to create the new streamer on. This may not be nullptr.
* @returns the handle to a new capture streamer if it is successfully created. When this
* handle is no longer needed, it must be destroyed with destroyCaptureStreamer().
* @returns @ref kInvalidStreamerId if the new capture streamer could not be created.
*/
OMNI_USD_API StreamerId createCaptureStreamer(AudioManager* mgr);
/** destroys a capture streamer.
*
* @param[in] mgr the audio manager to destroy the streamer for. This may not be nullptr.
* @param[in] id the streamer to be destroyed. If this streamer is currently running a
* capture, it will be stopped first. Note that currently stopping one
* streamer will stop all installed streamers. All but the removed one
* will be restarted afterward. This will have the side effect of
* overwriting each other streamer's file though. This can be avoided
* by stopping all streamers simultaneously first with stopCaptures().
* @returns no return value.
*/
OMNI_USD_API void destroyCaptureStreamer(AudioManager* mgr, StreamerId id);
/** sets the filename that a capture streamer will write to.
*
* @param[in] mgr the audio manager that owns the streamer @p id. This may not be nullptr.
* @param[in] id the streamer to set the filename for. This handle will have been
* returned from a previous call to createCaptureStreamer(). This may
* not be @ref kInvalidStreamerId.
* @param[in] filename the name and path of the file to write the streamer's data to once
* its capture is started. If the filename is set here, a nullptr
* filename may be passed into startCapture().
* @returns `true` if the given filename is valid and writable.
* @returns `false` if the streamer ID @p id is not valid.
* @returns `false` if the given filename is not writable.
*
* @note A streamer can have one of: a filename, an interface or an event stream.
* Attaching this filename will remove the interface set by @ref setCaptureInterface()
* or the event stream set by @ref createEventStreamForCapture().
* Calling either of @ref setCaptureInterface() or @ref createEventStreamForCapture()
* will remove the attached filename.
*
*/
OMNI_USD_API bool setCaptureFilename(AudioManager* mgr, StreamerId id, const char* filename);
/** Sets the streamer interface that data will be streamed to.
* @param[in] mgr The audio manager that owns the streamer @p id. This may not be nullptr.
* @param[in] id The streamer to set the callbacks for. This handle will have been
* returned from a previous call to createCaptureStreamer(). This may
* not be @ref kInvalidStreamerId.
* @param[in] streamer The interface that data will be sent to.
* This may not be nullptr.
* The lifetime of this object is managed by the caller.
* This object must remain valid until destroyCaptureStreamer() is called.
* @returns `true` if the operation succeeded.
* @returns `false` if an error occurred.
*
* @note A streamer can have one of: a filename, an interface or an event stream.
* Attaching this interface will remove the filename set by @ref setCaptureFilename()
* or the event stream set by @ref createEventStreamForCapture().
* Calling either of @ref setCaptureFilename() or @ref createEventStreamForCapture()
* will remove the attached interface.
*/
OMNI_USD_API bool setCaptureInterface(AudioManager* mgr, StreamerId id, Streamer* streamer);
/** Creates an event stream that the capture streamer will send data to.
* @param[in] mgr The audio manager that owns the streamer @p id. This may not be nullptr.
* @param[in] id The streamer to set the callbacks for. This handle will have been
* returned from a previous call to createCaptureStreamer(). This may
* not be @ref kInvalidStreamerId.
*
* @returns The newly created event stream that's attached to streamer @p id.
* This event streamer is a @ref carb::audio::EventStreamer, so you can
* use @ref carb::audio::EventListener or another interoperable
* implementation to subscribe to this event stream.
* `IEventStreamPtr` objects are RAII ref counted, so you discard the
* object or call `release()` on it when you're done with it.
* If another streamer output is set with @ref setCaptureFilename() or
* @ref setCaptureInterface() after this, the returned object will
* still be valid but events will no longer be pushed to it.
*
* @note A streamer can have one of: a filename, an interface or an event stream.
* Creating this event stream will remove the filename set by @ref setCaptureFilename()
* or the interface set by @ref setCaptureInterface().
* Calling either of @ref setCaptureFilename() or @ref setCaptureInterface()
* will disconnect the returned event stream.
*/
OMNI_USD_API carb::events::IEventStreamPtr createEventStreamForCapture(AudioManager* mgr, StreamerId id);
/** starts the capture on a single streamer.
*
* @param[in] mgr the audio manager that owns the streamer @p id. This may not be nullptr.
* @param[in] id the handle of the streamer to start. This handle will have been
* returned from a previous call to createCaptureStreamer(). This
* may not be @ref kInvalidStreamerId.
* @param[in] filename the name and path of the filename to write the streamer's data to
* once its capture is started. If a filename was set with a previous
* call to setCaptureFilename() on the same streamer, this may be
* nullptr to use that filename. If a non-nullptr and non-empty
* filename is given here, it will always override any filename
* previously set on the streamer.
* Set this to `nullptr` if you're using a capture callback.
* @returns true if the streamer is successfully started. Note that starting a streamer
* currently has the side effect of stopping and restarting all other streamers
* that are currently running a capture. This will result in each streamer's
* output file being overwritten. If multiple streamers need to be started
* simultaneously, startCaptures() should be used instead.
* @returns false if the streamer could not be started.
*/
OMNI_USD_API bool startCapture(AudioManager* mgr, StreamerId id, const char* filename = nullptr);
/** starts multiple streamers simultaneously.
*
* @param[in] mgr the audio manager that owns the streamer handles in @p ids. This
* may not be nullptr.
* @param[in] ids the table of streamers to start a capture on. Any entries that
* are set to @ref kInvalidStreamerId in this table will be ignored.
* Each valid entry must have had its filename set with
* setCaptureFilename() first otherwise it will be skipped. Any
* streamer that is already running a capture will be skipped, but
* a side effect of this operation will be that its stream will be
* closed and reopened thereby overwriting its file. this may not
* be nullptr.
* @param[in] count the total number of entries in the @p streamers table to start.
* Since @ref kInvalidStreamerId entries are allowed in the table,
* this count must include those invalid entries.
* @returns true if at least one streamer is successfully started.
* @returns false if no streamers could be started or all streamers were skipped for one
* of the reasons listed under @p streamers.
*
* @remarks This attempts to start one or more streamers simultaneously. If successful,
* all streamers are guaranteed to be started in sync with each other such that
* their first written audio frame matches. If this method is used to start
* multiple streamers, the stopCaptures() function must also be used to stop
* those same streamers simultaneously. If another streamer starts or stops
* independently, it will cause all streamers to be closed then reopened
* which will overwrite each of their files.
*/
OMNI_USD_API bool startCaptures(AudioManager* mgr, StreamerId* ids, size_t count);
/** stops the capture on a single streamer.
*
* @param[in] mgr the audio manager that owns the streamer @p id. This may not be nullptr.
* @param[in] id the handle to the streamer to stop. This will have been returned from
* a previous call to createCaptureStreamer(). If a capture is not running
* on this streamer, it will be ignored. This may not be
* @ref kInvalidStreamerId.
* @returns true if the streamer is successfully stopped.
* @returns false if the streamer handle was invalid or a capture was not running on it.
*/
OMNI_USD_API bool stopCapture(AudioManager* mgr, StreamerId id);
/** stops the capture on multiple streamers simultaneously.
*
* @param[in] mgr the audio manager that owns the streamer handles in @p ids. This
* may not be nullptr.
* @param[in] ids the table of streamers to stop the capture on. Any
* @ref kInvalidStreamerId entries will be ignored. Each valid
* entry must be currently running a capture otherwise it will be
* skipped. This may not be nullptr.
* @param[in] count the total number of entries in the @p streamers table to stop.
* Since @ref kInvalidStreamerId entries are allowed in the table,
* this count must include those invalid entries.
* @returns true if at least one streamer is successfully stopped.
* @returns false if no streamers could be stopped.
*/
OMNI_USD_API bool stopCaptures(AudioManager* mgr, StreamerId* ids, size_t count);
/** Wait until the capture streamer has been disconnected.
* @param[in] mgr The audio manager that owns the streamer handles in @p ids. This
* may not be nullptr.
* @param[in] id The handle to the streamer to wait for. This will have been returned from
* a previous call to createCaptureStreamer(). If a capture is not running
* on this streamer, it will be ignored. This may not be
* @ref kInvalidStreamerId.
* @param[in] timeoutMilliseconds The maximum number of milliseconds to wait for the streamer to close.
* @returns `true` if the capture streamer has disconnected.
* @returns `false` if the call timed out before the streamer could disconnect.
* @returns `false` if @p id uses an event stream; that system is asynchronous
* and may continue to send data after the streamer has disconnected.
* Unsubscribe from the event stream to ensure data callbacks will no
* longer be sent. You can call the `unsubscribe()` method on the
* `ISubscriptionPtr` object to unsubscribe from the stream.
* @remarks Because stopCapture() does not stop the audio system or otherwise block
* to ensure that the streamer is disconnected, you must call waitForCapture()
* to verify that a capture streamer has actually finished.
* This is mainly useful if you need to verify that a file written by
* a streamer has finished being written.
* For a callback streamer, waitForCapture() will begin returning true
* immediately before close() is called.
*/
OMNI_USD_API bool waitForCapture(AudioManager* mgr, StreamerId id, size_t timeoutMilliseconds);
/** retrieve the event stream for metadata changes.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @returns An event stream which is pushed when metadata is changed.
* @returns nullptr if the event stream could not be created for some reason.
*
* @remarks This generates events of type @ref kEventMetadataChange when the
* audio metadata in the USD scene changes.
*/
OMNI_USD_API carb::events::IEventStream* getMetadataChangeStream(AudioManager* mgr);
/** Draw the waveform for the sound asset of an audio prim.
* @param[in] mgr The stage audio manager instance that this function acts upon.
* This must not be nullptr.
* @param[in] primPath The path to sound prim which has the sound asset that will
* be rendered.
* Note that the `mediaOffsetStart` and `mediaOffsetEnd`
* properties of the prim are used to choose the region of
* the sound that is drawn.
* The asset for this prim must have been loaded or the
* call will fail.
* @param[in] image The description of how the image should be rendered.
* If this descriptor is invalid, the call will fail.
*
* @returns `true` if the image was successfully drawn.
* @returns `false` if @p primPath isn't a valid prim.
* @returns `false` if the sound asset has not been loaded yet.
* @returns `false` if @p image was invalid.
*
* @remarks This will draw an RGBA image of the waveform of the sound asset
* in use by a `OmniSound` prim.
*/
OMNI_USD_API bool drawWaveform(AudioManager* mgr, const char* primPath, AudioImageDesc *image);
/** @} */
}
}
}
| 51,087 | C | 51.886128 | 124 | 0.678646 |
omniverse-code/kit/include/omni/usd/UsdContext.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#ifndef USD_CONTEXT_INCLUDES
# error "Please include UsdContextIncludes.h before including this header or in pre-compiled header."
#endif
#include <carb/events/EventsUtils.h>
#include <omni/usd/UsdContextOverrides.h>
#include <omni/usd/Api.h>
#include <omni/usd/UsdTypes.h>
#include <omni/usd/ViewportTypes.h>
#include <omni/usd/IUsdMutex.h>
#include <omni/usd-abi/IPathAbi.h>
#include <memory>
PXR_NAMESPACE_OPEN_SCOPE
class UsdGeomBBoxCache;
PXR_NAMESPACE_CLOSE_SCOPE
namespace carb
{
namespace renderer
{
struct Renderer;
struct Context;
enum class FrameDataType;
}
namespace scenerenderer
{
struct Scene;
typedef struct Scene* SceneId;
enum class CameraFit;
struct SceneRenderer;
struct Context;
}
namespace settings
{
struct ISettings;
}
}
namespace rtx
{
namespace resourcemanager
{
// TODO: This must stay in sync with the actual typedef of SyncScopeId
typedef uint32_t SyncScopeId;
}
}
namespace omni
{
namespace timeline
{
class Timeline;
using TimelinePtr = std::shared_ptr<Timeline>;
};
namespace usd
{
typedef std::unordered_set<PXR_NS::SdfPath, PXR_NS::SdfPath::Hash> SdfPathUSet;
class Selection;
struct Layers;
class UsdManager;
namespace hydra
{
class IHydraEngine;
struct IHydraSceneDelegate;
struct CameraSettings;
struct ViewportHydraRenderResults;
struct OpaqueSharedHydraEngineContext;
typedef struct OpaqueSharedHydraEngineContext* OpaqueSharedHydraEngineContextPtr;
struct HydraEngineContextConfig;
struct EngineCreationConfig;
enum class EngineCreationFlags : uint32_t;
OMNI_DECLARE_INTERFACE(IViewOverrideBase);
}
namespace audio
{
class AudioManager;
}
struct HydraEngineDesc
{
uint32_t tickRate;
const char* engineName;
const char* threadName;
uint32_t currentHydraEngineIdx;
uint32_t deviceMask;
hydra::EngineCreationFlags flags;
};
/**
* @brief Specifies the initial set of prims to load when opening a UsdStage.
*/
enum class UsdContextInitialLoadSet
{
eLoadAll,
eLoadNone,
};
class UsdContext
{
public:
// TODO: getContext needs to me removed, but it's called 160 times across 33 files.
// Keep stub that invokes UsdManager::getContext for now to reduce MR
/**
* Gets a UsdContext.
*
* @param name of the UsdContext to get. The default context is named with empty string "".
*/
OMNI_USD_API static UsdContext* getContext(const std::string& name = "");
/**
* Adds a hydra engine with associated renderer to context. The syncScopes determines
* which rendering thread the hydra engine should run on. It should correspond
* to the syncScope that was passed into the IHydraEngine during creation
*
* @return true if hydra engines are created, false otherwise
*/
OMNI_USD_API bool addHydraEngine(const char* name,
omni::usd::hydra::IHydraEngine* hydraEngine,
omni::usd::hydra::OpaqueSharedHydraEngineContextPtr ctx,
const omni::usd::hydra::HydraEngineContextConfig& config,
bool defer);
/**
* Destroys all hydra engines
*/
OMNI_USD_API void removeAllHydraEngines();
/**
* Controls two things:
* 1. Specifies the default hydra engine to use with hydraEngine = null in CreateViewport
* 2. [TODO] Controls the hydra engine used for selection and picking, this feels wrong
* and instead the picking api should include a hydra engine, and if non specified
* use the default. This API should instead be setDefaultHydraEngine
*
*/
OMNI_USD_API void setActiveHydraEngine(const char* name);
/**
* Return the name of active hydra engine
*/
OMNI_USD_API const char* getActiveHydraEngineName(void);
/**
* Adds a hydra scene delegate with associated input data to the context
*
* @param name should be unique, and will be used for identifying the scene delegate in
* future calls. If the name is not unique, the add call will fail.
* @param hydraEngine a string representing which hydra engine this delegate should be
* added for. For instance, "rtx"
* @param sceneDelegate the new scene delegate interface to add
* @param delegateCreateParam a parameter to pass to the sceneDelegate's Create function
*
* @return true if successfully added, false otherwise
*/
OMNI_USD_API bool addHydraSceneDelegate(const char* name,
const char* hydraEngine,
const omni::usd::hydra::IHydraSceneDelegate& sceneDelegate,
const char* delegateCreateParam);
/**
* Removes a hydra scene delegate
*
* @param name should match the name passed to addHydraSceneDelegate
*
* @return true if successfully removed, false otherwise
*/
OMNI_USD_API bool removeHydraSceneDelegate(const char* name);
/**
* Sets a global tansform for all content in a named hydra scene delegate
*
* @param name should match the name passed to addHydraSceneDelegate
* @param xform a transform to apply to everything in the delegate
*
* @return true if successfully removed, false otherwise
*/
OMNI_USD_API bool setHydraSceneDelegateRootTransform(const char* name, const PXR_NS::GfMatrix4d& xform);
/**
* Gets a named attribute of a prim from a named hydra scene delegate
*
* @param name should match the name passed to addHydraSceneDelegate
* @param primPath is the path to the prim containing the attribute
* @param attributeName name of the attribute
* @param attributeValue a VtValue to populate with the value of the attribute
*
* @return true if successfully accessed the scene delegate, false otherwise
*/
OMNI_USD_API bool getHydraSceneDelegateAttribute(const char* name, const PXR_NS::SdfPath &primPath, const PXR_NS::TfToken &attribueName, PXR_NS::VtValue &attributeValue);
/**
* Computs a world bounding box for all content in a named hydra scene delegate
*
* @param name should match the name passed to addHydraSceneDelegate
* @param bbox is an array of 12 elements (4 x vector3, min/max bounds, center, size)
*/
OMNI_USD_API void computeHydraSceneDelegateWorldBoundingBox(const char* name, double* bbox);
/**
* Returns true if the Fabric scene delegate is in use. This changes
* behavior in Fabric population, StageReaderWriter copies to the ring
* buffer, and Fabric USD notice handling
*
* This is the value of the "/app/useFabricSceneDelegate" carb setting
* when the stage is first loaded, and remains constant until the
* next stage load to avoid bad behavior with already allocated scene
* delegates and hydra engines.
*/
OMNI_USD_API bool useFabricSceneDelegate() const;
/**
* Checks if any Hydra Renderer supports MDL
*
* @return true if a Hydra renderer supports MDL, false otherwise.
*/
OMNI_USD_API bool hasMDLHydraRenderer() const;
/**
* Returns the RTX SceneRenderer if a "rtx" hydra engine
* exists, otherwise nullptr. Note, tighly coupled with getScene()
*
* [TODO] Remove this API
* Used for PrimitiveListDrawing
* Trigger "compile shaders" for F9
* MaterialWatcher for getNeurayDbScopeName()
* Kit.Legacy Editor python bindings for get_current_renderer_status
*
*/
OMNI_USD_API carb::scenerenderer::SceneRenderer* getSceneRenderer() const;
/**
* Returns the RTX SceneRenderer Context if a "rtx" hydra engine
* exists, otherwise nullptr
*
*/
OMNI_USD_API carb::scenerenderer::Context* getSceneRendererContext() const;
/**
* Update function to be called once every frame.
*
* @param elapsedTime Elapsed time in seconds since last update call.
* @return true if omniverse has new update during this frame.
*/
OMNI_USD_API bool update(float elapsedTime);
/**
* Creates a new USD stage. This is an asynchronous call.
*
* @param fn the callback function when stage is created or fails to create.
*/
OMNI_USD_API bool newStage(const OnStageResultFn& resultFn);
/**
* Synchronous version of @see newStage(const OnStageResultFn& resultFn);
*/
OMNI_USD_API bool newStage();
/**
* Attaches an opened USD stage. This is an asynchronous call.
*
* @param stageId The stage id saved into UsdUtilsStageCache.
* @param fn The callback function when stage is attached successfully or fails to attach.
*/
OMNI_USD_API bool attachStage(long int stageId, const OnStageResultFn& resultFn);
/**
* Opens a existing USD stage. This is an asynchronous call.
*
* @param url The file path. For Omniverse file, you must connect to Omniverse first and pass the url with prefix
* "omniverse:".
* @param fn The callback function when stage is opened or fails to open.
* @param loadSet Specifies the initial set of prims to load when opening a UsdStage.
*/
OMNI_USD_API bool openStage(const char* fileUrl,
const OnStageResultFn& resultFn,
UsdContextInitialLoadSet loadSet = UsdContextInitialLoadSet::eLoadAll);
/**
* Synchronous version of @see openStage(const char* fileUrl, const OnStageResultFn& resultFn);
*/
OMNI_USD_API bool openStage(const char* fileUrl,
UsdContextInitialLoadSet loadSet = UsdContextInitialLoadSet::eLoadAll);
/**
* Reopens current USD stage. This is an asynchronous call.
*
* @param fn The callback function when stage is reopened or fails to reopen.
*/
OMNI_USD_API bool reopenStage(const OnStageResultFn& resultFn,
UsdContextInitialLoadSet loadSet = UsdContextInitialLoadSet::eLoadAll);
/**
* Synchronous version of @see reopenStage(const OnStageResultFn& resultFn);
*/
OMNI_USD_API bool reopenStage(UsdContextInitialLoadSet loadSet = UsdContextInitialLoadSet::eLoadAll);
/**
* Close current USD stage. This is an asynchronous call.
*
* @param fn The callback function when stage is closed for fails to close.
*/
OMNI_USD_API bool closeStage(const OnStageResultFn& resultFn);
/**
* Synchronous version of @see closeStage(const OnStageResultFn& resultFn);
*/
OMNI_USD_API bool closeStage();
/**
* Saves specific layer only. This is an asynchronous call.
*
* @param layerIdentifier The layer to save.
* @param fn The callback function when stage is saved or fails to save.
* @return true if it's saved successfully.
*/
OMNI_USD_API bool saveLayer(const std::string& layerIdentifier, const OnLayersSavedResultFn& resultFn);
/**
* Synchronous version of @see saveLayer(const std::string& layerIdentifier, const OnStageResultFn& resultFn);
*/
OMNI_USD_API bool saveLayer(const std::string& layerIdentifier);
/**
* Saves specific layers only. This is an asynchronous call.
*
* @param newRootLayerPath If it's not empty, it means to do save root layer
* to new place. This will trigger stage reload to open new root layer.
* @param layerIdentifiers The layers to save. It will save all dirty changes of them.
* @param fn The callback function when stage is saved or fails to save.
* @return true if it's saved successfully.
*/
OMNI_USD_API bool saveLayers(const std::string& newRootLayerPath,
const std::vector<std::string>& layerIdentifiers,
const OnLayersSavedResultFn& resultFn);
/**
* Synchronous version of @see saveLayers
*/
OMNI_USD_API bool saveLayers(const std::string& newRootLayerPath, const std::vector<std::string>& layerIdentifiers);
/**
* Saves current USD stage. This is an asynchronous call.
*
* @param fn The callback function when stage is saved or fails to save.
*/
OMNI_USD_API bool saveStage(const OnLayersSavedResultFn& resultFn);
/**
* Synchronous version of @see saveStage(const OnStageResultFn& resultFn);
*/
OMNI_USD_API bool saveStage();
/**
* Saves current USD stage to a different location. This is an asynchronous call.
*
* @param url The new location to save the USD stage.
* @param fn The callback function when stage is saved or fails to save.
*/
OMNI_USD_API bool saveAsStage(const char* url, const OnLayersSavedResultFn& resultFn);
/**
* Synchronous version of @see saveAsStage(const char* url, const OnStageResultFn& resultFn);
*/
OMNI_USD_API bool saveAsStage(const char* url);
/**
* Exports current USD stage to a different location. This is an asynchronous call.
* It will composite current stage into a single flattened layer.
*
* @param url The new location to save the USD stage.
* @param fn The callback function when stage is saved or fails to save.
*/
OMNI_USD_API bool exportAsStage(const char* url, const OnStageResultFn& resultFn) const;
/**
* Synchronous version of @see exportAsStage(const char* url, const OnStageResultFn& resultFn) const;
*/
OMNI_USD_API bool exportAsStage(const char* url) const;
/**
* Checks if currently opened stage is created by calling @ref newStage.
*
* @return true if current stage is a new stage.
*/
OMNI_USD_API bool isNewStage() const;
/**
* Checks if it's safe to close stage at calling time.
*
* @return true if it is safe to close the stage (when current stage is fully opened).
* false if it's unsafe to close current stage (when current stage is still being opened or closed).
*/
OMNI_USD_API bool canCloseStage() const;
/**
* Checks if a USD stage is opened and in a savable stage (not opening/closing in progress).
*
* @return true if the stage is opened and savable, false is no stage is opened or opened stage is not savable.
*/
OMNI_USD_API bool canSaveStage() const;
/**
* Checks if it's safe to open a different stage at calling time.
*
* @return true if it is safe to open a different stage (when current stage is fully opened or closed).
* false if it's unsafe to open different stage (when current stage is still being opened or closed).
*/
OMNI_USD_API bool canOpenStage() const;
/**
* Checks if there is enough permissions to save the stage at calling time.
*
* @return true if it is possible to save the stage.
* false if it's not possible to save current stage.
*/
OMNI_USD_API bool isWritable() const;
/**
* Gets the state of current stage.
*
* @return state of current stage.
*/
OMNI_USD_API omni::usd::StageState getStageState() const;
/**
* Gets UsdStage.
*
* @return UsdStageWeakPtr of current stage.
*/
OMNI_USD_API PXR_NS::UsdStageWeakPtr getStage() const;
/**
* Gets UsdStage id.
*
* @return id of current stage.
*/
OMNI_USD_API long int getStageId() const;
/**
* Gets the url of current stage.
*
* @return url of current stage.
*/
OMNI_USD_API const std::string& getStageUrl() const;
/**
* Checks if current stage is dirty.
*
* @return true if current stage is dirty.
*/
OMNI_USD_API bool hasPendingEdit() const;
/**
* Marks the edits state of current opened stage. It means changes are
* pending to be saved if you set it to true, or false otherwise. This will
* disgard the real state of opened stage. For example, if the opened stage
* has real changes to be saved, hasPendingEdit() will still return false if
* you set it to false.
*
* @param edit true to set pending edits state, false to unset pending edits state
*/
OMNI_USD_API void setPendingEdit(bool edit);
/**
* Gets the carb::events::IEventStreamPtr for StageEvent.
*
* @return the carb::events::IEventStream for StageEvent.
*/
OMNI_USD_API carb::events::IEventStreamPtr getStageEventStream();
/**
* Gets the carb::events::IEventStreamPtr for RenderingEvent.
*
* @return the carb::events::IEventStream for RenderingEvent.
*/
OMNI_USD_API carb::events::IEventStreamPtr getRenderingEventStream();
/**
* Sends a StageEvent to UsdStageEvent stream.
* It chooses to send event sync/async based on syncUsdLoads option.
*
* @param event The event to be sent.
* @param blockingAsync If the event is sent as async, true to wait on the event until it has been processed by all
* subscribers. false to return immediately.
*/
OMNI_USD_API void sendEvent(carb::events::IEventPtr& event, bool blockingAsync = false);
/**
* Gets if the current stage is opened from Omniverse.
*
* @return true if the stage is opened from Omniverse.
*/
OMNI_USD_API bool isOmniStage() const;
/**
* Saves render settings to current opened USD stage.
*/
OMNI_USD_API void saveRenderSettingsToCurrentStage();
/**
* Loads render settings from stage.
*
* @param stageId The stage id saved into UsdUtilsStageCache.
*/
OMNI_USD_API void loadRenderSettingsFromStage(long int stageId);
/**
* Gets the picked position in world space since last picking request.
*
* @param outWorldPos The picked world space position.
* @return true if the result is valid, false if result is not valid.
*/
OMNI_USD_API bool getPickedWorldPos(ViewportHandle handle, carb::Double3& outWorldPos);
/**
* Gets the picked geometry hit data - position in world space and normal since last picking request.
*
* @param outWorldPos The picked world space position.
* @param outNormal The picked normal.
* @return true if the result is valid, false if result is not valid.
*/
OMNI_USD_API bool getPickedGeometryHit(ViewportHandle handle, carb::Double3& outWorldPos, carb::Float3& outNormal);
/**
* Gets the AABB of a prim.
*
* @param prim The prim to get AABB from.
* @return The AABB of the prim.
*/
OMNI_USD_API PXR_NS::GfRange3d computePrimWorldBoundingBox(const pxr::UsdPrim& prim);
/**
* Gets the AABB of a path as carb::Doubles3 (primarily for Python).
*
* @param path The path to get AABB from.
* @param aabbMin Where to store the min-extents.
* @param aabbMax Where to store the max-extents.
*/
OMNI_USD_API void computePathWorldBoundingBox(const std::string& path, carb::Double3& aabbMin, carb::Double3& aabbMax);
/**
* Gets the GfMatrix4 of a prim as stored in the current bbox cache.
*
* @param prim The prim to get the transform of.
* @return The world-space GfMatrix4 of the prim.
*/
OMNI_USD_API PXR_NS::GfMatrix4d computePrimWorldTransform(const pxr::UsdPrim& prim);
/**
* Gets the GfMatrix4 of a path as stored in the current bbox cache.
*
* @param path The path to a prim to get the transform of.
* @return The world-space GfMatrix4 of the prim at the path.
*/
OMNI_USD_API void computePrimWorldTransform(const std::string& path, std::array<double, 16>& flattened);
/**
* Gets the stage loading status.
*
* @param The message of current stage loading.
* @param filesLoaded Number of files already loaded.
* @param totalFiles Total number of files to be loaded.
*/
OMNI_USD_API void getStageLoadingStatus(std::string& message, int32_t& filesLoaded, int32_t& totalFiles);
/**
* Returns all renderable paths for given prim path and its descendatns.
* Renderable paths are prims of type instancer or geometry.
*
* @param primPath Prim path
* @param renderablePathSet An unordered output path set.
*/
OMNI_USD_API void getRenderablePaths(PXR_NS::SdfPath primPath, SdfPathUSet& unOrderedRenderablePathSet);
/**
* Returns all renderable paths for given prim path and its descendatns.
* Renderable paths are prims of type instancer or geometry.
*
* @param primPath Prim path
* @param renderablePathSet An ordered output path set.
*/
template <typename T>
OMNI_USD_API void getRenderablePaths(PXR_NS::SdfPath primPath, T& renderablePathSet);
/**
* Sets the mouse pickable state of a prim.
*
* @param primPath The path of the prim to set pickable state.
* @param isPickable true if to set the prim to be pickable, false to set to unpickable.
*/
OMNI_USD_API void setPickable(const char* primPath, bool isPickable);
/**
* Returns the SceneId from the RTX SceneRenderer if a "rtx" hydra engine
* exists. Note, usage coupled with getSceneRenderer()
*
* @return carb::scenerenderer::SceneId of current scene.
*/
OMNI_USD_API carb::scenerenderer::SceneId getRendererScene();
/**
* Stops all async hydra rendering. Waits for completion of in-flight tasks
* then requests RunLoops for rendering to exit
*/
OMNI_USD_API void stopAsyncRendering();
/**
* Currently writing to usd during async rendering can cause a data race.
* This necessitates the prescence of certain mutex to protect usd data access.
* This call controls the usage of this mutex and will block until it is safe to begin writes.
*
* If a usd write occurs while this is disabled, undefined behavior is likely.
*
* Can only be called from the main thread for safety reasons.
*
* @note This function is deprecated.
*
* @param enabled if true enables the usage of a mutex to protect usd write operations.
*/
OMNI_USD_API void enableUsdWrites(bool enabled);
/**
* USD is a global shared resource. Invoking enableUsdLocking()
* lets UsdContext manage the locking of this resource.
*
* enableUsdLocking will lock() the resource and manage locking/unlocking
* going forward
*
* disableUsdLokcing() will unlock() the resource and make no subsequent
* lock/unlock calls
*
* WARNING: enableUsdLocking and disableUsdLocking will only work when called from the main thread.
*/
OMNI_USD_API void enableUsdLocking();
OMNI_USD_API void disableUsdLocking();
OMNI_USD_API bool isUsdLockingEnabled();
/**
* Returns the status of usd write back. If not true, writing to usd
* may cause undefined behavior.
*
* @note This function is deprecated.
*
* @return true if write back is enabled and false otherwise.
*/
OMNI_USD_API bool usdWritesEnabled();
/**
* Creates a new ViewportHandle for the hydraEngine at the specified tick rate
* A tickrate of -1 means "render as fast as possible"
*
* Will not create a new HydraEngine, a HydraEngine must be available. HydraEngines
* are added by addHydraEngine()
*
* @return ViewportHandle that's used in addRender(), getRenderResults(), destroyViewport()
*/
OMNI_USD_API ViewportHandle createViewport(const char* hydraEngine, uint32_t tickrate, omni::usd::hydra::EngineCreationFlags hydraEngineFlags);
/**
* Destroys the ViewportHandle that was created in createViewport
* then requests RunLoops for rendering to exit
*/
OMNI_USD_API void destroyViewport(ViewportHandle viewportHandle);
/**
* Returns the latest available rendering result. It is assumed main/simulation thread runs
* at the same rate or faster than hydra engine tick rate. If you query the FPS of the
* returned value, it will match the hydra engine render rate
*
* bBlock == true will trigger hydraRendering() + checkForHydraResults() outside
* of defined update order in omni::kit::update::UpdateOrderings *if necessary*
*
* @return ViewportHydraRenderResults the latest available hydra render result
*/
OMNI_USD_API const omni::usd::hydra::ViewportHydraRenderResults* getRenderResults(ViewportHandle viewportHandle,
bool bBlock = false);
/**
* The ViewportHandle and the RenderProduct USD Prim Path to render
*
*/
OMNI_USD_API void addRender(ViewportHandle handle,
omni::usd::PathH renderProductPrimPath,
const Picking* picking = nullptr);
/**
* Gets Selection instance.
*/
OMNI_USD_API Selection* getSelection();
/**
* Gets const Selection instance.
*/
OMNI_USD_API const Selection* getSelection() const;
/**
* Retrieves the stage audio manager for use in the IStageAudio interface.
* @returns The USD context's stage audio manager instance.
* This is valid until the USD context is destroyed.
* @returns nullptr if the stage audio manager was not loaded or failed
* to load.
*/
OMNI_USD_API audio::AudioManager* getAudioManager() const;
OMNI_USD_API void enableSaveToRecentFiles();
OMNI_USD_API void disableSaveToRecentFiles();
/**
* By default UsdContext subscribes to IApp for updates. That can be disabled. Temp function until we refactor
* Editor.cpp
*/
OMNI_USD_API void toggleAutoUpdate(bool enabled);
/**
* Query for instance IDs that are returned to synthetic data
*/
OMNI_USD_API size_t GetGeometryInstanceId(const PXR_NS::SdfPath& path, uint32_t* instanceList);
/**
* Query for geometry IDs that are returned to synthetic data
*/
OMNI_USD_API size_t GetGeometryId(const PXR_NS::SdfPath& path, uint32_t* geometryList);
/**
* Query for mesh instance path that is returned to synthetic data
*/
OMNI_USD_API const std::string& GetGeometryInstancePath(uint32_t instanceId);
/**
* Query for mesh geometry path that is returned to synthetic data
*/
OMNI_USD_API const std::string& GetGeometryPath(uint32_t geometryId);
/**
* Adds path to material/shader loading queue
*
* @param path the path of UsdShadeShader to create MDL materials.
* @param recreate If to force recreating the inputs if it's already populated
* @param loadInputs If to create MDL inputs as UsdAttribute on the UsdShadeShader prim.
* @return true if scheduled successfully, false if inputs are already created and @ref recreate is false.
*/
OMNI_USD_API bool addToPendingCreatingMdlPaths(const std::string& path, bool recreate = false, bool loadInputs = true);
/**
* Get unique gizmo id.
* When it not needed freeGizmoUID should be called so that it can be reused.
* If it is not called this method return the same uid on next call with given path.
* @param path Prim path that will be used for prim selection when gizmo uid is picked.
*/
OMNI_USD_API uint32_t getGizmoUID(const PXR_NS::SdfPath& path);
/**
* Allows to notify that gizmo uid is no longer used.
* @param uid Gizmo unique id.
*/
OMNI_USD_API void freeGizmoUID(uint32_t uid);
/**
* Returns prim path for given gizmo uid.
* @param uid Gizmo unique id.
* @return A pointer to path for given uid or nullptr for invalid uid.
*/
OMNI_USD_API const PXR_NS::SdfPath* getPathForGizmoUID(uint32_t uid);
/**
* Register selection group.
* Note: Supposed that this function called once at app initialization.
*/
OMNI_USD_API uint8_t registerSelectionGroup();
/**
* Setup selection group outline color.
*/
OMNI_USD_API void setSelectionGroupOutlineColor(uint8_t groupId, const carb::Float4& color);
/**
* Setup selection group shade color.
*/
OMNI_USD_API void setSelectionGroupShadeColor(uint8_t groupId, const carb::Float4& color);
/**
* Set selection group for specified primitives path.
*/
OMNI_USD_API void setSelectionGroup(uint8_t groupId, const std::string& path);
/**
* Query for camera settings for the camera prim
*/
OMNI_USD_API omni::usd::hydra::CameraSettings getCameraSettings(const PXR_NS::SdfPath& path, double aspectRatio);
/**
* Set the aperture fit policy
*/
OMNI_USD_API void setCameraWindowPolicy(carb::scenerenderer::CameraFit policy);
/**
* Returns the current frame data based on the requested feature, such as profiler data.
* If frame is not finished processing the data, the result of the previous frame is returned.
* For multi-GPU, query the device count and then set deviceIndex to the desired device index.
*
* @param dataType Specified the requested data type to return.
* @param deviceIndex The index of GPU device to get the frame data from. Set to zero in Single-GPU mode.
* You may query the number of devices with FrameDataType::eGpuProfilerDeviceCount.
* deviceIndex is ignored when the type is set to eGpuProfilerDeviceCount.
* @param data A pointer to the returned data. Returns nullptr for failures or eGpuProfilerDeviceCount.
* You may pass nullptr if you only need dataSize.
* @param dataSize The size of the returned data in bytes, the number of structures, or device count based on
* the dataType. For strings, it includes the null-termination.
* @param engineIndex The index of an attached HydraEngine or -1 for the -active- HydraEngine.
*/
OMNI_USD_API void getFrameData(carb::renderer::FrameDataType dataType,
uint32_t deviceIndex,
void** data,
size_t* dataSize,
uint32_t engineIndex = -1);
// Exposed to Python (see viewport based api getHydraEngineDesc() below)
OMNI_USD_API size_t getAttachedHydraEngineCount() const;
OMNI_USD_API const char* getAttachedHydraEngineName(size_t hydraEngineIdx) const;
// Returns the HydraEngineDesc describing the hydra engine being used by this viewport
OMNI_USD_API HydraEngineDesc getHydraEngineDesc(ViewportHandle handle) const;
/**
* Allow for viewoverrides to be added through the usd context
*/
OMNI_USD_API void registerViewOverrideToHydraEngines(omni::usd::hydra::IViewOverrideBase* viewOverride);
/**
* Allow for viewoverrides to be removed through the usd context
*/
OMNI_USD_API void unregisterViewOverrideToHydraEngines(omni::usd::hydra::IViewOverrideBase* viewOverride);
/**
* Allow scheduling override to be set for usd context
*/
OMNI_USD_API void setUsdContextSchedulingOverride(IUsdContextSchedulingOverride* schedulingOverride);
/**
* Reset scheduling override
*/
OMNI_USD_API void resetUsdContextSchedulingOverride();
/**
* Retrieves the mutex for `*this`
*/
OMNI_USD_API IUsdMutex& getMutex();
/**
* Stop any picking in flight for a specific View
*/
OMNI_USD_API void stopAllPickingForView(ViewPickingId pickingId);
/**
* Sets the timeline. This must be called before the context is used, right after its creation.
*/
OMNI_USD_API void setTimeline(const std::string& name = "");
/**
* Retrieves the name of the timeline
*/
OMNI_USD_API std::string getTimelineName() const;
/**
* Retrieves the timeline
*/
OMNI_USD_API timeline::TimelinePtr getTimeline() const;
/**
* Retrieves the name of the context
*/
OMNI_USD_API std::string getName() const;
/**
* Trigger creation of the runloop associated with the given hydraengine configuration
* (otherwise it will only be created the first time an associated viewport is renderer)
*/
int32_t getOrCreateRunloopThread(const char* name, const hydra::EngineCreationConfig& engineConfig, bool setWarmup);
/**
* Extract the engine warmup config from the settings
*/
typedef std::unordered_map<uint32_t, hydra::EngineCreationConfig> EngineWarmupConfig;
static bool getEngineWarmupConfig(const carb::settings::ISettings& settings, const char* hydraEngineName, EngineWarmupConfig& config);
/**
* Return the default config for hydraengine creation for this engine type, and index
*/
static hydra::EngineCreationConfig getDefaultEngineCreationConfig(const carb::settings::ISettings& settings, const char* engineName,
uint32_t engineIndex);
/*
* Opens a existing USD stage with specified session layer. This is an asynchronous call.
* This funciton can be used to speed up the stage composition to avoid re-composing stage
* caused by inserting a sublayer under session layer after stage opened.
*
* @param url The file path. For Omniverse file, you must connect to Omniverse first and pass the url with prefix
* "omniverse:".
* @param sessionLayerUrl. The specified session layer to use. If it's empty or not provided, it will work
* as the same as openStage. If it's provided but cannot be opened, it will return false.
* @param fn The callback function when stage is opened or fails to open.
* @param loadSet Specifies the initial set of prims to load when opening a UsdStage.
*/
OMNI_USD_API bool openStageWithSessionLayer(const char* fileUrl,
const char* sessionLayerUrl,
const OnStageResultFn& resultFn,
UsdContextInitialLoadSet loadSet = UsdContextInitialLoadSet::eLoadAll);
/*
* Tries to cancel save. It only take effects when it's called after receiving event StageEventType::eSaving or StageEventType::eSettingsSaving.
*/
OMNI_USD_API void tryCancelSave();
private:
/**
* Constructor.
*
* @param name The name of the context.
*/
UsdContext(const std::string& name);
/**
* No copy.
*/
UsdContext(const UsdContext&) = delete;
/**
* No assign.
*/
UsdContext& operator=(const UsdContext&) = delete;
/**
* Destructor.
*/
~UsdContext();
friend UsdManager;
struct Impl;
std::unique_ptr<Impl> m_impl;
};
}
}
| 35,155 | C | 35.393375 | 174 | 0.670886 |
omniverse-code/kit/include/omni/usd/Api.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#if defined _WIN32
# ifdef OMNI_USD_EXPORTS
# define OMNI_USD_API __declspec(dllexport)
# else
# define OMNI_USD_API __declspec(dllimport)
# endif
#else
# ifdef OMNI_USD_EXPORTS
# define OMNI_USD_API __attribute__((visibility("default")))
# else
# define OMNI_USD_API
# endif
#endif
| 783 | C | 31.666665 | 77 | 0.719029 |
omniverse-code/kit/include/omni/usd/UsdManager.h | // 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.
//
#pragma once
#include <carb/IObject.h>
#include <omni/kit/KitTypes.h>
#include <omni/usd/Api.h>
#include <memory.h>
namespace carb
{
namespace settings
{
struct ISettings;
}
}
namespace gpu
{
namespace foundation
{
struct GpuFoundation;
}
}
namespace carb
{
namespace renderer
{
struct Context;
struct Renderer;
}
}
namespace omni
{
namespace usd
{
namespace hydra
{
class IHydraEngineFactory;
enum class EngineCreationFlags : uint32_t;
using IHydraEngineFactoryPtr = carb::ObjectPtr<IHydraEngineFactory>;
struct OpaqueSharedHydraEngineContext;
typedef struct OpaqueSharedHydraEngineContext* OpaqueSharedHydraEngineContextPtr;
/**
* Configuration of an hydraengine
* - UsdManager::getOrCreateHydraEngine will return the same engine if the configuration parameters match
*/
struct EngineCreationConfig
{
EngineCreationFlags flags;
uint32_t tickRateInHz = uint32_t(-1);
};
inline bool operator<(const omni::usd::hydra::EngineCreationConfig& a, const omni::usd::hydra::EngineCreationConfig& b)
{
if (a.tickRateInHz == b.tickRateInHz)
{
return a.flags < b.flags;
}
return (a.tickRateInHz < b.tickRateInHz);
}
}
class UsdContext;
class UsdManager
{
public:
/**
* Creates a UsdContext.
*
* @param name Name of the UsdContext to be created. The default context is named with empty string "".
* @return Created UsdContext, or existing one if a context with same name is already created.
*/
OMNI_USD_API static UsdContext* createContext(const std::string& name = "");
/**
* Destroys a UsdContext.
*
* @param name of the UsdContext to be destroyed. The default context is named with empty string "".
* @return true if destroyed successfully, false if failed.
*/
OMNI_USD_API static bool destroyContext(const std::string& name = "");
/**
* Gets a UsdContext.
*
* @param name of the UsdContext to get. The default context is named with empty string "".
*/
OMNI_USD_API static UsdContext* getContext(const std::string& name = "");
/*
* Use by IHydraEngines at load/unload to register their factory class
*
*/
OMNI_USD_API static void registerHydraEngineFactory(const char* name,
omni::usd::hydra::IHydraEngineFactoryPtr factory);
OMNI_USD_API static void unregisterHydraEngineFactory(const char* name);
/*
* Creates a new hydra engine instance using the registered factory and attaches
* it to the UsdContext. The hydra engine will have it's own unique syncScope
* and run in a separate rendering thread if asyncRendering is enabled
*/
OMNI_USD_API static void addHydraEngine(const char* name, UsdContext* context);
/**
* Adds all loaded hydra engines to the USDContext. Used at startup
*
* All loaded hydra engines will share a single syncScope and run in a single rendering
* thread when asyncRendering is enabled.
*
* Return type, first is the name of the engine, second is an opaque pointer to engine data
*
* Until legacy carb settings /renderer/active and /renderer/enabled are no longer used to
* set the default hydra engine or override what extensions are "enabled", we need this function
* to support legacy STARTUP behavior and it should be executed once AFTER all the extensions have loaded
*/
OMNI_USD_API static std::vector<std::pair<std::string, hydra::OpaqueSharedHydraEngineContextPtr>> attachAllHydraEngines(
UsdContext* context);
/*
* Advances all the hydra engines sync scopes rtx::kMaxFramesInFlight to trigger
* deferred releases of all objects. Typically used to allow fully unloading
* the USD Mesh data before loading another USD Stage
*/
OMNI_USD_API static void advanceAllSyncScopes();
/**
* releaseAllHydraEngines() is designed to support the legacy Kit 1.0 Editor
*
* Unregisters all HydraEngineFactories and destroys any created OpaqueSharedHydraEngineContextPtr.
*
* @param context Optional, if valid, context releases all hydra engines prior to destroying any
* OpaqueSharedHydraEngineContextPtr
*/
OMNI_USD_API static void releaseAllHydraEngines(UsdContext* context = nullptr);
/*
* setSettingsPlugin() + setFoundationPlugins() are required initialization
* methods of USDManager
*/
OMNI_USD_API static void setSettingsPlugin(carb::settings::ISettings* settings);
OMNI_USD_API static void setFoundationPlugins(gpu::foundation::GpuFoundation* gpuFoundation,
uint32_t syncScope);
// Until Kit redoes their implmentation of GpuFoundations integration, let's provide a global
// getter for those that need GpuFoundations to be unblocked
OMNI_USD_API static void getFoundationPlugins(gpu::foundation::GpuFoundation** outGpuFoundation);
/**
* @brief Called when from omni.usd extension shutdown
*
*/
OMNI_USD_API static void shutdownUsd();
/**
* Gets corresponding UsdContext of specified stage id.
*/
OMNI_USD_API static UsdContext* getContextFromStageId(long int stageId);
/*
* Obtains a hydraengine instance with a matching config to the one passed in (If none exist yet, will create a new one).
* A new hydra engine will have it's own unique syncScope and run in a separate rendering thread if asyncRendering is enabled
*/
OMNI_USD_API static hydra::OpaqueSharedHydraEngineContextPtr
getOrCreateHydraEngine(const char* name, UsdContext* context, const hydra::EngineCreationConfig& config);
private:
/**
* Constructor.
*/
UsdManager();
/**
* No copy.
*/
UsdManager(const UsdManager&) = delete;
/**
* No assign.
*/
UsdManager& operator=(const UsdManager&) = delete;
/**
* Destructor.
*/
~UsdManager();
static UsdManager* instance();
struct Impl;
std::unique_ptr<Impl> m_impl;
};
}
}
| 6,494 | C | 29.78199 | 129 | 0.698953 |
omniverse-code/kit/include/omni/usd/UsdContextIncludes.h | // 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.
//
#pragma once
// Define this macro so that other headers that are supposed to have this header included before them can check against
// it.
#define USD_CONTEXT_INCLUDES
// Include cstdio here so that vsnprintf is properly declared. This is necessary because pyerrors.h has
// #define vsnprintf _vsnprintf which later causes <cstdio> to declare std::_vsnprintf instead of the correct and proper
// std::vsnprintf. By doing it here before everything else, we avoid this nonsense.
#include <cstdio>
// Python must be included first because it monkeys with macros that cause
// TBB to fail to compile in debug mode if TBB is included before Python
#include <boost/python/object.hpp>
#include <pxr/usd/usdGeom/bboxCache.h>
#include <pxr/usd/usdLux/cylinderLight.h>
#include <pxr/usd/usdLux/diskLight.h>
#include <pxr/usd/usdLux/distantLight.h>
#include <pxr/usd/usdLux/domeLight.h>
#include <pxr/usd/usdLux/rectLight.h>
#include <pxr/usd/usdLux/sphereLight.h>
#include <pxr/usd/usdShade/material.h>
#include <pxr/usd/usdShade/shader.h>
| 1,469 | C | 44.937499 | 120 | 0.782165 |
omniverse-code/kit/include/omni/usd/PathUtils.h | // 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.
//
#pragma once
#include <carb/Framework.h>
#include <carb/extras/Path.h>
#include <random>
#include <string>
#if CARB_PLATFORM_WINDOWS
# define strncasecmp(x, y, z) _strnicmp(x, y, z)
#endif
namespace omni
{
namespace usd
{
constexpr const char* const kWritableUsdFileExts = "usd|usda|usdc|live";
class PathUtils
{
public:
/**
* Checks if path is omniverse path (prefixed with omni:).
*
* @param path Path string.
* @return true if it's omniverse path.
*/
static bool isOmniPath(const std::string& path)
{
return path.length() > 10 && strncasecmp(path.c_str(), "omniverse:", 10) == 0;
}
/**
* Appends a random number to path. This is used to construct unique path.
*
* @param path Path string.
* @return unique path string.
*/
static std::string appendRandomNumberToFilename(const std::string& path)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<uint64_t> dis(0, std::numeric_limits<uint64_t>::max());
carb::extras::Path carbPath(path);
return carbPath.getParent() / carbPath.getStem() + std::to_string(dis(gen)) + carbPath.getExtension();
}
};
}
}
| 1,656 | C | 26.616666 | 110 | 0.673913 |
omniverse-code/kit/include/omni/usd/Selection.h | // 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.
//
#pragma once
#ifndef USD_CONTEXT_INCLUDES
# error "Please include UsdContextIncludes.h before including this header or in pre-compiled header."
#endif
#include <omni/kit/KitTypes.h>
#include <omni/usd/Api.h>
#include <memory.h>
#include <mutex>
namespace omni
{
namespace usd
{
class UsdContext;
typedef std::vector<std::pair<PXR_NS::SdfPath, uint8_t>> SdfPathGroupIdVector;
class Selection
{
public:
Selection(UsdContext* usdContext);
~Selection();
Selection(const Selection&) = delete;
Selection& operator=(const Selection&) = delete;
/**
* Sets all selected prim paths. This will replace existing selected paths with given ones.
*
* @param paths The vector of selected prim paths to be set.
* @param expandInStage true to expand the path in Stage Window on selection.
* @return true if the selected paths are changed.
*/
OMNI_USD_API bool setSelectedPrimPaths(const std::vector<std::string>& paths, bool expandInStage);
/**
* Gets all selected prim paths.
*
* @return a vector containing all selected prim paths.
*/
OMNI_USD_API std::vector<std::string> getSelectedPrimPaths();
/**
* Clears all selected prim paths.
*
* @return true if the selected paths are changed.
*/
OMNI_USD_API bool clearSelectedPrimPaths();
/**
* Sets all selected prim paths. This will replace existing selected paths with given ones.
*
* @param paths The array of selected prim paths to be set.
* @param count Size of the array.
* @param expandInStage true to expand the path in Stage Window on selection.
* @return true if the selected paths are changed.
*/
OMNI_USD_API bool setPrimPathSelected(
const char* path, bool selected, bool forcePrim, bool clearSelected, bool expandInStage);
/**
* Gets if a prim path is selected.
*
* @return true if prim path is selected.
*/
OMNI_USD_API bool isPrimPathSelected(const char* path) const;
/**
* Something has changed (layers may have been added, removed, or muted), where we can no longer
* guarantee the selection paths are valid, so mark them as dirty.
*
*/
OMNI_USD_API void setDirty();
OMNI_USD_API bool add(PXR_NS::SdfPath path, bool forcePrimMode, bool clearSelected, bool expandInStage);
OMNI_USD_API bool remove(PXR_NS::SdfPath path, bool forcePrimMode);
OMNI_USD_API bool removePathAndDescendents(PXR_NS::SdfPath path);
OMNI_USD_API PXR_NS::SdfPathVector& getRenderablePaths();
OMNI_USD_API PXR_NS::SdfPathVector& getAddedRenderablePaths();
OMNI_USD_API PXR_NS::SdfPathVector& getRemovedRenderablePaths();
OMNI_USD_API const PXR_NS::SdfPathVector& getModelPaths();
OMNI_USD_API const PXR_NS::SdfPathVector& getCameraPaths();
OMNI_USD_API const std::vector<PXR_NS::UsdLuxDistantLight>& getDistantLights();
OMNI_USD_API const std::vector<PXR_NS::UsdLuxRectLight>& getRectLights();
OMNI_USD_API const std::vector<PXR_NS::UsdLuxSphereLight>& getSphereLights();
OMNI_USD_API const std::vector<PXR_NS::UsdLuxCylinderLight>& getCylinderLights();
OMNI_USD_API const std::vector<PXR_NS::UsdLuxDiskLight>& getDiskLights();
OMNI_USD_API const std::vector<PXR_NS::UsdPrim>& getSounds();
OMNI_USD_API const std::vector<PXR_NS::UsdPrim>& getListeners();
OMNI_USD_API const std::vector<PXR_NS::UsdShadeMaterial>& getMaterials();
OMNI_USD_API const std::vector<PXR_NS::UsdShadeShader>& getShaders();
OMNI_USD_API PXR_NS::SdfPath getQueriedPath() const;
OMNI_USD_API void setQueriedPath(PXR_NS::SdfPath path, bool addOutline = false);
OMNI_USD_API void getPrimBySelectionMode(PXR_NS::UsdPrim& prim) const;
OMNI_USD_API std::recursive_mutex& getMutex();
OMNI_USD_API void update();
OMNI_USD_API bool setSelectedPrimPathsV2(const PXR_NS::SdfPathVector& paths);
OMNI_USD_API PXR_NS::SdfPathVector getSelectedPrimPathsV2() const;
OMNI_USD_API bool empty() const;
OMNI_USD_API void selectAllPrims(const std::vector<std::string>& typeNames);
OMNI_USD_API void selectInvertedPrims();
/*
* Custom selection with groupId.
* ibychkov: I added new methods for that to be sure there is no regression for regular selection.
* But it might be considered just add groupId support for regular selection.
*/
OMNI_USD_API SdfPathGroupIdVector& getCustomRenderablePaths();
OMNI_USD_API SdfPathGroupIdVector& getAddedCustomRenderablePaths();
OMNI_USD_API PXR_NS::SdfPathVector& getRemovedCustomRenderablePaths();
OMNI_USD_API void setCustomSelection(const PXR_NS::SdfPathVector& paths, uint8_t groupId);
OMNI_USD_API void clearCustomSelection();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
}
}
| 5,245 | C | 38.443609 | 108 | 0.713251 |
omniverse-code/kit/include/omni/usd/UsdContextOverrides.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/core/Api.h>
#include <omni/core/IObject.h>
#include <omni/core/OmniAttr.h>
namespace omni
{
namespace usd
{
OMNI_DECLARE_INTERFACE(IUsdContextSchedulingOverride);
class IUsdContextSchedulingOverride_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.usd.IUsdContextSchedulingOverride")>
{
protected:
/**
* Function to run before scheduling the next round of renders
*
* @param elapsedTime time since the call was called last time
* @param asyncRendering whether async rendering was enabled
*
* @return whether pre render scheduling function succeeded
*/
virtual void preScheduleRender_abi(float elapsedTime, bool asyncRendering) noexcept = 0;
/**
* Function to run after scheduling and before usd lock is grabbed again.
*/
virtual void postRenderScheduledGate_abi() noexcept = 0;
/**
* Function to run after scheduling when main thread has usd lock again.
*/
virtual void postRenderUsdLockAcquired_abi() noexcept = 0;
};
}
}
template <>
class omni::core::Generated<omni::usd::IUsdContextSchedulingOverride_abi>
: public omni::usd::IUsdContextSchedulingOverride_abi
{
public:
/**
* Function to run before scheduling the next round of renders
*
* @param elapsedTime time since the call was called last time
* @param asyncRendering whether async rendering was enabled
*
* @return whether pre render scheduling function succeeded
*/
inline void preScheduleRender(float elapsedTime, bool asyncRendering)
{
preScheduleRender_abi(elapsedTime, asyncRendering);
}
/**
* Function to run after scheduling and before usd lock is grabbed again.
*/
inline void postRenderScheduledGate()
{
postRenderScheduledGate_abi();
}
/**
* Function to run after scheduling when main thread has usd lock again.
*/
inline void postRenderUsdLockAcquired()
{
postRenderUsdLockAcquired_abi();
}
};
namespace omni
{
namespace usd
{
using UsdContextSchedulingOverridePtr = omni::core::ObjectPtr<omni::usd::IUsdContextSchedulingOverride>;
}
}
| 2,636 | C | 27.354838 | 110 | 0.715099 |
omniverse-code/kit/include/omni/usd/LayerUtils.h | // 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.
//
#pragma once
#ifndef USD_UTILS_INCLUDES
# error "Please include UtilsIncludes.h before including this header or in pre-compiled header."
#endif
#include "PathUtils.h"
#include <carb/extras/Path.h>
#include <carb/filesystem/IFileSystem.h>
#include <carb/profiler/Profile.h>
#include <carb/tokens/TokensUtils.h>
#include <carb/profiler/Profile.h>
#include <omni/kit/AssetUtils.h>
#include <omni/kit/KitUtils.h>
#include <omni/usd/UsdUtils.h>
#include <pxr/base/tf/pathUtils.h>
#include <pxr/pxr.h>
#include <pxr/usd/ar/resolver.h>
#include <pxr/usd/ar/resolverScopedCache.h>
#include <pxr/usd/sdf/assetPath.h>
#include <pxr/usd/sdf/copyUtils.h>
#include <pxr/usd/sdf/layerUtils.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdUtils/flattenLayerStack.h>
#include <random>
namespace omni
{
namespace usd
{
/**
* USD does not provide the way to save muteness. Kit will save those inside the custom data of root layer
* of the stage.
*/
static const std::string kLayerMuteCustomKey = "omni_layer:muteness";
static const std::string kLayerNameCustomKey = "omni_layer:custom_name";
static const std::string kLayerLockedCustomKey = "omni_layer:locked";
static constexpr size_t kLayerIndexNone = SIZE_MAX;
class LayerUtils
{
public:
/**
* Gets the global muteness. Global muteness is the one that's saved inside the custom data of stage's root layer.
* @param stage Root layer to get muteness from.
* @param layerIdentifier Layer identifier.
* @return True if it muted, or false otherwise.
*/
static bool getLayerGlobalMuteness(PXR_NS::SdfLayerRefPtr rootLayer, const std::string& layerIdentifier)
{
bool muted = false;
getLayerCustomFieldInRootLayer<bool>(rootLayer, layerIdentifier, kLayerMuteCustomKey, muted);
return muted;
}
/**
* Set global muteness for layer.
* @param rootLayer Root layer to save muteness to.
* @param layerIdentifier Layer identifier.
* @param muted Mute or not.
* @return true if it's successful.
*/
static void setLayerGlobalMuteness(PXR_NS::SdfLayerRefPtr rootLayer, const std::string& layerIdentifier, bool muted)
{
setLayerCustomFieldInRootLayer(rootLayer, layerIdentifier, kLayerMuteCustomKey, muted);
}
/**
* Clear all muteness from stage.
*/
static void clearLayerMutenessFromCustomFields(PXR_NS::SdfLayerRefPtr rootLayer)
{
auto rootLayerCustomData = rootLayer->GetCustomLayerData();
rootLayerCustomData.EraseValueAtPath(kLayerMuteCustomKey);
rootLayer->SetCustomLayerData(rootLayerCustomData);
}
/**
* Set layer's muteness based on global muteness saved in custom fields from stage.
*/
static void setLayerMuteStateFromCustomFields(PXR_NS::UsdStageRefPtr stage)
{
auto rootLayer = stage->GetRootLayer();
auto rootLayerCustomData = rootLayer->GetCustomLayerData();
const PXR_NS::VtValue* muteness = rootLayerCustomData.GetValueAtPath(kLayerMuteCustomKey);
PXR_NS::VtDictionary mutenessDict;
if (muteness && !muteness->IsEmpty())
{
mutenessDict = muteness->Get<PXR_NS::VtDictionary>();
}
std::vector<std::string> mutedLayers;
std::vector<std::string> unmutedLayers;
for (const auto& identifierMutenessPair : mutenessDict)
{
const std::string& layerIdentifier = rootLayer->ComputeAbsolutePath(identifierMutenessPair.first);
bool muted = identifierMutenessPair.second.Get<bool>();
if (muted != stage->IsLayerMuted(layerIdentifier))
{
if (muted)
{
mutedLayers.push_back(layerIdentifier);
}
else
{
unmutedLayers.push_back(layerIdentifier);
}
}
}
if (mutedLayers.size() > 0 || unmutedLayers.size() > 0)
{
stage->MuteAndUnmuteLayers(mutedLayers, unmutedLayers);
}
}
// Checks if the layer can be saved to disk.
static bool isLayerSavable(PXR_NS::UsdStageRefPtr stage, const std::string& layerIdentifier)
{
bool anonymous = PXR_NS::SdfLayer::IsAnonymousLayerIdentifier(layerIdentifier);
bool locked = LayerUtils::isLayerLocked(stage->GetRootLayer(), layerIdentifier);
bool muted = stage->IsLayerMuted(layerIdentifier);
bool writable = omni::kit::isWritableUrl(layerIdentifier.c_str());;
if (!anonymous && !locked && !muted && writable)
{
return true;
}
return false;
}
// Gets the customized layer lock status in root layer.
static bool isLayerLocked(PXR_NS::SdfLayerRefPtr rootLayer, const std::string& layerIdentifier)
{
// Layer lock is a concept extended from Kit that does not use real ACL
// from disk to control the lock of layer but only an instruction to
// save that this layer is locked and should not be touched.
bool locked = false;
getLayerCustomFieldInRootLayer<bool>(rootLayer, layerIdentifier, kLayerLockedCustomKey, locked);
return locked;
}
static void setLayerLockStatus(PXR_NS::SdfLayerRefPtr rootLayer, const std::string& layerIdentifier, bool locked)
{
setLayerCustomFieldInRootLayer(rootLayer, layerIdentifier, kLayerLockedCustomKey, locked);
}
static std::string getLayerName(const std::string& identifier, bool includeExtension = true)
{
if (PXR_NS::SdfLayer::IsAnonymousLayerIdentifier(identifier))
{
return identifier;
}
carb::extras::Path path;
auto omniclient = carb::getCachedInterface<carb::omniclient::IOmniClient>();
if (omniclient)
{
auto url = omniclient->breakUrl(identifier.c_str());
if (url && url->path)
{
path = carb::extras::Path(url->path);
}
else
{
path = carb::extras::Path(identifier);
}
}
else
{
path = carb::extras::Path(identifier);
}
if (includeExtension)
{
return path.getFilename().getString();
}
else
{
return path.getStem().getString();
}
}
static std::string getCustomLayerName(PXR_NS::SdfLayerRefPtr layer)
{
PXR_NS::VtDictionary valueMap;
const PXR_NS::VtDictionary& layerCustomData = layer->GetCustomLayerData();
const auto& customDataValue = layerCustomData.GetValueAtPath(kLayerNameCustomKey);
if (customDataValue && !customDataValue->IsEmpty())
{
auto value = customDataValue->Get<PXR_NS::TfToken>();
return value.GetString();
}
else
{
return LayerUtils::getLayerName(layer->GetIdentifier());
}
}
/**
* Select a existing layer as edit target.
*
* @param stage The stage of the operation.
* @param layerIdentifier Layer identifier.
* @return true if the layer is selected, false otherwise.
*
**/
static bool setAuthoringLayer(PXR_NS::UsdStageRefPtr stage, const std::string& layerIdentifier)
{
if (stage->IsLayerMuted(layerIdentifier))
{
return false;
}
const auto& sublayer = PXR_NS::SdfLayer::FindOrOpen(layerIdentifier);
if (!sublayer)
{
return false;
}
PXR_NS::UsdEditTarget editTarget(sublayer);
stage->SetEditTarget(editTarget);
return true;
}
/**
* Gets the current authoring layer (edit target).
*
* @param stage The stage of the operation.
* @return layer identifier of the authoring layer.
**/
static std::string getAuthoringLayerIdentifier(PXR_NS::UsdStageRefPtr stage)
{
if (stage->GetEditTarget().GetLayer())
{
return stage->GetEditTarget().GetLayer()->GetIdentifier();
}
return "";
}
/**
* Gets the layer identifier of sublayer at specific position.
*
* @param hostLayer Layer handle to query.
* @param position Sublayer position. It should not be over the count of total sublayers.
* @param sublayerIdentifier Returned identifier.
* @return false if position is over the count of total sublayers, or true otherwise.
*/
static bool getSublayerIdentifier(const PXR_NS::SdfLayerRefPtr& hostLayer,
size_t position,
std::string& sublayerIdentifier)
{
if (position >= hostLayer->GetNumSubLayerPaths())
{
return false;
}
const auto& sublayerPaths = hostLayer->GetSubLayerPaths();
const std::string& sublayer = sublayerPaths[position];
sublayerIdentifier = computeAbsolutePath(hostLayer, sublayer);
return true;
}
/**
* Gets sublayer position of specific layer in parent layer.
*
* @param hostLayer Parent layer to search.
* @param layerIdentifier Layer identifier.
* @return Sublayer position if it's found, or kLayerIndexNone if it's not found.
*/
static size_t getSublayerPositionInHost(const PXR_NS::SdfLayerRefPtr& hostLayer, const std::string& layerIdentifier)
{
const auto& sublayerPaths = hostLayer->GetSubLayerPaths();
for (size_t i = 0; i < sublayerPaths.size(); i++)
{
const auto& absolutePath = computeAbsolutePath(hostLayer, sublayerPaths[i]);
if (normalizeUrl(absolutePath) == normalizeUrl(layerIdentifier))
{
return i;
}
}
return kLayerIndexNone;
}
/**
* Gets the sublayer handle at specific position.
*
* @param hostLayer Layer handle.
* @param position Sublayer position.
* @return layer handle if position is valid, otherwise, nullptr is returned.
*/
static PXR_NS::SdfLayerRefPtr getSublayer(const PXR_NS::SdfLayerRefPtr& hostLayer, size_t position)
{
if (position >= hostLayer->GetNumSubLayerPaths())
{
return nullptr;
}
const auto& sublayerPaths = hostLayer->GetSubLayerPaths();
const std::string& path = sublayerPaths[position];
const auto& absolutePath = hostLayer->ComputeAbsolutePath(path);
return findOrOpen(absolutePath);
};
/**
* Adds a new layer.
*
* @param stage The stage this sublayer will be inserted to.
* @param hostLayer Host Layer to create sublayer.
* @param position The position to insert the new layer before. If position > sublayerCount,
* it will create the layer at the end.
* @param anonymous If the layer should be anonymous. Anonymous layer is in memory only and will not be saved to
* file.
* @param saveOnCreate Saves layer file after create or not.
* @param finalPosition Real sublayer position of new layer in hostLayer. It's valid only when the return is not
* nullptr.
* @return layer handle. It will be nullptr if it's failed.
*/
static PXR_NS::SdfLayerRefPtr createSublayer(PXR_NS::UsdStageRefPtr stage,
PXR_NS::SdfLayerRefPtr hostLayer,
size_t position,
const char* layerPath,
bool saveOnCreate,
size_t& finalPosition)
{
size_t newLayerPos;
size_t numLayers = hostLayer->GetNumSubLayerPaths();
if (position > numLayers)
{
newLayerPos = numLayers;
}
else
{
newLayerPos = position;
}
// It's possible that this layer is already existed
PXR_NS::SdfLayerRefPtr newLayer = nullptr;
if (layerPath && layerPath[0] != '\0')
{
newLayer = PXR_NS::SdfLayer::FindOrOpen(layerPath);
if (!newLayer)
{
if (saveOnCreate)
{
newLayer = PXR_NS::SdfLayer::CreateNew(layerPath);
}
else
{
newLayer = PXR_NS::SdfLayer::New(hostLayer->GetFileFormat(), layerPath);
}
}
else
{
newLayer->Clear();
}
}
else
{
newLayer = PXR_NS::SdfLayer::CreateAnonymous();
}
if (newLayer)
{
std::string relativePath = newLayer->GetIdentifier();
UsdUtils::makePathRelativeToLayer(hostLayer, relativePath);
hostLayer->InsertSubLayerPath(relativePath, (int)newLayerPos);
finalPosition = newLayerPos;
}
return newLayer;
}
/**
* Inserts a layer into the current sublayers.
*
* @param stage The stage this sublayer will be inserted to.
* @param hostLayer The Layer to create sublayer.
* @param position The position to insert the new layer before. If sublayerPosition > sublayerCount,
* it will create the layer at the end.
* @param name Name of the new layer.
* @param path Absolute path of the new layer.
* @param newLayerIndex Real sublayer position this layer creates to. It's valid only when return is not nullptr.
* @return layer identifier of created identifier. It's failed if it's empty.
*/
static PXR_NS::SdfLayerRefPtr insertSublayer(PXR_NS::UsdStageRefPtr stage,
PXR_NS::SdfLayerRefPtr hostLayer,
size_t position,
const std::string& path,
size_t& newLayerIndex)
{
size_t newLayerPos;
size_t numLayers = hostLayer->GetNumSubLayerPaths();
if (position > numLayers)
{
newLayerPos = numLayers;
}
else
{
newLayerPos = position;
}
const auto& absolutePath = computeAbsolutePath(hostLayer, path);
const PXR_NS::SdfLayerRefPtr& newLayer = PXR_NS::SdfLayer::FindOrOpen(absolutePath);
if (newLayer)
{
std::string relativePath = absolutePath;
UsdUtils::makePathRelativeToLayer(hostLayer, relativePath);
hostLayer->InsertSubLayerPath(relativePath, (int)newLayerPos);
}
else
{
CARB_LOG_ERROR("ERROR! Failed to insert sublayer at path %s", absolutePath.c_str());
}
newLayerIndex = newLayerPos;
return newLayer;
}
/**
* Replaces layer with new path.
*
* @param stage The stage this sublayer will be inserted to.
* @param hostLayer The layer handle to create sublayer.
* @param position The position to replace. It must be [0, num_of_sublayers).
* @param path New layer path.
* @return layer handle. It will be nullptr if it's failed.
**/
static PXR_NS::SdfLayerRefPtr replaceSublayer(PXR_NS::UsdStageRefPtr stage,
PXR_NS::SdfLayerRefPtr hostLayer,
size_t position,
const std::string& path)
{
if (position >= hostLayer->GetNumSubLayerPaths())
{
CARB_LOG_ERROR("ERROR! Failed to replace sublayer as position %zu is invalid", position);
return nullptr;
}
const auto& absolutePath = computeAbsolutePath(hostLayer, path);
const PXR_NS::SdfLayerRefPtr& newLayer = PXR_NS::SdfLayer::FindOrOpen(absolutePath);
if (newLayer)
{
PXR_NS::SdfChangeBlock changeBlock;
auto sublayerPaths = hostLayer->GetSubLayerPaths();
std::string oldSublayerPath = sublayerPaths[position];
oldSublayerPath = computeAbsolutePath(hostLayer, oldSublayerPath);
std::string relativePath = absolutePath;
UsdUtils::makePathRelativeToLayer(hostLayer, relativePath);
sublayerPaths[position] = relativePath;
}
else
{
CARB_LOG_ERROR("ERROR! Failed to replace sublayer at path %s", absolutePath.c_str());
}
return newLayer;
}
/**
* Delete a existing layer. Delete root layer will do nothing.
*
* @param stage The stage of the operation.
* @param hostLayer The layer to create sublayer.
* @param position The sublayer position to delete. If it's not a valid sublayer index, it will do nothing.
* @return true if the layer is deleted, false otherwise.
*
**/
static bool deleteSublayer(PXR_NS::SdfLayerRefPtr hostLayer, size_t position)
{
std::string sublayerIdentifier;
if (!getSublayerIdentifier(hostLayer, position, sublayerIdentifier))
{
return false;
}
hostLayer->RemoveSubLayerPath((int)position);
return true;
}
/**
* Move sublayer from source to target position.
*
* @param fromLayerIdentifier Layer identifier of source layer.
* @param fromSublayerIndex The sublayer position of source layer to move.
* @param toLayerIdentifier Layer identifier of target layer.
* @param toSublayerIndex The sublayer position of target layer that source sublayer moves to.
* @return true if the layer is moved successfully, false otherwise.
*/
static bool moveSublayer(const std::string& fromLayerIdentifier,
size_t fromSublayerIndex,
const std::string& toLayerIdentifier,
size_t toSublayerIndex,
size_t& toFinalPosition)
{
if (fromLayerIdentifier == toLayerIdentifier && fromSublayerIndex == toSublayerIndex)
{
return false;
}
auto fromLayer = PXR_NS::SdfLayer::FindOrOpen(fromLayerIdentifier);
auto toLayer = PXR_NS::SdfLayer::FindOrOpen(toLayerIdentifier);
if (!fromLayer || !toLayer)
{
return false;
}
if (fromSublayerIndex >= fromLayer->GetNumSubLayerPaths())
{
return false;
}
if (fromLayerIdentifier != toLayerIdentifier && toSublayerIndex > toLayer->GetNumSubLayerPaths())
{
toFinalPosition = toLayer->GetNumSubLayerPaths();
}
else if (toSublayerIndex > toLayer->GetNumSubLayerPaths())
{
toFinalPosition = toLayer->GetNumSubLayerPaths() - 1;
}
else
{
toFinalPosition = toSublayerIndex;
}
const auto& sublayerPaths = fromLayer->GetSubLayerPaths();
std::string sublayer = sublayerPaths[fromSublayerIndex];
sublayer = computeAbsolutePath(fromLayer, sublayer);
UsdUtils::makePathRelativeToLayer(toLayer, sublayer);
fromLayer->RemoveSubLayerPath((int)fromSublayerIndex);
toLayer->InsertSubLayerPath(sublayer, (int)toFinalPosition);
return true;
}
/**
* Save all changes of the specified layers.
* @param layerIdentifiers List of layer identifiers to be saved.
*/
static bool saveLayers(const std::vector<std::string>& layerIdentifiers)
{
bool success = true;
for (const auto& layerIdentifier : layerIdentifiers)
{
if (!LayerUtils::saveLayer(layerIdentifier))
{
success = false;
CARB_LOG_ERROR("ERROR! Failed to save layer %s due to permission issue.", layerIdentifier.c_str());
}
}
return success;
}
/**
* Gets all identifiers of all dirty layers in the local stack of stage (anonymous layers are not included).
*/
static std::vector<std::string> getLocalDirtyLayers(PXR_NS::UsdStageRefPtr stage)
{
std::vector<std::string> layerIdentifiers;
PXR_NS::SdfLayerHandleVector layerStack = stage->GetLayerStack(true);
for (const auto& layer : layerStack)
{
if (layer && !layer->IsAnonymous() && layer->IsDirty())
{
layerIdentifiers.push_back(layer->GetIdentifier());
}
}
return layerIdentifiers;
}
/**
* Saves layer and all its sublayers.
*
* @param layerIdentifier Layer identifier.
* @return true if it's successful, or false otherwise.
*/
static bool saveLayer(const std::string& layerIdentifier, bool saveSublayers = false)
{
auto layer = PXR_NS::SdfLayer::Find(layerIdentifier);
if (!layer)
{
return false;
}
if (saveSublayers)
{
auto stage = PXR_NS::UsdStage::Open(layer);
stage->Save();
return true;
}
else
{
return layer->Save();
}
}
/**
* Checks if a layer is empty (no root prims) or not.
*
* @param layerIdentifier Layer identifier.
* @return true if it includes root prims, or false otherwise.
*/
static bool hasRootPrimSpecs(const std::string& layerIdentifier)
{
auto layer = PXR_NS::SdfLayer::FindOrOpen(layerIdentifier);
if (!layer)
{
return false;
}
return layer->GetPseudoRoot()->GetNameChildren().size() > 0;
}
struct PairHash
{
template <class T1, class T2>
std::size_t operator()(const std::pair<T1, T2>& pair) const
{
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
// Depth-first pre-order traverse of layer and its sublayer descendants.
// LayerGroupStartCallback will be called before iterating sublayers of a layer.
// If LayerGroupStartCallback returns false, it will stop to traverse this layer.
// For each layer it found, it will call LayerCallback.
// After all sublayers have been traversed, it will call LayerGroupEndCallback.
// You need to track the depth of whole traverse.
// If layer is not found, LayerGroupStartCallback and LayerGroupEndCallback will be called
// also by passing a nullptr as the layer handle, and its layer identifier.
// REMINDER: Don't call this per frame, which may be harmful to performance as
// it insolves with resolver.
using LayerGroupStartCallback =
std::function<bool(PXR_NS::SdfLayerRefPtr hostLayer, const std::string& layerIdentifier)>;
using LayerCallback = std::function<void(
PXR_NS::SdfLayerRefPtr hostLayer, PXR_NS::SdfLayerRefPtr sublayer, const std::string& layerIdentifier, size_t sublayerIndex)>;
using LayerGroupEndCallback =
std::function<void(PXR_NS::SdfLayerRefPtr hostLayer, const std::string& layerIdentifier)>;
static void iterateSublayerTreeDFS(PXR_NS::SdfLayerRefPtr rootLayer,
const LayerGroupStartCallback groupStartCallback,
const LayerCallback callback,
const LayerGroupEndCallback groupEndCallback)
{
CARB_PROFILE_ZONE(1, "iterateSublayerTreeDFS");
PXR_NS::ArResolverScopedCache cache;
// If there is circular reference like layer1 -> sublayer1 -> layer1 -> sublayer2 ...,
// it needs to be detected to avoid endless loop.
// This map is used to record if <parent layer, current layer> has been accessed already
// to avoid endless loop.
std::unordered_set<std::pair<std::string, std::string>, PairHash> accessMap;
iterateSublayerTreeDFSInternal(nullptr, rootLayer, rootLayer->GetIdentifier(), kLayerIndexNone,
groupStartCallback, callback, groupEndCallback, accessMap);
}
// Depth-first pre-order traverse of prim tree.
// PrimSpecGroupStartCallback will be called before iterating children of a prim.
// It will stop to traverse it's children if it returns false.
// For each prim it found, it will call PrimSpecCallback.
// After all children haved been traversed, it will call PrimSpecGroupEndCallback.
// You need to track the depth of whole traverse.
using PrimSpecGroupStartCallback = std::function<bool(PXR_NS::SdfPrimSpecHandle parentSpecPrim)>;
using PrimSpecCallback = std::function<void(
PXR_NS::SdfPrimSpecHandle parentSpecPrim, PXR_NS::SdfPrimSpecHandle childSpecPrim, size_t primSpecIndex)>;
using PrimSpecGroupEndCallback = std::function<void(PXR_NS::SdfPrimSpecHandle parentSpecPrim)>;
static void iteratePrimSpecTreeDFS(PXR_NS::SdfLayerRefPtr layer,
const PrimSpecGroupStartCallback groupStartCallback,
const PrimSpecCallback callback,
const PrimSpecGroupEndCallback groupEndCallback)
{
CARB_PROFILE_ZONE(1, "iteratePrimSpecTreeDFS");
PXR_NS::SdfPrimSpecHandle empty;
auto children = layer->GetPseudoRoot()->GetNameChildren();
for (size_t i = 0; i < children.size(); i++)
{
iteratePrimTreeDFSInternal(empty, children[i], 0, groupStartCallback, callback, groupEndCallback);
}
}
static void iteratePrimSpecTreeDFS(const std::string& layerIdentifier,
const PrimSpecGroupStartCallback groupStartCallback,
const PrimSpecCallback callback,
const PrimSpecGroupEndCallback groupEndCallback)
{
auto layer = PXR_NS::SdfLayer::FindOrOpen(layerIdentifier);
if (!layer)
{
return;
}
iteratePrimSpecTreeDFS(layer, groupStartCallback, callback, groupEndCallback);
}
/**
* Gets the absolute path that's relative to root layer.
*
* @param rootLayer Root layer that the path is relative to.
* @param path Path string.
* @return Absolute path. If it's anonymous layer path, it will return it directly.
*/
static std::string computeAbsolutePath(const PXR_NS::SdfLayerRefPtr& rootLayer, const std::string& path)
{
if (PXR_NS::SdfLayer::IsAnonymousLayerIdentifier(path) || rootLayer->IsAnonymous())
{
return path;
}
else
{
// Compute the path through the resolver
const std::string& absolutePath = rootLayer->ComputeAbsolutePath(path);
return normalizePath(absolutePath);
}
}
/**
* Similar to SdfLayer::FindOrOpen, but only calls SdfLayer::Find on anonymous layer to prevent USD Coding Error.
*
* @param identifier Layer identifier to be found or opened.
* @return Found layer, or nullptr if not found.
*/
static PXR_NS::SdfLayerRefPtr findOrOpen(const std::string& identifier)
{
if (PXR_NS::SdfLayer::IsAnonymousLayerIdentifier(identifier))
{
return PXR_NS::SdfLayer::Find(identifier);
}
return PXR_NS::SdfLayer::FindOrOpen(identifier);
}
static bool hasDirtyLayers(PXR_NS::UsdStageRefPtr stage)
{
CARB_PROFILE_ZONE(1, "hasDirtyLayers");
if (!stage)
{
return false;
}
for (auto& layer : stage->GetUsedLayers())
{
if (!layer->IsAnonymous() && layer->IsDirty())
{
return true;
}
}
return false;
}
// Checks if layerIdentifier is in the sublayer tree rooted from hostLayer, and this layer
// must be existed.
static bool isLayerInSublayerTree(PXR_NS::SdfLayerRefPtr hostLayer, const std::string& identifier)
{
bool found = false;
LayerUtils::iterateSublayerTreeDFS(hostLayer,
[&identifier, &found](const pxr::SdfLayerRefPtr layer, const std::string& layerIdentifier) {
if (layer && identifier == layerIdentifier)
{
found = true;
return false;
}
return true;
},
nullptr,
nullptr
);
return found;
}
static std::string normalizePath(const std::string& path)
{
static auto replaceAll = [](std::string str, const std::string& from, const std::string& to)
{
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos)
{
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;
};
std::string finalPath = path;
// FIXME: Need a better way to normalize path.
finalPath = replaceAll(finalPath, "%3C", "<");
finalPath = replaceAll(finalPath, "%3E", ">");
finalPath = replaceAll(finalPath, "%20", " ");
finalPath = replaceAll(finalPath, "%5C", "/");
std::replace(finalPath.begin(), finalPath.end(), '\\', '/');
return finalPath;
}
static std::string normalizeUrl(const std::string& url)
{
std::string result;
auto omniclient = carb::getCachedInterface<carb::omniclient::IOmniClient>();
if (omniclient)
{
size_t bufferSize = 0;
omniclient->normalizeUrl(url.c_str(), nullptr, &bufferSize);
if (bufferSize != 0)
{
auto stringBufferHeap = std::unique_ptr<char[]>(new char[bufferSize]);
const char* normalizedUrl = omniclient->normalizeUrl(url.c_str(), stringBufferHeap.get(), &bufferSize);
if (!normalizedUrl)
{
result = url;
}
else
{
result = normalizedUrl;
}
}
else
{
result = url;
}
}
else
{
result = url;
}
return result;
}
private:
template<typename T>
static bool getLayerCustomFieldInRootLayer(PXR_NS::SdfLayerRefPtr rootLayer, const std::string& layerIdentifier, const std::string& key, T& value)
{
// By default, the layer is not muted.
PXR_NS::VtDictionary valueMap;
const PXR_NS::VtDictionary& rootLayerCustomData = rootLayer->GetCustomLayerData();
const auto& customDataValue = rootLayerCustomData.GetValueAtPath(key);
if (customDataValue && !customDataValue->IsEmpty())
{
valueMap = customDataValue->Get<PXR_NS::VtDictionary>();
}
auto omniclient = carb::getCachedInterface<carb::omniclient::IOmniClient>();
for (const auto& valuePair : valueMap)
{
std::string absolutePath = rootLayer->ComputeAbsolutePath(valuePair.first);
if (normalizeUrl(absolutePath) == normalizeUrl(layerIdentifier))
{
value = valuePair.second.Get<T>();
return true;
}
}
return false;
}
template<typename T>
static bool setLayerCustomFieldInRootLayer(PXR_NS::SdfLayerRefPtr rootLayer, const std::string& layerIdentifier,
const std::string& key, const T& value)
{
PXR_NS::VtDictionary valueMap;
PXR_NS::VtDictionary rootLayerCustomData = rootLayer->GetCustomLayerData();
const auto& oldValue = rootLayerCustomData.GetValueAtPath(key);
if (oldValue && !oldValue->IsEmpty())
{
valueMap = oldValue->Get<PXR_NS::VtDictionary>();
}
std::string relativePath = layerIdentifier;
UsdUtils::makePathRelativeToLayer(rootLayer, relativePath);
LayerUtils::normalizePath(relativePath);
for (auto iter = valueMap.begin(); iter != valueMap.end(); iter++)
{
const std::string& absolutePath = rootLayer->ComputeAbsolutePath(iter->first);
if (normalizeUrl(absolutePath) == normalizeUrl(layerIdentifier))
{
valueMap.erase(iter);
break;
}
}
valueMap[relativePath] = PXR_NS::VtValue(value);
rootLayerCustomData.SetValueAtPath(key, PXR_NS::VtValue(valueMap));
rootLayer->SetCustomLayerData(rootLayerCustomData);
return true;
}
static void iterateSublayerTreeDFSInternal(PXR_NS::SdfLayerRefPtr hostLayer,
PXR_NS::SdfLayerRefPtr currentlayer,
const std::string& currentLayeridentifier,
size_t sublayerIndex,
const LayerGroupStartCallback& groupStartCallback,
const LayerCallback& callback,
const LayerGroupEndCallback& groupEndCallback,
std::unordered_set<std::pair<std::string, std::string>, PairHash>& accessMap)
{
std::string hostLayerIdentifier;
if (hostLayer)
{
hostLayerIdentifier = hostLayer->GetIdentifier();
}
auto iter = accessMap.find({ hostLayerIdentifier, currentLayeridentifier });
if (iter != accessMap.end()) // This layer has been accessed already
{
return;
}
else
{
accessMap.insert({ hostLayerIdentifier, currentLayeridentifier });
}
if (callback)
{
callback(hostLayer, currentlayer, currentLayeridentifier, sublayerIndex);
}
bool stop = false;
if (groupStartCallback && !groupStartCallback(currentlayer, currentLayeridentifier))
{
stop = true;
}
if (!stop && currentlayer)
{
const auto& sublayerPaths = currentlayer->GetSubLayerPaths();
for (size_t i = 0; i < sublayerPaths.size(); i++)
{
auto sublayer = getSublayer(currentlayer, i);
std::string layerIdentifier;
if (sublayer)
{
layerIdentifier = sublayer->GetIdentifier();
}
else
{
getSublayerIdentifier(currentlayer, i, layerIdentifier);
}
iterateSublayerTreeDFSInternal(currentlayer, sublayer, layerIdentifier, i, groupStartCallback, callback,
groupEndCallback, accessMap);
}
}
if (groupEndCallback)
{
groupEndCallback(currentlayer, currentLayeridentifier);
}
}
static void iteratePrimTreeDFSInternal(PXR_NS::SdfPrimSpecHandle parentPrim,
PXR_NS::SdfPrimSpecHandle currentPrim,
size_t primIndex,
const PrimSpecGroupStartCallback& groupStartCallback,
const PrimSpecCallback& callback,
const PrimSpecGroupEndCallback& groupEndCallback)
{
if (!currentPrim || currentPrim->IsDormant())
{
return;
}
if (callback)
{
callback(parentPrim, currentPrim, primIndex);
}
// Early stop
bool stop = false;
if (groupStartCallback)
{
stop = !groupStartCallback(currentPrim);
}
if (!stop)
{
auto childrenPrims = currentPrim->GetNameChildren();
for (size_t i = 0; i < childrenPrims.size(); i++)
{
iteratePrimTreeDFSInternal(
currentPrim, childrenPrims[i], i, groupStartCallback, callback, groupEndCallback);
}
}
if (groupEndCallback)
{
groupEndCallback(currentPrim);
}
return;
}
};
}
}
| 36,913 | C | 35.404339 | 150 | 0.591851 |
omniverse-code/kit/include/omni/usd/ViewportTypes.h | // 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.
//
#pragma once
#include <omni/usd/UsdTypes.h>
#include <memory>
namespace rtx
{
namespace resourcemanager
{
class RpResource;
}
}
namespace omni
{
namespace usd
{
typedef size_t ViewPickingId;
typedef int32_t ViewportHandle;
static constexpr int32_t kInvalidViewportHandle = -1;
using OnPickingCompleteFn = std::function<void(const char* path, const carb::Double3* worldPos)>;
struct Picking
{
int left;
int top;
int right;
int bottom;
enum class Mode
{
eNone,
eResetAndSelect,
eMergeSelection,
eInvertSelection,
eQuery, /// request that do not change selection
eTrack, /// track mouse position, picking request is allowed.
eTrackBlocking, /// track mouse position, picking request is blocked.
} mode;
ViewPickingId pickingId;
bool queryAddsOutline; // Used only when mode == eQuery
OnPickingCompleteFn onCompleteFn;
};
struct RenderVar
{
const char* name;
union {
void* rawResource;
rtx::resourcemanager::RpResource* rpResource;
};
bool isRpResource;
};
}
}
| 1,531 | C | 21.202898 | 97 | 0.709993 |
omniverse-code/kit/include/omni/usd/AssetUtils.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#ifndef USD_UTILS_INCLUDES
# error "Please include UtilsIncludes.h before including this header or in pre-compiled header."
#endif
#include <omniAudioSchema/sound.h>
#include <omni/usd/UsdUtils.h>
#include <condition_variable>
namespace omni
{
namespace usd
{
class AssetUtils
{
public:
/**
* Imports an external file in to the stage.
*
* @param stage The stage to import file into.
* @param importUrl The URL of the imported file.
* @param path The path to create the imported prim at.
* @param dataSourcePath The path of the file in its dataSource (Only needed for MDL).
* @param dataSource DataSource associated with this file (Only needed for MDL).
* @param connection Connection associated with this file (Only needed for MDL).
*/
static pxr::UsdPrim createPrimFromAssetPath(pxr::UsdStageWeakPtr stage,
const char* importUrl,
const char* primPath,
const char* dataSourcePath = "",
carb::datasource::IDataSource* dataSource = nullptr,
carb::datasource::Connection* connection = nullptr)
{
pxr::UsdPrim prim;
std::string newPrimPath = omni::usd::UsdUtils::findNextNoneExisitingNodePath(stage, primPath, true);
// MDL file
static const std::regex kMdlFile("^.*\\.mdl(?:\\?.*)?$", std::regex_constants::icase | std::regex_constants::optimize);
// the supported audio formats
static const std::regex kAudioFile(
"^.*\\.(?:wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(?:\\?.*)?$", std::regex_constants::icase | std::regex_constants::optimize);
std::string relativeUrl = importUrl;
omni::usd::UsdUtils::makePathRelativeToLayer(stage->GetEditTarget().GetLayer(), relativeUrl);
if (std::regex_search(importUrl, kMdlFile))
{
CARB_ASSERT(dataSource && connection);
prim = createMdlMaterial(
stage, pxr::SdfPath(newPrimPath), relativeUrl.c_str(), dataSourcePath, "", dataSource, connection);
}
else if (std::regex_search(importUrl, kAudioFile))
{
auto sound = pxr::OmniAudioSchemaOmniSound::Define(stage, pxr::SdfPath(newPrimPath));
if (sound)
{
sound.CreateFilePathAttr(pxr::VtValue(pxr::SdfAssetPath(relativeUrl.c_str())));
prim = sound.GetPrim();
}
else
CARB_LOG_ERROR("failed to define an OmniAudioSchemaOmniSound");
}
return prim;
}
static pxr::UsdPrim createMdlMaterial(pxr::UsdStageWeakPtr stage,
const pxr::SdfPath& primPath,
const char* mdlPath,
const char* mdlDataSourcePath,
const char* mdlMaterialName = "",
carb::datasource::IDataSource* dataSource = nullptr,
carb::datasource::Connection* connection = nullptr)
{
// How do we get the material name:
// - If user provides one via mdlMaterialName, use it.
// - If user doesn't provide mdlMaterialName, but provides dataSource and connection, we do a regex search on
// the MDL file's content and extract the first material name.
// - If user provides nothing, or previous step fails, we take the MDL filename as the material name.
std::string materialName = (mdlMaterialName == nullptr) ? "" : mdlMaterialName;
if (materialName.empty() && dataSource && connection)
{
materialName = findMaterialNameFromMdlContent(dataSource, connection, mdlPath, mdlDataSourcePath);
}
if (materialName.empty())
{
carb::extras::Path mdlCarbPath(mdlPath);
materialName = mdlCarbPath.getStem();
}
if (materialName.empty())
{
CARB_LOG_ERROR("Failed to find material name for MDL file %s", mdlPath);
}
auto materialPrim = pxr::UsdShadeMaterial::Define(stage, primPath);
if (materialPrim)
{
pxr::SdfPath shaderPrimPath = primPath.AppendPath(pxr::SdfPath("Shader"));
auto shaderPrim = pxr::UsdShadeShader::Define(stage, shaderPrimPath);
if (shaderPrim)
{
carb::settings::ISettings* settings = carb::getFramework()->acquireInterface<carb::settings::ISettings>();
bool authorOldMdlSchema = settings->getAsBool(omni::usd::kAuthorOldMdlSchemaSettingPath);
if (authorOldMdlSchema)
{
materialPrim.CreateSurfaceOutput().ConnectToSource(
shaderPrim.CreateOutput(pxr::TfToken("out"), pxr::SdfValueTypeNames->Token));
shaderPrim.CreateIdAttr(pxr::VtValue(pxr::TfToken("mdlMaterial")));
shaderPrim.GetPrim()
.CreateAttribute(pxr::TfToken("module"), pxr::SdfValueTypeNames->Asset)
.Set(pxr::SdfAssetPath(mdlPath));
shaderPrim.GetPrim().CreateAttribute(pxr::TfToken("name"), pxr::SdfValueTypeNames->String).Set(materialName);
}
else
{
pxr::TfToken mdlToken("mdl");
auto shaderOut = shaderPrim.CreateOutput(pxr::TfToken("out"), pxr::SdfValueTypeNames->Token);
materialPrim.CreateSurfaceOutput(mdlToken).ConnectToSource(shaderOut);
materialPrim.CreateVolumeOutput(mdlToken).ConnectToSource(shaderOut);
materialPrim.CreateDisplacementOutput(mdlToken).ConnectToSource(shaderOut);
shaderPrim.GetImplementationSourceAttr().Set(pxr::UsdShadeTokens->sourceAsset);
shaderPrim.SetSourceAsset(pxr::SdfAssetPath(mdlPath), mdlToken);
shaderPrim.SetSourceAssetSubIdentifier(pxr::TfToken(materialName), mdlToken);
}
}
}
return materialPrim.GetPrim();
}
static std::string findMaterialNameFromMdlContent(carb::datasource::IDataSource* dataSource,
carb::datasource::Connection* connection,
const char* mdlPath,
const char* mdlDataSourcePath)
{
std::string materialName;
struct ReadArgs
{
std::string mdlContent;
std::atomic<bool> readDone{ false };
std::condition_variable readDoneCondition;
std::mutex readDoneMutex;
} readArgs;
dataSource->readData(connection, mdlDataSourcePath, std::malloc,
[](carb::datasource::Response response, const char* path, uint8_t* payload,
size_t payloadSize, void* userData) {
ReadArgs* readArgs = reinterpret_cast<ReadArgs*>(userData);
if (response == carb::datasource::Response::eOk)
{
readArgs->mdlContent = std::string(payload, payload + payloadSize);
}
std::free(payload);
std::unique_lock<std::mutex> lock(readArgs->readDoneMutex);
readArgs->readDone.store(true, std::memory_order_relaxed);
readArgs->readDoneCondition.notify_all();
},
&readArgs);
{
std::unique_lock<std::mutex> lock(readArgs.readDoneMutex);
readArgs.readDoneCondition.wait(
lock, [&readArgs] { return readArgs.readDone.load(std::memory_order_relaxed); });
}
if (readArgs.mdlContent.length() == 0)
{
CARB_LOG_ERROR("Failed to load %s when creating MDL material from it", mdlPath);
return "";
}
// Do a regex search on the content of MDL file to get first valid material name to use
const static std::regex kExportedMaterialRegex(
"export\\s+material\\s+([^\\s]+)\\s*\\(", std::regex_constants::optimize);
std::smatch match;
if (std::regex_search(readArgs.mdlContent, match, kExportedMaterialRegex))
{
if (match.size() >= 2)
{
materialName = match[1];
}
else
{
CARB_LOG_WARN("Could not extract material name from %s. Fallback to filename.", mdlPath);
}
}
return materialName;
}
};
}
}
| 9,483 | C | 43.947867 | 141 | 0.560793 |
omniverse-code/kit/include/omni/compiletime/CompileTime.h | // Copyright (c) 2020-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.
//
/** @file
* @brief Compiler time helper functions.
*/
#pragma once
#include "../../carb/Defines.h"
#include <cstdint>
namespace omni
{
/** Namespace for various compile time helpers. */
namespace compiletime
{
/** Returns the length of the string at compile time.
*
* @param[in] str The string to calculate the length of. This string must either be a string
* literal or another `constexpr` symbol that can be evaluated at compile time.
* This may not be `nullptr`.
* @returns The total number of elements in the string. Note that this does not necessarily
* count the length in characters of a UTF-8 string properly. It effectively counts
* how many entries (ie: bytes in this case) are in the string's buffer up to but
* not including the terminating null character.
*/
constexpr size_t strlen(const char* str)
{
return *str ? 1 + strlen(str + 1) : 0;
}
/** Compile time std::strcmp(). Return 0 if equal, not 0 otherwise.
*
* @param[in] a The first string to compare. This must either be a string literal or another
* `constexpr` symbol that can be evaluated at compile time. This may not be
* `nullptr`.
* @param[in] b The second string to compare. This must either be a string literal or another
* `constexpr` symbol that can be evaluated at compile time. This may not be
* `nullptr`.
* @returns `0` if the two strings match exactly. Returns a negative value if the string @p a
* should be ordered before @p b alphanumerically. Returns a positive value if the
* string @p a should be ordered after @p b alphanumerically.
*/
constexpr int strcmp(const char* a, const char* b)
{
return ((*a == *b) ? (*a ? strcmp(a + 1, b + 1) : 0) : (*a - *b));
}
// compile time unit tests...
static_assert(0 == strlen(""), "compiletime::strlen logic error");
static_assert(1 == strlen("a"), "compiletime::strlen logic error");
static_assert(2 == strlen("ab"), "compiletime::strlen logic error");
static_assert(strcmp("b", "c") < 0, "compiletime::strcmp logic error");
static_assert(strcmp("b", "a") > 0, "compiletime::strcmp logic error");
static_assert(strcmp("b", "b") == 0, "compiletime::strcmp logic error");
static_assert(strcmp("", "") == 0, "compiletime::strcmp logic error");
static_assert(strcmp("", "a") < 0, "compiletime::strcmp logic error");
static_assert(strcmp("a", "") > 0, "compiletime::strcmp logic error");
static_assert(strcmp("carbonite", "carb") > 0, "compiletime::strcmp logic error");
} // namespace compiletime
} // namespace omni
| 3,095 | C | 43.228571 | 98 | 0.670113 |
omniverse-code/kit/include/omni/log/ILogChannelFilter.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/OmniAttr.h>
#include <omni/core/Interface.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <utility>
#include <type_traits>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Read-only object to encapsulate a channel filter's pattern and effects.
//!
//! A channel filter is a pattern matcher. If a channel's name matches the pattern, the filter can set both the
//! channel's enabled flag and/or level.
template <>
class omni::core::Generated<omni::log::ILogChannelFilter_abi> : public omni::log::ILogChannelFilter_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::log::ILogChannelFilter")
//! Returns the channels pattern. The returned memory is valid for the lifetime of this object.
//!
//! This method is thread safe.
const char* getFilter() noexcept;
//! Returns the desired enabled state for this filter.
//!
//! All parameters must not be nullptr.
//!
//! If *isUsed is false after calling this method, *isEnabled and *behavior should not be used.
//!
//! This method is thread safe.
void getEnabled(bool* isEnabled, omni::log::SettingBehavior* behavior, bool* isUsed) noexcept;
//! Returns the desired level for this filter.
//!
//! All parameters must not be nullptr.
//!
//! If *isUsed is false after calling this method, *level and *behavior should not be used.
//!
//! This method is thread safe.
void getLevel(omni::log::Level* level, omni::log::SettingBehavior* behavior, bool* isUsed) noexcept;
//! Given a channel name, returns if the channel name matches the filter's pattern.
//!
//! The matching algorithm used is implementation specific (e.g. regex, glob, etc).
//!
//! This method is thread safe.
bool isMatch(const char* channel) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline const char* omni::core::Generated<omni::log::ILogChannelFilter_abi>::getFilter() noexcept
{
return getFilter_abi();
}
inline void omni::core::Generated<omni::log::ILogChannelFilter_abi>::getEnabled(bool* isEnabled,
omni::log::SettingBehavior* behavior,
bool* isUsed) noexcept
{
getEnabled_abi(isEnabled, behavior, isUsed);
}
inline void omni::core::Generated<omni::log::ILogChannelFilter_abi>::getLevel(omni::log::Level* level,
omni::log::SettingBehavior* behavior,
bool* isUsed) noexcept
{
getLevel_abi(level, behavior, isUsed);
}
inline bool omni::core::Generated<omni::log::ILogChannelFilter_abi>::isMatch(const char* channel) noexcept
{
return isMatch_abi(channel);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 3,551 | C | 34.52 | 117 | 0.649395 |
omniverse-code/kit/include/omni/log/ILog.gen.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/OmniAttr.h>
#include <omni/core/Interface.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <utility>
#include <type_traits>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Consumes (listens for) log messages.
//!
//! @ref omni::log::ILogMessageConsumer is usually associated with an @ref omni::log::ILog instance. Add a consumer to
//! an @ref omni::log::ILog object with @ref omni::log::ILog::addMessageConsumer().
template <>
class omni::core::Generated<omni::log::ILogMessageConsumer_abi> : public omni::log::ILogMessageConsumer_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::log::ILogMessageConsumer")
//! Receives a log message.
//!
//! Logging a message from this method results in undefined behavior.
//!
//! Accessing the owning @ref omni::log::ILog from this method will lead to undefined behavior.
//!
//! The memory pointed to by the provided pointers will remain valid only during the duration of this call.
//!
//! @thread_safety This method must be thread safe as the attached @ref omni::log::ILog may send messages to this
//! object in parallel.
void onMessage(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp) noexcept;
};
//! Consumes (listens for) state change to one or more @ref omni::log::ILog objects.
//!
//! Add this object to an omni::log::ILog via @ref omni::log::ILog::addChannelUpdateConsumer().
template <>
class omni::core::Generated<omni::log::ILogChannelUpdateConsumer_abi> : public omni::log::ILogChannelUpdateConsumer_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::log::ILogChannelUpdateConsumer")
//! Called when an attached @ref omni::log::ILog's state changes.
//!
//! Accessing the given omni::log::ILog from this method is safe.
//!
//! If @p name is @c nullptr, the change happened to the global log (i.e. not to a specific channel).
//!
//! @thread_safety
//! This method must be thread safe as the attached ILogs may send messages to this object in parallel.
//!
//! Updates may come out-of-order and may be spurious.
void onChannelUpdate(omni::core::ObjectParam<omni::log::ILog> log,
omni::core::ObjectParam<omni::str::IReadOnlyCString> name,
omni::log::ChannelUpdateReason reason) noexcept;
};
//! Multi-channel logging interface which can write logs to multiple consumers.
//!
//! See the @rstref{Omniverse Logging Guide <carb_logging>} to better understand how logging works from both the user's
//! and developer's point-of-view.
//!
//! In practice, use of this interface is hidden to the user. Most logging occurs via the following macros:
//!
//! - @ref OMNI_LOG_VERBOSE
//! - @ref OMNI_LOG_INFO
//! - @ref OMNI_LOG_WARN
//! - @ref OMNI_LOG_ERROR
//! - @ref OMNI_LOG_FATAL
//!
//! The macros above internally call @ref omniGetLogWithoutAcquire(), which returns an @ref omni::log::ILog pointer. See
//! @ref omniGetLogWithoutAcquire() for details on how to control which @ref omni::log::ILog pointer is returned.
//!
//! The logging interface defines two concepts: **log channels** and **log consumers**.
//!
//! **Log channels** are identified by a string and represent the idea of a logging "channel". Each channel has a:
//!
//! - Enabled/Disabled flag (see @ref omni::log::ILog::setChannelEnabled()).
//!
//! - Log level at which messages should be ignored (see @ref omni::log::ILog::setChannelLevel()).
//!
//! Each message logged is associated with a single log channel.
//!
//! Each time a message is logged, the channel's settings are checked to see if the message should be filtered out. If
//! the message is not filtered, the logging interface formats the message and passes it to each log message consumer.
//!
//! **Log consumers** (e.g. @ref omni::log::ILogMessageConsumer) are attached to the logging system via @ref
//! omni::log::ILog::addMessageConsumer(). Along with the formatted message, log consumers are passed a bevvy of
//! additional information, such as filename, line number, channel name, message level, etc. The consumer may choose to
//! perform additional filtering at this point. Eventually, it is up to the log consumer to "log" the message to its
//! backing store (e.g. `stdout`).
//!
//! The @ref omni::log::ILog interface itself has a global enable/disabled flag and log level. Each channel can choose
//! to respect the global flags (via @ref omni::log::SettingBehavior::eInherit) or override the global flags with their
//! own (via @ref omni::log::SettingBehavior::eOverride).
//!
//! With these settings, user have fine-grain control over which messages are filtered and where messages are logged.
//!
//! See @ref OMNI_LOG_ADD_CHANNEL() for information on creating and registering log channels.
//!
//! In order to support rich user experiences, the logging system also allows consumers to be notified of internal state
//! changes such as a channel being added, the logging level changing, etc. See @ref
//! omni::log::ILog::addChannelUpdateConsumer() for details.
template <>
class omni::core::Generated<omni::log::ILog_abi> : public omni::log::ILog_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::log::ILog")
//! Sends the supplied message to all registered @ref omni::log::ILogMessageConsumer objects.
//!
//! @param str Must be a `\0` terminated string.
//!
//! @param strCharCount The number of characters in @p str (including the terminating `\0`). If @p strCharCount is
//! 0, its value will be computed by this method.
void log(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* str,
uint32_t strCharCount) noexcept;
//! Formats the supplied message and sends the result to all registered @ref omni::log::ILogMessageConsumer objects.
void logf(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* format,
...) noexcept;
//! Adds the given log consumer to the internal list of log consumers.
//!
//! Each message is associated with a single log channel. When a message is logged by a log channel, the message is
//! checked to see if it should be filtered. If not, it is given to the logging system (@ref omni::log::ILog) which
//! eventually sends the message to each registered @ref omni::log::ILogMessageConsumer.
//!
//! A consumer can be registered a single time with a given @ref omni::log::ILog instance but can be registered with
//! multiple @ref omni::log::ILog instances.
//!
//! Each message may be sent to registered consumers in parallel.
//!
//! Logging a message from a consumer callback will lead to undefined behavior.
//!
//! Calling @ref omni::log::ILog::addMessageConsumer() from @ref omni::log::ILogMessageConsumer::onMessage() will
//! lead to undefined behavior.
//!
//! @thread_safety This method is thread safe.
void addMessageConsumer(omni::core::ObjectParam<omni::log::ILogMessageConsumer> consumer) noexcept;
//! Removes the given consumer from the internal consumer list.
//!
//! This method silently accepts `nullptr`.
//!
//! This method silently accepts consumers that have not been registered with this object.
//!
//! Calling @ref omni::log::ILog::removeMessageConsumer() from omni::log::ILogMessageConsumer::onMessage() will lead
//! to undefined behavior.
//!
//! @thread_safety This method is thread safe.
void removeMessageConsumer(omni::core::ObjectParam<omni::log::ILogMessageConsumer> consumer) noexcept;
//! Set the logging level of this object.
//!
//! By default log channels obey the logging level set on this object. However, this behavior can be overridden
//! with @ref omni::log::ILog::setChannelLevel().
//!
//! @thread_safety This method is thread safe.
void setLevel(omni::log::Level level) noexcept;
//! Returns the logging level of this object.
//!
//! @thread_safety This method is thread safe.
omni::log::Level getLevel() noexcept;
//! Set if the log is enabled/disabled.
//!
//! By default log channels obey the enable/disabled flag set on this object. However, this behavior can be
//! overridden with @ref omni::log::ILog::setChannelEnabled().
//!
//! @thread_safety This method is thread safe.
void setEnabled(bool isEnabled) noexcept;
//! Returns if the log is enabled/disabled.
//!
//! @thread_safety This method is thread safe.
bool isEnabled() noexcept;
//! Instructs the logging system to deliver all log messages to the logging backends asynchronously.
//!
//! This causes @ref omni::log::ILog::log() calls to be buffered so that @ref omni::log::ILog::log() may return as
//! quickly as possible. A background thread then issues these buffered log messages to the registered Logger
//! backend objects.
//!
//! @thread_safety This method is thread safe.
//!
//! @returns Returns the state of asynchronous logging before this method was called.
bool setAsync(bool logAsync) noexcept;
//! Returns `true` if asynchronous logging is enabled.
//!
//! @thread_safety This method is thread safe.
bool isAsync() noexcept;
//! Associates a log channel's id with a chunk of memory to store its settings.
//!
//! A log channel can be registered multiple times. In fact, this is quite common, as a log channel's settings are
//! usually stored per-module and a log channel may span multiple modules.
//!
//! When registering a channel via this API, the given setting's memory is updated.
//!
//! @param name Name of the channel. Copied by this method.
//!
//! @param level Pointer to where the channels level is stored. The pointer must point to valid memory until @ref
//! omni::log::ILog::removeChannel() is called.
//!
//! @param description The description of the channel. Can be `nullptr`. If not `nullptr`, and a description for
//! the channel is already set and not empty, the given description is ignored. Otherwise, the description is
//! copied by this method.
//!
//! @thread_safety This method is thread safe.
void addChannel(const char* name, omni::log::Level* level, const char* description) noexcept;
//! Removes a log channel's settings memory.
//!
//! Use this method when unloading a module to prevent the log writing settings to unloaded memory.
//!
//! @thread_safety This method is thread safe.
void removeChannel(const char* name, omni::log::Level* level) noexcept;
//! Sets the given channel's log level.
//!
//! If the channel has not yet been registered with @ref omni::log::ILog::addChannel(), the setting will be
//! remembered and applied when the channel is eventually added.
//!
//! @thread_safety This method is thread safe.
void setChannelLevel(const char* name, omni::log::Level level, omni::log::SettingBehavior behavior) noexcept;
//! Returns the given channel's logging level and override behavior.
//!
//! All parameters must be non-`nullptr`.
//!
//! If the given channel is not found, an @ref omni::core::kResultNotFound is returned.
//!
//! @return Returns @ref omni::core::kResultSuccess upon success, a failure code otherwise.
//!
//! @thread_safety This method is thread safe.
omni::core::Result getChannelLevel(const char* name,
omni::log::Level* outLevel,
omni::log::SettingBehavior* outBehavior) noexcept;
//! Sets the given channel's enabled/disabled flag.
//!
//! If the channel has not yet been registered with @ref omni::log::ILog::addChannel(), the setting will be
//! remembered and applied when the channel is eventually added.
//!
//! @thread_safety This method is thread safe.
void setChannelEnabled(const char* name, bool isEnabled, omni::log::SettingBehavior behavior) noexcept;
//! Returns the given channel's logging enabled state and override behavior.
//!
//! All parameters must be non-`nullptr`.
//!
//! If the given channel is not found, an @ref omni::core::kResultNotFound is returned.
//!
//! Return @ref omni::core::kResultSuccess upon success, a failure code otherwise.
//!
//! @thread_safety This method is thread safe.
omni::core::Result getChannelEnabled(const char* name,
bool* outIsEnabled,
omni::log::SettingBehavior* outBehavior) noexcept;
//! Sets a channel's description. If the channel does not exists, it is created.
//!
//! The given channel @p name and @p description must not be `nullptr`.
//!
//! The memory pointed to by @p description is copied by this method.
//!
//! If the channel already has a description, it is replaced.
//!
//! @thread_safety This method is thread safe.
void setChannelDescription(const char* name, const char* description) noexcept;
//! Returns the given channel's description.
//!
//! All parameters must be non-`nullptr`.
//!
//! When calling this method, @p *outDescription must be `nullptr`.
//!
//! If the channel does not have a description set, @p *outDescription is set to `nullptr`.
//!
//! If @p *outDescription is set to non-`nullptr`, it will have @ref omni::core::IObject::acquire() called on it
//! before it is passed back to the caller.
//!
//! If the given channel is not found, an @ref omni::core::kResultNotFound is returned.
//!
//! @return Returns @ref omni::core::kResultSuccess upon success, a failure code otherwise.
//!
//! @thread_safety This method is thread safe.
omni::core::Result getChannelDescription(const char* name, omni::str::IReadOnlyCString** outDescription) noexcept;
//! Given a channel and a verbosity level, returns `true` if the channel is actively logging at the given level.
//!
//! Using the `OMNI_LOG_*` macros is preferred over this method, as those macros use a much more efficient method to
//! filter messages. However, the mechanics utilized by `OMNI_LOG_*` are not viable when binding to languages such
//! as Python, thus this method's existence.
//!
//! @thread_safety This method is thread safe.
bool isLoggingAtLevel(const char* name, omni::log::Level level) noexcept;
//! Flush all queued messages to message consumers.
//!
//! If asynchronous logging is enabled (see @ref omni::log::ILog::setAsync), blocks until all pending messages have
//! been delivered to message consumers.
//!
//! @thread_safety This method is thread safe.
void flush() noexcept;
//! Adds the given channel updated consumer to the internal list of update consumers.
//!
//! Each time the state of the log changes, each update consumer is notified.
//!
//! A consumer can be registered a single time with a given @ref omni::log::ILog instance but can be registered with
//! multiple @ref omni::log::ILog instances.
//!
//! Each message may be sent to registered consumers in parallel.
//!
//! It is safe to access @ref omni::log::ILog from the callback.
//!
//! @thread_safety This method is thread safe.
void addChannelUpdateConsumer(omni::core::ObjectParam<omni::log::ILogChannelUpdateConsumer> consumer) noexcept;
//! Removes the given consumer from the internal consumer list.
//!
//! This method silently accepts `nullptr`.
//!
//! This method silently accepts consumers that have not been registered with this object.
//!
//! Calling @ref omni::log::ILog::removeChannelUpdateConsumer() from @ref
//! omni::log::ILogMessageConsumer::onMessage() will lead to undefined behavior.
//!
//! @thread_safety This method is thread safe.
void removeChannelUpdateConsumer(omni::core::ObjectParam<omni::log::ILogChannelUpdateConsumer> consumer) noexcept;
//! Adds the given log consumer to the internal list of log consumers.
//!
//! Each message is associated with a single log channel. When a message is logged by a log channel, the message is
//! checked to see if it should be filtered. If not, it is given to the logging system (@ref omni::log::ILog) which
//! eventually sends the message to each registered @ref omni::log::ILogMessageConsumer.
//!
//! A consumer can be registered a single time with a given @ref omni::log::ILog instance but can be registered with
//! multiple @ref omni::log::ILog instances.
//!
//! Each message may be sent to registered consumers in parallel.
//!
//! Logging a message from a consumer callback will lead to undefined behavior.
//!
//! Calling @ref omni::log::ILog::addMessageConsumer() from @ref omni::log::ILogMessageConsumer::onMessage() will
//! lead to undefined behavior.
//!
//! @thread_safety This method is thread safe.
omni::core::ObjectPtr<omni::log::ILogMessageConsumer> addMessageConsumer(
std::function<void(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp)> fun) noexcept;
//! Adds the given channel updated consumer to the internal list of update consumers.
//!
//! Each time the state of the log changes, each update consumer is notified.
//!
//! A consumer can be registered a single time with a given @ref omni::log::ILog instance but can be registered with
//! multiple @ref omni::log::ILog instances.
//!
//! Each message may be sent to registered consumers in parallel.
//!
//! It is safe to access @ref omni::log::ILog from the callback.
//!
//! @thread_safety This method is thread safe.
omni::core::ObjectPtr<omni::log::ILogChannelUpdateConsumer> addChannelUpdateConsumer(
std::function<void(omni::log::ILog* log, omni::str::IReadOnlyCString* name, omni::log::ChannelUpdateReason reason)>
fun) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void omni::core::Generated<omni::log::ILogMessageConsumer_abi>::onMessage(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp) noexcept
{
onMessage_abi(channel, level, moduleName, fileName, functionName, lineNumber, msg, pid, tid, timestamp);
}
inline void omni::core::Generated<omni::log::ILogChannelUpdateConsumer_abi>::onChannelUpdate(
omni::core::ObjectParam<omni::log::ILog> log,
omni::core::ObjectParam<omni::str::IReadOnlyCString> name,
omni::log::ChannelUpdateReason reason) noexcept
{
onChannelUpdate_abi(log.get(), name.get(), reason);
}
inline void omni::core::Generated<omni::log::ILog_abi>::log(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* str,
uint32_t strCharCount) noexcept
{
log_abi(channel, level, moduleName, fileName, functionName, lineNumber, str, strCharCount);
}
inline void omni::core::Generated<omni::log::ILog_abi>::logf(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* format,
...) noexcept
{
va_list arg_list_;
va_start(arg_list_, format);
logf_abi(channel, level, moduleName, fileName, functionName, lineNumber, format, arg_list_);
va_end(arg_list_);
}
inline void omni::core::Generated<omni::log::ILog_abi>::addMessageConsumer(
omni::core::ObjectParam<omni::log::ILogMessageConsumer> consumer) noexcept
{
addMessageConsumer_abi(consumer.get());
}
inline void omni::core::Generated<omni::log::ILog_abi>::removeMessageConsumer(
omni::core::ObjectParam<omni::log::ILogMessageConsumer> consumer) noexcept
{
removeMessageConsumer_abi(consumer.get());
}
inline void omni::core::Generated<omni::log::ILog_abi>::setLevel(omni::log::Level level) noexcept
{
setLevel_abi(level);
}
inline omni::log::Level omni::core::Generated<omni::log::ILog_abi>::getLevel() noexcept
{
return getLevel_abi();
}
inline void omni::core::Generated<omni::log::ILog_abi>::setEnabled(bool isEnabled) noexcept
{
setEnabled_abi(isEnabled);
}
inline bool omni::core::Generated<omni::log::ILog_abi>::isEnabled() noexcept
{
return isEnabled_abi();
}
inline bool omni::core::Generated<omni::log::ILog_abi>::setAsync(bool logAsync) noexcept
{
return setAsync_abi(logAsync);
}
inline bool omni::core::Generated<omni::log::ILog_abi>::isAsync() noexcept
{
return isAsync_abi();
}
inline void omni::core::Generated<omni::log::ILog_abi>::addChannel(const char* name,
omni::log::Level* level,
const char* description) noexcept
{
addChannel_abi(name, level, description);
}
inline void omni::core::Generated<omni::log::ILog_abi>::removeChannel(const char* name, omni::log::Level* level) noexcept
{
removeChannel_abi(name, level);
}
inline void omni::core::Generated<omni::log::ILog_abi>::setChannelLevel(const char* name,
omni::log::Level level,
omni::log::SettingBehavior behavior) noexcept
{
setChannelLevel_abi(name, level, behavior);
}
inline omni::core::Result omni::core::Generated<omni::log::ILog_abi>::getChannelLevel(
const char* name, omni::log::Level* outLevel, omni::log::SettingBehavior* outBehavior) noexcept
{
return getChannelLevel_abi(name, outLevel, outBehavior);
}
inline void omni::core::Generated<omni::log::ILog_abi>::setChannelEnabled(const char* name,
bool isEnabled,
omni::log::SettingBehavior behavior) noexcept
{
setChannelEnabled_abi(name, isEnabled, behavior);
}
inline omni::core::Result omni::core::Generated<omni::log::ILog_abi>::getChannelEnabled(
const char* name, bool* outIsEnabled, omni::log::SettingBehavior* outBehavior) noexcept
{
return getChannelEnabled_abi(name, outIsEnabled, outBehavior);
}
inline void omni::core::Generated<omni::log::ILog_abi>::setChannelDescription(const char* name,
const char* description) noexcept
{
setChannelDescription_abi(name, description);
}
inline omni::core::Result omni::core::Generated<omni::log::ILog_abi>::getChannelDescription(
const char* name, omni::str::IReadOnlyCString** outDescription) noexcept
{
return getChannelDescription_abi(name, outDescription);
}
inline bool omni::core::Generated<omni::log::ILog_abi>::isLoggingAtLevel(const char* name, omni::log::Level level) noexcept
{
return isLoggingAtLevel_abi(name, level);
}
inline void omni::core::Generated<omni::log::ILog_abi>::flush() noexcept
{
flush_abi();
}
inline void omni::core::Generated<omni::log::ILog_abi>::addChannelUpdateConsumer(
omni::core::ObjectParam<omni::log::ILogChannelUpdateConsumer> consumer) noexcept
{
addChannelUpdateConsumer_abi(consumer.get());
}
inline void omni::core::Generated<omni::log::ILog_abi>::removeChannelUpdateConsumer(
omni::core::ObjectParam<omni::log::ILogChannelUpdateConsumer> consumer) noexcept
{
removeChannelUpdateConsumer_abi(consumer.get());
}
inline omni::core::ObjectPtr<omni::log::ILogMessageConsumer> omni::core::Generated<omni::log::ILog_abi>::addMessageConsumer(
std::function<void(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp)> fun) noexcept
{
class Consumer : public omni::core::Implements<omni::log::ILogMessageConsumer>
{
public:
virtual void onMessage_abi(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp) noexcept override
{
m_function(channel, level, moduleName, fileName, functionName, lineNumber, msg, pid, tid, timestamp);
}
Consumer(std::function<void(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp)> cb)
: m_function(std::move(cb))
{
}
private:
std::function<void(const char* channel,
omni::log::Level level,
const char* moduleName,
const char* fileName,
const char* functionName,
uint32_t lineNumber,
const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp)>
m_function;
};
auto consumer{ omni::core::steal(new Consumer{ std::move(fun) }) };
addMessageConsumer_abi(consumer.get());
return consumer;
}
inline omni::core::ObjectPtr<omni::log::ILogChannelUpdateConsumer> omni::core::Generated<omni::log::ILog_abi>::addChannelUpdateConsumer(
std::function<void(omni::log::ILog* log, omni::str::IReadOnlyCString* name, omni::log::ChannelUpdateReason reason)> fun) noexcept
{
class Consumer : public omni::core::Implements<omni::log::ILogChannelUpdateConsumer>
{
public:
virtual void onChannelUpdate_abi(omni::log::ILog* log,
omni::str::IReadOnlyCString* name,
omni::log::ChannelUpdateReason reason) noexcept override
{
m_function(log, name, reason);
}
Consumer(std::function<
void(omni::log::ILog* log, omni::str::IReadOnlyCString* name, omni::log::ChannelUpdateReason reason)> cb)
: m_function(std::move(cb))
{
}
private:
std::function<void(omni::log::ILog* log, omni::str::IReadOnlyCString* name, omni::log::ChannelUpdateReason reason)>
m_function;
};
auto consumer{ omni::core::steal(new Consumer{ std::move(fun) }) };
addChannelUpdateConsumer_abi(consumer.get());
return consumer;
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 31,045 | C | 44.455344 | 136 | 0.610018 |
omniverse-code/kit/include/omni/log/LogChannel.h | // Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
//! @file
//!
//! @brief Utilities for handling logging channels.
#pragma once
#include <cstdint>
#include <vector>
//! Given a channel name (as a string), declares a global variable to identify the channel.
//!
//! This macro must be called at global scope.
//!
//! This macro can be called multiple times in a module (think of it as a forward declaration).
//!
//! @ref OMNI_LOG_ADD_CHANNEL() must be called, only once, to define the properties of the channel (e.g. name,
//! description, etc.).
//!
//! For example, the following declares a channel identified by the `kImageChannel` variable:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_DECLARE_CHANNEL(kImageLoadChannel);
//!
//! @endcode
//!
//! Later, we can log to that channel:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_VERBOSE(kImageLoadChannel, "I loaded a cool image: %s", imageFilename);
//!
//! @endcode
//!
//! Above, `kImageChannel` is just a variable describing the channel. To define the channel name (what the user sees)
//! use @ref OMNI_LOG_ADD_CHANNEL().
#define OMNI_LOG_DECLARE_CHANNEL(varName_) extern omni::log::LogChannelData varName_;
//! Defines the properties of a channel and adds it to a module specific list of channels.
//!
//! This macro must be called at global scope and is expected to run during static initialization.
//!
//! Example usage:
//!
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ADD_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! @endcode
//!
//! For each module, this macro should only be called once per channel.
//!
//! To tell the log about a module's channels added during static initialization (i.e. by this macro), call
//! @ref omni::log::addModulesChannels().
//!
//! @ref OMNI_LOG_DECLARE_CHANNEL() does not have to be called before calling this macro.
#define OMNI_LOG_ADD_CHANNEL(varName_, channelName_, description_) \
OMNI_LOG_DEFINE_CHANNEL_(varName_, channelName_, description_, true)
//! Defines the properties of a channel.
//!
//! This macro must be called at global scope.
//!
//! Example usage:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_DEFINE_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! @endcode
//!
//! For each module, this macro should only be called once per channel.
//!
//! @ref OMNI_LOG_DECLARE_CHANNEL() does not have to be called before calling this macro.
//!
//! Use of this macro is rare (currently used only for unit testing) as it does not add the channel to the log. See
//! @ref OMNI_LOG_ADD_CHANNEL for a more useful way to define a channel. Note, per-channel, either call this macro or
//! @ref OMNI_LOG_ADD_CHANNEL once. Never call both.
#define OMNI_LOG_DEFINE_CHANNEL(varName_, channelName_, description_) \
OMNI_LOG_DEFINE_CHANNEL_(varName_, channelName_, description_, false)
//! Implementation detail. Do not call.
#define OMNI_LOG_DEFINE_CHANNEL_(varName_, channelName_, description_, add_) \
omni::log::LogChannelData varName_{ channelName_, 0, description_, nullptr }; \
omni::log::LogChannelRegistrar varName_##Registrar{ &varName_, add_ };
#ifndef OMNI_LOG_DEFAULT_CHANNEL
//! The default channel variable to use when no channel is supplied to the `OMNI_LOG_*` macros.
//!
//! By default, the channel variable to use is `kDefaultChannel`.
//!
//! See @rstref{Defining the Default Logging Channel <carb_logging_default_channel>} on how to use this `#define` in
//! practice.
# define OMNI_LOG_DEFAULT_CHANNEL kDefaultChannel
#endif
namespace omni
{
namespace log
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
//! Describes a channel.
//!
//! This is an implementation detail.
struct LogChannelData
{
const char* const name;
int32_t level;
const char* const description;
LogChannelData* next;
};
#endif
//! Returns a per-module list of channels defined during static initialization via @ref OMNI_LOG_ADD_CHANNEL.
//!
//! Call @ref omni::log::addModulesChannels() to iterate over this list and add the channels to the global log.
inline LogChannelData*& getModuleLogChannels() noexcept
{
static LogChannelData* sHead = nullptr;
return sHead;
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
//! Template to allocate storage for a channel.
//!
//! Do not directly use this object. Rather call @ref OMNI_LOG_ADD_CHANNEL().
class LogChannelRegistrar
{
public:
LogChannelRegistrar(LogChannelData* data, bool add) noexcept
{
if (add)
{
data->next = getModuleLogChannels();
getModuleLogChannels() = data;
}
}
};
#endif
} // namespace log
} // namespace omni
#ifndef DOXYGEN_SHOULD_SKIP_THIS
# define OMNI_LOG_DECLARE_DEFAULT_CHANNEL_1(chan_) OMNI_LOG_DECLARE_CHANNEL(chan_)
# define OMNI_LOG_DECLARE_DEFAULT_CHANNEL() OMNI_LOG_DECLARE_DEFAULT_CHANNEL_1(OMNI_LOG_DEFAULT_CHANNEL)
// forward declare the default channel
OMNI_LOG_DECLARE_DEFAULT_CHANNEL()
#endif
| 5,504 | C | 31.573964 | 120 | 0.684411 |
omniverse-code/kit/include/omni/log/ILog.h | // Copyright (c) 2020-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.
//
//! @file
//!
//! @brief Fast, multi-channel logging.
#pragma once
#include "../core/Api.h"
#include "../core/BuiltIn.h"
#include "../core/IObject.h"
#include "../str/IReadOnlyCString.h"
#include "../log/LogChannel.h"
#include "../extras/OutArrayUtils.h"
#include "../../carb/thread/Util.h"
#include <cstring>
#include <vector>
//! Logs a message at @ref omni::log::Level::eVerbose level.
//!
//! The first argument can be either a channel or the format string.
//!
//! If the first argument is a channel, the second argument is the format string. Channels can be created with the @ref
//! OMNI_LOG_ADD_CHANNEL macro.
//!
//! For example:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ADD_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! ...
//!
//! OMNI_LOG_VERBOSE(kImageLoadChannel, "I loaded a cool image: %s", imageFilename);
//!
//! @endcode
//!
//! If the first argument is the format string, the channel defined by the @ref OMNI_LOG_DEFAULT_CHANNEL is used.
//! Example usage:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_VERBOSE("This message is going to the default channel: %s", "woo-hoo");
//!
//! @endcode
//!
//! The given format string uses the same tokens as the `printf` family of functions.
//!
//! The @ref omni::log::ILog used to log the message is the log returned by @ref omniGetLogWithoutAcquire().
//!
//! @see @ref OMNI_LOG_INFO, @ref OMNI_LOG_WARN, @ref OMNI_LOG_ERROR, @ref OMNI_LOG_FATAL.
//!
//! @thread_safety This macro is thread safe though may block if `omniGetLogWithAcquire()->isAsync()` is `false`.
#define OMNI_LOG_VERBOSE(channelOrFormat_, ...) \
OMNI_LOG_WRITE(channelOrFormat_, omni::log::Level::eVerbose, ##__VA_ARGS__)
//! Logs a message at @ref omni::log::Level::eInfo level.
//!
//! The first argument can be either a channel or the format string.
//!
//! If the first argument is a channel, the second argument is the format string. Channels can be created with the @ref
//! OMNI_LOG_ADD_CHANNEL macro.
//!
//! For example:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ADD_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! ...
//!
//! OMNI_LOG_INFO(kImageLoadChannel, "I loaded a cool image: %s", imageFilename);
//!
//! @endcode
//!
//! If the first argument is the format string, the channel defined by the @ref OMNI_LOG_DEFAULT_CHANNEL is used.
//! Example usage:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_INFO("This message is going to the default channel: %s", "woo-hoo");
//!
//! @endcode
//!
//! The given format string uses the same tokens as the `printf` family of functions.
//!
//! The @ref omni::log::ILog used to log the message is the log returned by @ref omniGetLogWithoutAcquire().
//!
//! @see @ref OMNI_LOG_VERBOSE, @ref OMNI_LOG_WARN, @ref OMNI_LOG_ERROR, @ref OMNI_LOG_FATAL.
//!
//! @thread_safety This macro is thread safe though may block if `omniGetLogWithAcquire()->isAsync()` is `false`.
#define OMNI_LOG_INFO(channelOrFormat_, ...) OMNI_LOG_WRITE(channelOrFormat_, omni::log::Level::eInfo, ##__VA_ARGS__)
//! Logs a message at @ref omni::log::Level::eWarn level.
//!
//! The first argument can be either a channel or the format string.
//!
//! If the first argument is a channel, the second argument is the format string. Channels can be created with the @ref
//! OMNI_LOG_ADD_CHANNEL macro.
//!
//! For example:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ADD_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! ...
//!
//! OMNI_LOG_WARN(kImageLoadChannel, "I loaded a cool image: %s", imageFilename);
//!
//! @endcode
//!
//! If the first argument is the format string, the channel defined by the @ref OMNI_LOG_DEFAULT_CHANNEL is used.
//! Example usage:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_WARN("This message is going to the default channel: %s", "woo-hoo");
//!
//! @endcode
//!
//! The given format string uses the same tokens as the `printf` family of functions.
//!
//! The @ref omni::log::ILog used to log the message is the log returned by @ref omniGetLogWithoutAcquire().
//!
//! @see @ref OMNI_LOG_VERBOSE, @ref OMNI_LOG_INFO, @ref OMNI_LOG_ERROR, @ref OMNI_LOG_FATAL.
//!
//! @thread_safety This macro is thread safe though may block if `omniGetLogWithAcquire()->isAsync()` is `false`.
#define OMNI_LOG_WARN(channelOrFormat_, ...) OMNI_LOG_WRITE(channelOrFormat_, omni::log::Level::eWarn, ##__VA_ARGS__)
//! Logs a message at @ref omni::log::Level::eError level.
//!
//! The first argument can be either a channel or the format string.
//!
//! If the first argument is a channel, the second argument is the format string. Channels can be created with the @ref
//! OMNI_LOG_ADD_CHANNEL macro.
//!
//! For example:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ADD_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! ...
//!
//! OMNI_LOG_ERROR(kImageLoadChannel, "I loaded a cool image: %s", imageFilename);
//!
//! @endcode
//!
//! If the first argument is the format string, the channel defined by the @ref OMNI_LOG_DEFAULT_CHANNEL is used.
//! Example usage:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ERROR("This message is going to the default channel: %s", "woo-hoo");
//!
//! @endcode
//!
//! The given format string uses the same tokens as the `printf` family of functions.
//!
//! The @ref omni::log::ILog used to log the message is the log returned by @ref omniGetLogWithoutAcquire().
//!
//! @see @ref OMNI_LOG_VERBOSE, @ref OMNI_LOG_INFO, @ref OMNI_LOG_WARN, @ref OMNI_LOG_FATAL.
//!
//! @thread_safety This macro is thread safe though may block if `omniGetLogWithAcquire()->isAsync()` is `false`.
#define OMNI_LOG_ERROR(channelOrFormat_, ...) OMNI_LOG_WRITE(channelOrFormat_, omni::log::Level::eError, ##__VA_ARGS__)
//! Logs a message at @ref omni::log::Level::eFatal level.
//!
//! The first argument can be either a channel or the format string.
//!
//! If the first argument is a channel, the second argument is the format string. Channels can be created with the @ref
//! OMNI_LOG_ADD_CHANNEL macro.
//!
//! For example:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ADD_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! ...
//!
//! OMNI_LOG_FATAL(kImageLoadChannel, "I loaded a cool image: %s", imageFilename);
//!
//! @endcode
//!
//! If the first argument is the format string, the channel defined by the @ref OMNI_LOG_DEFAULT_CHANNEL is used.
//! Example usage:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_FATAL("This message is going to the default channel: %s", "woo-hoo");
//!
//! @endcode
//!
//! The given format string uses the same tokens as the `printf` family of functions.
//!
//! The @ref omni::log::ILog used to log the message is the log returned by @ref omniGetLogWithoutAcquire().
//!
//! @rst
//!
//! .. note:: This macro does not terminate the process, it just logs a message.
//!
//! @endrst
//!
//! @see @ref OMNI_LOG_VERBOSE, @ref OMNI_LOG_INFO, @ref OMNI_LOG_WARN, @ref OMNI_LOG_ERROR.
//!
//! @thread_safety This macro is thread safe though may block if `omniGetLogWithAcquire()->isAsync()` is `false`.
#define OMNI_LOG_FATAL(channelOrFormat_, ...) OMNI_LOG_WRITE(channelOrFormat_, omni::log::Level::eFatal, ##__VA_ARGS__)
//! Logs a message.
//!
//! The first argument can be either a channel or the format string.
//!
//! The second argument must be @ref omni::log::Level at which to log the message.
//!
//! If the first argument is a channel, the third argument is the format string. Channels can be created with the @ref
//! OMNI_LOG_ADD_CHANNEL macro.
//!
//! For example:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_ADD_CHANNEL(kImageLoadChannel, "omni.image.load", "Messages when loading an image.");
//!
//! ...
//!
//! OMNI_LOG_WRITE(kImageLoadChannel, omni::log::Level::eVerbose, "I loaded a cool image: %s", imageFilename);
//!
//! @endcode
//!
//! If the first argument is the format string, the channel defined by the @ref OMNI_LOG_DEFAULT_CHANNEL is used.
//! Example usage:
//!
//! @code{.cpp}
//!
//! OMNI_LOG_WRITE("This message is going to the default channel: %s", omni::log::Level::eInfo, "woo-hoo");
//!
//! @endcode
//!
//! The given format string uses the same tokens as the `printf` family of functions.
//!
//! The @ref omni::log::ILog used to log the message is the log returned by @ref omniGetLogWithoutAcquire().
//!
//! Rather than using this function, consider using @ref OMNI_LOG_VERBOSE, @ref OMNI_LOG_INFO, @ref OMNI_LOG_WARN, @ref
//! OMNI_LOG_ERROR, @ref OMNI_LOG_FATAL.
//!
//! @thread_safety This macro is thread safe though may block if `omniGetLogWithAcquire()->isAsync()` is `false`.
//! Implementation detail. Figure out if the first arg is a channel or a format string, check if the channel (or
//! default channel) is enabled, and only then evaluate the given arguments and call into the logger.
#define OMNI_LOG_WRITE(channelOrFormat_, level_, ...) \
do \
{ \
OMNI_LOG_VALIDATE_FORMAT(channelOrFormat_, ##__VA_ARGS__) \
if (omni::log::detail::isChannelEnabled(level_, OMNI_LOG_DEFAULT_CHANNEL, channelOrFormat_)) \
{ \
omni::log::ILog* log_ = omniGetLogWithoutAcquire(); \
if (log_) \
{ \
omni::log::detail::writeLog(OMNI_LOG_DEFAULT_CHANNEL, channelOrFormat_, log_, level_, __FILE__, \
__func__, __LINE__, ##__VA_ARGS__); \
} \
} \
} while (0)
namespace omni
{
//! Multi-channel logging.
namespace log
{
//! Defines if a log channel's setting should be respected or if the global logging system's settings should be used.
enum class OMNI_ATTR("prefix=e") SettingBehavior : uint32_t
{
eInherit, //!< Use the log system's setting.
eOverride //!< Use the setting defined by the log channel.
};
//! Reason for a channel update notification.
enum class OMNI_ATTR("prefix=e") ChannelUpdateReason : uint32_t
{
eChannelAdded, //!< A channel was added.
eChannelRemoved, //!< A channel was removed.
eLevelUpdated, //!< The channel's level or level behavior was updated.
eEnabledUpdated, //!< The channel's enabled flag or enabled behavior was updated.
eDescriptionUpdated, //!< The channel's description was updated.
};
//! Severity of a message.
enum class OMNI_ATTR("prefix=e") Level : int32_t
{
//! Verbose level, for detailed diagnostics messages.
//!
//! Expect to see some verbose messages on every frame under certain conditions.
eVerbose = -2,
//! Info level, this is for informational messages.
//!
//! They are usually triggered on state changes and typically we should not see the same
//! message on every frame.
eInfo = -1,
//! Warning level, this is for warning messages.
//!
//! Something could be wrong but not necessarily an error.
//! Therefore anything that could be a problem but cannot be determined to be an error
//! should fall into this category. This is the default log level threshold, if nothing
//! else was specified via configuration or startup arguments. This is also the reason
//! why it has a value of 0 - the default is zero.
eWarn = 0,
//! Error level, this is for error messages.
//!
//! An error has occurred but the program can continue.
eError = 1,
//! Fatal level, this is for messages on unrecoverable errors.
//!
//! An error has occurred and the program cannot continue.
//! After logging such a message the caller should take immediate action to exit the
//! program or unload the module.
eFatal = 2,
//! Internal flag used to disable logging.
eDisabled = 3,
};
class ILogMessageConsumer_abi;
class ILogMessageConsumer;
class ILogChannelUpdateConsumer_abi;
class ILogChannelUpdateConsumer;
class ILog_abi;
class ILog;
//! Consumes (listens for) log messages.
//!
//! @ref omni::log::ILogMessageConsumer is usually associated with an @ref omni::log::ILog instance. Add a consumer to
//! an @ref omni::log::ILog object with @ref omni::log::ILog::addMessageConsumer().
class ILogMessageConsumer_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.log.ILogMessageConsumer")>
{
protected:
//! Receives a log message.
//!
//! Logging a message from this method results in undefined behavior.
//!
//! Accessing the owning @ref omni::log::ILog from this method will lead to undefined behavior.
//!
//! The memory pointed to by the provided pointers will remain valid only during the duration of this call.
//!
//! @thread_safety This method must be thread safe as the attached @ref omni::log::ILog may send messages to this
//! object in parallel.
virtual void onMessage_abi(OMNI_ATTR("c_str, not_null") const char* channel,
Level level,
OMNI_ATTR("c_str") const char* moduleName,
OMNI_ATTR("c_str") const char* fileName,
OMNI_ATTR("c_str") const char* functionName,
uint32_t lineNumber,
OMNI_ATTR("c_str, not_null") const char* msg,
carb::thread::ProcessId pid,
carb::thread::ThreadId tid,
uint64_t timestamp) noexcept = 0;
};
//! Consumes (listens for) state change to one or more @ref omni::log::ILog objects.
//!
//! Add this object to an omni::log::ILog via @ref omni::log::ILog::addChannelUpdateConsumer().
class ILogChannelUpdateConsumer_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.log.ILogChannelUpdateConsumer")>
{
protected:
//! Called when an attached @ref omni::log::ILog's state changes.
//!
//! Accessing the given omni::log::ILog from this method is safe.
//!
//! If @p name is @c nullptr, the change happened to the global log (i.e. not to a specific channel).
//!
//! @thread_safety
//! This method must be thread safe as the attached ILogs may send messages to this object in parallel.
//!
//! Updates may come out-of-order and may be spurious.
virtual void onChannelUpdate_abi(OMNI_ATTR("not_null") ILog* log,
omni::str::IReadOnlyCString* name,
ChannelUpdateReason reason) noexcept = 0;
};
//! Multi-channel logging interface which can write logs to multiple consumers.
//!
//! See the @rstref{Omniverse Logging Guide <carb_logging>} to better understand how logging works from both the user's
//! and developer's point-of-view.
//!
//! In practice, use of this interface is hidden to the user. Most logging occurs via the following macros:
//!
//! - @ref OMNI_LOG_VERBOSE
//! - @ref OMNI_LOG_INFO
//! - @ref OMNI_LOG_WARN
//! - @ref OMNI_LOG_ERROR
//! - @ref OMNI_LOG_FATAL
//!
//! The macros above internally call @ref omniGetLogWithoutAcquire(), which returns an @ref omni::log::ILog pointer. See
//! @ref omniGetLogWithoutAcquire() for details on how to control which @ref omni::log::ILog pointer is returned.
//!
//! The logging interface defines two concepts: **log channels** and **log consumers**.
//!
//! **Log channels** are identified by a string and represent the idea of a logging "channel". Each channel has a:
//!
//! - Enabled/Disabled flag (see @ref omni::log::ILog::setChannelEnabled()).
//!
//! - Log level at which messages should be ignored (see @ref omni::log::ILog::setChannelLevel()).
//!
//! Each message logged is associated with a single log channel.
//!
//! Each time a message is logged, the channel's settings are checked to see if the message should be filtered out. If
//! the message is not filtered, the logging interface formats the message and passes it to each log message consumer.
//!
//! **Log consumers** (e.g. @ref omni::log::ILogMessageConsumer) are attached to the logging system via @ref
//! omni::log::ILog::addMessageConsumer(). Along with the formatted message, log consumers are passed a bevvy of
//! additional information, such as filename, line number, channel name, message level, etc. The consumer may choose to
//! perform additional filtering at this point. Eventually, it is up to the log consumer to "log" the message to its
//! backing store (e.g. `stdout`).
//!
//! The @ref omni::log::ILog interface itself has a global enable/disabled flag and log level. Each channel can choose
//! to respect the global flags (via @ref omni::log::SettingBehavior::eInherit) or override the global flags with their
//! own (via @ref omni::log::SettingBehavior::eOverride).
//!
//! With these settings, user have fine-grain control over which messages are filtered and where messages are logged.
//!
//! See @ref OMNI_LOG_ADD_CHANNEL() for information on creating and registering log channels.
//!
//! In order to support rich user experiences, the logging system also allows consumers to be notified of internal state
//! changes such as a channel being added, the logging level changing, etc. See @ref
//! omni::log::ILog::addChannelUpdateConsumer() for details.
class ILog_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.log.ILog")>
{
protected:
//! Sends the supplied message to all registered @ref omni::log::ILogMessageConsumer objects.
//!
//! @param str Must be a `\0` terminated string.
//!
//! @param strCharCount The number of characters in @p str (including the terminating `\0`). If @p strCharCount is
//! 0, its value will be computed by this method.
virtual OMNI_ATTR("no_py") void log_abi(OMNI_ATTR("c_str, not_null") const char* channel,
Level level,
OMNI_ATTR("c_str") const char* moduleName,
OMNI_ATTR("c_str") const char* fileName,
OMNI_ATTR("c_str") const char* functionName,
uint32_t lineNumber,
OMNI_ATTR("c_str, not_null") const char* str,
uint32_t strCharCount) noexcept = 0;
//! Formats the supplied message and sends the result to all registered @ref omni::log::ILogMessageConsumer objects.
virtual OMNI_ATTR("no_py") void logf_abi(OMNI_ATTR("c_str, not_null") const char* channel,
Level level,
OMNI_ATTR("c_str") const char* moduleName,
OMNI_ATTR("c_str") const char* fileName,
OMNI_ATTR("c_str") const char* functionName,
uint32_t lineNumber,
OMNI_ATTR("c_str, not_null") const char* format,
va_list args) noexcept = 0;
//! Adds the given log consumer to the internal list of log consumers.
//!
//! Each message is associated with a single log channel. When a message is logged by a log channel, the message is
//! checked to see if it should be filtered. If not, it is given to the logging system (@ref omni::log::ILog) which
//! eventually sends the message to each registered @ref omni::log::ILogMessageConsumer.
//!
//! A consumer can be registered a single time with a given @ref omni::log::ILog instance but can be registered with
//! multiple @ref omni::log::ILog instances.
//!
//! Each message may be sent to registered consumers in parallel.
//!
//! Logging a message from a consumer callback will lead to undefined behavior.
//!
//! Calling @ref omni::log::ILog::addMessageConsumer() from @ref omni::log::ILogMessageConsumer::onMessage() will
//! lead to undefined behavior.
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("consumer=onMessage_abi") void addMessageConsumer_abi(OMNI_ATTR("not_null")
ILogMessageConsumer* consumer) noexcept = 0;
//! Removes the given consumer from the internal consumer list.
//!
//! This method silently accepts `nullptr`.
//!
//! This method silently accepts consumers that have not been registered with this object.
//!
//! Calling @ref omni::log::ILog::removeMessageConsumer() from omni::log::ILogMessageConsumer::onMessage() will lead
//! to undefined behavior.
//!
//! @thread_safety This method is thread safe.
virtual void removeMessageConsumer_abi(ILogMessageConsumer* consumer) noexcept = 0;
//! Returns the list of message consumers.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! @p consumersCount must not be `nullptr` in both modes.
//!
//! **Query mode** is enabled when consumers is `nullptr`. When in this mode, @p *consumersCount will be populated
//! with the number of consumers in the log and @ref omni::core::kResultSuccess is returned.
//!
//! **Get mode** is enabled when consumers is not `nullptr`. Upon entering the function, @p *consumersCount stores
//! the number of entries in consumers. If @p *consumersCount is less than the number of consumers in the log, @p
//! *consumersCount is updated with the number of consumers in the log and @ref
//! omni::core::kResultInsufficientBuffer is returned. If @p *consumersCount is greater or equal to the number of
//! channels, @p *consumersCount is updated with the number of consumers in the log, consumers array is populated,
//! and @ref omni::core::kResultSuccess is returned.
//!
//! If the @p consumers array is populated, each written entry in the array will have had @ref
//! omni::core::IObject::acquire() called on it.
//!
//! Upon entering the function, the pointers in the @p consumers array must be `nullptr`.
//!
//! @returns Return values are as above. Additional error codes may be returned (e.g. @ref
//! omni::core::kResultInvalidArgument if @p consumersCount is `nullptr`).
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("no_api, no_py") omni::core::Result getMessageConsumers_abi( // disable omni.bind until OM-21202
OMNI_ATTR("out, count=*consumersCount, *not_null") ILogMessageConsumer** consumers,
OMNI_ATTR("in, out, not_null") uint32_t* consumersCount) noexcept = 0;
//! Set the logging level of this object.
//!
//! By default log channels obey the logging level set on this object. However, this behavior can be overridden
//! with @ref omni::log::ILog::setChannelLevel().
//!
//! @thread_safety This method is thread safe.
virtual void setLevel_abi(Level level) noexcept = 0;
//! Returns the logging level of this object.
//!
//! @thread_safety This method is thread safe.
virtual Level getLevel_abi() noexcept = 0;
//! Set if the log is enabled/disabled.
//!
//! By default log channels obey the enable/disabled flag set on this object. However, this behavior can be
//! overridden with @ref omni::log::ILog::setChannelEnabled().
//!
//! @thread_safety This method is thread safe.
virtual void setEnabled_abi(bool isEnabled) noexcept = 0;
//! Returns if the log is enabled/disabled.
//!
//! @thread_safety This method is thread safe.
virtual bool isEnabled_abi() noexcept = 0;
//! Instructs the logging system to deliver all log messages to the logging backends asynchronously.
//!
//! This causes @ref omni::log::ILog::log() calls to be buffered so that @ref omni::log::ILog::log() may return as
//! quickly as possible. A background thread then issues these buffered log messages to the registered Logger
//! backend objects.
//!
//! @thread_safety This method is thread safe.
//!
//! @returns Returns the state of asynchronous logging before this method was called.
virtual OMNI_ATTR("py_not_prop") bool setAsync_abi(bool logAsync) noexcept = 0;
//! Returns `true` if asynchronous logging is enabled.
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("py_not_prop") bool isAsync_abi() noexcept = 0;
//! Associates a log channel's id with a chunk of memory to store its settings.
//!
//! A log channel can be registered multiple times. In fact, this is quite common, as a log channel's settings are
//! usually stored per-module and a log channel may span multiple modules.
//!
//! When registering a channel via this API, the given setting's memory is updated.
//!
//! @param name Name of the channel. Copied by this method.
//!
//! @param level Pointer to where the channels level is stored. The pointer must point to valid memory until @ref
//! omni::log::ILog::removeChannel() is called.
//!
//! @param description The description of the channel. Can be `nullptr`. If not `nullptr`, and a description for
//! the channel is already set and not empty, the given description is ignored. Otherwise, the description is
//! copied by this method.
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("no_py") void addChannel_abi(OMNI_ATTR("c_str, not_null") const char* name,
OMNI_ATTR("in, out, not_null") Level* level,
OMNI_ATTR("c_str") const char* description) noexcept = 0;
//! Removes a log channel's settings memory.
//!
//! Use this method when unloading a module to prevent the log writing settings to unloaded memory.
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("no_py") void removeChannel_abi(OMNI_ATTR("c_str, not_null") const char* name,
OMNI_ATTR("in, out, not_null") Level* level) noexcept = 0;
//! Returns the list of channels names.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! @p namesCount must not be `nullptr` in both modes.
//!
//! **Query mode** is enabled when names is `nullptr`. When in this mode, @p *namesCount will be populated with the
//! number of channels in the log and @ref omni::core::kResultSuccess is returned.
//!
//! **Get mode** is enabled when names is not `nullptr`. Upon entering the function, @p *namesCount stores the
//! number of entries in names. If @p *namesCount is less than the number of channels in the log, @p *namesCount is
//! updated with the number of channels in the log and @ref omni::core::kResultInsufficientBuffer is returned. If
//! @p *namesCount is greater or equal to the number of channels, @p *namesCount is updated with the number of
//! channels in the log, names array is populated, and @ref omni::core::kResultSuccess is returned.
//!
//! If the @p names array is populated, each written entry in the array will have had @ref
//! omni::core::IObject::acquire() called on it.
//!
//! Upon entering the function, the pointers in the @p names array must be `nullptr`.
//!
//! @return Return values are as above. Additional error codes may be returned (e.g. @ref
//! omni::core::kResultInvalidArgument if @p namesCount is `nullptr`).
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("no_api, no_py") omni::core::Result getChannelNames_abi( // disable omni.bind until OM-21202
OMNI_ATTR("out, count=*namesCount, *not_null") omni::str::IReadOnlyCString** names,
OMNI_ATTR("in, out, not_null") uint32_t* namesCount) noexcept = 0;
//! Sets the given channel's log level.
//!
//! If the channel has not yet been registered with @ref omni::log::ILog::addChannel(), the setting will be
//! remembered and applied when the channel is eventually added.
//!
//! @thread_safety This method is thread safe.
virtual void setChannelLevel_abi(OMNI_ATTR("c_str, not_null") const char* name,
Level level,
SettingBehavior behavior) noexcept = 0;
//! Returns the given channel's logging level and override behavior.
//!
//! All parameters must be non-`nullptr`.
//!
//! If the given channel is not found, an @ref omni::core::kResultNotFound is returned.
//!
//! @return Returns @ref omni::core::kResultSuccess upon success, a failure code otherwise.
//!
//! @thread_safety This method is thread safe.
virtual omni::core::Result getChannelLevel_abi(OMNI_ATTR("c_str, not_null") const char* name,
OMNI_ATTR("out, not_null") Level* outLevel,
OMNI_ATTR("out, not_null") SettingBehavior* outBehavior) noexcept = 0;
//! Sets the given channel's enabled/disabled flag.
//!
//! If the channel has not yet been registered with @ref omni::log::ILog::addChannel(), the setting will be
//! remembered and applied when the channel is eventually added.
//!
//! @thread_safety This method is thread safe.
virtual void setChannelEnabled_abi(OMNI_ATTR("c_str, not_null") const char* name,
bool isEnabled,
SettingBehavior behavior) noexcept = 0;
//! Returns the given channel's logging enabled state and override behavior.
//!
//! All parameters must be non-`nullptr`.
//!
//! If the given channel is not found, an @ref omni::core::kResultNotFound is returned.
//!
//! Return @ref omni::core::kResultSuccess upon success, a failure code otherwise.
//!
//! @thread_safety This method is thread safe.
virtual omni::core::Result getChannelEnabled_abi(OMNI_ATTR("c_str, not_null") const char* name,
OMNI_ATTR("out, not_null") bool* outIsEnabled,
OMNI_ATTR("out, not_null")
SettingBehavior* outBehavior) noexcept = 0;
//! Sets a channel's description. If the channel does not exists, it is created.
//!
//! The given channel @p name and @p description must not be `nullptr`.
//!
//! The memory pointed to by @p description is copied by this method.
//!
//! If the channel already has a description, it is replaced.
//!
//! @thread_safety This method is thread safe.
virtual void setChannelDescription_abi(OMNI_ATTR("c_str, not_null") const char* name,
OMNI_ATTR("c_str, not_null") const char* description) noexcept = 0;
//! Returns the given channel's description.
//!
//! All parameters must be non-`nullptr`.
//!
//! When calling this method, @p *outDescription must be `nullptr`.
//!
//! If the channel does not have a description set, @p *outDescription is set to `nullptr`.
//!
//! If @p *outDescription is set to non-`nullptr`, it will have @ref omni::core::IObject::acquire() called on it
//! before it is passed back to the caller.
//!
//! If the given channel is not found, an @ref omni::core::kResultNotFound is returned.
//!
//! @return Returns @ref omni::core::kResultSuccess upon success, a failure code otherwise.
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("no_py") omni::core::Result getChannelDescription_abi( // OM-21456: disable omni.bind py bindings
OMNI_ATTR("c_str, not_null") const char* name,
OMNI_ATTR("out, not_null") omni::str::IReadOnlyCString** outDescription) noexcept = 0;
//! Given a channel and a verbosity level, returns `true` if the channel is actively logging at the given level.
//!
//! Using the `OMNI_LOG_*` macros is preferred over this method, as those macros use a much more efficient method to
//! filter messages. However, the mechanics utilized by `OMNI_LOG_*` are not viable when binding to languages such
//! as Python, thus this method's existence.
//!
//! @thread_safety This method is thread safe.
virtual bool isLoggingAtLevel_abi(OMNI_ATTR("c_str, not_null") const char* name, Level level) noexcept = 0;
//! Flush all queued messages to message consumers.
//!
//! If asynchronous logging is enabled (see @ref omni::log::ILog::setAsync), blocks until all pending messages have
//! been delivered to message consumers.
//!
//! @thread_safety This method is thread safe.
virtual void flush_abi() noexcept = 0;
//! Adds the given channel updated consumer to the internal list of update consumers.
//!
//! Each time the state of the log changes, each update consumer is notified.
//!
//! A consumer can be registered a single time with a given @ref omni::log::ILog instance but can be registered with
//! multiple @ref omni::log::ILog instances.
//!
//! Each message may be sent to registered consumers in parallel.
//!
//! It is safe to access @ref omni::log::ILog from the callback.
//!
//! @thread_safety This method is thread safe.
virtual void OMNI_ATTR("consumer=onChannelUpdate_abi")
addChannelUpdateConsumer_abi(OMNI_ATTR("not_null") ILogChannelUpdateConsumer* consumer) noexcept = 0;
//! Removes the given consumer from the internal consumer list.
//!
//! This method silently accepts `nullptr`.
//!
//! This method silently accepts consumers that have not been registered with this object.
//!
//! Calling @ref omni::log::ILog::removeChannelUpdateConsumer() from @ref
//! omni::log::ILogMessageConsumer::onMessage() will lead to undefined behavior.
//!
//! @thread_safety This method is thread safe.
virtual void removeChannelUpdateConsumer_abi(ILogChannelUpdateConsumer* consumer) noexcept = 0;
//! Returns the list of update consumers.
//!
//! This method operates in two modes: **query mode** or **get mode**.
//!
//! @p consumersCount must not be `nullptr` in both modes.
//!
//! **Query mode** is enabled when consumers is `nullptr`. When in this mode, @p *consumersCount will be populated
//! with the number of consumers in the log and @ref omni::core::kResultSuccess is returned.
//!
//! **Get mode** is enabled when consumers is not `nullptr`. Upon entering the function, @p *consumersCount stores
//! the number of entries in consumers. If @p *consumersCount is less than the number of consumers in the log, @p
//! *consumersCount is updated with the number of consumers in the log and @ref
//! omni::core::kResultInsufficientBuffer is returned. If @p *consumersCount is greater or equal to the number of
//! channels, @p *consumersCount is updated with the number of consumers in the log, consumers array is populated,
//! and @ref omni::core::kResultSuccess is returned.
//!
//! If the @p consumers array is populated, each written entry in the array will have had @ref
//! omni::core::IObject::acquire() called on it.
//!
//! Upon entering the function, the pointers in the @p consumers array must be `nullptr`.
//!
//! Return values are as above. Additional error codes may be returned (e.g. @ref
//! omni::core::kResultInvalidArgument if @p consumersCount is `nullptr`).
//!
//! @thread_safety This method is thread safe.
virtual OMNI_ATTR("no_api, no_py") omni::core::Result getChannelUpdateConsumers_abi( // disable omni.bind until
// OM-21202
OMNI_ATTR("out, count=*consumersCount, *not_null") ILogChannelUpdateConsumer** consumers,
OMNI_ATTR("in, out, not_null") uint32_t* consumersCount) noexcept = 0;
};
} // namespace log
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "ILog.gen.h"
#ifdef OMNI_COMPILE_AS_DYNAMIC_LIBRARY
OMNI_API omni::log::ILog* omniGetLogWithoutAcquire();
#else
//! Returns the global log. omni::core::IObject::acquire() is **not** called on the returned pointer.
//!
//! The global omni::log::ILog instance can be configured by passing an omni::log::ILog to omniCoreStart().
//! If an instance is not provided, omniCreateLog() is called.
inline omni::log::ILog* omniGetLogWithoutAcquire()
{
return static_cast<omni::log::ILog*>(omniGetBuiltInWithoutAcquire(OmniBuiltIn::eILog));
}
#endif
//! Instantiates a default implementation of @ref omni::log::ILog. @ref omni::core::IObject::acquire() is called on the
//! returned pointer.
OMNI_API omni::log::ILog* omniCreateLog();
// omniGetModuleFilename is also forward declared in omni/core/Omni.h. Exhale doesn't like that.
#ifndef DOXYGEN_SHOULD_SKIP_THIS
//! Returns the module's name (e.g. "c:/foo/omni-glfw.dll"). The pointer returned is valid for the lifetime of the
//! module.
//!
//! The returned path will be delimited by '/' on all platforms.
OMNI_API const char* omniGetModuleFilename();
#endif
//! @copydoc omni::log::ILogMessageConsumer_abi
class omni::log::ILogMessageConsumer : public omni::core::Generated<omni::log::ILogMessageConsumer_abi>
{
};
//! @copydoc omni::log::ILogChannelUpdateConsumer_abi
class omni::log::ILogChannelUpdateConsumer : public omni::core::Generated<omni::log::ILogChannelUpdateConsumer_abi>
{
};
//! @copydoc omni::log::ILog_abi
class omni::log::ILog : public omni::core::Generated<omni::log::ILog_abi>
{
public:
//! Returns a snapshot of the array of message consumers attached to the log.
//!
//! @thread_safety This method is thread safe.
std::vector<omni::core::ObjectPtr<omni::log::ILogMessageConsumer>> getMessageConsumers() noexcept;
//! Returns a snapshot of the array of channels attached to the log.
//!
//! @thread_safety This method is thread safe.
std::vector<omni::core::ObjectPtr<omni::str::IReadOnlyCString>> getChannelNames() noexcept;
//! Returns a snapshot of the array of update consumers attached to the log.
//!
//! @thread_safety This method is thread safe.
std::vector<omni::core::ObjectPtr<omni::log::ILogChannelUpdateConsumer>> getChannelUpdateConsumers() noexcept;
//! @copydoc omni::log::ILog_abi::setChannelEnabled_abi
void setChannelEnabled(const omni::log::LogChannelData& channel,
bool isEnabled,
omni::log::SettingBehavior behavior) noexcept
{
setChannelEnabled(channel.name, isEnabled, behavior);
}
//! @copydoc omni::log::ILog_abi::getChannelEnabled_abi
omni::core::Result getChannelEnabled(const omni::log::LogChannelData& channel,
bool* outEnabled,
omni::log::SettingBehavior* outBehavior) noexcept
{
return getChannelEnabled(channel.name, outEnabled, outBehavior);
}
// We must expose setChannelEnabled(const char*, ...) since setChannelEnabled(LogChannelData, ...) hides it.
using omni::core::Generated<omni::log::ILog_abi>::setChannelEnabled;
using omni::core::Generated<omni::log::ILog_abi>::getChannelEnabled;
//! @copydoc omni::log::ILog_abi::setChannelLevel_abi
void setChannelLevel(const omni::log::LogChannelData& channel,
omni::log::Level level,
omni::log::SettingBehavior behavior) noexcept
{
setChannelLevel(channel.name, level, behavior);
}
//! @copydoc omni::log::ILog_abi::getChannelLevel_abi
omni::core::Result getChannelLevel(const omni::log::LogChannelData& channel,
omni::log::Level* outLevel,
omni::log::SettingBehavior* outBehavior) noexcept
{
return getChannelLevel(channel.name, outLevel, outBehavior);
}
// We must expose setChannelLevel(const char*, ...) since setChannelEnabled(LogChannelData, ...) hides it.
using omni::core::Generated<omni::log::ILog_abi>::setChannelLevel;
using omni::core::Generated<omni::log::ILog_abi>::getChannelLevel;
//! @copydoc omni::log::ILog_abi::isLoggingAtLevel_abi
bool isLoggingAtLevel(const omni::log::LogChannelData& channel, omni::log::Level level)
{
return isLoggingAtLevel(channel.name, level);
}
// We must expose isLoggingAtLevel(const char*, ...) since isLoggingAtLevel(LogChannelData, ...) hides it.
using omni::core::Generated<omni::log::ILog_abi>::isLoggingAtLevel;
};
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "ILog.gen.h"
namespace omni
{
namespace log
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace detail
{
# if CARB_COMPILER_GNUC || CARB_TOOLCHAIN_CLANG
// clang sees compileTimeValidateFormat<>() as an unimplemented function (which it intentionally
// is) on mac and generates a warning. We'll just silence that warning.
CARB_IGNOREWARNING_CLANG_WITH_PUSH("-Wundefined-internal")
// Utilizes an __attribute__ to validates the given fmt at compile time. Does not produce any code. Works for GCC but
// not MSVC.
void compileTimeValidateFormat(const LogChannelData& channel, const char* fmt, ...) CARB_PRINTF_FUNCTION(2, 3);
// Utilizes an __attribute__ to validates the given fmt at compile time. Does not produce any code. Works for GCC but
// not MSVC.
void compileTimeValidateFormat(const char* fmt, ...) CARB_PRINTF_FUNCTION(1, 2);
# define OMNI_LOG_VALIDATE_FORMAT(...) \
if (false) \
{ \
omni::log::detail::compileTimeValidateFormat(__VA_ARGS__); \
}
CARB_IGNOREWARNING_CLANG_POP
# else
# define OMNI_LOG_VALIDATE_FORMAT(...)
# endif
// Implementation detail. Checks the message's level against the channel's level and logs as appropriate.
template <class... ArgList>
void writeLog(const LogChannelData& /*ignore*/,
const LogChannelData& channel,
ILog* log,
Level level,
const char* filename,
const char* function,
int32_t line,
const char* fmt,
ArgList&&... args)
{
log->logf(
channel.name, level, omniGetModuleFilename(), filename, function, line, fmt, std::forward<ArgList>(args)...);
}
// Implementation detail. Initiates logging to the default channel.
template <class... ArgList>
void writeLog(const LogChannelData& channel,
const char* fmt,
ILog* log,
Level level,
const char* filename,
const char* function,
int32_t line,
ArgList&&... args)
{
log->logf(
channel.name, level, omniGetModuleFilename(), filename, function, line, fmt, std::forward<ArgList>(args)...);
}
// Implementation detail. Checks the message's level against the channel's level.
inline bool isChannelEnabled(Level level, const LogChannelData& /*ignore*/, const LogChannelData& channel)
{
return (static_cast<Level>(channel.level) <= level);
}
// Implementation detail. Checks the message's level against the default channel
inline bool isChannelEnabled(Level level, const LogChannelData& channel, const char* /*fmt*/)
{
return (static_cast<Level>(channel.level) <= level);
}
} // namespace detail
#endif
//! Registers known channels with the log returned by @ref omniGetLogWithoutAcquire().
//!
//! The @ref OMNI_LOG_ADD_CHANNEL macro adds the specified channel to a module specific list of channels. This happens
//! pre-`main()` (i.e. during static initialization).
//!
//! Call this function, to iterate over the said list of channels and add them to the log. This function should be
//! called per-module/application.
//!
//! Upon unloading a plugin, see @ref omni::log::removeModulesChannels to unregister channels registered with this
//! function.
//!
//! Carbonite plugin authors should consider using @ref CARB_PLUGIN_IMPL, which will call @ref
//! omni::log::addModulesChannels() and @ref omni::log::removeModulesChannels() for you.
//!
//! Omniverse Native Interface plugin authors do not need to call this function, logging channels are registered and
//! unregistered via @ref OMNI_MODULE_SET_EXPORTS.
//!
//! Python bindings authors should consider using @ref OMNI_PYTHON_GLOBALS, which will call @ref
//! omni::log::addModulesChannels() and @ref omni::log::removeModulesChannels() for you.
//!
//! Application author should consider using @ref OMNI_CORE_INIT() which will call @ref omni::log::addModulesChannels()
//! and @ref omni::log::removeModulesChannels() for you.
inline void addModulesChannels()
{
auto log = omniGetLogWithoutAcquire();
if (log)
{
for (auto channel = getModuleLogChannels(); channel; channel = channel->next)
{
log->addChannel(channel->name, reinterpret_cast<Level*>(&channel->level), channel->description);
}
}
}
//! Removes channels added by @ref omni::log::addModulesChannels().
//!
//! @see See @ref omni::log::addModulesChannels() to understand who should call this function.
inline void removeModulesChannels()
{
auto log = omniGetLogWithoutAcquire();
if (log)
{
for (auto channel = getModuleLogChannels(); channel; channel = channel->next)
{
log->removeChannel(channel->name, reinterpret_cast<Level*>(&channel->level));
}
}
}
} // namespace log
} // namespace omni
#ifndef DOXYGEN_SHOULD_SKIP_THIS
inline std::vector<omni::core::ObjectPtr<omni::log::ILogMessageConsumer>> omni::log::ILog::getMessageConsumers() noexcept
{
std::vector<omni::core::ObjectPtr<omni::log::ILogMessageConsumer>> out;
auto result = omni::extras::getOutArray<omni::log::ILogMessageConsumer*>(
[this](omni::log::ILogMessageConsumer** consumers, uint32_t* consumersCount) // get func
{
std::memset(consumers, 0, sizeof(omni::log::ILogMessageConsumer*) * *consumersCount); // incoming ptrs
// must be nullptr
return this->getMessageConsumers_abi(consumers, consumersCount);
},
[&out](omni::log::ILogMessageConsumer** names, uint32_t namesCount) // fill func
{
out.reserve(namesCount);
for (uint32_t i = 0; i < namesCount; ++i)
{
out.emplace_back(names[i], omni::core::kSteal);
}
});
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to retrieve log channel settings consumers: 0x%08X", result);
}
return out;
}
inline std::vector<omni::core::ObjectPtr<omni::str::IReadOnlyCString>> omni::log::ILog::getChannelNames() noexcept
{
std::vector<omni::core::ObjectPtr<omni::str::IReadOnlyCString>> out;
auto result = omni::extras::getOutArray<omni::str::IReadOnlyCString*>(
[this](omni::str::IReadOnlyCString** names, uint32_t* namesCount) // get func
{
std::memset(names, 0, sizeof(omni::str::IReadOnlyCString*) * *namesCount); // incoming ptrs must be nullptr
return this->getChannelNames_abi(names, namesCount);
},
[&out](omni::str::IReadOnlyCString** names, uint32_t namesCount) // fill func
{
out.reserve(namesCount);
for (uint32_t i = 0; i < namesCount; ++i)
{
out.emplace_back(names[i], omni::core::kSteal);
}
});
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to retrieve log channel names: 0x%08X", result);
}
return out;
}
inline std::vector<omni::core::ObjectPtr<omni::log::ILogChannelUpdateConsumer>> omni::log::ILog::getChannelUpdateConsumers() noexcept
{
std::vector<omni::core::ObjectPtr<omni::log::ILogChannelUpdateConsumer>> out;
auto result = omni::extras::getOutArray<omni::log::ILogChannelUpdateConsumer*>(
[this](omni::log::ILogChannelUpdateConsumer** consumers, uint32_t* consumersCount) // get func
{
std::memset(consumers, 0, sizeof(omni::log::ILogChannelUpdateConsumer*) * *consumersCount); // incoming
// ptrs must
// be nullptr
return this->getChannelUpdateConsumers_abi(consumers, consumersCount);
},
[&out](omni::log::ILogChannelUpdateConsumer** names, uint32_t namesCount) // fill func
{
out.reserve(namesCount);
for (uint32_t i = 0; i < namesCount; ++i)
{
out.emplace_back(names[i], omni::core::kSteal);
}
});
if (OMNI_FAILED(result))
{
OMNI_LOG_ERROR("unable to retrieve log channel updated consumers: 0x%08X", result);
}
return out;
}
#endif
| 51,029 | C | 44.644007 | 133 | 0.629877 |
omniverse-code/kit/include/omni/log/ILogChannelFilter.h | // Copyright (c) 2020-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.
//
//! @file
//! @brief Provides a base class for a filter for log channel patterns.
#pragma once
#include "../core/IObject.h"
#include "../str/IReadOnlyCString.h"
#include "ILog.h"
#include "../extras/OutArrayUtils.h"
namespace omni
{
//! Namespace for logging functionality.
namespace log
{
class ILogChannelFilter_abi;
class ILogChannelFilter;
//! Read-only object to encapsulate a channel filter's pattern and effects.
//!
//! A channel filter is a pattern matcher. If a channel's name matches the pattern, the filter can set both the
//! channel's enabled flag and/or level.
class ILogChannelFilter_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.log.ILogChannelFilter")>
{
protected:
//! Returns the channels pattern. The returned memory is valid for the lifetime of this object.
//!
//! This method is thread safe.
virtual OMNI_ATTR("c_str, not_null") const char* getFilter_abi() noexcept = 0;
//! Returns the desired enabled state for this filter.
//!
//! All parameters must not be nullptr.
//!
//! If *isUsed is false after calling this method, *isEnabled and *behavior should not be used.
//!
//! This method is thread safe.
virtual void getEnabled_abi(OMNI_ATTR("out, not_null") bool* isEnabled,
OMNI_ATTR("out, not_null") SettingBehavior* behavior,
OMNI_ATTR("out, not_null") bool* isUsed) noexcept = 0;
//! Returns the desired level for this filter.
//!
//! All parameters must not be nullptr.
//!
//! If *isUsed is false after calling this method, *level and *behavior should not be used.
//!
//! This method is thread safe.
virtual void getLevel_abi(OMNI_ATTR("out, not_null") Level* level,
OMNI_ATTR("out, not_null") SettingBehavior* behavior,
OMNI_ATTR("out, not_null") bool* isUsed) noexcept = 0;
//! Given a channel name, returns if the channel name matches the filter's pattern.
//!
//! The matching algorithm used is implementation specific (e.g. regex, glob, etc).
//!
//! This method is thread safe.
virtual bool isMatch_abi(OMNI_ATTR("c_str, not_null") const char* channel) noexcept = 0;
};
} // namespace log
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "ILogChannelFilter.gen.h"
//! \copydoc omni::log::ILogChannelFilter_abi
class omni::log::ILogChannelFilter : public omni::core::Generated<omni::log::ILogChannelFilter_abi>
{
};
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "ILogChannelFilter.gen.h"
| 3,060 | C | 36.790123 | 122 | 0.683987 |
omniverse-code/kit/include/omni/telemetry/ITelemetry.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
/** Interface to handle performing telemetry related tasks.
*
* This provides an abstraction over the lower level telemetry and structured logging systems
* and allows control over some common features of it.
*/
template <>
class omni::core::Generated<omni::telemetry::ITelemetry_abi> : public omni::telemetry::ITelemetry_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::telemetry::ITelemetry")
/** Sends a generic structured log event with caller specified data.
*
* @param[in] eventType A string describing the event that occurred. There is no
* restriction on the content or formatting of this value.
* This should neither be `nullptr` nor an empty string.
* @param[in] duration A generic duration value that can be optionally included
* with the event. It is the caller's respsonsibility to
* decide on the usage and semantics of this value depending
* on the @p eventType value. This may be 0.0 if no duration
* value is needed for the event.
* @param[in] data1 A string data value to be sent with the event. The contents
* and interpretation of this string depend on the @p eventTyoe
* value.
* @param[in] data2 A string data value to be sent with the event. The contents
* and interpretation of this string depend on the @p eventTyoe
* value.
* @param[in] value1 A floating point value to be sent with the event. This value
* will be interpreted according to the @p eventType value.
* @param[in] value2 A floating point value to be sent with the event. This value
* will be interpreted according to the @p eventType value.
*
* @returns No return value.
*
* @remarks This sends a generic event to the structured logging log file. The contents,
* semantics, and interpretation of this event are left entirely up to the caller.
* This will be a no-op if telemetry is disabled (ie: the telemetry module either
* intentionally was not loaded or failed to load).
*/
void sendGenericEvent(const char* eventType,
double duration,
const char* data1,
const char* data2,
double value1,
double value2) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void omni::core::Generated<omni::telemetry::ITelemetry_abi>::sendGenericEvent(
const char* eventType, double duration, const char* data1, const char* data2, double value1, double value2) noexcept
{
sendGenericEvent_abi(eventType, duration, data1, data2, value1, value2);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 3,890 | C | 43.215909 | 120 | 0.630848 |
omniverse-code/kit/include/omni/telemetry/ITelemetry.h | // 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.
//
/// @file
/// @brief Provides a helper interface to allow access to some common telemetry operations.
#pragma once
#include <omni/core/Omni.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/IObject.h>
namespace omni
{
/** Namespace for telemetry related interfaces and functionality. */
namespace telemetry
{
/** Forward declaration of the ITelemetry interface implementation class. */
class ITelemetry;
/** Interface to handle performing telemetry related tasks.
*
* This provides an abstraction over the lower level telemetry and structured logging systems
* and allows control over some common features of it.
*/
class ITelemetry_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.kit.telemetry.ITelemetry")>
{
protected:
/** Sends a generic structured log event with caller specified data.
*
* @param[in] eventType A string describing the event that occurred. There is no
* restriction on the content or formatting of this value.
* This should neither be `nullptr` nor an empty string.
* @param[in] duration A generic duration value that can be optionally included
* with the event. It is the caller's respsonsibility to
* decide on the usage and semantics of this value depending
* on the @p eventType value. This may be 0.0 if no duration
* value is needed for the event.
* @param[in] data1 A string data value to be sent with the event. The contents
* and interpretation of this string depend on the @p eventTyoe
* value.
* @param[in] data2 A string data value to be sent with the event. The contents
* and interpretation of this string depend on the @p eventTyoe
* value.
* @param[in] value1 A floating point value to be sent with the event. This value
* will be interpreted according to the @p eventType value.
* @param[in] value2 A floating point value to be sent with the event. This value
* will be interpreted according to the @p eventType value.
*
* @returns No return value.
*
* @remarks This sends a generic event to the structured logging log file. The contents,
* semantics, and interpretation of this event are left entirely up to the caller.
* This will be a no-op if telemetry is disabled (ie: the telemetry module either
* intentionally was not loaded or failed to load).
*/
virtual void sendGenericEvent_abi(OMNI_ATTR("c_str, in") const char* eventType, double duration, OMNI_ATTR("c_str, in") const char* data1, OMNI_ATTR("c_str, in") const char* data2, double value1, double value2) noexcept = 0;
};
} // namespace telemetry
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "ITelemetry.gen.h"
/** @copydoc omni::telemetry::ITelemetry_abi */
class omni::telemetry::ITelemetry
: public omni::core::Generated<omni::telemetry::ITelemetry_abi>
{
public:
static void sendCustomEvent(const char* eventType, double duration = 0.0, const char* data1 = nullptr, const char* data2 = nullptr, double value1 = 0.0, double value2 = 0.0)
{
omni::core::ObjectPtr<omni::telemetry::ITelemetry> ptr = omni::core::createType<omni::telemetry::ITelemetry>();
if (ptr.get() == nullptr)
return;
ptr->sendGenericEvent(eventType, duration, data1, data2, value1, value2);
}
};
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "ITelemetry.gen.h"
| 4,219 | C | 45.888888 | 228 | 0.655369 |
omniverse-code/kit/include/omni/telemetry/ITelemetry2.h | // 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.
//
/// @file
/// @brief Provides a helper interface to allow access to some common telemetry operations.
#pragma once
#include "ITelemetry.h"
namespace omni
{
/** Namespace for telemetry related interfaces and functionality. */
namespace telemetry
{
/** Forward declaration of the ITelemetry2 interface implementation class. */
class ITelemetry2;
/** Names for the current Run environment used for telemetry.
*
* Identifiers used to outline what kind of environment this process is currently running
* in. This may be individual (OVI), cloud (OVC), or enterprise (OVE).
*/
enum class OMNI_ATTR("prefix=e") RunEnvironment
{
/** The run environment has not been determined yet.
*
* This indicates that the required startup events have not occurred yet or the run
* environment could not be determined yet. An attempt to retrieve the run environment
* should be made again at a later time.
*/
eUndetermined,
/** Omniverse individual (OVI) desktop session.
*
* This is typically installed and run through the Omniverse desktop launcher app.
* Telemetry is enabled through this environment using the public Kratos authenticated
* endpoint.
*/
eIndividual,
/** Omniverse Cloud (OVC) session.
*
* This type of session is launched through the OVC services portal and the visual output
* streamed over the network. Telemetry is enabled through this environment using a Kratos
* authenticated endpoint specific to cloud deployments.
*/
eCloud,
/** Omniverse Enterprise (OVE) session.
*
* This type of session is typically installed and run through the Omniverse enterprise
* launcher app. Telemetry is enabled through this environment using the Kratos open
* endpoint for enterprise.
*/
eEnterprise,
};
/** Retrieves the name of a run environment enum value.
*
* @param[in] env The run environment value to retrieve the name for.
* @returns The name of the requested enum if valid. If an invalid enum value is passed in,
* a placeholder string will be returned instead.
*/
inline const char* getRunEnvironmentName(RunEnvironment env)
{
#define GETNAME(name, prefix) case name: return &(#name)[sizeof(#prefix) - 1]
switch (env)
{
GETNAME(RunEnvironment::eUndetermined, RunEnvironment::e);
GETNAME(RunEnvironment::eIndividual, RunEnvironment::e);
GETNAME(RunEnvironment::eCloud, RunEnvironment::e);
GETNAME(RunEnvironment::eEnterprise, RunEnvironment::e);
default:
return "<unknown_run_environment>";
}
#undef GETNAME
}
/** Interface to handle performing telemetry related tasks.
*
* This provides an abstraction over the lower level telemetry and structured logging systems
* and allows control over some common features of it.
*/
class ITelemetry2_abi : public omni::core::Inherits<omni::telemetry::ITelemetry, OMNI_TYPE_ID("omni.kit.telemetry.ITelemetry2")>
{
protected:
/** Tests whether this session is running as a cloud session.
*
* @returns `true` if this current session is detected as running on a cloud architecture.
* Returns `false` if this current session is running outside of a cloud system.
*
* @remarks A cloud session is one that runs on a cloud service provider's system and streams
* to a user's machine. The session runs on behalf of the given user using that
* user's privacy information. When running on a cloud system, the user does not
* have direct access to the hardware. Telemetry handling also differs since the
* telemetry transmitter process will not send data anywhere, but simply write to
* a log file that can be scraped when the session ends (or in parts during the
* session).
*/
virtual bool isCloudSession_abi() noexcept = 0;
/** Retrieves the cloud session ID if running as a cloud session.
*
* @returns A string representing the cloud session ID if running as a cloud session.
* Returns `nullptr` otherwise. This will always return `nullptr` if the current
* run environment is anything other than @ref RunEnvironment::eCloud.
*
* @remarks The cloud session ID will be a UUID style string that can be used to uniquely
* identify one session from another. When not running as a cloud session, no
* string will be returned. The caller must be able to properly and gracefully
* handle this potential failure case.
*/
virtual const char* getCloudSessionId_abi() noexcept = 0;
/** Retrieves the current run environment.
*
* @returns The current run environment if it has been detected yet. If the run environment
* could not be determined yet, @ref RunEnvironment::eUndetermined will be returned
* instead. Once a value other than @ref RunEnvironment::eUndetermined is returned,
* the run environment will not change for the remainder of the session and can be
* safely cached for quicker lookups later.
*/
virtual RunEnvironment getRunEnvironment_abi() noexcept = 0;
/** Retrieves the customer ID for enterprise sessions.
*
* @returns The loaded customer ID value if found. This will be the same value that is
* listed as 'org-name' for a given customer on the NVIDIA Licensing Portal web
* page. Returns `nullptr` if the customer ID value was either not found or this
* is not an enterprise session.
*/
virtual const char* getCustomerId_abi() noexcept = 0;
};
} // namespace telemetry
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "ITelemetry2.gen.h"
/** @copydoc omni::telemetry::ITelemetry2_abi */
class omni::telemetry::ITelemetry2
: public omni::core::Generated<omni::telemetry::ITelemetry2_abi>
{
};
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "ITelemetry2.gen.h"
| 6,536 | C | 40.903846 | 128 | 0.694002 |
omniverse-code/kit/include/omni/telemetry/ITelemetry2.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
/** Interface to handle performing telemetry related tasks.
*
* This provides an abstraction over the lower level telemetry and structured logging systems
* and allows control over some common features of it.
*/
template <>
class omni::core::Generated<omni::telemetry::ITelemetry2_abi> : public omni::telemetry::ITelemetry2_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::telemetry::ITelemetry2")
/** Tests whether this session is running as a cloud session.
*
* @returns `true` if this current session is detected as running on a cloud architecture.
* Returns `false` if this current session is running outside of a cloud system.
*
* @remarks A cloud session is one that runs on a cloud service provider's system and streams
* to a user's machine. The session runs on behalf of the given user using that
* user's privacy information. When running on a cloud system, the user does not
* have direct access to the hardware. Telemetry handling also differs since the
* telemetry transmitter process will not send data anywhere, but simply write to
* a log file that can be scraped when the session ends (or in parts during the
* session).
*/
bool isCloudSession() noexcept;
/** Retrieves the cloud session ID if running as a cloud session.
*
* @returns A string representing the cloud session ID if running as a cloud session.
* Returns `nullptr` otherwise. This will always return `nullptr` if the current
* run environment is anything other than @ref RunEnvironment::eCloud.
*
* @remarks The cloud session ID will be a UUID style string that can be used to uniquely
* identify one session from another. When not running as a cloud session, no
* string will be returned. The caller must be able to properly and gracefully
* handle this potential failure case.
*/
const char* getCloudSessionId() noexcept;
/** Retrieves the current run environment.
*
* @returns The current run environment if it has been detected yet. If the run environment
* could not be determined yet, @ref RunEnvironment::eUndetermined will be returned
* instead. Once a value other than @ref RunEnvironment::eUndetermined is returned,
* the run environment will not change for the remainder of the session and can be
* safely cached for quicker lookups later.
*/
omni::telemetry::RunEnvironment getRunEnvironment() noexcept;
/** Retrieves the customer ID for enterprise sessions.
*
* @returns The loaded customer ID value if found. This will be the same value that is
* listed as 'org-name' for a given customer on the NVIDIA Licensing Portal web
* page. Returns `nullptr` if the customer ID value was either not found or this
* is not an enterprise session.
*/
const char* getCustomerId() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline bool omni::core::Generated<omni::telemetry::ITelemetry2_abi>::isCloudSession() noexcept
{
return isCloudSession_abi();
}
inline const char* omni::core::Generated<omni::telemetry::ITelemetry2_abi>::getCloudSessionId() noexcept
{
return getCloudSessionId_abi();
}
inline omni::telemetry::RunEnvironment omni::core::Generated<omni::telemetry::ITelemetry2_abi>::getRunEnvironment() noexcept
{
return getRunEnvironment_abi();
}
inline const char* omni::core::Generated<omni::telemetry::ITelemetry2_abi>::getCustomerId() noexcept
{
return getCustomerId_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,608 | C | 39.429824 | 124 | 0.694661 |
omniverse-code/kit/include/omni/videoencoding/IVideoEncoding.h | // 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.
//
#pragma once
#include <carb/Interface.h>
#include <memory>
namespace omni
{
struct IVideoEncoding
{
CARB_PLUGIN_INTERFACE("omni::IVideoEncoding", 0, 1)
/**
* Prepare the encoding plugin to process frames.
* @param videoFilename name of the MP4 file where the encoded video will be written
* @param framerate number of frames per second
* @param nframes total number of frames; if unknown, set to 0
* @param overwriteVideo if set, overwrite existing MP4 file; otherwise, refuse to do anything if the file specified
* in videoFilename exists.
*/
bool(CARB_ABI* startEncoding)(const char* videoFilename, double framerate, uint32_t nframes, bool overwriteVideo);
/**
* Encode a frame and write the result to disk.
* @param bufferRGBA8 raw frame image data; format: R8G8B8A8; size: width * height * 4
* @param width frame width
* @param height frame height
*/
void(CARB_ABI* encodeNextFrameFromBuffer)(const uint8_t* bufferRGBA8, uint32_t width, uint32_t height);
/**
* Read a frame from an image file, encode, and write to disk. Warning: pixel formats other than RGBA8 will probably
* not work (yet).
* @param FrameFilename name of the file to read. Supported file formats: see carb::imaging
*/
void(CARB_ABI* encodeNextFrameFromFile)(const char* FrameFilename);
/**
* Indicate that all frames have been encoded. This will ensure that writing to the output video file is done, and
* close it.
*/
void(CARB_ABI* finalizeEncoding)();
};
}
| 2,008 | C | 35.527272 | 120 | 0.713147 |
omniverse-code/kit/include/omni/geometry/Geometry.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
#include <carb/Types.h>
#include <list>
#include <string>
namespace omni
{
namespace geometry
{
struct Geometry
{
CARB_PLUGIN_INTERFACE("omni::geometry::Geometry", 0, 1)
/*
ABI Definitions
*/
bool(CARB_ABI* triangulate)(long int stageId, const char* inputPath, const char* outputPath);
/**
* @param stageId Identfier for stage to work in
* @param layerPath The path of the layer in which to create the collision representation. If NULL or zero-length,
* the root layer is used
* @param inputPath The path of the original graphics mesh
* @param outputRoot The path of the new collision grouping
* @param proxyName If not NULL or zero-length, the root name of the collision meshes
* @param maxConvexHulls How many convex hulls can be used in the decomposition. If set to 1, the convex hull of
* the mesh vertices is used
* @param maxNumVerticesPerCH Maximum number of vertices per convex hull
* @param usePlaneShifting Whether or not to use plane shifting when building the hull
* @param resolution Voxel resolution for VHACD when convex decomposition is performed (maxConvexHulls > 1)
* @param visible Whether or not to make the collision hulls visible
* @return number of convex hulls, return 0 in case of failure
*/
int(CARB_ABI* createConvexHull)(long int stageId,
const char* layerPath,
const char* inputPath,
const char* outputRoot,
const char* proxyName,
const int maxConvexHulls,
const int maxNumVerticesPerCH,
const bool usePlaneShifting,
const int resolution,
const bool visible);
bool(CARB_ABI* createConvexHullFromSkeletalMesh)(long int stageId,
const char* inputMeshPath,
const char* proxyName,
const int maxConvexHulls,
const int maxNumVerticesPerCH,
const int resolution,
const bool makeConvexHullsVisible);
// It applies for all proxy prims, such as triangle proxy prim as well as convex proxy prim
bool(CARB_ABI* removeConvexHull)(long int stageId, const char* outputPath);
// Return a UsdGeomCube at path outputPath
bool(CARB_ABI* computeAABB)(long int stageId, const char* inputPath, const char* outputPath);
// Return a UsdGeomSphere at path outputPath
bool(CARB_ABI* computeBoundingSphere)(long int stageId, const char* inputPath, const char* outputPath);
};
}
}
| 3,440 | C | 44.879999 | 119 | 0.609012 |
omniverse-code/kit/include/omni/kit/EditorUsd.h | // 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.
//
#pragma once
#include <carb/Defines.h>
namespace omni
{
namespace kit
{
/**
* Defines a Kit specific usd metadata set.
* The python counterpart is at source/extensions/omni.usd/bindings/python/omni.usd/impl/editor.py
*/
class EditorUsd
{
public:
/**
* Sets if to hide the prim in Stage Window.
*
* @param prim The prim to set metadata value to.
* @param hide true to hide prim in Stage Window, false to show in Stage Window.
*/
static void setHideInStageWindow(const pxr::UsdPrim& prim, bool hide)
{
static const pxr::TfToken kHideInStageWindow("hide_in_stage_window");
setMetadata(prim, kHideInStageWindow, hide);
}
/**
* Gets whether the prim should be hidden in Stage Window.
*
* @param prim The prim to get metadata value from.
* @return true if prim is hidden, false otherwise.
*/
static bool isHideInStageWindow(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kHideInStageWindow("hide_in_stage_window");
return getMetadata(prim, kHideInStageWindow, false);
}
/**
* Sets if to disallow deletion of a prim.
*
* @param prim The prim to set metadata value to.
* @param noDelete true to disallow deletion, false to allow deletion.
*/
static void setNoDelete(const pxr::UsdPrim& prim, bool noDelete)
{
static const pxr::TfToken kNoDelete("no_delete");
setMetadata(prim, kNoDelete, noDelete);
}
/**
* Gets whether deletion on the prim is disallowed.
*
* @param prim The prim to get metadata value from.
* @return true if prim cannot be disabled, false otherwise.
*/
static bool isNoDelete(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kNoDelete("no_delete");
return getMetadata(prim, kNoDelete, false);
}
/**
* Sets if to override the picking preference of a prim.
*
* @param prim The prim to set metadata value to.
* @param pickModel true to always pick the enclosing model regardless of editor preferences, false to follow editor
* preferences.
*/
static void setAlwaysPickModel(const pxr::UsdPrim& prim, bool pickModel)
{
static const pxr::TfToken kAlwaysPickModel("always_pick_model");
setMetadata(prim, kAlwaysPickModel, pickModel);
}
/**
* Gets whether prim overrides the picking mode to always pick model.
*
* @param prim The prim to get metadata value from.
* @return true if pick on the prim always select its enclosing model, false otherwise.
*/
static bool isAlwaysPickModel(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kAlwaysPickModel("always_pick_model");
return getMetadata(prim, kAlwaysPickModel, false);
}
/**
* Sets if a prim should ignore material updates.
*
* @param prim The material prim to set metadata value to.
* @param ignore true if prim has set to ignore material updates.
*/
static void setIgnoreMaterialUpdates(const pxr::UsdPrim& prim, bool ignore)
{
static const pxr::TfToken kIgnoreMaterialUpdates("ignore_material_updates");
setMetadata(prim, kIgnoreMaterialUpdates, ignore);
}
/**
* Gets whether the prim should ignore material updates.
*
* @param prim The prim to get metadata value from.
* @return true if prim has set to ignore material updates
*/
static bool hasIgnoreMaterialUpdates(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kIgnoreMaterialUpdates("ignore_material_updates");
return getMetadata(prim, kIgnoreMaterialUpdates, false);
}
/**
* Sets if a prim should show a selection outline
*
* @param prim The material prim to set metadata value to.
* @param ignore true if prim has set to not show a selection outline
*/
static void setNoSelectionOutline(const pxr::UsdPrim& prim, bool ignore)
{
static const pxr::TfToken kNoSelectionOutline("no_selection_outline");
setMetadata(prim, kNoSelectionOutline, ignore);
}
/**
* Gets whether the prim should show a selection outline
*
* @param prim The prim to get metadata value from.
* @return true if prim has set to not show a selection outline
*/
static bool hasNoSelectionOutline(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kNoSelectionOutline("no_selection_outline");
return getMetadata(prim, kNoSelectionOutline, false);
}
private:
template <typename T>
static void setMetadata(const pxr::UsdPrim& prim, const pxr::TfToken& token, T value)
{
pxr::UsdEditContext context(prim.GetStage(), prim.GetStage()->GetSessionLayer());
bool ret = prim.SetMetadata(token, value);
CARB_ASSERT(ret);
}
template <typename T>
static T getMetadata(const pxr::UsdPrim& prim, const pxr::TfToken& token, T defaultVal)
{
T val = defaultVal;
prim.GetMetadata(token, &val);
return val;
}
};
}
}
| 5,517 | C | 32.646341 | 120 | 0.671198 |
omniverse-code/kit/include/omni/kit/IScriptEditor.h | // 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.
//
#pragma once
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
/**
* Defines the interface for ScriptEditor Window.
*/
struct IScriptEditor
{
CARB_PLUGIN_INTERFACE("omni::kit::IScriptEditor", 1, 0);
void(CARB_ABI* showHideWindow)(void* window, bool visible);
};
}
}
| 725 | C | 24.928571 | 77 | 0.755862 |
omniverse-code/kit/include/omni/kit/FilterGroup.h | // 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.
//
#pragma once
#include <carb/logging/Log.h>
#include <omni/kit/EventSubscribers.h>
#include <functional>
#include <map>
#include <regex>
namespace omni
{
namespace kit
{
/**
* Defines the filter group class
* @param ItemT Type of the item to be filtered.
* @param FilterT Type of the filter used to test item.
* @param Pred Predicate to test if an item is accepted by a filter.
*/
template <typename ItemT, typename FilterT, typename Pred>
class FilterGroup
{
public:
using SubscriptionId = uint64_t;
using OnFilterChangedFn = std::function<void()>;
/**
* Tests an item against all enabled filters.
*
* @param item The item to be tested.
* @return True if the item matches any enabled filter.
*/
bool match(const ItemT& item) const
{
if (m_enabledCount == 0 || m_groupEnabled == false)
{
return true;
}
bool accepted = false;
for (auto&& filter : m_filters)
{
if (!filter.second.enabled)
{
continue;
}
accepted |= m_pred(item, filter.second.filter);
if (accepted)
{
break;
}
}
return accepted;
}
/**
* Adds a filter to the FilterGroup.
*
* @param name The name of the filter.
* @param filter The filter to be added.
* @param enabled True to enable the filter on add.
* @return True if filter is added successfully.
*/
bool addFilter(const std::string& name, const FilterT& filter, bool enabled)
{
auto filterEntry = m_filters.find(name);
if (filterEntry == m_filters.end())
{
m_filters.emplace(name, FilterData{ filter, enabled });
m_enabledCount += enabled ? 1 : 0;
// Turn on filterGroup if not already enabled
m_groupEnabled |= enabled;
m_filterChangeSubscribers.send();
return true;
}
else
{
CARB_LOG_WARN("Failed to add filter %s. Already existed", name.c_str());
}
return false;
}
/**
* Gets names of all filters in the FilterGroup.
*
* @param filterNames The vector to store all filter names to.
*/
void getFilterNames(std::vector<std::string>& filterNames) const
{
filterNames.reserve(m_filters.size());
for (auto&& filter : m_filters)
{
filterNames.push_back(filter.first);
}
}
/**
* Checks if a filter is enabled by its name.
*
* @param name The name of the filter to be checked.
* @return True if the filter is enabled. False if filter is disabled or not exists.
*/
bool isFilterEnabled(const std::string& name) const
{
auto filterEntry = m_filters.find(name);
if (filterEntry != m_filters.end())
{
return filterEntry->second.enabled;
}
return false;
}
/**
* Enable or disable a filter by its name.
* If the filter is the first one to be enabled in the FilterGroup, the FilterGroup will be enabled.
* If the filter is the last one to be disabled in the FilterGroup, the FilterGroup will be disabled.
*
* @param name The name of the filter.
* @param enabled True to enable the filter. False to disable the filter.
*/
void setFilterEnabled(const std::string& name, bool enabled)
{
auto filterEntry = m_filters.find(name);
if (filterEntry != m_filters.end())
{
if (filterEntry->second.enabled != enabled)
{
m_enabledCount += enabled ? 1 : -1;
filterEntry->second.enabled = enabled;
if (m_groupEnabled && m_enabledCount == 0)
{
m_groupEnabled = false;
}
else if (!m_groupEnabled && enabled)
{
m_groupEnabled |= true;
}
m_filterChangeSubscribers.send();
}
}
}
/**
* Checks if the FilterGroup is enabled.
* If a FilterGroup is disabled, none of its enabled filter will filter any item.
*
* @return True if FilterGroup is enabled.
*/
bool isFilterGroupEnabled() const
{
return m_groupEnabled;
}
/**
* Enabled or disable the FilterGroup
*
* @param enabled True to enable the FilterGroup. False to disable the FilterGroup.
*/
void setFilterGroupEnabled(bool enabled)
{
if (m_groupEnabled != enabled)
{
m_groupEnabled = enabled;
m_filterChangeSubscribers.send();
}
}
/**
* Checks if any of the filter in the FilterGroup is enabled.
*
* @return True if at least one filter in the FilterGroup is enabled.
*/
bool isAnyFilterEnabled() const
{
return m_enabledCount > 0;
}
/**
* Remove all filters in the group.
*/
void clear()
{
m_filters.clear();
m_enabledCount = 0;
m_groupEnabled = false;
m_filterChangeSubscribers.send();
}
/**
* Subscribes to filter change event.
*
* @param onFilterEvent The function to be called when filter has changed.
* @return SubscriptionId to be used when unsubscribe from filter event.
*/
SubscriptionId subscribeForFilterEvent(const OnFilterChangedFn& onFilterEvent)
{
// Since we're using std::function, userData is not needed anymore.
return m_filterChangeSubscribers.subscribe([onFilterEvent](void*) { onFilterEvent(); }, nullptr);
}
/**
* Unsubscribe from filter change event.
*
* @param subId the SubscriptionId obtain when calling @ref subscribeForFilterEvent.
*/
void unsubscribeFromFilterEvent(SubscriptionId subId)
{
m_filterChangeSubscribers.unsubscribe(subId);
}
private:
using OnFilterChangedInternalFn = std::function<void(void*)>;
struct FilterData
{
FilterT filter;
bool enabled;
};
bool m_groupEnabled = false;
Pred m_pred;
std::map<std::string, FilterData> m_filters;
size_t m_enabledCount = 0;
carb::EventSubscribers<OnFilterChangedInternalFn, SubscriptionId> m_filterChangeSubscribers;
};
/**
* Defines a FilterGroup that tests string against regular expression.
*/
struct RegexPred
{
bool operator()(const std::string& str, const std::regex& regex) const
{
return std::regex_search(str, regex);
}
};
using RegexFilterGroup = FilterGroup<std::string, std::regex, RegexPred>;
}
}
| 7,123 | C | 27.047244 | 105 | 0.600309 |
omniverse-code/kit/include/omni/kit/ValueGuard.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Defines.h>
namespace omni
{
namespace kit
{
template <typename T, T inVal, T outVal>
class ValueGuard
{
public:
explicit ValueGuard(T& val) : m_val(val)
{
CARB_ASSERT(m_val == outVal);
m_val = inVal;
}
~ValueGuard()
{
m_val = outVal;
}
private:
T& m_val;
};
using BoolGuard = ValueGuard<bool, true, false>;
}
}
| 839 | C | 19 | 77 | 0.693683 |
omniverse-code/kit/include/omni/kit/IExtensionWindow.h | // 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.
//
#pragma once
#include "ExtensionWindowTypes.h"
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
/**
* Defines the minimal interface for an extension window.
*/
struct IExtensionWindow
{
CARB_PLUGIN_INTERFACE("omni::kit::IExtensionWindow", 1, 1);
/**
* Creates an instance of the extension window.
*
* @return created instance of extension window.
*/
ExtensionWindowHandle(CARB_ABI* createInstance)();
/**
* Destroys an instance of extension window.
*
* @param handle The window handle to be destroyed.
* @return true if window is destroyed, false if not.
*/
bool(CARB_ABI* destroyInstance)(const ExtensionWindowHandle handle);
/**
* Query if an instance of extension window is visible.
*
* @param handle The window handle to be destroyed.
*/
bool(CARB_ABI* isInstanceVisible)(const ExtensionWindowHandle handle);
/**
* Display or hide an instance of extension window.
*
* @param handle The window handle to be destroyed.
* @param visible true to show the window, false to hide the window.
*/
void(CARB_ABI* setInstanceVisible)(const ExtensionWindowHandle handle, bool visible);
/**
* Creates an instance of the viewport window with custom name and usdd stage.
*
* @param name The window name.
* @param usdContextName The usd context to show in the window.
* @param createMenu When true, the Window menu is created.
* @return created instance of extension window.
*/
ExtensionWindowHandle(CARB_ABI* createCustomizedInstance)(const char* name,
const char* usdContextName,
bool createMenu);
};
}
}
| 2,245 | C | 31.085714 | 89 | 0.664588 |
omniverse-code/kit/include/omni/kit/IStageUpdate.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#if (!defined(PXR_USD_SDF_PATH_H))
namespace pxr
{
class SdfPath;
};
#endif
#include "KitTypes.h"
#include <carb/Interface.h>
#include <carb/InterfaceUtils.h>
#include <memory>
namespace omni
{
namespace kit
{
struct StageUpdateNode;
struct StageUpdateSettings
{
bool playSimulations;
bool playComputegraph;
bool isPlaying;
};
struct StageUpdateNodeDesc
{
const char* displayName;
void* userData;
int order;
/**
Attach usd stage to physics.
This function gets called when Kit loads a new usd file or create a new scene.
To convert stageId to stage ref, use
pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId))
*/
void(CARB_ABI* onAttach)(long int stageId, double metersPerUnit, void* userData);
// detach the stage
void(CARB_ABI* onDetach)(void* userData);
// simulation was paused
void(CARB_ABI* onPause)(void* userData);
// simulation was stopped(reset)
void(CARB_ABI* onStop)(void* userData);
// simulation was resumed
void(CARB_ABI* onResume)(float currentTime, void* userData);
// this gets called in every update cycle of Kit (typically at each render frame)
void(CARB_ABI* onUpdate)(float currentTime, float elapsedSecs, const StageUpdateSettings* settings, void* userData);
/*
The following call backs are called when there is change in usd scene (e.g. user interaction, scripting, )
Each plugin should query the usd stage based on provided prim path name and sync changes related to their data
*/
// this gets called when a new Usd prim was added to the scene
void(CARB_ABI* onPrimAdd)(const pxr::SdfPath& primPath, void* userData);
// this gets called when some properties in the usd prim was changed (e.g. manipulator or script changes transform)
void(CARB_ABI* onPrimOrPropertyChange)(const pxr::SdfPath& primOrPropertyPath, void* userData);
// this gets called when the named usd prim was removed from the scene
void(CARB_ABI* onPrimRemove)(const pxr::SdfPath& primPath, void* userData);
/**
* Temporary raycast handler. This will become part of a more general user event handler.
*
* @param orig the ray origin. Set to NULL to send a stop command for grabbing.
* @param dir the ray direction (should be normalized).
* @param input whether the input control is set or reset (e.g. mouse down).
*/
void(CARB_ABI* onRaycast)(const float* orig, const float* dir, bool input, void* userData);
};
struct StageUpdateNodeDescV2 : public StageUpdateNodeDesc
{
// simulation was resumed
void(CARB_ABI* onResumeV2)(double currentTime, double absoluteSimTime, void* userData);
// this gets called in every update cycle of Kit (typically at each render frame)
void(CARB_ABI* onUpdateV2)(double currentTime,
float elapsedSecs,
double absoluteSimTime,
const StageUpdateSettings* settings,
void* userData);
};
struct StageUpdateNodeInfo
{
const char* name;
bool enabled;
int order;
};
typedef void (*OnStageUpdateNodesChangeFn)(void* userData);
struct StageUpdate
{
virtual StageUpdateNode* createStageUpdateNode(const StageUpdateNodeDesc& desc) = 0;
virtual void destroyStageUpdateNode(StageUpdateNode* node) = 0;
virtual size_t getStageUpdateNodeCount() const = 0;
virtual void getStageUpdateNodes(StageUpdateNodeInfo* nodes) const = 0;
virtual void setStageUpdateNodeOrder(size_t index, int order) = 0;
virtual void setStageUpdateNodeEnabled(size_t index, bool enabled) = 0;
virtual SubscriptionId subscribeToStageUpdateNodesChangeEvents(OnStageUpdateNodesChangeFn onChange,
void* userData) = 0;
virtual void unsubscribeToStageUpdateNodesChangeEvents(SubscriptionId subscriptionId) = 0;
virtual void attach(long int stageId) = 0;
virtual void detach() = 0;
virtual void setPlaying(float currentTime, bool isPlaying, bool isStop /*= false*/) = 0;
virtual void applyPendingEdit() = 0;
virtual void update(float currentTime, float elapsedSecs, StageUpdateSettings& settings) = 0;
virtual void handleAddedPrim(const pxr::SdfPath& primPath) = 0;
virtual void handleChangedPrimOrProperty(const pxr::SdfPath& primOrPropertyPath, bool& isTransformDirty) = 0;
virtual void handleRemovedPrim(const pxr::SdfPath& primPath) = 0;
virtual void handleRaycast(const float* orig, const float* dir, bool input) = 0;
virtual StageUpdateNode* createStageUpdateNodeV2(const StageUpdateNodeDescV2& desc) = 0;
virtual void setPlayingV2(double currentTime, double absoluteSimTime, bool isPlaying, bool isStop /*= false*/) = 0;
virtual void updateV2(double currentTime, float elapsedSecs, double absoluteSimTime, StageUpdateSettings& settings) = 0;
};
using StageUpdatePtr = std::shared_ptr<StageUpdate>;
/**
* Defines an interface for the editor stage update API part.
*/
struct IStageUpdate
{
CARB_PLUGIN_INTERFACE("omni::kit::IStageUpdate", 1, 0);
//------------------------
// Deprecated interface
//------------------------
StageUpdateNode*(CARB_ABI* createStageUpdateNode)(const StageUpdateNodeDesc& desc);
void(CARB_ABI* destroyStageUpdateNode)(StageUpdateNode* node);
size_t(CARB_ABI* getStageUpdateNodeCount)();
void(CARB_ABI* getStageUpdateNodes)(StageUpdateNodeInfo* nodes);
void(CARB_ABI* setStageUpdateNodeOrder)(size_t index, int order);
void(CARB_ABI* setStageUpdateNodeEnabled)(size_t index, bool enabled);
SubscriptionId(CARB_ABI* subscribeToStageUpdateNodesChangeEvents)(OnStageUpdateNodesChangeFn onChange,
void* userData);
void(CARB_ABI* unsubscribeToStageUpdateNodesChangeEvents)(SubscriptionId subscriptionId);
void(CARB_ABI* attach)(long int stageId);
void(CARB_ABI* detach)();
void(CARB_ABI* setPlaying)(float currentTime, bool isPlaying, bool isStop /*= false*/);
void(CARB_ABI* applyPendingEdit)();
void(CARB_ABI* update)(float currentTime, float elapsedSecs, StageUpdateSettings& settings);
void(CARB_ABI* handleAddedPrim)(const pxr::SdfPath& primPath);
void(CARB_ABI* handleChangedPrimOrProperty)(const pxr::SdfPath& primOrPropertyPath, bool& isTransformDirty);
void(CARB_ABI* handleRemovedPrim)(const pxr::SdfPath& primPath);
void(CARB_ABI* handleRaycast)(const float* orig, const float* dir, bool input);
StageUpdateNode*(CARB_ABI* createStageUpdateNodeV2)(const StageUpdateNodeDescV2& desc);
void(CARB_ABI* setPlayingV2)(double currentTime, double absoluteSimTime, bool isPlaying, bool isStop /*= false*/);
void(CARB_ABI* updateV2)(double currentTime, float elapsedSecs, double absoluteSimTime, StageUpdateSettings& settings);
//---------------
// New interface
//---------------
/**
* Gets the StageUpdate object with the given name. Creates a new one if it does not exist.
* Pass nullptr to retrieve the default StageUpdate, which is the StageUpdate object of the default UsdContext.
*
* @param name Name of the StageUpdate object.
*
* @return The StageUpdate
*/
StageUpdatePtr(CARB_ABI* getStageUpdateByName)(const char* name);
inline StageUpdatePtr getStageUpdate(const char* name)
{
return getStageUpdateByName(name);
}
inline StageUpdatePtr getStageUpdate()
{
return getStageUpdateByName(nullptr);
}
/**
* Destroys the StageUpdate with the given name if nothing references it. Does not release the default StageUpdate (name==null).
*
* @param name Name of the StageUpdate.
*
* @return True if a StageUpdate was deleted, false otherwise. The latter happens when the StageUpdate does not exist, it
* is in use, or it is the StageUpdate of the default UsdContext.
*/
bool(CARB_ABI* destroyStageUpdate)(const char* name);
};
/**
* Gets the StageUpdate object with the given name via cached IStageUpdate interface. Creates a new one if it does not exist.
* Pass nullptr to retrieve the default StageUpdate, which is the StageUpdate object of the default UsdContext.
*
* @param name Name of the StageUpdate object.
*
* @return The StageUpdate
*/
inline StageUpdatePtr getStageUpdate(const char* name = nullptr)
{
auto iface = carb::getCachedInterface<omni::kit::IStageUpdate>();
return iface == nullptr ? nullptr : iface->getStageUpdate(name);
}
}
}
| 9,131 | C | 33.722433 | 132 | 0.701566 |
omniverse-code/kit/include/omni/kit/KitTypes.h | // 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.
//
#pragma once
#include <carb/datasource/IDataSource.h>
namespace carb
{
namespace input
{
struct Keyboard;
struct Mouse;
}
namespace imgui
{
struct ImGui;
}
}
namespace omni
{
namespace kit
{
typedef uint64_t SubscriptionId;
constexpr size_t kBackBufferCount = 3; ///< Maximum number of frames to queue up.
struct Prompt;
struct Window;
struct ContentWindowWidget;
struct ContentWindowToolButton;
typedef void (*OnUpdateEventFn)(float elapsedTime, void* userData);
typedef void (*OnConnectionEventFn)(const carb::datasource::ConnectionEventType& eventType, void* userData);
typedef void (*OnWindowDrawFn)(const char* windowName, float elapsedTime, void* userData);
typedef void (*OnWindowStateChangeFn)(const char* name, bool open, void* userData);
typedef void (*OnExtensionsChangeFn)(void* userData);
typedef void (*OnShutdownEventFn)(void* userData);
typedef void (*OnLogEventFn)(
const char* source, int32_t level, const char* filename, int lineNumber, const char* message, void* userData);
typedef void (*OnUIDrawEventFn)(carb::imgui::ImGui*,
const double* viewMatrix,
const double* projMatrix,
const carb::Float4& viewPortRect,
void* userData);
struct ExtensionInfo
{
const char* id;
bool enabled;
const char* name;
const char* description;
const char* path;
};
struct ExtensionFolderInfo
{
const char* path;
bool builtin;
};
enum class GraphicsMode
{
eVulkan,
eDirect3D12
};
enum class RendererMode
{
eRtx, ///< NVIDIA RTX renderer, a fully ray traced renderer.
eNvf ///< NVIDIA NVF renderer. reserved for internal use.
};
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
}
}
| 2,308 | C | 24.097826 | 114 | 0.701906 |
omniverse-code/kit/include/omni/kit/IFileDialog.h | // 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.
//
#pragma once
#include "KitTypes.h"
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
struct FileDialog;
typedef void (*OnFileDialogFileSelected)(const char* realpath, void* userData);
typedef void (*OnFileDialogCancelled)(void* userData);
enum class FileDialogOpenMode
{
eOpen,
eSave
};
enum class FileDialogSelectType
{
eFile,
eDirectory,
eAll
};
enum class FileDialogDataSource
{
eLocal, ///! Show local files only
eOmniverse, ///! Show omniverse files only
eAll ///! Show files form all data sources
};
/**
* Defines an interface for the editor stage update API part.
*/
struct IFileDialog
{
CARB_PLUGIN_INTERFACE("omni::kit::IFileDialog", 0, 6);
/**
* Create file dialog that uses for file/folder picker
* @param title Window title.
* @param mode Create dialog for save or open.
* @param type Create dialog to select file or folder.
* @param onFileSelectedFn Callback for file selection.
* @param onDialogCancelled Callback for dialog cancel.
* @param width Initial window width.
* @param height Initial window height.
* @return FileDialog instance
*/
FileDialog*(CARB_ABI* createFileDialog)(const char* title,
FileDialogOpenMode mode,
FileDialogSelectType type,
OnFileDialogFileSelected onFileSelectedFn,
void* selectedFnUserData,
OnFileDialogCancelled onDialogCancelled,
void* cancelFnUserData,
float width,
float height);
/**
* Destroy file dialog
* @param dialog FileDialog instance
*/
void(CARB_ABI* destroyFileDialog)(FileDialog* dialog);
/**
* Sets file selection callback.
* @param dialog FileDialog instance.
* @param onFileSelctedFn Callback if file is selected.
*/
void(CARB_ABI* setFileSelectedFnForFileDialog)(FileDialog* dialog,
OnFileDialogFileSelected onFileSelctedFn,
void* userData);
/**
* Sets file dialog cancelled callback.
* @param dialog FileDialog instance.
* @param onDialogCancelled Callback ifdialog is cancelled.
*/
void(CARB_ABI* setCancelFnForFileDialog)(FileDialog* dialog, OnFileDialogCancelled onDialogCancelled, void* userData);
/**
* Adds filter to file dialog to filter file type
* @param dialog FileDialog instance
*/
void(CARB_ABI* addFilterToFileDialog)(FileDialog* dialog, const char* name, const char* spec);
/**
* Clear all filters of file dialog
* @param dialog FileDialog instance
*/
void(CARB_ABI* clearAllFiltersOfFileDialog)(FileDialog* dialog);
/**
* Show file dialog
*/
void(CARB_ABI* showFileDialog)(FileDialog* dialog, FileDialogDataSource dataSource);
/**
* Draw file dialog
*/
void(CARB_ABI* drawFileDialog)(FileDialog* dialog, float elapsedTime);
/**
* If file dialog is opened or not
*/
bool(CARB_ABI* isFileDialogOpened)(FileDialog* dialog);
/**
* Gets title of file dialog
*/
const char*(CARB_ABI* getTitleOfFileDialog)(FileDialog* dialog);
/**
* Sets title for file dialog
*/
void(CARB_ABI* setTitleForFileDialog)(FileDialog* dialog, const char* title);
/**
* Gets selection type for file dialog
*/
FileDialogSelectType(CARB_ABI* getSelectionType)(FileDialog* dialog);
/**
* Sets selection type for file dialog
*/
void(CARB_ABI* setSelectionType)(FileDialog* dialog, FileDialogSelectType type);
/**
* Sets the directory where the dialog will open
*/
void(CARB_ABI* setCurrentDirectory)(FileDialog* dialog, const char* dir);
/** sets the default name to use for the filename on save dialogs.
*
* @param[in] dialog the file picker dialog to set the default save name for. This
* may not be nullptr.
* @param[in] name the default filename to use for this dialog. This may be nullptr
* or an empty string to use the USD stage's default prim name. In
* this case, if the prim name cannot be retrieved, "Untitled" will
* be used instead. If a non-empty string is given here, this will
* always be used as the initial suggested filename.
* @returns no return value.
*
* @remarks This sets the default filename to be used when saving a file. This name will
* be ignored if the dialog is not in @ref FileDialogOpenMode::eSave mode. The
* given name will still be stored regardless. This default filename may omit
* the file extension to take the extension from the current filter. If an
* extension is explicitly given here, no extension will be appended regardless
* of the current filter.
*/
void(CARB_ABI* setDefaultSaveName)(FileDialog* dialog, const char* name);
};
}
}
| 5,788 | C | 33.254438 | 122 | 0.623013 |
omniverse-code/kit/include/omni/kit/SettingsUtils.h | // Copyright (c) 2019-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.
//
//! @file
//! @brief Settings utilities for omni.kit.app
#pragma once
/**
* The settings prefix to indicate that a setting is persistent.
*/
#define PERSISTENT_SETTINGS_PREFIX "/persistent"
//! The separator character used by carb.settings
#define SETTING_SEP "/"
| 708 | C | 32.761903 | 77 | 0.769774 |
omniverse-code/kit/include/omni/kit/KitUtils.h | // 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.
//
#pragma once
#include <carb/Framework.h>
#include <carb/datasource/DataSourceUtils.h>
#include <carb/datasource/IDataSource.h>
#include <carb/events/IEvents.h>
#include <carb/imgui/ImGui.h>
#include <carb/input/IInput.h>
#include <carb/input/InputUtils.h>
#include <carb/settings/SettingsUtils.h>
#include <carb/tokens/ITokens.h>
#include <omni/kit/AssetUtils.h>
#include <omni/kit/IFileDialog.h>
#include <omni/kit/SettingsUtils.h>
#include <omni/ui/IGlyphManager.h>
#include <atomic>
namespace omni
{
namespace kit
{
/**
* Set of helpers to pass std::function in Carbonite interfaces.
* This is borrowed from <carb/BindingsPythonUtils.h>.
*/
template <typename ReturnT, typename... ArgsT>
class FuncUtils
{
public:
using StdFuncT = std::function<ReturnT(ArgsT...)>;
using CallbackT = ReturnT (*)(ArgsT..., void*);
static ReturnT callbackWithUserData(ArgsT... args, void* userData)
{
StdFuncT* fn = (StdFuncT*)userData;
if (fn)
return (*fn)(args...);
else
return ReturnT();
}
static StdFuncT* createStdFuncCopy(const StdFuncT& fn)
{
return new StdFuncT(fn);
}
static void destroyStdFuncCopy(StdFuncT* fn)
{
delete fn;
}
};
template <class T>
struct StdFuncUtils;
template <class R, class... Args>
struct StdFuncUtils<std::function<R(Args...)>> : public omni::kit::FuncUtils<R, Args...>
{
};
template <class R, class... Args>
struct StdFuncUtils<const std::function<R(Args...)>> : public FuncUtils<R, Args...>
{
};
template <class R, class... Args>
struct StdFuncUtils<const std::function<R(Args...)>&> : public FuncUtils<R, Args...>
{
};
inline omni::kit::IFileDialog* getIFileDialog()
{
return carb::getCachedInterface<omni::kit::IFileDialog>();
}
inline carb::imgui::ImGui* getImGui()
{
return carb::getCachedInterface<carb::imgui::ImGui>();
}
inline carb::input::IInput* getInput()
{
return carb::getCachedInterface<carb::input::IInput>();
}
inline carb::dictionary::IDictionary* getDictionary()
{
return carb::getCachedInterface<carb::dictionary::IDictionary>();
}
inline carb::settings::ISettings* getSettings()
{
return carb::getCachedInterface<carb::settings::ISettings>();
}
inline carb::filesystem::IFileSystem* getFileSystem()
{
return carb::getCachedInterface<carb::filesystem::IFileSystem>();
}
inline omni::ui::IGlyphManager* getGlyphManager()
{
return carb::getCachedInterface<omni::ui::IGlyphManager>();
}
struct ProcessEventSkipHotkey
{
carb::input::KeyboardModifierFlags mod;
carb::input::KeyboardInput key;
};
inline void processImguiInputEvents(ProcessEventSkipHotkey* skipHotkeys = nullptr,
size_t skipHotkeysCount = 0,
carb::input::IInput* input = nullptr,
carb::imgui::ImGui* imgui = nullptr)
{
if (!imgui)
{
imgui = getImGui();
}
if (!input)
{
input = getInput();
}
carb::input::filterBufferedEvents(input, [&](carb::input::InputEvent& evt) -> carb::input::FilterResult {
if (evt.deviceType != carb::input::DeviceType::eKeyboard)
{
return carb::input::FilterResult::eRetain;
}
const carb::input::KeyboardEvent* event = &evt.keyboardEvent;
{
bool needToConsume = false;
bool needToFeed = false;
// Always pass through key release events to make sure keys do not get "stuck".
// Possibly limit the keys in the future to maintain a map of pressed keys on the widget activation.
if (event->type == carb::input::KeyboardEventType::eKeyRelease)
{
needToConsume = false;
needToFeed = true;
}
else
{
// Always consume character input events
if (event->type == carb::input::KeyboardEventType::eChar)
{
needToConsume = true;
needToFeed = true;
}
// Do not consume Tab key to allow free navigation
else if (event->key != carb::input::KeyboardInput::eTab)
{
needToConsume = true;
needToFeed = true;
}
// Check if the event hotkey is in the list of skip hotkeys, and if so, always avoid passing those to
// imgui
if (skipHotkeys)
{
for (size_t hkIdx = 0; hkIdx < skipHotkeysCount; ++hkIdx)
{
ProcessEventSkipHotkey& skipHk = skipHotkeys[hkIdx];
if (event->modifiers == skipHk.mod && event->key == skipHk.key)
{
needToConsume = false;
needToFeed = false;
break;
}
}
}
}
if (needToFeed)
{
imgui->feedKeyboardEvent(imgui->getCurrentContext(), *event);
}
if (needToConsume)
{
return carb::input::FilterResult::eConsume;
}
}
return carb::input::FilterResult::eRetain;
});
}
// Helper functions for the child windows
inline bool predictActiveProcessImguiInput(const char* widgetIdString,
ProcessEventSkipHotkey* skipHotkeys = nullptr,
size_t skipHotkeysCount = 0)
{
carb::imgui::ImGui* imgui = getImGui();
carb::input::IInput* input = getInput();
uint32_t widgetId = imgui->getIdString(widgetIdString);
bool isItemPredictedActive = imgui->isItemIdActive(widgetId);
if (isItemPredictedActive)
{
processImguiInputEvents(skipHotkeys, skipHotkeysCount, input, imgui);
}
return isItemPredictedActive;
}
inline bool isWritableUrl(const char* url)
{
bool writable = false;
auto omniClientDataSource =
carb::getFramework()->acquireInterface<carb::datasource::IDataSource>("carb.datasource-omniclient.plugin");
omniClientDataSource->isWritable(
nullptr, url,
[](carb::datasource::Response response, const char* path, bool isWritable, void* userData) {
if (response == carb::datasource::Response::eOk)
{
*reinterpret_cast<bool*>(userData) = isWritable;
}
},
&writable);
return writable;
}
// Copied from Client Library
inline const char* getDefaultUser()
{
for (auto e : { "OV_USER", "USER", "USERNAME", "LOGNAME" })
{
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4996) // 'sprintf': This function or variable may be unsafe.
#endif
auto user = getenv(e);
#ifdef _MSC_VER
# pragma warning(pop)
#endif
if (user)
{
return user;
}
}
return "";
}
}
}
| 7,492 | C | 28.042636 | 117 | 0.595168 |
omniverse-code/kit/include/omni/kit/ContentWindowUtils.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/InterfaceUtils.h>
#include <omni/kit/IContentUi.h>
namespace omni
{
namespace kit
{
/**
* Gets the default (first) IContentWindow
*
* @return Default IContentWindow
*/
inline IContentWindow* getDefaultContentWindow()
{
auto contentWindow = carb::getCachedInterface<omni::kit::IContentUi>();
if (contentWindow)
{
return contentWindow->getContentWindow(nullptr);
}
return nullptr;
}
}
}
| 889 | C | 23.722222 | 77 | 0.748031 |
omniverse-code/kit/include/omni/kit/IMinimal.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
/**
* Minimal interface.
*
* It doesn't have any functions, but just implementing it and acquiring will load your plugin, trigger call of
* carbOnPluginStartup() and carbOnPluginShutdown() methods and allow you to use other Carbonite plugins. That by itself
* can get you quite far and useful as basic building block for Kit extensions. One can define their own interface with
* own python python bindings when needed and abandon that one.
*/
struct IMinimal
{
CARB_PLUGIN_INTERFACE("omni::kit::IMinimal", 1, 0);
};
}
}
| 1,048 | C | 31.781249 | 120 | 0.766221 |
omniverse-code/kit/include/omni/kit/IAppWindow.h | // 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.
//
#pragma once
#include <carb/IObject.h>
#include <carb/Interface.h>
#include <carb/events/EventsUtils.h>
#include <carb/events/IEvents.h>
#include <carb/input/IInput.h>
#include <carb/windowing/IWindowing.h>
namespace omni
{
namespace kit
{
constexpr const char* kWindowEnabledPath = "/app/window/enabled";
constexpr const char* kWindowWidthPath = "/app/window/width";
constexpr const char* kWindowHeightPath = "/app/window/height";
constexpr const char* kpWindowWidthPath = "/persistent/app/window/width";
constexpr const char* kpWindowHeightPath = "/persistent/app/window/height";
constexpr const char* kWindowMaximizedPath = "/app/window/maximized";
constexpr const char* kpWindowMaximizedPath = "/persistent/app/window/maximized";
constexpr const char* kWindowXPath = "/app/window/x";
constexpr const char* kWindowYPath = "/app/window/y";
constexpr const char* kWindowTitlePath = "/app/window/title";
constexpr const char* kWindowFullscreenPath = "/app/window/fullscreen";
constexpr const char* kWindowNoResizePath = "/app/window/noResize";
constexpr const char* kWindowScaleToMonitorPath = "/app/window/scaleToMonitor";
constexpr const char* kWindowAlwaysOnTopPath = "/app/window/alwaysOnTop";
constexpr const char* kWindowNoDecorationsPath = "/app/window/noDecorations";
constexpr const char* kWindowHideMouseInFullscreenPath = "/app/window/hideMouseInFullscreen";
constexpr const char* kWindowDpiScaleOverridePath = "/app/window/dpiScaleOverride";
constexpr const char* kWindowBlockAllInputPath = "/app/window/blockAllInput";
constexpr const char* kWindowIconPath = "/app/window/iconPath";
constexpr const char* kWindowChildWindowsOnTopPath = "/app/window/childWindowsOnTop";
constexpr const char* kWindowCursorBlinkPath = "/app/window/cursorBlink";
constexpr const uint64_t kPositionCentered = (uint64_t)-1;
constexpr const uint64_t kPositionUnset = (uint64_t)-2;
enum class Decorations
{
eFull,
eNone
};
enum class Resize
{
eAllowed,
eNotAllowed
};
enum class Floating
{
eRegular,
eAlwaysOnTop
};
enum class Scaling
{
eScaleToMonitor,
eNotScaled
};
enum class Fullscreen
{
eWindowed,
eFullscreen,
};
enum class WindowState
{
eNormal,
eMaximized,
eMinimized,
};
enum class CursorBlink
{
eBlink,
eNoBlink
};
struct WindowDesc
{
size_t structSize; // This field is needed to maintain ABI stability
uint64_t width, height;
uint64_t x, y;
const char* title;
Fullscreen fullscreen;
Decorations decorations;
Resize resize;
Floating floating;
Scaling scaling;
float dpiScaleOverride;
CursorBlink cursorBlink;
WindowState windowState;
};
inline WindowDesc getDefaultWindowDesc()
{
WindowDesc windowDesc;
windowDesc.structSize = sizeof(WindowDesc);
windowDesc.width = 1440;
windowDesc.height = 900;
windowDesc.x = kPositionUnset;
windowDesc.y = kPositionUnset;
windowDesc.title = "Application Window";
windowDesc.fullscreen = Fullscreen::eWindowed;
windowDesc.windowState = WindowState::eNormal;
windowDesc.decorations = Decorations::eFull;
windowDesc.resize = Resize::eAllowed;
windowDesc.floating = Floating::eRegular;
windowDesc.scaling = Scaling::eScaleToMonitor;
windowDesc.dpiScaleOverride = -1.0f;
windowDesc.cursorBlink = CursorBlink::eBlink;
return windowDesc;
}
const carb::events::EventType kEventTypeWindowCreated = 1;
const carb::events::EventType kEventTypeWindowDestroyed = 2;
const carb::events::EventType kEventTypeWindowStartup = 3;
const carb::events::EventType kEventTypeWindowShutdown = 4;
enum class WindowType
{
eVirtual,
eOs,
};
class IAppWindow : public carb::IObject
{
public:
/**
* Initializes the window taking parameters from carb::settings.
* @param name Name that identifies the window, can be nullptr.
* @return Whether the startup operation was completed successfully.
*/
virtual bool startup(const char* name) = 0;
/**
* Initializes the window with custom description.
* @return Whether the startup operation was completed successfully.
*/
virtual bool startupWithDesc(const char* name, const WindowDesc& desc) = 0;
/**
* Deinitializes the window.
* @return Whether the shutdown operation was completed successfully.
*/
virtual bool shutdown() = 0;
/**
* Call one update loop iteration on application.
* Normally, explicitly calling update is not required, as in presence of IApp interface,
* a subscription will be created that will be this function automatically.
*
* @ param dt Time elapsed since previous call. If <0 application ignores passed value and measures elapsed time
* automatically.
*/
virtual void update(float dt = -1.0f) = 0;
/**
* Returns the Carbonite window the editor is working with, or nullptr if headless.
* @return Carbonite window the editor is working with, or nullptr if headless.
*/
virtual carb::windowing::Window* getWindow() = 0;
/**
* @return The event stream that fires events on window resize.
*/
virtual carb::events::IEventStream* getWindowResizeEventStream() = 0;
/**
* @return The event stream that fires events on window close.
*/
virtual carb::events::IEventStream* getWindowCloseEventStream() = 0;
/**
* @return The event stream that fires events on window move.
*/
virtual carb::events::IEventStream* getWindowMoveEventStream() = 0;
/**
* @return The event stream that fires events on window DPI scale change.
* Content scale event stream provides DPI and "real DPI". The first one is affected by the DPI override, while
* the second one is raw hardware DPI induced this event.
*/
virtual carb::events::IEventStream* getWindowContentScaleEventStream() = 0;
/**
* @return The event stream that fires events on window drag-n-drop events.
*/
virtual carb::events::IEventStream* getWindowDropEventStream() = 0;
/**
* @return The event stream that fires events on window focus change.
*/
virtual carb::events::IEventStream* getWindowFocusEventStream() = 0;
/**
* @return The event stream that fires events on window minimize events.
*/
virtual carb::events::IEventStream* getWindowMinimizeEventStream() = 0;
/**
* Sets fullscreen state of editor Window.
*
* @param fullscreen true to set Editor Window to fullscreen.
*/
virtual void setFullscreen(bool fullscreen) = 0;
/**
* Gets the fullscreen state of editor Window.
*
* @return true if Editor is fullscreen.
*/
virtual bool isFullscreen() = 0;
/**
* Resizes the window.
*
* @param width The width of the window.
* @param height The height of the window.
*/
virtual void resize(uint32_t width, uint32_t height) = 0;
/**
* @return window width.
*/
virtual uint32_t getWidth() = 0;
/**
* @return window height.
*/
virtual uint32_t getHeight() = 0;
/**
* @return window size.
*/
virtual carb::Uint2 getSize() = 0;
/**
* Moves the window.
*
* @param x The x coordinate of the window.
* @param y The y coordinate of the window.
*/
virtual void move(int x, int y) = 0;
/**
* @return window position.
*/
virtual carb::Int2 getPosition() = 0;
/**
* @return UI scale multiplier that is applied on top of the OS DPI scale.
*/
virtual float getUiScaleMultiplier() const = 0;
/**
* Sets the UI scale multiplier that is applied on top of OS DPI scale.
*
* @param uiScaleCoeff UI scale coefficient.
*/
virtual void setUiScaleMultiplier(float uiScaleMultiplier) = 0;
/**
* @return UI scale. Includes UI scale multiplier and OS DPI scale.
*/
virtual float getUiScale() const = 0;
/**
* Gets current action mapping set settings path.
*
* @return action mapping set settings path.
*/
virtual const char* getActionMappingSetPath() = 0;
/**
* Gets the keyboard associated with the window.
*
* @return The window keyboard.
*/
virtual carb::input::Keyboard* getKeyboard() = 0;
/**
* Gets the mouse associated with the window.
*
* @return The window mouse.
*/
virtual carb::input::Mouse* getMouse() = 0;
/**
* Gets one of the gamepads available.
*
* @return The window gamepad or nullptr if index is invalid.
*/
virtual carb::input::Gamepad* getGamepad(size_t index) = 0;
/**
* @return Window title.
*/
virtual const char* getTitle() = 0;
/**
* @return DPI scale.
*/
virtual float getDpiScale() const = 0;
/**
* Sets the DPI scale override. Negative value means no override.
*/
virtual void setDpiScaleOverride(float dpiScaleOverride) = 0;
/**
* @return DPI scale override.
*/
virtual float getDpiScaleOverride() const = 0;
/**
* Sets the forced rejecting of all input events from a certain device type.
*/
virtual void setInputBlockingState(carb::input::DeviceType deviceType, bool shouldBlock) = 0;
/**
* @return whether the input for a certain device types is being blocked.
*/
virtual bool getInputBlockingState(carb::input::DeviceType deviceType) const = 0;
void broadcastInputBlockingState(bool shouldBlock)
{
for (size_t i = 0; i < (size_t)carb::input::DeviceType::eCount; ++i)
{
setInputBlockingState((carb::input::DeviceType)i, shouldBlock);
}
}
/**
* @brief Virtual/OS window
*/
virtual WindowType getWindowType() const = 0;
/**
* @return True if cursor (caret) blinks in input fields.
*/
virtual bool getCursorBlink() const = 0;
/**
* Gets the text from the clipboard associated with the window.
*
* @return The text in the window's clipboard.
*/
virtual const char* getClipboard() = 0;
/**
* Sets the text in the clipboard associated with the window.
*/
virtual void setClipboard(const char* text) = 0;
/**
* Maximize the editor window.
*/
virtual void maximizeWindow() = 0;
/**
* Restore the editor window (exit maximize/minimize).
*/
virtual void restoreWindow() = 0;
/**
* Gets the maxinized state of editor Window.
*
* @return true if Editor is maximized.
*/
virtual bool isMaximized() = 0;
/**
* @brief Allows to replace the keyboard.
*
* @param keyboard the keyboard this AppWindow should follow.
*/
virtual void setKeyboard(carb::input::Keyboard* keyboard) = 0;
};
using IAppWindowPtr = carb::ObjectPtr<IAppWindow>;
class IAppWindowFactory
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IAppWindowFactory", 2, 4);
/**
* Create new application window.
*/
IAppWindowPtr createWindowFromSettings();
virtual IAppWindow* createWindowPtrFromSettings() = 0;
virtual void destroyWindowPtr(IAppWindow* appWindow) = 0;
/**
* Set and get default application window.
*/
virtual IAppWindow* getDefaultWindow() = 0;
virtual void setDefaultWindow(IAppWindow*) = 0;
virtual size_t getWindowCount() = 0;
virtual IAppWindow* getWindowAt(size_t index) = 0;
virtual void startupActionMappingSet() = 0;
virtual void shutdownActionMappingSet() = 0;
virtual carb::input::ActionMappingSet* getActionMappingSet() const = 0;
virtual bool startup() = 0;
virtual bool shutdown() = 0;
virtual carb::events::IEventStream* getWindowCreationEventStream() = 0;
virtual IAppWindow* getAppWindowFromHandle(int64_t appWindowHandle) = 0;
IAppWindowPtr createWindowByType(WindowType windowType);
virtual IAppWindow* createWindowPtrByType(WindowType windowType) = 0;
};
inline IAppWindowPtr IAppWindowFactory::createWindowFromSettings()
{
return carb::stealObject(this->createWindowPtrFromSettings());
}
inline IAppWindowPtr IAppWindowFactory::createWindowByType(WindowType windowType)
{
return carb::stealObject(this->createWindowPtrByType(windowType));
}
inline IAppWindow* getDefaultAppWindow()
{
IAppWindowFactory* factory = carb::getCachedInterface<IAppWindowFactory>();
return factory ? factory->getDefaultWindow() : nullptr;
}
}
}
| 12,891 | C | 28.10158 | 116 | 0.681949 |
omniverse-code/kit/include/omni/kit/IViewport.h | // 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.
//
#pragma once
#include <carb/Interface.h>
#include <omni/kit/IExtensionWindow.h>
#include <omni/kit/ViewportTypes.h>
namespace omni
{
namespace kit
{
/**
* Defines the interface for Viewport Window.
*/
struct IViewport
{
CARB_PLUGIN_INTERFACE("omni::kit::IViewport", 1, 0);
/**
* Gets a ViewportWindow instance from its ExtensionWindowHandle.
*
* @param handle The ExtensionWindowHandle. Pass nullptr to get the first available viewport (in creation order).
* @return ViewportWindow instance associated with the ExtensionWindowHandle.
*/
IViewportWindow*(CARB_ABI* getViewportWindow)(const ExtensionWindowHandle handle);
/**
* Creates a viewport window.
*
* TODO: add @param name (optional) The name of the viewport.
* If no name is specified the default names are Viewport, Viewport_2, etc.
* @return the viewport window count
*/
ExtensionWindowHandle(CARB_ABI* createViewportWindow)(/* TODO support: const char* name */);
/**
* Destroys a viewport window.
*
* @param handle The window handle to be destroyed.
* @return true if window is destroyed, false if not.
*/
bool(CARB_ABI* destroyViewportWindow)(const ExtensionWindowHandle viewportWindow);
/**
* Gets a ViewportWindow's ExtensionWindowHandle from its name.
*
* @param name the window name to retrieve an ExtensionWindowHandle for.
* @return ExtensionWindowHandle associated with the window name.
*/
ExtensionWindowHandle(CARB_ABI* getViewportWindowInstance)(const char* name);
/**
* Gets a ViewportWindow name from its ExtensionWindowHandle.
*
* @param handle The ExtensionWindowHandle. Pass nullptr to get the first available viewport (in creation order).
* @return ViewportWindow name associated with the ExtensionWindowHandle.
*/
const char*(CARB_ABI* getViewportWindowName)(const ExtensionWindowHandle handle);
/**
* Gets the number of viewport windows currently open
*
* @return the viewport window count
*/
size_t(CARB_ABI* getViewportWindowInstanceCount)();
/**
* Returns a list of all open viewport window handles
*
* @param viewportWindowList An array of viewport window handles
*
* @param count number of viewport window handles to retrieve
*
* @remarks It is up to the caller to allocate memory for the viewport
* list, using getViewportWindowInstanceCount() to determine the list
* size.
* The call will fail if count is larger than the number of
* viewport windows, or if viewportWindowList is NULL.
*
* @return true if successful, false otherwise
*/
bool(CARB_ABI* getViewportWindowInstances)(ExtensionWindowHandle* viewportWindowList, size_t count);
/**
* Add a viewport drop helper
* Returns the current drop helper node.
*
* @param dropHelper Specified the drop helper.
*/
DropHelperNode*(CARB_ABI* addDropHelper)(const DropHelper& dropHelper);
/**
* Remove a viewport drop helper
*
* @param node Specified the drop helper node to remove.
*/
void(CARB_ABI* removeDropHelper)(const DropHelperNode* node) = 0;
};
struct IViewportAddOn
{
CARB_PLUGIN_INTERFACE("omni::kit::IViewportAddOn", 0, 1);
void* (CARB_ABI* getCarbRendererContext)();
};
}
}
| 3,857 | C | 32.547826 | 117 | 0.693803 |
omniverse-code/kit/include/omni/kit/Wildcard.h | // Copyright (c) 2020-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.
//
//! @file
//! @brief Wildcard utilities for omni.kit.app
#pragma once
#include <regex>
#include <string>
#include <unordered_set>
namespace omni
{
namespace kit
{
/**
* Defines the wildcard class.
*
* @warning This class uses `std::regex` which can be performance intensive. Consider using the functions in
* \ref omni::str instead.
*/
class Wildcard
{
public:
/**
* Sets the wildcard string.
*
* After this is set, call \ref isMatching() to determine if a string matches the wildcard pattern.
*
* @param pattern The wildcard pattern string to set.
*/
void setPatternString(const char* pattern)
{
// Special regex character
static const std::unordered_set<char> kSpecialCharacters = { '.', '^', '$', '|', '(', ')', '[',
']', '{', '}', '*', '+', '?', '\\' };
std::string expression = "^.*";
size_t len = strlen(pattern);
char prev_char = ' ';
for (size_t i = 0; i < len; i++)
{
const char character = pattern[i];
switch (character)
{
case '?':
expression += '.';
break;
case ' ':
expression += ' ';
break;
case '*':
if (i == 0 || prev_char != '*')
{
// make sure we don't have continuous * which will make std::regex_search super heavy, leading
// to crash
expression += ".*";
}
break;
default:
if (kSpecialCharacters.find(character) != kSpecialCharacters.end())
{
// Escape special regex characters
expression += '\\';
}
expression += character;
}
prev_char = character;
}
expression += ".*$";
m_expression = expression;
buildRegex();
}
/**
* Tests a string against the wildcard to see if they match.
*
* @param str The string to be tested.
* @retval true the string matches the wildcard
* @retval false the string does not match the wildcard
*/
bool isMatching(const char* str) const
{
return std::regex_search(str, m_wildcardRegex);
}
/**
* Sets if the wildcard should be case sensitive.
*
* The default is false (case insensitive).
*
* @param sensitive `true` if the wildcard should be case sensitive; `false` to be case insensitive
*/
void setCaseSensitive(bool sensitive)
{
if (m_caseSensitive != sensitive)
{
m_caseSensitive = sensitive;
buildRegex();
}
}
private:
void buildRegex()
{
if (m_expression.length())
{
auto flags = std::regex_constants::optimize;
if (!m_caseSensitive)
{
flags |= std::regex_constants::icase;
}
m_wildcardRegex = std::regex(m_expression, flags);
}
}
std::string m_expression;
std::regex m_wildcardRegex;
bool m_caseSensitive = false;
};
} // namespace kit
} // namespace omni
| 3,827 | C | 27.781955 | 118 | 0.51999 |
omniverse-code/kit/include/omni/kit/ISearch.h | // 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.
//
#pragma once
#include <carb/Interface.h>
#include <carb/events/IEvents.h>
namespace omni
{
namespace kit
{
const carb::events::EventType kEventSearchFinished = CARB_EVENTS_TYPE_FROM_STR("SEARCH_FINISHED");
/**
* Defines an interface for the search service plugin.
*
* This plugin handles communication between the content window and the search service python client.
*/
struct ISearch
{
CARB_PLUGIN_INTERFACE("omni::kit::search::ISearch", 1, 0);
/**
* Attempt to discover the search service
*
* @param url host url
*/
void(CARB_ABI* tryConnection)(const char* url);
/**
* Return true if we have discovered the search service at this host url
*
* @param url host url
* @return True if found
*/
bool(CARB_ABI* isConnected)(const char* url);
/**
* Set connection status (called from python)
*
* @param hostName host Name (not full url)
* @param isConnected true if connected, false if not
*/
void(CARB_ABI* setConnection)(const char* hostName, bool isConnected);
/**
* Perform a recursive file and tag search
*
* @param query The search query.
* @param parent The parent url to search, including the host name.
*/
void(CARB_ABI* recursiveSearch)(const char* query, const char* parent);
/**
* Status of search plugin connection. Returns true if connection attempt is pending.
*
* @param url The host url
* @return False if search is ready or unavailable. True if a connection attempt is pending.
*/
bool(CARB_ABI* connectionPending)(const char* url);
/**
* Status of search
*
* @return True if search is ongoing.
*/
bool(CARB_ABI* isSearching)();
/**
* Set status of search (called from python)
*
* @param isSearching True if searching.
*/
void(CARB_ABI* setSearching)(bool isSearching);
/**
* Add a search result to the internal cache.
*
* @param query The search query
* @param result The path to a file matching the query
* @param path The parent url
*/
void(CARB_ABI* addResult)(const char* query, const char* result, const char* path);
/**
* Get all the results from a query from the cache. Call clearMemory afterwards to cleanup.
*
* @param query The search query
* @param path The parent url
* @param nResults output: number of results.
* @return list of result paths
*/
char**(CARB_ABI* populateResults)(const char* query, const char* path, size_t* nResults);
/**
* clear memory from populateResults
*
* @param results Memory to clear
* @param nResults Number of results from populateResults
*/
void(CARB_ABI* clearMemory)(char** results, size_t nResults);
/**
* Search events occur when the search is finished.
*
* @return Search event stream
*/
carb::events::IEventStream*(CARB_ABI* getSearchEventStream)();
/**
* Shutdown the plugin
*
*/
void(CARB_ABI* shutdown)();
};
}
}
| 3,520 | C | 27.168 | 101 | 0.653977 |
omniverse-code/kit/include/omni/kit/IAppMessageBox.h | // Copyright (c) 2020-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.
//
//! @file
//! @brief Message box interface for omni.kit.app
#pragma once
#include "../../carb/Interface.h"
namespace omni
{
namespace kit
{
//! Message box type.
//! @see IAppMessageBox::show()
enum class MessageBoxType
{
eInfo, //!< Informational
eWarning, //!< Warning
eError, //!< Error
eQuestion //!< Question
};
//! Buttons to place on the message box.
enum class MessageBoxButtons
{
eOk, //!< Only an "Ok" button should be presented
eOkCancel, //!< Both "Ok" and "Cancel" buttons should be presented
eYesNo //!< Both "Yes" and "No" buttons should be presented
};
//! Message box user response.
enum class MessageBoxResponse
{
eOk, //!< User pressed "Ok" button
eCancel, //!< User pressed "Cancel" button
eYes, //!< User pressed "Yes" button
eNo, //!< User pressed "No" button
eNone, //!< User pressed "Ok" button when that was the only choice
eError //!< An error occurred
};
//! Interface for producing an OS-specific modal message box.
class IAppMessageBox
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IAppMessageBox", 1, 1);
/**
* Shows an OS specific modal message box.
*
* @note This is a blocking call that will return user response to the message box. The thread that calls it will be
* blocked until the user presses a button.
* @param message The message to display
* @param title The title of the message box
* @param type The \ref MessageBoxType to display
* @param buttons The \ref MessageBoxButtons to present
* @returns A \ref MessageBoxResponse value based on the button that the user pressed, or
* \ref MessageBoxResponse::eError if an error occurred.
*/
virtual MessageBoxResponse show(const char* message,
const char* title,
MessageBoxType type,
MessageBoxButtons buttons) = 0;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline Functions //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace kit
} // namespace omni
| 2,790 | C | 32.22619 | 120 | 0.585305 |
omniverse-code/kit/include/omni/kit/ViewportTypes.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/events/EventsUtils.h>
namespace carb
{
struct Double4x4
{
double m[16];
};
namespace renderer
{
struct Renderer;
struct Context;
}
namespace scenerenderer
{
struct SceneRenderer;
struct Context;
}
}
namespace rtx
{
namespace resourcemanager
{
class RpResource;
}
}
namespace carb
{
namespace sensors
{
enum class SensorType;
}
namespace renderer
{
enum class FrameDataType;
}
}
namespace omni
{
namespace usd
{
using TokenH = uint64_t;
typedef int32_t ViewportHandle;
namespace hydra
{
enum class EngineCreationFlags : uint32_t;
}
}
namespace kit
{
typedef uint64_t SubscriptionId;
constexpr uint64_t kInvalidSubscriptionId = 0xFFFF'FFFF'FFFF'FFFFULL;
enum class ViewportMenuAlignment
{
eTopLeft,
eTopRight,
eCount
};
typedef bool (*CheckCameraOverrideFn)(void* userdata);
typedef bool (*ApplyCameraOverrideFn)(carb::Double4x4& worldToView,
carb::Double3& translate,
carb::Double2& rotate,
void* userdata);
typedef void (*ResetCameraOverrideFn)(void* userdata);
typedef void (*OnQueriedNextPickedWorldPositionFn)(const carb::Double3* worldPos, void* userData);
struct CameraOverrideDesc
{
CheckCameraOverrideFn checkCameraOverrideActive;
ApplyCameraOverrideFn applyCameraOverride;
ResetCameraOverrideFn resetCameraOverride;
void* userdata;
};
enum class ViewportPrimReferencePoint
{
eBoundBoxCenter,
eBoundBoxLeft,
eBoundBoxRight,
eBoundBoxTop,
eBoundBoxBottom
};
struct DropHelper
{
bool pickable;
bool addOutline;
void* userPointer;
bool(CARB_ABI* onDropAccepted)(const char* url, void* userPointer);
std::string(CARB_ABI* onDrop)(
const char* url, const char* target, const char* viewport_name, const char* context_name, void* userPointer);
void(CARB_ABI* onPick)(const char* url, const char* target, const char* context_name, void* userPointer);
};
struct DropHelperNode
{
bool accepted;
DropHelper dropHelper;
};
// a temporary set of overrides to make XR's life easier
// TODO - further cleanup
struct ViewportWindowXROverrideDesc
{
bool disableGizmo;
const char* resolutionString;
const char** additionalMessages;
size_t additionalMessagesCount;
bool disableViewportResolutionOverride;
};
class IViewportWindow
{
public:
/**
* Setting path to retrieve viewport display options
*/
static const char* const kViewportDisplayOptionsPath;
/**
* Defines viewport element visibility flags
*/
using ShowFlags = uint32_t;
static const ShowFlags kShowFlagNone = 0;
static const ShowFlags kShowFlagFps = 1 << 0;
static const ShowFlags kShowFlagAxis = 1 << 1;
static const ShowFlags kShowFlagLayer = 1 << 2;
static const ShowFlags kShowFlagResolution = 1 << 3;
static const ShowFlags kShowFlagTimeline = 1 << 4;
static const ShowFlags kShowFlagCamera = 1 << 5;
static const ShowFlags kShowFlagGrid = 1 << 6;
static const ShowFlags kShowFlagSelectionOutline = 1 << 7;
static const ShowFlags kShowFlagLight = 1 << 8;
static const ShowFlags kShowFlagSkeleton = 1 << 9;
static const ShowFlags kShowFlagMesh = 1 << 10;
static const ShowFlags kShowFlagPathTracingResults = 1 << 11;
static const ShowFlags kShowFlagAudio = 1 << 12;
static const ShowFlags kShowFlagDeviceMemory = 1 << 13;
static const ShowFlags kShowFlagHostMemory = 1 << 14;
static const ShowFlags kShowFlagAll = kShowFlagFps | kShowFlagAxis | kShowFlagLayer | kShowFlagResolution |
kShowFlagPathTracingResults | kShowFlagTimeline | kShowFlagCamera |
kShowFlagGrid | kShowFlagSelectionOutline | kShowFlagLight |
kShowFlagSkeleton | kShowFlagMesh | kShowFlagAudio |
kShowFlagDeviceMemory | kShowFlagHostMemory;
/**
* Setting path to retrieve gizmo options
*/
static const char* const kViewportGizmoScalePath;
static const char* const kViewportGizmoConstantScaleEnabledPath;
static const char* const kViewportGizmoConstantScalePath;
static const char* const kViewportGizmoBillboardStyleEnabledPath;
typedef bool (*OnMenuDrawSubmenuFn)();
/**
* Destructor.
*/
virtual ~IViewportWindow() = default;
/**
* Adds a menu item to the viewport, those are currently only Top Left aligned or Top Right aligned.
* We currently only support Button type from the UI Toolkit
* Because the caller of this function might not have access to the UI Class directly a void * is used
* The function call does sanity check on the * and will handle wrong * properly.
*
* @param name is the name of the button.
* @param button is a pointer to a Button class.
* @param alignment is the alignment of the button either Left or Right.
*/
virtual void addMenuButtonItem(const char* name, void* button, ViewportMenuAlignment alignment) = 0;
/**
* Removes the bottom from the menu, the name is the Key in the named array.
*
* @param name the name of the button to remove
* @param alignment the alignment of the button, name are unique only per Menu
*/
virtual void removeMenuButtonItem(const char* name, ViewportMenuAlignment alignment) = 0;
/**
* Adds a menu to the show/hide type submenu
* @param name the name of the submenu
* @param drawMenuCallback draw menu function pointer
*/
virtual void addShowByTypeSubmenu(const char* name,
OnMenuDrawSubmenuFn drawMenuCallback,
OnMenuDrawSubmenuFn resetMenuCallback,
OnMenuDrawSubmenuFn isResetMenuCallback) = 0;
/**
* Removes a menu to the show/hide type submenu
* @param name the name of the submenu
*/
virtual void removeShowByTypeSubmenu(const char* name) = 0;
/**
* Posts a toast message to viewport.
*
* @param message The message to be posted.
*/
virtual void postToast(const char* message) = 0;
/**
* Request a picking query for the next frame.
*/
virtual void requestPicking() = 0;
/**
* Enable picking.
*
* @param enable Enable/disable picking.
*/
virtual void setEnabledPicking(bool enable) = 0;
/**
* Is picking enabled.
*
* @return True if picking is enabled.
*/
virtual bool isEnabledPicking() const = 0;
/**
* Gets the EventStream for in-viewport draw event.
*
* @return EventStream for in-viewport draw event.
*/
virtual carb::events::IEventStreamPtr getUiDrawEventStream() = 0;
/**
* Query the visibility of the window.
*
* @return visibility of the window.
*/
virtual bool isVisible() const = 0;
/**
* Sets the visibility of the window.
*
* @param visible true to show the window, false to hide the window.
*/
virtual void setVisible(bool visible) = 0;
/**
* Query the window name.
*
* @return the window name
*/
virtual const char* getWindowName() = 0;
/**
* Sets the active camera in the viewport to a USD camera.
*
* @param path Path of the camera prim on the stage.
*/
virtual void setActiveCamera(const char* path) = 0;
/**
* Gets the active camera in the viewport.
*
* @return Path of the camera prim on the stage.
*/
virtual const char* getActiveCamera() const = 0;
/**
* Sends signal to the currently activecamera controller to focus on target (either selected scene primitive,
* or the whole scene).
*/
virtual void focusOnSelected() = 0;
/**
* Gets camera's target.
*
* @param path The path of the Camera prim.
* @param target The target of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraTarget(const char* path, carb::Double3& target) const = 0;
/**
* Gets prim's clipping pos in current active camera.
* It's calculated with prim_pos * view_matrix_of_camera * projection_matrix_of_camera.
* The x or y pos of returned value is [-1, 1]. In xy plane, y is facing up and x is facing right,
* which is unliking window coordinates that y is facing down and the range of xy is [0, 1]x[0, 1].
* and the z pos is [0, 1], where z is in reverse form that 0 is the far plane, and 1 is the near plane.
*
* @param path The path of the prim.
* @param pos The offset pos of the prim to be written to.
* @param referencePoint The reference point of prim to be calculated for clipping pos.
* By default, it's the center of the prim bound box.
* @return true on success, false if prim doesn't exist at path. Or
* prim's position is out of the active camera's view frustum.
*/
virtual bool getPrimClippingPos(
const char* path,
carb::Double3& pos,
ViewportPrimReferencePoint referencePoint = ViewportPrimReferencePoint::eBoundBoxCenter) const = 0;
/**
* Sets camera's target.
*
* @param path The path of the Camera prim.
* @param target The target of the camera to be set to.
* @param rotate true to keep position but change orientation and radius (camera rotates to look at new target).
* false to keep orientation and radius but change position (camera moves to look at new target).
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool setCameraTarget(const char* path, const carb::Double3& target, bool rotate) = 0;
/**
* Gets camera's position.
*
* @param path The path of the Camera prim.
* @param position The position of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraPosition(const char* path, carb::Double3& position) const = 0;
/**
* Sets camera's position.
*
* @param path The path of the Camera prim.
* @param position The position of the camera to be set to.
* @param rotate true to keep position but change orientation and radius (camera moves to new position while still
* looking at the same target).
* false to keep orientation and radius but change target (camera moves to new position while keeping
the relative position of target unchanged).
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool setCameraPosition(const char* path, const carb::Double3& position, bool rotate) = 0;
/**
* Gets camera's forward vector.
*
* @param path The path of the Camera prim.
* @param vector The forward vector of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraForward(const char* path, carb::Double3& vector) const = 0;
/**
* Gets camera's right vector.
*
* @param path The path of the Camera prim.
* @param vector The right vector of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraRight(const char* path, carb::Double3& vector) const = 0;
/**
* Gets camera's up vector.
*
* @param path The path of the Camera prim.
* @param vector The up vector of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraUp(const char* path, carb::Double3& vector) const = 0;
/**
* Gets camera move speed when pilot in viewport with camera control.
*
* @return camera move speed.
*/
virtual double getCameraMoveVelocity() const = 0;
/**
* Sets camera move speed when pilot in viewport with camera control.
*
* @param velocity camera move speed.
*/
virtual void setCameraMoveVelocity(double velocity) = 0;
/**
* Enables or disables gamepad for camera controller.
*
* @param enabled true to enable gamepad, false to disable.
*/
virtual void setGamepadCameraControl(bool enabled) = 0;
/**
* Temporary workaround for fullscreen mode. DO NOT USE directly.
*/
virtual void draw(const char* windowName, float elapsedTime) = 0;
/**
* Toggles Visibility settings. Lights/Camera/Skeleton/Grid/HUD etc.
*/
virtual void toggleGlobalVisibilitySettings() = 0;
/**
* Gets the mouse event stream
*
* @returns The mouse event stream
*/
virtual carb::events::IEventStream* getMouseEventStream() = 0;
/**
* Gets the viewport window rect
*
* @returns The viewport window rect
*/
virtual carb::Float4 getViewportRect() const = 0;
virtual carb::Int2 getViewportRenderResolution() const = 0;
/**
* Gets if camera is being manipulated.
*
* @returns true if camera is being manipulated.
*/
virtual bool isManipulatingCamera() const = 0;
/**
* Gets if viewport is being focused.
*
* @returns true if viewport is being focused.
*/
virtual bool isFocused() const = 0;
/**
* Allow camera motion to be overriden
*
* @returns a subscriptionId to remove override with
*/
virtual SubscriptionId addCameraOverride(const CameraOverrideDesc& cameraOverride) = 0;
/**
* Remove override
*/
virtual void removeCameraOverride(SubscriptionId subscription) = 0;
/**
* Sets the hydra engine to use for rendering
*
*/
virtual void setActiveHydraEngine(const char* hydraEngine) = 0;
/**
* Sets the tick rate for hydra engine used during rendering
* -1 means unlimited
*/
virtual void setHydraEngineTickRate(uint32_t tickRate) = 0;
/**
* Gets the render product prim path
*
*/
virtual const char* getRenderProductPrimPath() = 0;
/**
* Sets the render product prim path
*
*/
virtual void setRenderProductPrimPath(const char* path) = 0;
/**
* Enables an AOV on the viewport
*
* @param aov name of the AOV to add.
* @param verifyAvailableBeforeAdd if true add the AOV only if it belong to the list of available AOVs.
* @returns true if the AOV is added or already exists.
*/
virtual bool addAOV(omni::usd::TokenH aov, bool verifyAvailableBeforeAdd) = 0;
/**
* Disables an AOV on the viewport
*
* @returns true if the AOV is removed.
*/
virtual bool removeAOV(omni::usd::TokenH aov) = 0;
/**
* Returns all the AOVs output by the viewport
*
* @returns true if the AOV is removed.
*/
virtual const omni::usd::TokenH* getAOVs(uint32_t& outNumAovs) = 0;
/**
* Sets the window size
*/
virtual void setWindowSize(uint32_t w, uint32_t h) = 0;
/**
* Sets the window position
*/
virtual void setWindowPosition(uint32_t x, uint32_t y) = 0;
/**
* Sets the texture resolution. This overrides window size when viewport resolution is selected
* Pass -1,-1 to undo override
*/
virtual void setTextureResolution(int32_t x, int32_t y) = 0;
/**
* @returns current viewport's resource specified by the AOV (null if non-existent)
*/
virtual rtx::resourcemanager::RpResource* getDrawableResource(omni::usd::TokenH aov) = 0;
/**
* @returns whether the AOV is available on the current viewport
*/
virtual bool isDrawableAvailable(omni::usd::TokenH aov) = 0;
/**
* @returns fps of viewport's drawable
*/
virtual float getFps() = 0;
/**
* @ Calls the callback on next mouse click and passes the world position under mouse.
*
* @param fn callback function when world position is fetched after mouse click. The position can be nullptr if
* clicked on black background.
* @param userData user data to be passed back to fn when callback is triggered.
*/
virtual void queryNextPickedWorldPosition(OnQueriedNextPickedWorldPositionFn fn, void* userData) = 0;
/**
* Returns the current frame data based on the requested feature, such as profiler data.
* If frame is not finished processing the data, the result of the previous frame is returned.
* For multi-GPU, query the device count and then set deviceIndex to the desired device index.
*
* @param dataType Specified the requested data type to return.
* @param deviceIndex The index of GPU device to get the frame data from. Set to zero in Single-GPU mode.
* You may query the number of devices with FrameDataType::eGpuProfilerDeviceCount.
* deviceIndex is ignored when the type is set to eGpuProfilerDeviceCount.
* @param data A pointer to the returned data. Returns nullptr for failures or eGpuProfilerDeviceCount.
* You may pass nullptr if you only need dataSize.
* @param dataSize The size of the returned data in bytes, the number of structures, or device count based on
* the dataType. For strings, it includes the null-termination.
*/
virtual void getFrameData(carb::renderer::FrameDataType dataType,
uint32_t deviceIndex,
void** data,
size_t* dataSize) = 0;
/**
* Checks if mouse is hovering over the viewport's content region, without being occluded by other UI elements.
*/
virtual bool isContentRegionHovered() const = 0;
/**
* Gets the hydra engine that is used for rendering.
*/
virtual const char* getActiveHydraEngine() = 0;
/* menu UI */
virtual void showHideWindow(bool visible) = 0;
virtual omni::usd::ViewportHandle getId() const = 0;
/**
* Get the picked world pos since last requested picking.
*
* @param outWorldPos picked world pos to be filled.
*
* @returns false if no picked pos is available.
*/
virtual bool getPickedWorldPos(carb::Double3& outWorldPos) = 0;
virtual bool getPickedGeometryHit(carb::Double3& outWorldPos, carb::Float3& outNormal) = 0;
virtual uint32_t getAvailableAovCount() const = 0;
virtual void getAvailableAovs(const char* outAovs[]) const = 0;
virtual const char* getUsdContextName() const = 0;
virtual void disableSelectionRect(bool enablePicking) = 0;
// A shim for XR until better paths for messages is ready
virtual void setXROverrideDesc(ViewportWindowXROverrideDesc xrOverrideDesc) = 0;
/**
* @returns scene renderer.
*/
virtual carb::scenerenderer::SceneRenderer* getSceneRenderer() = 0;
/**
* @ returns scene renderer context.
*/
virtual carb::scenerenderer::Context* getSceneRendererContext() = 0;
/**
* Sets the hydra engine flags for the hydra engine used to render this viewport
*/
virtual void setHydraEngineFlags(omni::usd::hydra::EngineCreationFlags flags) = 0;
};
}
}
| 19,832 | C | 31.24878 | 119 | 0.656263 |
omniverse-code/kit/include/omni/kit/ContentUiTypes.h | // 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.
//
#pragma once
namespace carb
{
namespace imgui
{
struct ImGui;
}
}
namespace omni
{
namespace kit
{
struct ContentWindowWidget;
class ContentExplorer;
using OnMenuItemClickedFn = void (*)(const char* menuPath, bool value, void* userData);
using OnMenuItemCheckFn = bool (*)(const char* contentUrl, void* userData);
using OnContentWindowToolButtonClickedFn = void (*)(const char* name, void* userData);
class IContentWindow
{
public:
/**
* Destructor.
*/
virtual ~IContentWindow() = default;
/**
* Query the visibility of the window.
*
* @return visibility of the window.
*/
virtual bool isVisible() const = 0;
/**
* Sets the visibility of the window.
*
* @param visible true to show the window, false to hide the window.
*/
virtual void setVisible(bool visible) = 0;
/**
* Navigates to a path.
*
* @param path The path to navigate to.
* @param changeSelection When true the path's parent directory will be expanded and leaf selected,
* when false the path itself will be expanded and nothing will be selected.
*/
virtual void navigateTo(const char* path, bool changeSelection = false) = 0;
/**
* Add context menu item to content window.
*
* @param menuItemName The name to the menu (e.g. "Open"), this name must be unique across context menu.
* @param tooltip The helper text.
* @param onMenuItemClicked The callback function called when menu item is clicked.
* @param userData The custom data to be passed back via callback function.
* @return true if success, false otherwise. When it returned with false,
* it means there is existing item that has the same name.
*/
virtual bool addContextMenu(const char* menuItemName,
const char* tooltip,
OnMenuItemClickedFn onMenuItemClicked,
void* userData) = 0;
/**
* Removes a context menu item in content window.
*
* @param menuItemName The name of the menu item to be removed.
*/
virtual void removeContextMenu(const char* menuItemName) = 0;
/**
* Add Icon menu item to content window.
* @param menuItemName The name to the menu (e.g. "Open"), this name must be unique across context menu.
* @param onMenuItemClicked The callback function called when menu item is clicked.
* @param userData The custom data to be passed back via callback function.
* @param onMenuItemCheck The callback function called when menu item is created. If the callback returns true, the
* menu item will not be created.
* @param userDataCheck The custom data to be passed back to onMenuItemCheck callback.
*/
virtual bool addIconMenu(const char* menuItemName,
OnMenuItemClickedFn onMenuItemClicked,
void* userData,
OnMenuItemCheckFn onMenuItemCheck,
void* userDataCheck) = 0;
/**
* Removes a Icon menu item in content window.
*
* @param menuItemName The name of the menu item to be removed.
*/
virtual void removeIconMenu(const char* menuItemName) = 0;
/**
* Refresh selected node of content window.
*/
virtual void refresh() = 0;
/**
* Adds tool button for content window, which locates at the left of search bar.
*
* @param name The name of the button, this name must be unique across tool bar of content window.
* @param toolTip The helper text.
* @param validDataSource If this is true, the button will only be enabled when a valid data source is selected.
* @param clickedFn The callback function called when button is clicked.
* @param userData The custom data to be passed back via callback function.
* @param priority The priority to sort tool buttons. It's sorted in ascending order.
* @return true if success, false otherwise. When it returned with false,
* it means there is existing item that has the same name.
*/
virtual bool addToolButton(const char* name,
const char* tooltip,
bool validDataSource,
OnContentWindowToolButtonClickedFn clickedFn,
void* userData,
int priority) = 0;
/**
* Removes tool button for content window.
*
* @param name Button name to be removed.
*/
virtual void removeToolButton(const char* name) = 0;
/**
* Gets current selected path protocol in content window.
*
* @return current selected path protocol in content window, (e.g. "" for local, or "omniverse:" for OV).
*/
virtual const char* getSelectedPathProtocol() const = 0;
/**
* Gets current selected directory in content window.
*
* @return current selected directory in content window, (e.g. "/Users/test/", or "E:/test/").
*/
virtual const char* getSelectedDirectoryPath() const = 0;
/**
* Gets current selected icon protocol in content window.
*
* @return current selected icon protocol in content window, (e.g. "" for local, or "omniverse:" for OV).
*/
virtual const char* getSelectedIconProtocol() const = 0;
/**
* Gets current selected icon in content window.
*
* @return current selected icon in content window, (e.g. "/Users/test/1.usd", or "E:/test/1.usd").
*/
virtual const char* getSelectedIconPath() const = 0;
};
}
}
| 6,103 | C | 35.771084 | 119 | 0.640669 |
omniverse-code/kit/include/omni/kit/IContentUi.h | // 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.
//
#pragma once
#include <carb/Interface.h>
#include <omni/kit/ContentUiTypes.h>
#include <omni/kit/IExtensionWindow.h>
namespace omni
{
namespace kit
{
/**
* Defines the interface for Content UI.
*/
class IContentUi
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IContentUi", 0, 1);
/**
* Gets a ContentWindow instance from its ExtensionWindowHandle.
*
* @param handle The ExtensionWindowHandle. Pass nullptr to get the first available ContentWindow (in creation
* order).
* @return ContentWindow instance associated with the ExtensionWindowHandle.
*/
virtual IContentWindow* getContentWindow(const ExtensionWindowHandle handle) = 0;
/**
* Creates content window widget.
*
* @param width Width in pixel
* @param height Height in pixel
* @return ContentWindowWidget instance
*/
virtual ContentWindowWidget* createContentWindowWidget(uint32_t width, uint32_t height) = 0;
/**
* Destroys content window widget.
*
* @param widget ContentWindowWidget instance
*/
virtual void destroyContentWindowWidget(ContentWindowWidget* widget) = 0;
/**
* Refreshes content window widget.
*
* @param widget ContentWindowWidget instance
*/
virtual void refreshContentWindowWidget(ContentWindowWidget* widget) = 0;
/**
* Draws content window widget.
*
* @param widget ContentWindowWidget instance
* @param elapsedTime Time in seconds since last draw
*/
virtual void drawContentWindowWidget(ContentWindowWidget* widget, float elapsedTime) = 0;
/**
* Allocates buffer and fill buffer with selected tree node information.
*
* @param ContentWindowWidget instance
* @param protocol Path protocol (e.g., "", or "omniverse:"")
* @param realUrl Real path (e.g., e:/test for local, or /Users/test for OV)
* @param contentUrl Content path (e.g., /e/test for local, or /Users/test/ for OV)
*/
virtual void createSelectedTreeNodeBuffersFromContentWindowWidget(ContentWindowWidget* widget,
const char** protocol,
const char** realUrl,
const char** contentUrl) = 0;
/**
* Allocates buffer and fill buffer with selected file node information.
*
* @param ContentWindowWidget instance
* @param protocol Path protocol (e.g., "", or "omniverse:"")
* @param realUrl Real path (e.g., e:/test/test.txt for local, or /Users/test/test.txt for OV)
* @param contentUrl Content path (e.g., /e/test/test.txt for local, or /Users/test/test.txt for OV)
*/
virtual void createSelectedFileNodeBuffersFromContentWindowWidget(ContentWindowWidget* widget,
const char** protocol,
const char** realUrl,
const char** contentUrl) = 0;
/**
* Destroys allocated buffers.
*/
virtual void destroyBuffersFromContentWindowWidget(const char* protocol,
const char* realUrl,
const char* contentUrl) = 0;
/**
* Sets filter for content window.
*
* @param widget ContentWindowWidget instance
* @param filter File filter that supports regex (e.g., *.usd).
*/
virtual void setFilterForContentWindowWidget(ContentWindowWidget* widget, const char* filter) = 0;
/**
* Navigates to path.
*
* @param widget ContentWindowWidget instance
* @param path
*/
virtual void navigateContentWindowWidget(ContentWindowWidget* widget, const char* path) = 0;
/**
* Gets the download task status from download manager.
*
* @param[out] finishedFiles Number of finished files.
* @param[out] totalFiles Number of total files.
* @param[out] lastUrl Url of last downloaded file.
* return true if download is in progress, false if no file is being downloaded.
*/
virtual bool getDownloadTaskStatus(int32_t& finishedFiles, int32_t& totalFiles, const char*& lastUrl) = 0;
};
}
}
| 4,837 | C | 36.503876 | 114 | 0.620219 |
omniverse-code/kit/include/omni/kit/AssetUtils.h | // 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.
//
#pragma once
#include <carb/Framework.h>
#include <carb/datasource/DataSourceUtils.h>
#include <carb/datasource/IDataSource.h>
#include <carb/filesystem/IFileSystem.h>
#include <carb/logging/Log.h>
#include <vector>
namespace omni
{
namespace kit
{
/** Obtain a list of datasources for the local file system.
* @returns A vector of the local filesystem connections.
* This vector contains pairs where the first member is the first
* character of the filesystem name (on windows, this is the upper
* case DOS drive label; on Linux, this is '/') and the second member
* is the connection to that filesystem.
* None of the connections in the returned vector will be nullptr.
*
* @remarks This function is used to workaround a limitation with the datasource
* system that prevents DOS paths from being used, so each separate DOS
* drive needs to be registered as a separate connection.
* This function will be removed eventually when this deficiency is fixed.
*/
inline std::vector<std::pair<char, carb::datasource::Connection*>> getFilesystemConnections()
{
carb::filesystem::IFileSystem* fs = carb::getFramework()->acquireInterface<carb::filesystem::IFileSystem>();
carb::datasource::IDataSource* dataSource =
carb::getFramework()->acquireInterface<carb::datasource::IDataSource>("carb.datasource-omniclient.plugin");
std::vector<std::pair<char, carb::datasource::Connection*>> vec;
if (fs == nullptr || dataSource == nullptr)
return vec;
#if CARB_PLATFORM_WINDOWS
for (char drive = 'A'; drive <= 'Z'; drive++)
{
std::string drivePath = std::string(1, drive) + ":";
if (fs->exists(drivePath.c_str()))
{
carb::datasource::Connection* connection =
carb::datasource::connectAndWait(carb::datasource::ConnectionDesc{ drivePath.c_str() }, dataSource);
if (connection == nullptr)
{
CARB_LOG_ERROR("failed to get connection for drive %c", drive);
continue;
}
vec.push_back(std::make_pair(drive, connection));
}
}
#else
// Just add the root of the filesystem
carb::datasource::Connection* connection =
carb::datasource::connectAndWait(carb::datasource::ConnectionDesc{ "/" }, dataSource);
if (connection == nullptr)
CARB_LOG_ERROR("failed to get connection for the filesystem root");
else
vec.push_back(std::make_pair('/', connection));
#endif
return vec;
}
}
}
| 3,019 | C | 36.75 | 116 | 0.673733 |
omniverse-code/kit/include/omni/kit/KitUpdateOrder.h | // Copyright (c) 2019-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.
//
/**
* @file
* @brief Helpers for kit update ordering
*
* Kit's event subscribers order numbers, which control the execution order flow of the application were previously
* magic values scattered across dozens of extensions across multiple repositories. This centralizes it for now.
*
* This file defines a ordering that can be used to by extensions to have a deterministic execution flow.
*/
#pragma once
#include "../../carb/events/IEvents.h"
namespace omni
{
namespace kit
{
//! Namespace for kit update ordering values
namespace update
{
//! @defgroup updateorder Kit Update Ordering values
//! @todo Although it is good that these values are together, this is not the correct place for them. Many of the values
//! are specific to Omniverse applications that consume Carbonite but are not based in Carbonite. They should likely
//! be in a data-driven format such as a configuration file and instead referred to as names (i.e. using
//! \ref carb::RString) that can be mapped to a value, and/or documented somewhere central.
//! @{
//! Ordering of events within a \ref omni::kit::RunLoop::preUpdate event loop.
//! \see updateorder
enum PreUpdateOrdering : int32_t
{
eTelmetryInitialize = -50, //!< Initialize Telemetry profiling. Typically the first item in a frame.
eFabricBeginFrame = -20, //!< Initiate a Fabric frame.
eUnspecifiedPreUpdateOrder = carb::events::kDefaultOrder //!< Default pre-update order value
};
//! Ordering of events within a \ref omni::kit::RunLoop::update event loop.
//! \see updateorder
enum UpdateOrdering : int32_t
{
//! Checks for HydraEngine::render completion on GPU.
//!
//! 1. Pushes StageRenderingEvent::NewFrame
//! 2. Triggers renderingEventStream::pump
eCheckForHydraRenderComplete = -100,
//! Applies pending Timeline state changes
eUsdTimelineStateRefresh = -90,
//! asyncio.Future blocked awaiting (update loop begin)
//!
//! 1. IApp.next_pre_update_async
//! 2. UsdContext.next_frame_async / next_usd_async
ePythonAsyncFutureBeginUpdate = -50,
//! Enables execution of all python blocked by \ref ePythonAsyncFutureBeginUpdate
//!
//! Enable python execution blocked awaiting UsdContext::RenderingEventStream::Pump()
//! @see ePythonAsyncFutureBeginUpdate
ePythonExecBeginUpdate = -45,
//! Run OmniClient after python but before main simulation
eOmniClientUpdate = -30,
//! ITimeline wants to execute before \ref eUsdContextUpdate
eUsdTimelineUpdate = -20,
//! Core UsdUpdate execution
//!
//! 1. Update liveModeUpdate listeners
//! 2. triggers stageEventStream::pump
//! 3. MaterialWatcher::update
//! 4. IHydraEngine::setTime
//! 5. triggers IUsdStageUpdate::pump (see IUsdStageEventOrdering below)
//! 6. AudioManager::update
eUsdContextUpdate = -10,
//! Default update order value
//!
//! @note extras::SettingWrapper is hardcoded to \ref carb::events::kDefaultOrder which means this is when during
//! the main update cycle, event listeners for settings changes events will fire. There are a minimum of 60+ unique
//! setting subscription listeners in a default kit session.
eUnspecifiedUpdateOrder = carb::events::kDefaultOrder,
//! Trigger UI/ImGui Drawing
eUIRendering = 15,
//! Fabric Flush after eUsdContextUpdate
//! @see eUsdContextUpdate
eFabricFlush = 20,
//! Triggers HydraEngine::render
eHydraRendering = 30,
//! asyncio.Future blocked awaiting (update loop end)
//!
//! 1. IApp.next_update_async (legacy)
ePythonAsyncFutureEndUpdate = 50,
//! Enables execution of all python blocked by ePythonAsyncFutureEndUpdate and awaiting
//! UsdContext::StageEventStream::Pump.
ePythonExecEndUpdate = 100,
};
/*
* IApp.next_update_async() is the original model of python scripting kit, a preferred
* approach is either App.pre_update_async() and/or App.post_update_async(). Both can be used inside
* a single app tick, pseudo python code:
* While true:
* await omni.kit.app.get_app().pre_update_async()
* # Do a bunch of python scripting things before USD Update or hydra rendering is scheduled
* await omni.kit.app.get_app().post_update_async()
* # Do a bunch of python scripting things after USD Update & hydra rendering has been scheduled
*
* Alternatively use either just pre_update_async() or post_update_async() in python depending on whether you want your
* script to execute before USDUpdate or after.
*/
//! Ordering of events within a \ref omni::kit::RunLoop::postUpdate event loop.
//! \see updateorder
enum PostUpdateOrdering : int32_t
{
//! Release GPU resources held by previous frame.
eReleasePrevFrameGpuResources = -50,
//! asyncio.Future blocked awaiting (post update loop).
//!
//! 1. IApp.post_update_async (deprecates IApp.next_update_async).
ePythonAsyncFuturePostUpdate = -25,
//! Enables execution of all python blocked by \ref ePythonAsyncFuturePostUpdate.
ePythonExecPostUpdate = -10,
//! Default post-update order value.
eUnspecifiedPostUpdateOrder = carb::events::kDefaultOrder,
//! Kit App Factory Update.
eKitAppFactoryUpdate = eUnspecifiedPostUpdateOrder,
//! Kit App OS Update.
eKitAppOSUpdate = eUnspecifiedPostUpdateOrder,
//! Kit Internal Update.
eKitInternalUpdate = 100
};
#pragma push_macro("min")
#undef min
//! Ordering of events within a \ref omni::kit::RunLoop::postUpdate event loop.
//! \see updateorder
enum KitUsdStageEventOrdering : int32_t
{
//! USD File Operation Stage Event.
eKitUsdFileStageEvent = std::numeric_limits<carb::events::Order>::min() + 1,
//! Default File Stage event order.
eKitUnspecifiedUsdStageEventOrder = carb::events::kDefaultOrder,
};
#pragma pop_macro("min")
//! Ordering of USD Stage Update events during USD Context Update
//! \see eUsdContextUpdate, updateorder
enum IUsdStageEventOrdering : int32_t
{
eIUsdStageUpdateAnimationGraph = 0, //!< Hard-coded in separate non kit-sdk repro (gitlab)
eIUsdStageUpdatePinocchioPrePhysics = 8, //!< Hard-coded in separate non kit-sdk repro (gitlab)
eIUsdStageUpdateTensorPrePhysics = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateForceFieldsPrePhysics = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsVehicle = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsCCT = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsCameraPrePhysics = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysics = 10, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateFabricPostPhysics = 11, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateVehiclePostPhysics = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateForceFieldsPostPhysics = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsCameraPostPhysics = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsUI = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePinocchioPostPhysics = 13, //!< Hard-coded in separate non kit-sdk repro (gitlab)
eIUsdStageUpdateOmnigraph = 100, //!< Defined inside kit-sdk
eIUsdStageUpdatePhysxFC = 102, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateDebugDraw = 1000, //!< Defined inside kit-sdk
eIUsdStageUpdateLast = 2000 //!< Must always be last when all prior StageUpdate events have been handled
};
//! @}
} // namespace update
} // namespace kit
} // namespace omni
| 8,269 | C | 39.539215 | 120 | 0.723546 |
omniverse-code/kit/include/omni/kit/ITagging.h | // 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.
//
#pragma once
#include <carb/Interface.h>
#include <carb/events/IEvents.h>
namespace carb
{
namespace datasource
{
struct IDataSource;
struct Connection;
}
}
namespace omni
{
namespace kit
{
const carb::events::EventType kEventGetTagsFinished = CARB_EVENTS_TYPE_FROM_STR("GET_TAGS_FINISHED");
const carb::events::EventType kEventTagQueryFinished = CARB_EVENTS_TYPE_FROM_STR("TAG_QUERY_FINISHED");
const carb::events::EventType kEventModifyTagFinished = CARB_EVENTS_TYPE_FROM_STR("MODIFY_TAG_FINISHED");
const carb::events::EventType kEventTagServiceConnected = CARB_EVENTS_TYPE_FROM_STR("TAG_SERVICE_CONNECTED");
/**
* Defines a tagging interface to a running tagging server.
*/
struct ITagging
{
CARB_PLUGIN_INTERFACE("omni::kit::ITagging", 2, 0);
/**
* Check connection to tagging service.
*
* @return true if connected to tagging service.
*/
bool(CARB_ABI* isConnected)(const char* host_url);
/**
* Sends a list of urls as a single query to the tagging server. Results can be found by calling getTagsForUrl.
* When the request returns, an event of type kEventGetTagsFinished will be dispatched.
*
* @param urls An array of usd file urls sent to the tagging server.
* @param nUrls The number of urls.
*/
void(CARB_ABI* getTags)(const char** urls, const size_t nUrls);
/**
* Sends a url & query as a recursive query to the tagging server. The query is a tag that will be matched
* with all the usd files in the url. If url is a folder, then all files in that folder and subfolders will
* be checked by the tagging service. Results can be found by calling getTagsForUrl.
* When the request returns, an event of type kEventTagQueryFinished will be dispatched.
*
* @param query
* @param url
*/
void(CARB_ABI* queryTags)(const char* query, const char* url);
/**
* Returns the tags for the usd file at the given url. Use getTags or queryTags before calling this function.
*
* @param url to the usd file that may have tags.
* @param nTags the number of tags as an output
* @param filterExcluded true if we should compare system tags and remove excluded ones
* @param resourceBusy set to true if we are blocked by another thread. This prevents ui blocking.
* @return A list of tags as a pointer. This must be freed with clearTagsMemory()
*/
char**(CARB_ABI* getTagsForUrl)(const char* url, size_t& nTags, bool filterExcluded, bool* resourceBusy);
/**
* See if url has the query after a recursive or normal search.
*
* @param url to the usd file that may have tags.
* @param query The query we are searching for
* @param resourceBusy set to true if we are blocked by another thread. This prevents ui blocking.
* @return true if we have found the query at the given url
*/
bool(CARB_ABI* urlHasTag)(const char* url, const char* query, bool* resourceBusy);
/**
* Frees the memory allocated in getTagsForUrl.
*
* @param tags pointer to tags that should be freed.
* @param nTags the number of tags as an output
*/
void(CARB_ABI* clearTagsMemory)(char** tags, size_t nTags);
/**
* Adds the tag to the usd file at url.
* When the request returns, an event of type kEventModifyTagFinished will be dispatched.
*
* @param url to the usd file.
* @param tag to add.
*/
void(CARB_ABI* addTag)(const char* url, const char* tag);
/**
* Removes the old tag and adds the new one.
* When the request returns, an event of type kEventModifyTagFinished will be dispatched.
*
* @param url to the usd file.
* @param oldTag to remove.
* @param newTag to add.
*/
void(CARB_ABI* updateTag)(const char* url, const char* oldTag, const char* newTag);
/**
* Removes the tag from the usd file at url.
* When the request returns, an event of type kEventModifyTagFinished will be dispatched.
*
* @param url to the usd file.
* @param tag to remove.
*/
void(CARB_ABI* removeTag)(const char* url, const char* tag);
/**
* Returns the event stream for tagging events.
*
* @return carb event stream for tagging.
*/
carb::events::IEventStream*(CARB_ABI* getTagEventStream)();
/**
* Shuts down the plugin
*
*/
void(CARB_ABI* shutdown)();
};
}
}
| 4,863 | C | 33.742857 | 115 | 0.680855 |
omniverse-code/kit/include/omni/kit/ExtensionWindowTypes.h | // 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.
//
#pragma once
namespace omni
{
namespace kit
{
struct _ExtensionWindow;
using ExtensionWindowHandle = _ExtensionWindow*;
}
}
| 565 | C | 28.789472 | 77 | 0.79115 |
omniverse-code/kit/include/omni/kit/IApp.h | // Copyright (c) 2020-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.
//
//! @file
//! @brief omni.kit.app interface definition file
#pragma once
#include "../../carb/Interface.h"
#include "../../carb/events/EventsUtils.h"
#include "../../carb/events/IEvents.h"
#include "../../carb/extras/Timer.h"
#include "../../carb/profiler/Profile.h"
#include "../String.h"
namespace omni
{
namespace ext
{
class ExtensionManager;
}
//! Namespace for kit
namespace kit
{
class IRunLoopRunner;
//! \defgroup appstruct IApp structs
//! @{
/**
* Application descriptor.
* @see IApp::startup()
*/
struct AppDesc
{
const char* carbAppName; //!< Carb application name. If `nullptr` it is derived from the executable filename.
const char* carbAppPath; //!< Carb application path. If `nullptr` it is derived from the executable folder.
int argc; //!< Number of values in `argv`
char** argv; //!< Array of arguments
};
/**
* Build information.
* @see IApp::getBuildInfo()
*/
struct BuildInfo
{
omni::string kitVersion; //!< Full kit version, e.g. `103.5+release.7032.aac30830.tc.windows-x86_64.release'
omni::string kitVersionShort; //!< Short kit version, `major.minor` e.g. `103.5`
omni::string kitVersionHash; //!< Git hash of kit build, 8 letters, e.g. `aac30830`
//! Full kernel version, e.g. `103.5+release.7032.aac30830.tc.windows-x86_64.release'
//! Note that this may be different than `kitVersion`
omni::string kernelVersion;
};
/**
* Platform information.
* @see IApp::getPlatformInfo()
*/
struct PlatformInfo
{
const char* config; //!< Build configuration e.g. "debug", "release"
//! Platform descriptor e.g. "windows-x86_64", "linux-x86_64", "linux-aarch64", "macos-universal"
const char* platform;
const char* pythonVersion; //!< Python version e.g. "cp37" for Python 3.7, "cp310" for Python 3.10
};
/**
* App information.
* @see IApp::getAppInfo(), AppDesc
*/
struct AppInfo
{
omni::string filename; //!< App filename. Name of a kit file or just 'kit'
omni::string name; //!< App name. It is app/name setting if defined, otherwise same as `filename`
omni::string version; //!< App version. Version in kit file or kit version
omni::string versionShort; //!< Short app version, currently major.minor, e.g. `2021.3`
//! Environment the application is running in, from `/app/environment/name` setting
//! e.g. "teamcity", "launcher", "etm", "default", etc.
omni::string environment;
bool isExternal; //!< Is external (public) configuration
};
/**
* Run Loop.
*
* A Run Loop is a collection of event streams that are pumped in order for each Run Loop iteration.
* @see IApp::getRunLoop(), carb::events::IEventStream, carb::events::IEvents
*/
class RunLoop
{
public:
carb::events::IEventStream* preUpdate; //!< Pre update events pushed every loop and stream is pumped.
carb::events::IEventStream* update; //!< Update events pushed every loop and stream is pumped.
carb::events::IEventStream* postUpdate; //!< Post update events pushed every loop and stream is pumped.
//! Stream for extensions to push events to, pumped every loop after postUpdate.
carb::events::IEventStream* messageBus;
};
//! @}
/**
* How to handle passed arguments when restarting an app.
* @see IApp::restart()
*/
enum class RestartArgsPolicy
{
eAppend, //!< Append to existing args
eReplace, //!< Replace existing args
};
// Few predefined run loop names. Serve as hints, doesn't have to use only those.
//! \defgroup apprunloop Run Loop Names
//! @{
//! Predefined Run Loop name
//!
//! Predefined names serve as hints for Run Loops but other names may also exist
constexpr char kRunLoopDefault[] = "main";
//! @copydoc kRunLoopDefault
constexpr char kRunLoopSimulation[] = "simulation";
//! @copydoc kRunLoopDefault
constexpr char kRunLoopRendering[] = "rendering";
//! @copydoc kRunLoopDefault
constexpr char kRunLoopUi[] = "ui";
//! @}
class IAppScripting;
//! \defgroup appevents App Events
//! @{
// App shutdown events pumped into IApp::getShutdownEventStream():
//! A shutdown event that is pushed during the next update after postQuit is called.
//!
//! Once \ref IApp::postQuit() is called, the next \ref IApp::update() call will check for shutdown requests and start
//! the shutdown sequence. The first step of this sequence is that this event (`kPostQuitEventType`) is dispatched
//! synchronously to the shutdown event stream (\ref IApp::getShutdownEventStream()) and the stream is pumped
//! immediately. During this event, any calls to \ref IApp::tryCancelShutdown() will abort this process (unless the
//! posted quit request is noncancellable). If no attempt to cancel the shutdown has been made,
//! \ref kPreShutdownEventType will be dispatched.
//! @see IApp::getShutdownEventStream(), IApp::postQuit(), IApp::tryCancelShutdown(), IApp::postUncancellableQuit()
//! \par Event Arguments
//! * "uncancellable" - boolean value indicating whether the requested type was noncancellable (`true`) or not
constexpr const carb::events::EventType kPostQuitEventType = 0;
//! A shutdown event that is pushed to indicate the start of shutdown
//! @see kPostQuitEventType, IApp::getShutdownEventStream(), IApp::postQuit(), IApp::tryCancelShutdown(),
//! IApp::postUncancellableQuit()
//! \par Event Arguments
//! * None
constexpr const carb::events::EventType kPreShutdownEventType = 1;
//! An event that is dispatched at app startup time.
//!
//! This event is dispatched to the stream returned by \ref IApp::getStartupEventStream() (and the stream is pumped)
//! immediately before \ref IApp::startup() returns.
//! \par Event Arguments
//! * None
const carb::events::EventType kEventAppStarted = CARB_EVENTS_TYPE_FROM_STR("APP_STARTED");
//! An event that is dispatched when the application becomes ready.
//!
//! After application startup (see \ref kEventAppStarted), every call to \ref IApp::update() after the first call will
//! check for readiness. Readiness can be delayed with \ref IApp::delayAppReady() which must be called during each main
//! run loop iteration to prevent readiness. Once a run loop completes with no calls to \ref IApp::delayAppReady() the
//! application is considered "ready" and this event is dispatched.
//! \par Event Arguments
//! * None
const carb::events::EventType kEventAppReady = CARB_EVENTS_TYPE_FROM_STR("APP_READY");
//! @}
/**
* Main Kit Application plugin.
*
* It runs all Kit extensions and contains necessary pieces to make them work together: settings, events, python, update
* loop. Generally an application will bootstrap *omni.kit.app* by doing the following steps:
* 1. Initialize the Carbonite \ref carb::Framework
* 2. Load the *omni.kit.app* plugin with \ref carb::Framework::loadPlugin()
* 3. Call \ref IApp::run() which will not return until the application shuts down
* 4. Shut down the Carbonite \ref carb::Framework
*
* The *kit* executable is provided by Carbonite for this purpose. It is a thin bootstrap executable around starting
* *omni.kit.app*.
*
* This interface can be acquired from Carbonite with \ref carb::Framework::acquireInterface().
*/
class IApp
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IApp", 1, 3);
//////////// main API ////////////
/**
* Starts up the application.
* @note Typically this function is not called directly. Instead use \ref run().
* @param desc the \ref AppDesc that describes the application
*/
virtual void startup(const AppDesc& desc) = 0;
/**
* Performs one application update loop.
* @note Typically this function is not called directly. Instead use \ref run().
*/
virtual void update() = 0;
/**
* Checks whether the application is still running.
* @retval true The application is still running
* @retval false The application has requested to quit and has shut down
*/
virtual bool isRunning() = 0;
/**
* Shuts down the application.
*
* This function should be called once \ref isRunning() returns false.
* @returns The application exit code (0 indicates success)
*/
virtual int shutdown() = 0;
/**
* A helper function that starts, continually updates, and shuts down the application.
*
* This function essentially performs:
* ```cpp
* startup(desc);
* while (isRunning())
* update();
* return shutdown()
* ```
* @see startup(), isRunning(), update(), shutdown()
* @param desc the \ref AppDesc that describes the application
* @returns The application exit code (0 indicates success)
*/
int run(const AppDesc& desc);
//////////// extensions API ////////////
/**
* Requests application exit.
*
* @note This does not immediately exit the application. The next call to \ref update() will evaluate the shutdown
* process.
* @note This shutdown request is cancellable by calling \ref tryCancelShutdown().
* @see kPostQuitEventType, postUncancellableQuit()
* @param returnCode The requested return code that will be returned by \ref shutdown() once the application exits.
*/
virtual void postQuit(int returnCode = 0) = 0;
/**
* Access the log event stream.
*
* Accesses a \ref carb::events::IEventStream that receives every "error" (or higher) message.
* \par Event Arguments
* * Event ID is always 0
* * "source" - The log source, typically plugin name (string)
* * "level" - The \ref loglevel (integer)
* * "filename" - The source file name, such as by `__FILE__` (string)
* * "lineNumber" - The line in the source file, such as by `__LINE__` (integer)
* * "functionName" - The name of the function doing the logging, such as by \ref CARB_PRETTY_FUNCTION (string)
* * "message" - The log message
* @returns a \ref carb::events::IEventStream that receives every error (or higher) log message
* @see carb::events::IEventStream, carb::events::IEvents
*/
virtual carb::events::IEventStream* getLogEventStream() = 0;
/**
* Replays recorded log messages for the specified target.
*
* This function will call \ref carb::logging::Logger::handleMessage() for each log message that has been retained.
* @param target The \ref carb::logging::Logger instance to replay messages for
*/
virtual void replayLogMessages(carb::logging::Logger* target) = 0;
/**
* Toggles log message recording.
*
* By default, \ref startup() enables log message recording. Recorded log messages can be replayed on a
* \ref carb::logging::Logger with \ref replayLogMessages().
*
* @param logMessageRecordingEnabled if `true`, future log messages are recorded; if `false` the log messages are
* not recorded
*/
virtual void toggleLogMessageRecording(bool logMessageRecordingEnabled) = 0;
/**
* Access and/or creates a Run Loop by name.
*
* @param name The Run Loop to create or find; `nullptr` is interpreted as \ref kRunLoopDefault
* @returns the specified \ref RunLoop instance
*/
virtual RunLoop* getRunLoop(const char* name) = 0;
/**
* Tests whether the specified run loop exists.
* @param name The Run Loop to find; `nullptr` is interpreted as \ref kRunLoopDefault
* @retval true The specified \p name has a valid \ref RunLoop
* @retval false The specified \p name does not have a valid \ref RunLoop
*/
virtual bool isRunLoopAlive(const char* name) = 0;
/**
* Requests the run loop to terminate
*
* @note This calls \ref IRunLoopRunner::onRemoveRunLoop() but the \ref RunLoop itself is not actually removed.
* @param name The Run Loop to find; `nullptr` is interpreted as \ref kRunLoopDefault
* @param block Passed to \ref IRunLoopRunner::onRemoveRunLoop()
*/
virtual void terminateRunLoop(const char* name, bool block) = 0;
/**
* Helper function to access a Run Loop event stream.
* @see RunLoop
* @param runLoopName The name of the Run Loop; `nullptr` is interpreted as \ref kRunLoopDefault
* @returns A \ref carb::events::IEventStream instance
*/
carb::events::IEventStream* getPreUpdateEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->preUpdate;
}
//! @copydoc getPreUpdateEventStream()
carb::events::IEventStream* getUpdateEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->update;
}
//! @copydoc getPreUpdateEventStream()
carb::events::IEventStream* getPostUpdateEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->postUpdate;
}
//! @copydoc getPreUpdateEventStream()
carb::events::IEventStream* getMessageBusEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->messageBus;
}
/**
* Set particular Run Loop runner implementation. This function must be called only once during app startup. If
* no `IRunLoopRunner` was set application will quit. If `IRunLoopRunner` is set it becomes responsible for spinning
* run loops. Application will call in functions on `IRunLoopRunner` interface to communicate the intent.
*/
/**
* Sets the current Run Loop Runner instance
*
* @note The \ref IRunLoopRunner instance is retained by `*this` until destruction when the plugin is unloaded. To
* un-set the \ref IRunLoopRunner instance, call this function with `nullptr`.
*
* @see RunLoop, IRunLoopRunner
* @param runner The \ref IRunLoopRunner instance that will receive notifications about Run Loop events; `nullptr`
* to un-set the \ref IRunLoopRunner instance.
*/
virtual void setRunLoopRunner(IRunLoopRunner* runner) = 0;
/**
* Accesses the Extension Manager.
* @returns a pointer to the \ref omni::ext::ExtensionManager instance
*/
virtual omni::ext::ExtensionManager* getExtensionManager() = 0;
/**
* Accesses the Application Scripting Interface.
* @returns a pointer to the \ref IAppScripting instance
*/
virtual IAppScripting* getPythonScripting() = 0;
/**
* Access the build version string.
*
* This is effectively `getBuildInfo().kitVersion.c_str()`.
* @see getBuildInfo(), BuildInfo
* @returns The build version string
*/
virtual const char* getBuildVersion() = 0;
/**
* Reports whether the application is running 'debug' configuration.
*
* @note This is based on whether the plugin exporting the \ref IApp interface (typically *omni.kit.app.plugin*)
* that is currently running was built as a debug configuration.
*
* A debug configuration is one where \ref CARB_DEBUG was non-zero at compile time.
*
* @retval true \ref CARB_DEBUG was non-zero at compile-time
* @retval false \ref CARB_DEBUG was zero at compile-time (release build)
*/
virtual bool isDebugBuild() = 0;
/**
* Retrieves information about the currently running platform.
* @returns a @ref PlatformInfo struct describing the currently running platform.
*/
virtual PlatformInfo getPlatformInfo() = 0;
/**
* Returns the time elapsed since startup.
*
* This function returns the fractional time that has elapsed since \ref startup() was called, in the requested
* scale units.
* @param timeScale Desired time scale for the returned time interval (seconds, milliseconds, etc.)
* @return time passed since \ref startup() was most recently called
*/
virtual double getTimeSinceStart(carb::extras::Timer::Scale timeScale = carb::extras::Timer::Scale::eMilliseconds) = 0;
/**
* Returns the time elapsed since update.
*
* This function returns the fractional time that has elapsed since \ref update() was called (or if \ref update()
* has not yet been called, since \ref startup() was called), in milliseconds.
* @return time passed since \ref update() or \ref startup() (whichever is lower) in milliseconds
*/
virtual double getLastUpdateTime() = 0;
/**
* Returns the current update number.
*
* This value is initialized to zero at \ref startup(). Every time the \ref kRunLoopDefault \ref RunLoop::postUpdate
* \ref carb::events::IEventStream is pumped, this value is incremented by one.
* @returns the current update number (number of times that the \ref kRunLoopDefault \ref RunLoop has updated)
*/
virtual uint32_t getUpdateNumber() = 0;
/**
* Formats and prints a log message.
*
* The given log \p message is prepended with the time since start (as via \ref getTimeSinceStart()) and first sent
* to `CARB_LOG_INFO()`, and then outputted to `stdout` if `/app/enableStdoutOutput` is true (defaults to true).
* @param message The message to log and print to `stdout`
*/
virtual void printAndLog(const char* message) = 0;
/**
* Accesses the shutdown event stream.
* @see carb::events::IEvents, kPostQuitEventType, kPreShutdownEventType
* @returns The \ref carb::events::IEventStream that contains shutdown events
*/
virtual carb::events::IEventStream* getShutdownEventStream() = 0;
/**
* Attempts to cancel a shutdown in progress.
* @param reason The reason to interrupt shutdown; `nullptr` is interpreted as an empty string
* @retval true The shutdown process was interrupted successfully
* @retval false A noncancellable shutdown is in progress and cannot be interrupted
*/
virtual bool tryCancelShutdown(const char* reason) = 0;
/**
* Requests application exit that cannot be cancelled.
*
* @note This does not immediately exit the application. The next call to \ref update() will evaluate the shutdown
* process.
* @note This shutdown request is **not** cancellable by calling \ref tryCancelShutdown().
* @see kPostQuitEventType, postQuit()
* @param returnCode The requested return code that will be returned by \ref shutdown() once the application exits.
*/
virtual void postUncancellableQuit(int returnCode) = 0;
/**
* Accesses the startup event stream.
* @see carb::events::IEvents, kEventAppStarted, kEventAppReady
* @returns The \ref carb::events::IEventStream that contains startup events
*/
virtual carb::events::IEventStream* getStartupEventStream() = 0;
/**
* Checks whether the app is in a ready state.
* @retval true The app is in a ready state; \ref kEventAppReady has been previously dispatched
* @retval false The app is not yet ready
*/
virtual bool isAppReady() = 0;
/**
* Instructs the app to delay setting the ready state.
*
* @note This function is only useful prior to achieving the ready state. Calling it after \ref isAppReady() reports
* `true` has no effect.
*
* Every \ref update() call resets the delay request; therefore to continue delaying the ready state this function
* must be called during every update cycle.
* @param requesterName (required) The requester who is delaying the ready state, used for logging
*/
virtual void delayAppReady(const char* requesterName) = 0;
/**
* Access information about how the plugin was built.
* @returns A reference to \ref BuildInfo describing version and hash information
*/
virtual const BuildInfo& getBuildInfo() = 0;
/**
* Access information about the running application.
* @returns A reference to \ref AppInfo describing how the application was started and configured
*/
virtual const AppInfo& getAppInfo() = 0;
/**
* Restarts the application.
*
* Quits the current process and starts a new process. The command line arguments can be inherited, appended or
* replaced.
*
* To quit a regular \ref postQuit() is used, unless \p uncancellable is set to `true` in which case
* \ref postUncancellableQuit() is called.
*
* @param args Array of command line arguments for a new process; may be `nullptr`
* @param argCount Number of command line arguments in \p args
* @param argsPolicy A \ref RestartArgsPolicy value that controls replacing existing args with \p args, or appending
* \p args to the existing args
* @param uncancellable If `true` \ref postUncancellableQuit() is used to quit the current process; `false` will
* instead of postQuit().
*/
virtual void restart(const char* const* args = nullptr,
size_t argCount = 0,
RestartArgsPolicy argsPolicy = RestartArgsPolicy::eAppend,
bool uncancellable = false) = 0;
};
//! \addtogroup appevents
//! @{
// TODO(anov): switch back to using string hash when fix for IEventStream.push binding is merged in from Carbonite.
//! An event that is pushed when a scripting command is issued.
//!
//! This event is pushed to \ref IAppScripting::getEventStream().
//! @see carb::events::IEventStream, carb::events::IEvents, IAppScripting::executeString(),
//! IAppScripting::executeFile(), IAppScripting::getEventStream()
//! \par Event Arguments
//! * "text" - A human-readable text block (string)
const carb::events::EventType kScriptingEventCommand = 0; // CARB_EVENTS_TYPE_FROM_STR("SCRIPT_COMMAND");
//! \copydoc kScriptingEventCommand
//! \brief An event that is pushed when python prints to stdout
const carb::events::EventType kScriptingEventStdOut = 1; // CARB_EVENTS_TYPE_FROM_STR("SCRIPT_STDOUT");
//! \copydoc kScriptingEventCommand
//! \brief An event that is pushed when python prints to stderr
const carb::events::EventType kScriptingEventStdErr = 2; // CARB_EVENTS_TYPE_FROM_STR("SCRIPT_STDERR");
//! @}
/**
* Scripting Engine interface.
*/
class IAppScripting
{
public:
/**
* Run script from a string.
*
* A \ref kScriptingEventCommand event is always dispatched before executing the script.
* @param str Content of the script to execute
* @param commandName (optional) A command name that will logged for multi-line scripts
* @param executeAsFile If `true`, \p str is first written to a temporary file which is then executed. The file is
* not removed which allows inspecting the script at a later point.
* @retval true if execution was successful
* @retval false if an error occurs (\ref kScriptingEventStdErr was dispatched with the error message)
*/
virtual bool executeString(const char* str, const char* commandName = nullptr, bool executeAsFile = false) = 0;
/**
* Run script from a file.
*
* A \ref kScriptingEventCommand event is always dispatched before executing the script.
* @param path The path to the script file. May be a file name that exists in folders that have been added to the
* search path with \ref addSearchScriptFolder(). A ".py" suffix is optional.
* @param args An optional array of string arguments to pass to the script file
* @param argCount The number of arguments in the \p args array
* @retval true if execution was successful
* @retval false if the file was not found (an error is logged), or the script could not be loaded (an error is
* logged), or execution failed (\ref kScriptingEventStdErr was dispatched with the error message)
*/
virtual bool executeFile(const char* path, const char* const* args, size_t argCount) = 0;
/**
* Adds a folder path that will be searched for scripts.
*
* Calls to \ref executeFile() will search the paths added in the order that they were added.
* @see removeSearchScriptFolder()
* @note If the given \p path does not exist it will be created.
* @param path A relative or absolute path. If the path does not exist it will be created.
* @retval true The given \p path was added to the list of search paths
* @retval false The given \p path already exists in the list of search paths
*/
virtual bool addSearchScriptFolder(const char* path) = 0;
/**
* Removes a folder from the list of folders that will be searched for scripts.
*
* @see addSearchScriptFolder()
* @param path A relative or absolute path which was previously passed to \ref addSearchScriptFolder()
* @retval true The given \p path was found and removed from the list of script search folders
* @retval false The given \p path was not found in the list of script search folders
*/
virtual bool removeSearchScriptFolder(const char* path) = 0;
/**
* Access the scripting event stream.
* @see kScriptingEventCommand, kScriptingEventStdOut, kScriptingEventStdErr
* @returns a \ref carb::events::IEventStream that receives scripting events
*/
virtual carb::events::IEventStream* getEventStream() = 0;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline Functions //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline int IApp::run(const AppDesc& desc)
{
this->startup(desc);
while (this->isRunning())
{
this->update();
}
return this->shutdown();
}
} // namespace kit
} // namespace omni
| 26,025 | C | 39.665625 | 123 | 0.679039 |
omniverse-code/kit/include/omni/kit/IRunLoopRunner.h | // Copyright (c) 2020-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.
//
//! @file
//! @brief Interface definition for IRunLoopRunner for *omni.kit.app*
#pragma once
#include "../../carb/IObject.h"
#include "../../carb/Interface.h"
namespace omni
{
namespace kit
{
class RunLoop;
/**
* Interface to implement by custom run loop runners.
*
* \ref IApp calls the functions on this interface if one was set with \ref IApp::setRunLoopRunner().
*/
class IRunLoopRunner : public carb::IObject
{
public:
/**
* Called once before starting application update.
*
* This is called by \ref IApp::startup(), and is called **after** the initial Run Loop notifications are given via
* \ref onAddRunLoop().
* @warning This function is **not** called by \ref IApp::setRunLoopRunner().
*/
virtual void startup() = 0;
/**
* Called each time a new run loop is created.
*
* This function can be called both prior to startup() (by \ref IApp::startup()), and whenever a new Run Loop is
* created by \ref IApp::getRunLoop().
*
* @thread_safety May be called from different threads simultaneously.
* @param name The run loop name; will not be `nullptr`
* @param loop The \ref RunLoop instance being added
*/
virtual void onAddRunLoop(const char* name, RunLoop* loop) = 0;
/**
* Called when IApp wants to remove a run loop.
*
* @param name The name of the run loop; will not be `nullptr`
* @param loop The \ref RunLoop instance, owned by \ref IApp
* @param block if `true`, this function should not return until the Run Loop has completed
*/
virtual void onRemoveRunLoop(const char* name, RunLoop* loop, bool block) = 0;
/**
* Called by each application update.
*
* Called by \ref IApp::update() before any work is done.
*/
virtual void update() = 0;
/**
* Called to notify of shut down.
* @warning This function is only called on the previous instance when \ref IApp::setRunLoopRunner() is called to
* switch to a different \ref IRunLoopRunner instance (or `nullptr`).
*/
virtual void shutdown() = 0;
};
//! RAII pointer type for \ref IRunLoopRunner
using IRunLoopRunnerPtr = carb::ObjectPtr<IRunLoopRunner>;
} // namespace kit
} // namespace omni
| 2,693 | C | 31.071428 | 119 | 0.67954 |
omniverse-code/kit/include/omni/kit/PythonInterOpHelper.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/kit/IApp.h>
#include <sstream>
namespace omni
{
namespace kit
{
/**
* Defines a helper class to build and run python command from C++.
* This class serves as a temporary solution before we can move editor completely into Python.
* Do not rely on it.
*/
class PythonInterOpHelper
{
public:
static void executeCommand(const char* command)
{
carb::getCachedInterface<omni::kit::IApp>()->getPythonScripting()->executeString(command);
}
static inline const char* pyBool(const bool value)
{
return (value ? "True" : "False");
}
template <typename T>
static inline std::ostream& addArgument(std::ostream& strm, const T& value)
{
strm << value;
return strm;
}
static inline std::ostream& addArgument(std::ostream& strm, const bool value)
{
strm << pyBool(value);
return strm;
}
template <typename T> static inline std::ostream&
addNamedArgument(std::ostream& strm, const char* name, const T& value)
{
strm << name << " = ";
return addArgument(strm, value);
}
#if defined(PXR_USD_USD_TIME_CODE_H)
static inline std::ostream& addArgument(std::ostream& strm, const pxr::UsdTimeCode& value)
{
strm << "Usd.TimeCode";
if (value == pxr::UsdTimeCode::Default())
strm << ".Default()";
else
strm << '(' << value.GetValue() << ')';
return strm;
}
template <typename T>
static inline std::ostream& addArrayArgument(std::ostream& strm, const char* pyType, const T* values, size_t N)
{
static_assert(std::is_same<double, T>::value || std::is_same<float, T>::value || std::is_same<int, T>::value, "Unsupported array type");
constexpr char typeMode = std::is_same<double, T>::value ? 'd' : (std::is_same<float, T>::value ? 'f' : 'i');
strm << pyType << typeMode << "(";
for (unsigned i = 0; i < (N-1); ++i)
{
strm << values[i] << ", ";
}
strm << values[N - 1] << ')';
return strm;
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfVec3i& value)
{
return addArrayArgument(strm , "Gf.Vec3", value.data(), 3);
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfVec3f& value)
{
return addArrayArgument(strm, "Gf.Vec3", value.data(), 3);
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfVec3d& value)
{
return addArrayArgument(strm, "Gf.Vec3", value.data(), 3);
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfMatrix4d& value)
{
return addArrayArgument(strm, "Gf.Matrix4", value.data(), 16);
}
static void runTransformPrimCommand(const std::string& path,
const pxr::GfMatrix4d& o,
const pxr::GfMatrix4d& n,
pxr::UsdTimeCode time_code = pxr::UsdTimeCode::Default(),
bool had_transform_at_key = false)
{
// Inject python command for undo/redo
std::ostringstream command;
command <<
"import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimCommand', path='" << path << "', ";
addNamedArgument(command, "old_transform_matrix", o) << ", ";
addNamedArgument(command, "new_transform_matrix", n) << ", ";
addNamedArgument(command, "time_code", time_code) << ", ";
addNamedArgument(command, "had_transform_at_key", had_transform_at_key) << ")\n";
executeCommand(command.str().c_str());
}
static void runTransformPrimSRTCommand(const std::string& path,
const pxr::GfVec3d o_t,
const pxr::GfVec3d o_re,
const pxr::GfVec3i o_ro,
const pxr::GfVec3d o_s,
const pxr::GfVec3d n_t,
const pxr::GfVec3d n_re,
const pxr::GfVec3i n_ro,
const pxr::GfVec3d n_s,
pxr::UsdTimeCode time_code = pxr::UsdTimeCode::Default(),
bool had_transform_at_key = false)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimSRTCommand', path='" << path << "', ";
addNamedArgument(command, "old_translation", o_t) << ", ";
addNamedArgument(command, "old_rotation_euler", o_re) << ", ";
addNamedArgument(command, "old_rotation_order", o_ro) << ", ";
addNamedArgument(command, "old_scale", o_s) << ", ";
addNamedArgument(command, "new_translation", n_t) << ", ";
addNamedArgument(command, "new_rotation_euler", n_re) << ", ";
addNamedArgument(command, "new_rotation_order", n_ro) << ", ";
addNamedArgument(command, "new_scale", n_s) << ", ";
addNamedArgument(command, "time_code", time_code) << ", ";
addNamedArgument(command, "had_transform_at_key", had_transform_at_key) << ")\n";
executeCommand(command.str().c_str());
}
struct TransformPrimsEntry
{
std::string path;
pxr::GfMatrix4d newTransform;
pxr::GfMatrix4d oldTransform;
bool hadTransformAtTime;
};
static void runTransformPrimsCommand(const std::vector<TransformPrimsEntry>& primsToTransform,
pxr::UsdTimeCode time_code)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimsCommand', prims_to_transform=[\n";
char separator = ' ';
for (auto& entry : primsToTransform)
{
command << separator << "('" << entry.path << "', ";
addArgument(command, entry.newTransform) << ", ";
addArgument(command, entry.oldTransform) << ", ";
addArgument(command, time_code) << ", ";
addArgument(command, entry.hadTransformAtTime) << ")\n";
separator = ',';
}
command << "])\n";
executeCommand(command.str().c_str());
}
struct TransformPrimsSRTEntry
{
std::string path;
pxr::GfVec3d newTranslation;
pxr::GfVec3d newRotationEuler;
pxr::GfVec3i newRotationOrder;
pxr::GfVec3d newScale;
pxr::GfVec3d oldTranslation;
pxr::GfVec3d oldRotationEuler;
pxr::GfVec3i oldRotationOrder;
pxr::GfVec3d oldScale;
bool hadTransformAtTime;
};
static void runTransformPrimsSRTCommand(const std::vector<TransformPrimsSRTEntry>& primsToTransform,
pxr::UsdTimeCode time_code)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimsSRTCommand', prims_to_transform=[\n";
char separator = ' ';
for (auto& entry : primsToTransform)
{
command << separator << "('" << entry.path << "', ";
addArgument(command, entry.newTranslation) << ", ";
addArgument(command, entry.newRotationEuler) << ", ";
addArgument(command, entry.newRotationOrder) << ", ";
addArgument(command, entry.newScale) << ", ";
addArgument(command, entry.oldTranslation) << ", ";
addArgument(command, entry.oldRotationEuler) << ", ";
addArgument(command, entry.oldRotationOrder) << ", ";
addArgument(command, entry.oldScale) << ", ";
addArgument(command, time_code) << ", ";
addArgument(command, entry.hadTransformAtTime) << ")\n";
separator = ',';
}
command << "])\n";
executeCommand(command.str().c_str());
}
template <typename StrT>
static std::string serializePrimPaths(StrT* paths, size_t count)
{
std::ostringstream out;
for (size_t i = 0; i < count; i++)
{
out << "'" << paths[i] << "'";
if (i != count - 1)
{
out << ",";
}
}
return out.str();
}
static void runSetSelectedPrimsCommand(const std::string& oldPaths, const std::string& newPaths, bool expandInStage)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('SelectPrimsCommand'"
<< ", old_selected_paths=[" << oldPaths << "]"
<< ", new_selected_paths=[" << newPaths << "]"
<< ", expand_in_stage=" << pyBool(expandInStage)
<< ")\n";
executeCommand(command.str().c_str());
}
static void runMovePrimCommand(const std::string& pathFrom, const std::string& pathTo, bool keepWorldTransfrom)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('MovePrimCommand', path_from='"
<< pathFrom << "', path_to='" << pathTo << "', keep_world_transform=" << pyBool(keepWorldTransfrom)
<< ")\n";
executeCommand(command.str().c_str());
}
static void runMovePrimsCommand(const std::vector<std::pair<pxr::SdfPath, pxr::SdfPath>>& pathsToMove,
bool keepWorldTransfrom)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('MovePrimsCommand', paths_to_move={";
for (auto& entry : pathsToMove)
{
command << "'" << entry.first << "' : '" << entry.second << "',";
}
command.seekp(-1, std::ios_base::end);
command << "}, keep_world_transform=" << pyBool(keepWorldTransfrom) << ")\n";
executeCommand(command.str().c_str());
}
static void runCopyPrimCommand(const char* srcPath, const char* tarPath, bool dupLayers, bool combineLayers)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('CopyPrimCommand', path_from='"
<< srcPath << "', path_to=" << (tarPath ? std::string("'") + tarPath + "'" : "None")
<< ", duplicate_layers=" << pyBool(dupLayers)
<< ", combine_layers=" << pyBool(combineLayers) << ")\n";
executeCommand(command.str().c_str());
}
static void runOpenStageCommand(const std::string& path)
{
std::ostringstream command;
command << "import omni.kit.window.file\n"
"omni.kit.window.file.open_stage('"
<< path << "')\n";
executeCommand(command.str().c_str());
}
// Open stage as a edit layer, that it will be a sublayer of an empty stage
// with a edit layer above this sublayer to make edits in.
static void runOpenStageAsEditLayerCommand(const std::string& path)
{
std::ostringstream command;
command << "import omni.kit.window.file\n"
"omni.kit.window.file.open_with_new_edit_layer('"
<< path << "')\n";
executeCommand(command.str().c_str());
}
static void runCreateReferenceCommand(const std::string& url, const std::string& pathTo, bool instanceable)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "import omni.usd\n"
<< "omni.kit.commands.execute('CreateReferenceCommand', usd_context=omni.usd.get_context(), path_to='"
<< pathTo << "', asset_path='" << url << "',"
<< "instanceable=" << pyBool(instanceable) << ")\n";
executeCommand(command.str().c_str());
}
static void runCreatePayloadCommand(const std::string& url, const std::string& pathTo, bool instanceable)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "import omni.usd\n"
<< "omni.kit.commands.execute('CreatePayloadCommand', usd_context=omni.usd.get_context(), path_to='"
<< pathTo << "', asset_path='" << url << "',"
<< "instanceable=" << pyBool(instanceable) << ")\n";
executeCommand(command.str().c_str());
}
static void runCreateAudioPrimFromAssetPathCommand(const std::string& url, const std::string& pathTo)
{
std::ostringstream command;
command
<< "import omni.kit.commands\n"
<< "import omni.usd\n"
<< "omni.kit.commands.execute('CreateAudioPrimFromAssetPathCommand', usd_context=omni.usd.get_context(), path_to='"
<< pathTo << "', asset_path='" << url << "')\n";
executeCommand(command.str().c_str());
}
static void runCreatePrimCommand(const char* primPath,
const char* primType,
const bool selectNewPrim,
const char* usdContextName = "")
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "omni.kit.commands.execute('CreatePrimCommand', prim_path='" << primPath << "', prim_type='"
<< primType << "', select_new_prim=" << pyBool(selectNewPrim) << ", context_name='"
<< usdContextName << "' )\n";
executeCommand(command.str().c_str());
}
static void runCreateMdlMaterialPrimCommand(const std::string& mdlUrl,
const std::string& mtlName,
const std::string& mdlPrimPath,
const std::string& targetPrimPath = "$$$")
{
std::ostringstream command;
// targetPrimPath "" is valid param, use "$$$" for no parameter passed
if (targetPrimPath.compare("$$$") == 0)
{
command << "import omni.kit.commands\n"
<< "omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url='" << mdlUrl
<< "', mtl_name='" << mtlName << "', mtl_path='" << mdlPrimPath << "', select_new_prim=False)\n";
}
else
{
command << "import asyncio\n"
<< "import omni.kit.commands\n"
<< "import omni.kit.material.library\n"
<< "import carb\n"
<< "async def create_material(prim_path):\n"
<< " def have_subids(subids):\n"
<< " if len(subids) > 1:\n"
<< " omni.kit.material.library.custom_material_dialog(mdl_path='" << mdlUrl
<< "', bind_prim_paths=[prim_path])\n"
<< " return\n";
if (targetPrimPath.empty())
{
command << " omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url='" << mdlUrl
<< "', mtl_name='" << mtlName << "', mtl_path='" << mdlPrimPath << "', select_new_prim=True)\n";
command << " await omni.kit.material.library.get_subidentifier_from_mdl('" << mdlUrl
<< "', on_complete_fn=have_subids)\n";
command << "asyncio.ensure_future(create_material(None))\n";
}
else
{
command
<< " with omni.kit.undo.group():\n"
<< " omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url='" << mdlUrl
<< "', mtl_name='" << mtlName << "', mtl_path='" << mdlPrimPath << "', select_new_prim=False)\n"
<< " omni.kit.commands.execute('BindMaterialCommand', prim_path = prim_path, material_path = '"
<< mdlPrimPath << "', strength = None )\n";
command << " await omni.kit.material.library.get_subidentifier_from_mdl('" << mdlUrl
<< "', on_complete_fn=have_subids)\n";
command << "omni.kit.material.library.multi_descendents_dialog(prim_paths=['" << targetPrimPath
<< "'], on_click_fn=lambda p: asyncio.ensure_future(create_material(prim_path=p)))\n";
}
}
executeCommand(command.str().c_str());
}
static void beginUndoGroup()
{
static constexpr char kCmd[] =
"import omni.kit.undo\n"
"omni.kit.undo.begin_group()";
executeCommand(kCmd);
}
static void endUndoGroup()
{
static constexpr char kCmd[] =
"import omni.kit.undo\n"
"omni.kit.undo.end_group()";
executeCommand(kCmd);
}
static void popLastUndoGroup()
{
static constexpr char kCmd[] =
"import omni.kit.undo\n"
"keep_going = True\n"
"undo_stack = omni.kit.undo.get_undo_stack()\n"
"while keep_going:\n"
" entry = undo_stack.pop()\n"
" if entry.level == 0:\n"
" keep_going = False\n";
executeCommand(kCmd);
}
static void createBuiltinCamera(const char* path, bool ortho, const char* usdContextName = "")
{
beginUndoGroup();
runCreatePrimCommand(path, "Camera", false, usdContextName);
std::ostringstream command;
command << "from pxr import Usd, UsdGeom, Gf, Kind\n"
"import omni.usd\n"
"import omni.kit.commands\n"
"stage = omni.usd.get_context('" << usdContextName << "').get_stage()\n"
"camera = UsdGeom.Camera.Get(stage, '" << path << "')\n"
"camera.CreateClippingRangeAttr(Gf.Vec2f(" << (ortho ? "2e4" : "1.0") << ", 1e7))\n"
"Usd.ModelAPI(camera).SetKind(Kind.Tokens.component)\n"
"camera.GetPrim().SetMetadata('no_delete', True)\n";
command << "import carb\n"
<< "cam_settings = carb.settings.get_settings().get_settings_dictionary('/persistent/app/primCreation/typedDefaults/"
<< (ortho ? "orthoCamera" : "camera") << "')\n"
<< "if cam_settings:\n"
<< " for name, value in cam_settings.get_dict().items():\n"
// Catch failures and issue an error, but continue on
<< " try:\n"
<< " attr = camera.GetPrim().GetAttribute(name)\n"
<< " if attr:\n"
<< " attr.Set(value)\n"
<< " except Exception:\n"
<< " import traceback\n"
<< " carb.log_error(traceback.format_exc())\n";
executeCommand(command.str().c_str());
endUndoGroup();
}
static void runFramePrimsCommand(const std::string& camera, const PXR_NS::SdfPathVector& paths, double aspectRatio, const pxr::UsdTimeCode& timeCode, const std::string& usdContext)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "omni.kit.commands.execute('FramePrimsCommand'"
<< ", prim_to_move='" << camera << "'"
<< ", aspect_ratio=" << (std::isfinite(aspectRatio) ? aspectRatio : 1.0)
<< ", usd_context_name='" << usdContext << "'"
<< ", time_code=";
addArgument(command, timeCode);
if (!paths.empty())
{
auto pathItr = paths.begin();
command << ", prims_to_frame = [ '" << *pathItr << "'";
++pathItr;
for (auto pathEnd = paths.end(); pathItr != pathEnd; ++pathItr)
{
command << ", '" << *pathItr << "'";
}
command << "]";
}
command << ")\n";
executeCommand(command.str().c_str());
}
static void runDuplicateFromActiveViewportCameraCommand(const char* viewportName)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='"
<< viewportName << "')\n";
executeCommand(command.str().c_str());
}
// Post notification utility from python
static void postNotification(const std::string& message, bool hide_after_timeout = true, bool info = true)
{
std::ostringstream command;
command << "try:\n"
<< " import omni.kit.notification_manager as nm\n"
<< " nm.post_notification(\"" << message << "\", hide_after_timeout=" << pyBool(hide_after_timeout);
if (!info)
{
command << ", status=nm.NotificationStatus.WARNING";
}
command << ")\n"
<< "except Exception:\n"
<< " pass\n";
executeCommand(command.str().c_str());
}
#endif // PXR_USD_USD_TIME_CODE_H
};
}
}
| 22,182 | C | 39.113924 | 184 | 0.53327 |
omniverse-code/kit/include/omni/kit/ViewportWindowUtils.h | // Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/dictionary/IDictionary.h>
#include <carb/events/EventsUtils.h>
#include <omni/kit/IViewport.h>
#include <omni/kit/ViewportTypes.h>
namespace omni
{
namespace kit
{
/**
* Gets payload from UiDrawEventStream.
*
* @param e Event from UiDrawEventStream.
* @param viewMtx The array to hold the data of view matrix. It must be big enough to store 16 doubles.
* @param projMtx The array to hold the data of projection matrix. It must be big enough to store 16 doubles.
* @param viewportRect The Float4 to hold the data of viewport rect.
*/
inline void getUiDrawPayloadFromEvent(const carb::events::IEvent& e,
double* viewMtx,
double* projMtx,
carb::Float4& viewportRect)
{
auto events = carb::dictionary::getCachedDictionaryInterface();
for (size_t i = 0; i < 16; i++)
{
static const std::string viewMatrixPrefix("viewMatrix/");
viewMtx[i] = events->get<double>(e.payload, (viewMatrixPrefix + std::to_string(i)).c_str());
}
for (size_t i = 0; i < 16; i++)
{
static const std::string projMatrixPrefix("projMatrix/");
projMtx[i] = events->get<double>(e.payload, (projMatrixPrefix + std::to_string(i)).c_str());
}
for (size_t i = 0; i < 4; i++)
{
static const std::string viewportRectPrefix("viewportRect/");
(&viewportRect.x)[i] = events->get<float>(e.payload, (viewportRectPrefix + std::to_string(i)).c_str());
}
}
/**
* Gets the default (first) IViewportWindow
*
* @return Default IViewportWindow
*/
inline IViewportWindow* getDefaultViewportWindow()
{
auto viewport = carb::getCachedInterface<omni::kit::IViewport>();
if (viewport)
{
return viewport->getViewportWindow(nullptr);
}
return nullptr;
}
}
}
| 2,314 | C | 31.152777 | 111 | 0.662057 |
omniverse-code/kit/include/omni/kit/EventSubscribers.h | // Copyright (c) 2019-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.
//
//! @file
//! @brief Utilities for managing EventSubscribers for omni.kit.app
#pragma once
#include "../../carb/Defines.h"
#include <vector>
namespace carb
{
/**
* A class that manages subscribers
*
* @thread_safety This class is **not** thread safe. Consider using \ref carb::delegate::Delegate which is thread-safe.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}. It's
* use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @tparam FuncT The function pointer type to manage
* @tparam SubIdT A type that is used as the subscriber type
*/
template <class FuncT, typename SubIdT>
class EventSubscribers
{
public:
/**
* Create a subscription, returning a handle to reference it.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @param fn The function pointer to register
* @param userData The user data that should be passed to \p fn when called
* @returns a `SubIdT` to reference the registered function. There is no invalid value, so `0` may be returned.
* Subscription IDs may also be reused as soon as they are unsubscribed. Call \ref unsubscribe() when finished
* with the subscription.
*/
SubIdT subscribe(FuncT fn, void* userData)
{
// Search for free slot
size_t index;
bool found = false;
for (size_t i = 0; i < m_subscribers.size(); i++)
{
if (!m_subscribers[i].fn)
{
index = i;
found = true;
break;
}
}
// Add new slot if haven't found a free one
if (!found)
{
m_subscribers.push_back({});
index = m_subscribers.size() - 1;
}
m_subscribers[index] = { fn, userData };
return (SubIdT)index;
}
/**
* Removes a subscriber previously subscribed with @ref subscribe().
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @warning Calling this function with an invalid Subscription ID will cause undefined behavior.
* @param id The subscriber ID previously passed to \ref subscribe().
*/
void unsubscribe(SubIdT id)
{
CARB_ASSERT(id < m_subscribers.size());
m_subscribers[id] = {};
}
/**
* Calls all subscribers.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @param args Arguments passed to the subscribed `FuncT` functions. These arguments are passed by value prior to
* the `userData` parameter that was registered with \ref subscribe().
*/
template <typename... Ts>
void send(Ts... args)
{
// Iterate by index because subscribers can actually change during iteration (vector can grow)
const size_t kCount = m_subscribers.size();
for (size_t i = 0; i < kCount; i++)
{
auto& subsribers = m_subscribers[i];
if (subsribers.fn)
subsribers.fn(args..., subsribers.userData);
}
}
/**
* Calls a single subscriber.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @warning Calling this function with an invalid Subscription ID will cause undefined behavior.
* @param id The subscriber ID previously passed to \ref subscribe().
* @param args Arguments passed to the subscribed `FuncT` functions. These arguments are passed by value prior to
* the `userData` parameter that was registered with \ref subscribe().
*/
template <typename... Ts>
void sendForId(uint64_t id, Ts... args)
{
CARB_ASSERT(id < m_subscribers.size());
if (m_subscribers[id].fn)
m_subscribers[id].fn(args..., m_subscribers[id].userData);
}
private:
struct EventData
{
FuncT fn;
void* userData;
};
std::vector<EventData> m_subscribers;
};
} // namespace carb
| 5,096 | C | 38.207692 | 119 | 0.645408 |
omniverse-code/kit/include/omni/kit/renderer/RendererUtils.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/logging/Log.h>
#include <omni/kit/renderer/IRenderer.h>
#include <rtx/resourcemanager/ResourceManager.h>
namespace
{
using namespace omni::kit::renderer;
using namespace rtx::resourcemanager;
static void* acquireGpuPointerReference(IRenderer::ResourceManagerState state, RpResource& rpRsrc, const carb::graphics::TextureDesc** texDesc)
{
if (!state.manager || !state.manager)
{
CARB_LOG_ERROR("ResourceManagerState doesn't have a ResourceManager or its Context");
return nullptr;
}
if (texDesc)
{
*texDesc = state.manager->getTextureDesc(*state.context, &rpRsrc);
if (!*texDesc)
{
CARB_LOG_ERROR("ResourceManager returned a null TextureDesc for the RpResource");
return nullptr;
}
}
auto texH = state.manager->getTextureHandle(*state.context, &rpRsrc);
if (!texH.ptr)
{
CARB_LOG_ERROR("ResourceManager could not retrieve a TextureHandle for the RpResource");
return nullptr;
}
state.manager->acquireResource(rpRsrc);
return texH.ptr;
}
static bool releaseGpuPointerReference(IRenderer::ResourceManagerState state, RpResource& rpRsrc)
{
if (state.manager)
{
state.manager->releaseResource(rpRsrc);
return true;
}
return false;
}
}
| 1,767 | C | 29.482758 | 143 | 0.706848 |
omniverse-code/kit/include/omni/kit/renderer/IGpuFoundation.h | // 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.
//
#pragma once
#include <carb/Interface.h>
namespace carb
{
namespace graphics
{
struct Graphics;
}
namespace graphicsmux
{
struct GraphicsMux;
}
namespace glinterop
{
struct GLInterop;
}
namespace cudainterop
{
struct CudaInterop;
}
}
namespace rtx
{
namespace resourcemanager
{
struct ResourceManager;
class Context;
typedef uint32_t SyncScopeId;
}
namespace rendergraph
{
struct RenderGraphBuilder;
class RenderGraphContext;
}
namespace shaderdb
{
struct ShaderDb;
class Context;
}
namespace psodb
{
struct PsoDb;
struct Context;
}
}
namespace gpu
{
namespace foundation
{
class IGpuFoundation;
struct GpuFoundationContext;
struct GpuDevices;
}
}
namespace omni
{
namespace kit
{
namespace renderer
{
class IGpuFoundation
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::renderer::IGpuFoundation", 1, 1);
virtual carb::graphics::Graphics* getGraphics() = 0;
virtual carb::graphicsmux::GraphicsMux* getGraphicsMux() = 0;
virtual rtx::resourcemanager::ResourceManager* getResourceManager() = 0;
virtual rtx::resourcemanager::Context* getResourceManagerContext() = 0;
virtual rtx::rendergraph::RenderGraphBuilder* getRenderGraphBuilder() = 0;
virtual rtx::shaderdb::ShaderDb* getShaderDb() = 0;
virtual rtx::shaderdb::Context* getShaderDbContext() = 0;
virtual rtx::psodb::PsoDb* getPipelineStateDb() = 0;
virtual rtx::psodb::Context* getPipelineStateDbContext() = 0;
virtual carb::glinterop::GLInterop* getOpenGlInterop() = 0;
virtual carb::cudainterop::CudaInterop* getCudaInterop() = 0;
virtual gpu::foundation::IGpuFoundation* getGpuFoundation() = 0;
virtual gpu::foundation::GpuDevices* getGpuFoundationDevices() = 0;
virtual bool isBindlessSupported() = 0;
virtual rtx::resourcemanager::SyncScopeId getSyncScopeId() = 0;
virtual bool isCompatibilityMode() = 0;
};
}
}
}
| 2,289 | C | 19.818182 | 78 | 0.753604 |
omniverse-code/kit/include/omni/kit/renderer/IImGuiRenderer.h | // 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.
//
#pragma once
#include "IRenderer.h"
#include <carb/Interface.h>
#include <omni/ui/windowmanager/IWindowCallbackManager.h>
namespace carb
{
namespace graphics
{
struct CommandList;
struct Descriptor;
struct DescriptorSet;
}
}
namespace rtx
{
namespace resourcemanager
{
class Context;
}
}
namespace carb
{
namespace graphics
{
struct Graphics;
struct Device;
struct ResourceBindingSignature;
}
namespace windowing
{
struct Cursor;
}
namespace imgui
{
struct Context;
}
}
namespace omni
{
namespace ui
{
namespace windowmanager
{
struct WindowSet;
}
}
namespace kit
{
namespace renderer
{
class DrawDataHandler;
class IImGuiRenderer
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::renderer::IImGuiRenderer", 1, 3);
virtual void startup() = 0;
virtual void shutdown() = 0;
virtual uint32_t getResourceManagerDeviceMask() = 0;
virtual carb::graphics::ResourceBindingSignature* getResourceBindingSignature() = 0;
virtual TextureGpuReference allocateReferenceForTexture() = 0;
virtual TextureGpuReference allocateReferenceForDrawable() = 0;
virtual bool isPossibleToAttachAppWindow() = 0;
virtual bool attachAppWindow(IAppWindow* appWindow) = 0;
virtual bool attachAppWindowWithImGuiContext(IAppWindow* appWindow, carb::imgui::Context* imGuiContext) = 0;
virtual void detachAppWindow(IAppWindow* appWindow) = 0;
virtual bool isAppWindowAttached(IAppWindow* appWindow) = 0;
virtual omni::ui::windowmanager::WindowSet* getWindowSet(IAppWindow* appWindow) = 0;
virtual void setCursorShapeOverride(IAppWindow* appWindow, carb::windowing::CursorStandardShape cursor) = 0;
virtual bool hasCursorShapeOverride(IAppWindow* appWindow) const = 0;
virtual carb::windowing::CursorStandardShape getCursorShapeOverride(IAppWindow* appWindow) const = 0;
virtual void clearCursorShapeOverride(IAppWindow* appWindow) = 0;
virtual void deallocateReferenceForTexture(const TextureGpuReference& textureGpuReference) = 0;
virtual void deallocateReferenceForDrawable(const TextureGpuReference& textureGpuReference) = 0;
virtual DrawDataHandler* createDrawData() const = 0;
virtual void destroyDrawData(DrawDataHandler* drawDataHandler) const = 0;
virtual void fillDrawData(DrawDataHandler* drawDataHandler, void* data) const = 0;
virtual void renderDrawData(IAppWindow* appWindow,
carb::graphics::CommandList* commandList,
const DrawDataHandler* drawDataHandler) const = 0;
virtual void registerCursorShapeExtend(const char* shapeName, const char* imagePath) = 0;
virtual void unregisterCursorShapeExtend(const char* shapeName) = 0;
virtual void setCursorShapeOverrideExtend(IAppWindow* appWindow, const char* shapeName) = 0;
virtual omni::string getCursorShapeOverrideExtend(IAppWindow* appWindow) const = 0;
virtual void getAllCursorShapeNames(const char** names, size_t count) const = 0;
virtual size_t getAllCursorShapeNamesCount() const = 0;
};
}
}
}
| 3,465 | C | 28.12605 | 112 | 0.761616 |
omniverse-code/kit/include/omni/kit/renderer/IRenderer.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "IGpuFoundation.h"
#include <carb/IObject.h>
#include <carb/Interface.h>
#include <carb/InterfaceUtils.h>
#include <carb/tasking/TaskingTypes.h>
#include <omni/kit/IAppWindow.h>
namespace carb
{
namespace events
{
class IEventStream;
}
namespace graphics
{
enum class DescriptorType : int32_t;
struct Device;
class DeviceGroup;
struct CommandList;
struct CommandQueue;
struct DescriptorPool;
struct ResourceBindingSignature;
struct TextureDesc;
// TextureGpuData
struct Texture;
struct Descriptor;
struct DescriptorSet;
}
namespace graphicsmux
{
class CommandList;
}
namespace renderer
{
struct TextureHandle;
}
}
namespace gpu
{
enum class GfResult : int32_t;
}
namespace rtx
{
namespace resourcemanager
{
class RpResource;
typedef uint32_t SyncScopeId;
}
}
namespace omni
{
namespace kit
{
namespace renderer
{
typedef int64_t CommandListHandle;
/**
* Defines a simple interface for texture GPU resources
*/
class TextureGpuData : public carb::IObject
{
public:
virtual carb::graphics::Texture* getGraphicsTexture() const = 0;
virtual carb::graphics::Descriptor* getGraphicsDescriptor() const = 0;
virtual carb::graphics::DescriptorSet* getGraphicsDescriptorSet() const = 0;
virtual rtx::resourcemanager::RpResource* getManagedResource() const = 0;
virtual uint32_t getBindlessDescriptorIndex() const = 0;
};
struct TextureGpuReference
{
union {
uint32_t gpuIndex;
void* ptr;
};
};
/**
* @brief The data for all the viewports in GUI. We use it when present thread
* is enabled to render viewport with more FPS that GUI.
*/
struct IRendererHydraViewportData
{
using Clock = ::std::chrono::high_resolution_clock;
using Duration = Clock::duration;
using TimePoint = Clock::time_point;
uint32_t viewportId;
size_t subFrameCount;
uint32_t subFrames[4];
size_t currentSubFrame;
TimePoint publishTime;
Duration frameAverageTime;
};
/**
* @brief Options for texture creation.
*/
struct IRendererTextureOptions
{
uint32_t gpuDeviceMask = 0; ///< Device mask to create texture on (0 for UI device only)
uint32_t textureUsageFlags = 0; ///< carb::graphics::TextureUsageFlags
uint32_t resourceUsageFlags = 0; ///< rtx::ResourceUsageFlags
uint32_t unusedExtPadding = 0; ///< Unused padding and expansion
};
/**
* Defines an interface for the small version of editor that provides simple GUI.
*/
class IRenderer
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::renderer::IRenderer", 1, 9);
virtual void startup() = 0;
virtual void shutdown() = 0;
/**
* Render events stream. Render events and pushed and popped every frame.
*/
virtual carb::events::IEventStream* getPreBeginFrameEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getPreBeginRenderPassEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getRenderFrameEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getPostEndRenderPassEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getPostEndRenderFrameEventStream(IAppWindow* appWindow) = 0;
virtual carb::graphics::Device* getGraphicsDevice(IAppWindow* appWindow) = 0;
virtual carb::graphics::DeviceGroup* getGraphicsDeviceGroup(IAppWindow* appWindow) = 0;
virtual uint32_t getGraphicsDeviceIndex(IAppWindow* appWindow) = 0;
virtual carb::Format getGraphicsSwapchainFormat(IAppWindow* appWindow) = 0;
virtual carb::graphics::CommandQueue* getGraphicsCommandQueue(IAppWindow* appWindow) = 0;
typedef void (*UploadCompleteCbDeprecated)(void* arg,
void* textureHandle,
carb::graphics::Descriptor* textureDescriptor,
size_t width,
size_t height,
void* userData);
struct UploadTextureDescDeprecated
{
const char* assetUri;
UploadCompleteCbDeprecated callback;
void* arg;
};
// TODO: remove these functions as they are merely wrappers around GPU data creation with integrated assets
// management
virtual void uploadTextureDeprecated(const UploadTextureDescDeprecated& desc, void* userData = nullptr) = 0;
virtual void destroyTextureDeprecated(void* texture) = 0;
virtual TextureGpuData* getTextureDataFromHandle(void* textureHandle) = 0;
static constexpr uint32_t kMaxDescriptorSetCount = 8192;
virtual carb::graphics::DescriptorPool* getDescriptorPool() = 0;
/**
* These functions are needed because carb::graphics doesn't have descriptor set deallocations, we have very
* finite set of allocations - we have to track them to make sure we can emit a warning if we're reaching the limit.
*/
virtual void notifyDescriptorPoolAllocation(carb::graphics::DescriptorType descriptorType) = 0;
virtual int getFreeDescriptorPoolSlotCount(carb::graphics::DescriptorType descriptorType) = 0;
/**
* Functions that allocate id to use in shaders, given the created/imported GPU data.
*/
virtual TextureGpuReference allocateReferenceForTexture(
carb::graphics::ResourceBindingSignature* resourceBindingSignature) = 0;
virtual TextureGpuReference allocateReferenceForDrawable(
carb::graphics::ResourceBindingSignature* resourceBindingSignature) = 0;
virtual TextureGpuReference updateReferenceFromTextureData(TextureGpuReference textureGpuReference,
TextureGpuData* textureGpuData) = 0;
virtual TextureGpuReference updateReferenceFromDrawableData(TextureGpuReference* textureGpuReference,
TextureGpuData* drawableGpuData) = 0;
/**
* Functions to manipulate GPU data that was created outside of the renderer.
*/
virtual TextureGpuData* createExternalTextureGpuData() = 0;
virtual void updateExternalTextureGpuData(
TextureGpuData* externalTextureGpuData,
carb::graphics::Descriptor* externalDescriptor,
uint32_t bindlessDescriptorIndex = CARB_UINT32_MAX) = 0;
/**
* Functions to create managed GPU data.
*/
virtual TextureGpuData* createGpuResourcesForTexture(carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides) = 0;
virtual void updateGpuResourcesForTexture(TextureGpuData* textureGpuData,
carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides) = 0;
virtual void resetGpuResourcesForTexture(TextureGpuData* textureGpuData) = 0;
virtual void destroyGpuResourcesForTexture(TextureGpuData* textureGpuData) = 0;
/**
* Functions to extract command lists from handles.
*/
virtual carb::graphics::CommandList* getGraphicsCommandList(CommandListHandle commandListHandle) = 0;
virtual carb::graphicsmux::CommandList* getGraphicsMuxCommandList(CommandListHandle commandListHandle) = 0;
virtual uint32_t getCurrentBackBufferIndex(IAppWindow* appWindow) = 0;
virtual uint32_t getBackBufferCount(IAppWindow* appWindow) = 0;
virtual size_t getFrameCount(IAppWindow* appWindow) = 0;
/**
* Framebuffer information.
*/
virtual carb::graphics::Texture* getFramebufferTexture(IAppWindow* appWindow) = 0;
virtual uint32_t getFramebufferWidth(IAppWindow* appWindow) = 0;
virtual uint32_t getFramebufferHeight(IAppWindow* appWindow) = 0;
virtual carb::Format getFramebufferFormat(IAppWindow* appWindow) = 0;
virtual CommandListHandle getFrameCommandList(IAppWindow* appWindow) = 0;
virtual TextureGpuReference getInvalidTextureReference() = 0;
static inline IGpuFoundation* getGpuFoundation();
virtual bool attachAppWindow(IAppWindow* appWindow) = 0;
virtual void detachAppWindow(IAppWindow* appWindow) = 0;
virtual bool isAppWindowAttached(IAppWindow* appWindow) = 0;
virtual void waitIdle(IAppWindow* appWindow) = 0;
virtual void forceRenderFrame(float dt) = 0;
virtual rtx::resourcemanager::SyncScopeId getSyncScopeId() = 0;
/**
* Get a reference to the current ResourceManager and it's Context.
* IAppWindow* can currently be null.
*/
struct ResourceManagerState
{
rtx::resourcemanager::ResourceManager* manager;
rtx::resourcemanager::Context* context;
};
virtual ResourceManagerState getResourceManagerState(IAppWindow* appWindow) = 0;
virtual void setClearColor(IAppWindow* appWindow, const carb::Float4& clearColor) = 0;
virtual carb::Float4 getClearColor(IAppWindow* appWindow) = 0;
virtual bool setRenderQueue(IAppWindow* appWindow, size_t renderQueueIdx) = 0;
virtual size_t getRenderQueue(IAppWindow* appWindow) = 0;
/**
* Functions that deallocate id to use in shaders, given the created/imported GPU data.
*/
virtual void deallocateReferenceForTexture(
carb::graphics::ResourceBindingSignature* resourceBindingSignature, const TextureGpuReference& textureGpuReference) = 0;
virtual void deallocateReferenceForDrawable(
carb::graphics::ResourceBindingSignature* resourceBindingSignature, const TextureGpuReference& textureGpuReference) = 0;
/**
* Present thread streams.
*
* Called from the separate thread (present thread) to render the saved UI
* with bigger framerate than it's generated.
*/
virtual carb::events::IEventStream* getPresentRenderFrameEventStream(IAppWindow* appWindow) = 0;
/**
* @brief Should be called when the new viewport frame is ready
*
* @param dt time to render this frame in ns
* @param viewportId the id of the viewport that should be replaced to the
* given textureId
* @param subFrameCount the number of subframes
* @param subFrames the viewport subframes
*/
virtual void notifyRenderingIsReady(float dtNs,
uint32_t viewportId,
size_t subFrameCount,
const uint32_t* subFrames) = 0;
/**
* Functions to create managed GPU data with optional multiGpu and GPU source support.
*
* @param multiGpu data will be uploaded or copied to all GPUs in device group
* @param fromGpu data is a gpu memory address, not host memory
*/
virtual TextureGpuData* createGpuResourcesForTexture(carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides,
bool multiGpu,
bool cudaBytes) = 0;
virtual void updateGpuResourcesForTexture(TextureGpuData* textureGpuData,
carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides,
bool cudaBytes) = 0;
/**
* Add a callback to be run in the IRenderer / Graphics initialization
*
* @param eventHandler An IEventListener to be called during IRenderer/Graphics setup.
* This handler is currently invoked with a null carb::event::IEvent pointer.
*
*/
virtual void addToInitPipeline(carb::events::IEventListenerPtr eventHandler) = 0;
/**
* Block current thread until renderer (& GPU Foundation) is fully setup
*
*/
virtual void waitForInit() = 0;
/**
* @brief Called immediately after the renderer presents the current frame
* to the frame buffer. This function allows the developer to perform any
* additional operations or processing on the frame after it has been
* presented, such as sending the frame data to a CUDA memory frame for
* further processing. Additionally, the callback can be used to trigger any
* additional actions that need to be taken after the frame has been
* presented, such as updating a status or sending a notification.
*/
virtual carb::events::IEventStream* getPostPresentFrameBufferEventStream(IAppWindow* appWindow) = 0;
/**
* @brief Frozen window is skipped from the run loop and it's not updated.
*/
virtual void freezeAppWindow(IAppWindow* appWindow, bool freeze) = 0;
/*
* @brief State of the present thread
*
* @return true The present thread is enabled
* @return false The present thread is disabled
*/
virtual bool isPresentThreadEnabled() const = 0;
/**
* @brief Create or update a GPU resource.
*
* @param format The format of the texture being created
* @param mipMapResolutions An array of resolutions to use for mip-mapped data
* @param mipMapDatas An array of bytes to upload, for each mip-level
* @param mipMapStrides An array of strides on the bytes to upload, for each mip-level
* @param mipMapCount The number of elements in the mipResolutions, mipDatas, and mipStrides arguments
* @param multiGpu Data will be uploaded or copied to all GPUs in device group
* @param createShared Whether to create the texture as shareable for later use in CUDA or OpenGL
* @param cudaBytes Whether the pointers in mipDatas refer to CPU memory or CUDA memory
* @param deviceMask The devices to create the texture for
*/
virtual TextureGpuData* createGpuResourcesForTexture(carb::Format format,
const carb::Uint2* mipMapResolutions,
const uint8_t* const* mipMapDatas,
const size_t* mipMapStrides,
size_t mipMapCount,
const IRendererTextureOptions& options = {}) = 0;
virtual void updateGpuResourcesForTexture(TextureGpuData* textureGpuData,
carb::Format format,
const carb::Uint2* mipMapResolutions,
const uint8_t* const* mipMapDatas,
const size_t* mipMapStrides,
size_t mipMapCount,
const IRendererTextureOptions& options = {}) = 0;
/**
* Ensures that the resource exists on the target display device, potentially performing an asynchronous GPU copy.
* @return The pointer to the resource on the target display device. If the resource is already on the target
* device, then this pointer will be the same as the input. This function will return nullptr on failure.
* @param resource The resource to potentially copy to the target display device
* @param timeout The timeout (in milliseconds) for the copy operation. The future will return eTimeout if the
* timeout is exceeded.
* @param outTextureHandle Optional: If not nullptr, the GPU handle for the resource on the target device.
* @param outTextureDesc Optional: If not nullptr, the TextureDesc of the returned RpResource will be returned in
* outTextureDesc.
* @param outFuture Optional: If not nullptr, the receiver for a future that can be waited on for the completion of
* the potential GPU copy.
*/
virtual rtx::resourcemanager::RpResource* ensureRpResourceOnTargetDevice(
rtx::resourcemanager::RpResource* resource,
uint32_t timeout,
carb::renderer::TextureHandle* outTextureHandle,
const carb::graphics::TextureDesc** outTextureDesc,
carb::tasking::SharedFuture<gpu::GfResult>* outFuture) = 0;
/**
* @brief Draw-frozen window is not skipped from the run loop and but the
* draw list of this window is not updated.
*/
virtual void drawFreezeAppWindow(IAppWindow* appWindow, bool freeze) = 0;
};
inline IGpuFoundation* IRenderer::getGpuFoundation()
{
return carb::getCachedInterface<IGpuFoundation>();
}
}
}
}
| 17,938 | C | 40.815851 | 128 | 0.640149 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/ParallelScheduler.h | // 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.
//
//! @file ParallelScheduler.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::ParallelSpawner.
#pragma once
#include <omni/graph/exec/unstable/AtomicBackoff.h>
#include <omni/kit/exec/core/unstable/ITbbSchedulerState.h>
#include <omni/kit/exec/core/unstable/TbbSchedulerState.h>
#ifndef __TBB_ALLOW_MUTABLE_FUNCTORS
//! Allow task functors to mutate captured by value state
# define __TBB_ALLOW_MUTABLE_FUNCTORS 1
#endif
#include <tbb/task.h>
#include <tbb/task_group.h>
#include <atomic>
#include <thread>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
#ifndef DOXYGEN_BUILD
//! Parallel scheduler for task dispatch.
//!
//! Currently only needs to handle special requests, actual parallel work is enqueue directly to TBB
class ParallelScheduler
{
public:
//! Access static per-DLL singleton.
static ParallelScheduler& getSingleton()
{
// this static is per-DLL, but the actual private data (s_state) is shared across DLLs
static ParallelScheduler sScheduler;
return sScheduler;
}
//! Class wrapping lambda into serial and parallel tasks. Additionally, this class keeps a track of all
//! created tasks to allow activating isolation pass when all serial and parallel work is completed.
template <typename Fn>
class TaskBody : public tbb::task
{
public:
//! Expected function signature is void(). Increments total task count.
TaskBody(Fn&& f) : m_fn(std::forward<Fn>(f)), m_sharedState(ParallelScheduler::getSingleton().s_state)
{
++m_sharedState->totalTasksInFlight;
}
//! Decrements total task count and starts processing isolate tasks if no more tasks are running.
~TaskBody()
{
--m_sharedState->totalTasksInFlight;
}
//! TBB task execute method calling into lambda. To track nested executions, we increment and decrement
//! tasks per thread atomic counter.
task* execute() override
{
struct ExecutingCountedTaskScope
{
ExecutingCountedTaskScope(tbb::enumerable_thread_specific<int>& executingPerThread)
: _executingPerThread(executingPerThread)
{
_executingPerThread.local()++;
}
~ExecutingCountedTaskScope()
{
_executingPerThread.local()--;
}
tbb::enumerable_thread_specific<int>& _executingPerThread;
} executingScope(m_sharedState->tasksExecutingPerThread);
return m_fn(); // allow for potential continuation
};
private:
Fn m_fn; //!< Lambda function to call from the execute() function.
TbbSchedulerState* m_sharedState{ nullptr }; //!< Scheduler shared state used to track total task count.
};
//! Class wrapping lambda into an isolated TBB task. No other tasks will be running when this task executes.
template <typename Fn>
class IsolateTaskBody : public tbb::task
{
public:
//! Constructor capturing the lambda function
//!
//! Expected function signature is void()
IsolateTaskBody(Fn&& f) : m_fn(std::forward<Fn>(f))
{
}
//! TBB task execute method calling into lambda.
task* execute() override
{
// isolate tasks are not counted in total in flight tasks to allow us detect when
// all other work is finished. Once we are entering scope of isolate task, we make sure
// PauseTaskScope doesn't consider this task as taking part in totalTasksInFlight
struct ExecutingNotCountedTaskScope
{
ExecutingNotCountedTaskScope(tbb::enumerable_thread_specific<int>& executingPerThread)
: _executingPerThread(executingPerThread)
{
auto& perThreadCount = _executingPerThread.local();
_originalPerThread = perThreadCount;
perThreadCount = 0;
}
~ExecutingNotCountedTaskScope()
{
_executingPerThread.local() = _originalPerThread;
}
tbb::enumerable_thread_specific<int>& _executingPerThread;
int _originalPerThread;
} executingScope(ParallelScheduler::getSingleton().s_state->tasksExecutingPerThread);
return m_fn(); // allow for potential continuation
};
private:
Fn m_fn; //!< Lambda function to call from the execute() function
};
//! RAII class used to pause and resume total tasks in flight when thread is about to pick up new tasks to work on.
class PauseTaskScope
{
public:
PauseTaskScope()
: m_scheduler(ParallelScheduler::getSingleton()),
m_isCountedTask(m_scheduler.s_state->tasksExecutingPerThread.local() > 0)
{
if (m_isCountedTask)
{
--m_scheduler.s_state->totalTasksInFlight;
}
}
~PauseTaskScope()
{
if (m_isCountedTask)
{
++m_scheduler.s_state->totalTasksInFlight;
}
}
private:
ParallelScheduler& m_scheduler; //!< To avoid calling into getSingleton multiple times
const bool m_isCountedTask; //!< Know if we are pausing task that was scheduled by us or someone else.
};
//! Typically parallel tasks are spawned right away, but when executed from isolation tasks, we defer spawning
//! until all isolation work is completed.
void pushParallelTask(tbb::task& t, bool isExecutingThread)
{
if (!isProcessingIsolate())
{
if (isExecutingThread && (s_state->totalTasksInFlight < 2))
{
// the executing thread never joins the arena, so won't process its local queue. add the task to the
// global queue. we only do this if there aren't already tasks in flight that can pick up task if we
// spawn() it.
tbb::task::enqueue(t);
}
else
{
tbb::task::spawn(t); // add to local queue
}
}
else
{
s_state->queueParallel.push(&t);
}
}
//! Add task /p t for serial dispatch. This tasks are guaranteed to be run one after another, but other thread-safe
//! tasks are allowed to run together with them
void pushSerialTask(tbb::task& t)
{
s_state->queueSerial.push(&t);
}
//! Store isolate task for execution when no other tasks are running.
void pushIsolateTask(tbb::task& t)
{
s_state->queueIsolate.push(&t);
}
//! Called to notify completion of a serial task and acquire more work if available.
tbb::task* completedSerialTask()
{
tbb::task* serialTask = nullptr;
s_state->queueSerial.try_pop(serialTask);
return serialTask;
}
//! Called to notify completion of an isolate task and acquire more work if available.
tbb::task* completedIsolateTask()
{
tbb::task* isolateTask = nullptr;
s_state->queueIsolate.try_pop(isolateTask);
return isolateTask;
}
//! Returns true if calling thread has been tagged as the one processing serial task. If so, this thread
//! is in the middle of processing a serial task.
bool isWithinSerialTask() const
{
return (s_state->serialThreadId.load() == std::this_thread::get_id());
}
//! Returns true if calling thread has been tagged as the one processing isolate task. If so, this thread
//! is in the middle of processing a isolate task.
bool isWithinIsolateTask() const
{
return (s_state->isolateThreadId.load() == std::this_thread::get_id());
}
//! Returns true if processing of isolate tasks is in progress.
bool isProcessingIsolate() const
{
return (s_state->isolateThreadId.load() != std::thread::id());
}
void processContextThread(tbb::empty_task* rootTask)
{
// See the note in TbbSchedulerState.h as to why we need this
// mutex lock here.
std::lock_guard<tbb::recursive_mutex> lock(s_state->executingThreadMutex);
graph::exec::unstable::AtomicBackoff backoff;
if (isWithinIsolateTask())
{
while (rootTask->ref_count() > 1)
{
if (processQueuedTasks())
backoff.reset();
else
backoff.pause();
}
}
else
{
while (rootTask->ref_count() > 1)
{
if (processSerialTasks() || processIsolateTasks())
backoff.reset();
else
backoff.pause();
}
}
}
private:
//! Explicit call to execute the serial task queueSerial until empty.
//!
bool processSerialTasks()
{
tbb::task* task = nullptr;
s_state->queueSerial.try_pop(task);
// No work
if (!task)
return false;
{
// Acquire the thread that's supposed to be handling serial task evaluation. Note
// that this thread can be derived from many different execution contexts kickstarted
// by multiple different threads.
std::thread::id currentThreadId = std::this_thread::get_id();
std::thread::id originalThreadId;
if (!s_state->serialThreadId.compare_exchange_strong(originalThreadId, currentThreadId) &&
originalThreadId != currentThreadId)
{
return false;
}
// Once serial tasks evaluation is complete, we will want to restore the serial thread ID
// back to its default value; employ an RAII helper to do so.
struct ScopeRelease
{
std::thread::id _originalThreadId;
std::atomic<std::thread::id>& _serialThreadId;
~ScopeRelease()
{
_serialThreadId = _originalThreadId;
}
} threadScope = { originalThreadId, s_state->serialThreadId };
// Run the loop over tasks. We are responsible here to delete the task since it is consumed outside of TBB.
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task);
task = nextTask;
}
}
// Let the caller know that we had something to do
return true;
}
//! When no more work is available execute isolated tasks.
bool processIsolateTasks()
{
if (s_state->totalTasksInFlight > 0 || s_state->queueIsolate.empty())
{
return false;
}
// try acquire the right to process isolated tasks. Need to support nested executions.
{
std::thread::id currentThreadId = std::this_thread::get_id();
std::thread::id originalThreadId;
if (!s_state->isolateThreadId.compare_exchange_strong(originalThreadId, currentThreadId) &&
originalThreadId != currentThreadId)
{
return false;
}
// we acquired the thread, nothing else will be running until the end of this scope
struct ScopeRelease
{
std::thread::id _originalThreadId;
std::atomic<std::thread::id>& _isolateThreadId;
~ScopeRelease()
{
_isolateThreadId = _originalThreadId;
}
} threadScope = { originalThreadId, s_state->isolateThreadId };
// we don't count isolate tasks, so just pick up the next one
tbb::task* task = completedIsolateTask();
// Run the loop over tasks. We are responsible here to delete the task since it is consumed outside of TBB.
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task);
task = nextTask;
}
// here we will release this thread from processing isolate tasks.
// We don't worry about synchronization between push tasks and this operation because
// all push call can only happen from within above loop (indirectly via execute). There is no
// other concurrent execution happening when we are in here.
}
// do NOT start parallel work in nested isolate task. it has to be all consumed on this thread until we can
// exit isolation
if (!isWithinIsolateTask())
{
// restart parallel task execution
tbb::task* dispatchTask = nullptr;
while (s_state->queueParallel.try_pop(dispatchTask))
{
if (s_state->totalTasksInFlight < 2)
{
tbb::task::enqueue(*dispatchTask);
}
else
{
tbb::task::spawn(*dispatchTask);
}
}
}
return true;
}
//! This processing should be avoided as much as possible but is necessary when work is generated and executed
//! from within isolate task. We have to empty all the queues and unblock the rest of work.
bool processQueuedTasks()
{
OMNI_ASSERT(isWithinIsolateTask());
bool ret = false;
tbb::task* task = nullptr;
if (s_state->queueIsolate.try_pop(task))
{
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task); // We are responsible here to delete the task since it is consumed manually
task = nextTask;
}
ret |= true;
}
if (s_state->queueSerial.try_pop(task))
{
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task); // We are responsible here to delete the task since it is consumed manually
task = nextTask;
}
ret |= true;
}
if (s_state->queueParallel.try_pop(task))
{
do
{
task->execute();
tbb::task::destroy(*task); // We are responsible here to delete the task since it is consumed manually
// parallel tasks don't do scheduling continuation, this is why we don't pick up the next task
} while (s_state->queueParallel.try_pop(task));
ret |= true;
}
return ret;
}
//! Constructor
explicit ParallelScheduler() noexcept
{
omni::core::ObjectPtr<ITbbSchedulerState> sInterface = omni::core::createType<ITbbSchedulerState>();
OMNI_ASSERT(sInterface);
s_state = sInterface->geState();
OMNI_ASSERT(s_state);
}
TbbSchedulerState* s_state; //!< One scheduler state shared by all DLLs
};
namespace detail
{
//! Utility to construct in-place /p allocTask a task /p TaskT wrapping given lambda /p f
template <template <class...> typename TaskT, typename A, typename Fn>
TaskT<Fn>* makeTask(A&& allocTask, Fn&& f)
{
return new (allocTask) TaskT<Fn>(std::forward<Fn>(f));
}
} // namespace detail
#endif // DOXYGEN_BUILD
//! Interface executors use to talk to the scheduler
struct ParallelSpawner
{
//! Constructor
ParallelSpawner(graph::exec::unstable::IExecutionContext* context) : m_context(context)
{
m_root = new (tbb::task::allocate_root()) tbb::empty_task;
m_root->set_ref_count(1);
}
//! Destructor
~ParallelSpawner()
{
tbb::task::destroy(*m_root);
}
//! Thread-safe schedule method called by executor to enqueue generated work.
//! Supports parallel, serial and isolate scheduling constraints.
template <typename Fn>
graph::exec::unstable::Status schedule(Fn&& task, graph::exec::unstable::SchedulingInfo schedInfo)
{
using namespace detail;
if (schedInfo == graph::exec::unstable::SchedulingInfo::eParallel)
{
auto* dispatchTask = detail::makeTask<ParallelScheduler::TaskBody>(
tbb::task::allocate_additional_child_of(*m_root),
[task = graph::exec::unstable::captureScheduleFunction(task), this]() mutable
{
graph::exec::unstable::Status ret = graph::exec::unstable::invokeScheduleFunction(task);
this->accumulateStatus(ret);
return nullptr;
});
ParallelScheduler::getSingleton().pushParallelTask(*dispatchTask, m_context->isExecutingThread());
}
else if (schedInfo == graph::exec::unstable::SchedulingInfo::eIsolate)
{
auto* dispatchTask = detail::makeTask<ParallelScheduler::IsolateTaskBody>(
tbb::task::allocate_additional_child_of(*m_root),
[task = graph::exec::unstable::captureScheduleFunction(task), this]() mutable
{
graph::exec::unstable::Status ret = graph::exec::unstable::invokeScheduleFunction(task);
this->accumulateStatus(ret);
return ParallelScheduler::getSingleton().completedIsolateTask();
});
ParallelScheduler::getSingleton().pushIsolateTask(*dispatchTask);
}
else
{
auto* dispatchTask = detail::makeTask<ParallelScheduler::TaskBody>(
tbb::task::allocate_additional_child_of(*m_root),
[task = graph::exec::unstable::captureScheduleFunction(task), this]() mutable -> tbb::task*
{
graph::exec::unstable::Status ret = graph::exec::unstable::invokeScheduleFunction(task);
this->accumulateStatus(ret);
return ParallelScheduler::getSingleton().completedSerialTask();
});
ParallelScheduler::getSingleton().pushSerialTask(*dispatchTask);
}
return graph::exec::unstable::Status::eSuccess;
}
//! Thread-safe accumulation of status returned by all spawned tasks
void accumulateStatus(graph::exec::unstable::Status ret)
{
graph::exec::unstable::Status current, newValue = graph::exec::unstable::Status::eUnknown;
do
{
current = m_status.load();
newValue = ret | current;
} while (!m_status.compare_exchange_weak(current, newValue));
}
//! Blocking call to acquire accumulated status.
//! When more work is still available, this thread will join the arena and pickup some work OR
//! will be reserved to process serial tasks if we end up here from a serial task (nested scenario).
graph::exec::unstable::Status getStatus()
{
// We are about to enter nested execution. This has an effect on total tasks in flight, i.e.
// we will suspend the current task by reducing the counters. All that is done by RAII class below.
ParallelScheduler::PauseTaskScope pauseTask;
// Note that in situations where multiple different contexts are running from multiple different
// threads, just having the first check (m_context->isExecutingThread()) won't be enough because
// we may be attempting to get the status of a serial/isolate task that was originally created in
// context A running on thread 1 while context B running on thread 2 is being processed in the
// below check; this can occur if context A/thread 1 was temporarily suspended in the past after
// context B/thread 2 beat it to acquiring the s_state->executingThreadMutex, meaning that we
// are currently processing nested tasks (which can be of any scheduling type) that are derived
// from some top-level set of serial/isolate tasks in context B. In such situations, we need to
// additionally check if we are currently within a serial or isolate task scope, since otherwise
// the task originally created in context A/thread 1 will incorrectly skip processing on context B's
// thread, despite thread 2 being the only running context thread at the moment, and take a different
// code-path that leads to hangs. Serial/isolate tasks don't need to be run exclusively on the
// context thread from which they were eventually scheduled - they can be run on any such context
// thread as long as that context thread is the only one running/processing serial/isolate tasks.
if (m_context->isExecutingThread() || ParallelScheduler::getSingleton().isWithinSerialTask() ||
ParallelScheduler::getSingleton().isWithinIsolateTask())
{
ParallelScheduler::getSingleton().processContextThread(m_root);
}
else
{
if (m_root->ref_count() > 1)
{
m_root->wait_for_all();
m_root->set_ref_count(1);
}
}
return m_status;
}
private:
graph::exec::unstable::IExecutionContext* m_context; //!< Execution context used to identify executing thread
tbb::empty_task* m_root{ nullptr }; //!< Root task for all spawned tasks.
std::atomic<graph::exec::unstable::Status> m_status{ graph::exec::unstable::Status::eUnknown }; //!< Accumulated
//!< status
};
} // namespace unable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
| 22,357 | C | 36.513423 | 119 | 0.596905 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionGraphSettings.h | // 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.
//
//! @file IExecutionGraphSettings.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionGraphSettings.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IExecutionGraphSettings;
class IExecutionGraphSettings_abi;
//! Interface for accessing global execution graph settings.
//!
//! This interface is a singleton. The settings are applied to all graphs.
//!
//! Access the singleton with @ref omni::kit::exec::core::unstable::getExecutionGraphSettings().
class IExecutionGraphSettings_abi
: public omni::core::Inherits<graph::exec::unstable::IBase,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionGraphSettings")>
{
protected:
//! If @c true all tasks will skip the scheduler and be executed immediately.
virtual bool shouldForceSerial_abi() noexcept = 0;
//! If @c true all tasks will be given to the scheduler and marked as being able to execute in parallel.
virtual bool shouldForceParallel_abi() noexcept = 0;
};
//! Returns the @ref omni::kit::exec::core::unstable::IExecutionGraphSettings singleton.
//!
//! May return @c nullptr if the *omni.kit.exec.core* extension has not been loaded.
//!
//! The returned pointer does not have @ref omni::core::IObject::acquire() called on it.
inline IExecutionGraphSettings* getExecutionGraphSettings() noexcept;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IExecutionGraphSettings.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IExecutionGraphSettings_abi
//!
//! @ingroup groupOmniKitExecCoreInterfaces
class omni::kit::exec::core::unstable::IExecutionGraphSettings
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>
{
};
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/IDef.h>
inline omni::kit::exec::core::unstable::IExecutionGraphSettings* omni::kit::exec::core::unstable::getExecutionGraphSettings() noexcept
{
// createType() always calls acquire() and returns an ObjectPtr to make sure release() is called. we don't want
// to hold a ref here to avoid static destruction issues. here we allow the returned ObjectPtr to destruct
// (after calling get()) to release our ref. we know the DLL in which the singleton was created is maintaining a
// ref and will keep the singleton alive for the lifetime of the DLL.
static auto* sSingleton = omni::core::createType<IExecutionGraphSettings>().get();
return sSingleton;
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IExecutionGraphSettings.gen.h>
| 3,376 | C | 36.522222 | 134 | 0.751777 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/Module.h | // 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.
//
//! @file Module.h
//!
//! @brief Helpers for writing modules/plugins based on @ref omni::kit::exec::core.
#pragma once
#include <omni/graph/exec/unstable/Module.h>
#include <omni/kit/exec/core/unstable/IExecutionControllerFactory.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
#ifndef DOXYGEN_BUILD
namespace detail
{
void _addClearCallback()
{
}
template <typename Fn>
void _addClearCallback(Fn&& fn)
{
addClearCallback(std::forward<Fn>(fn));
}
} // namespace detail
#endif
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
//! Helper macro to ensure EF features are enabled in the current module/plugin.
//!
//! This macro should be called from either @ref carbOnPluginStartup or @c onStarted.
//!
//! If your module/plugin registers EF nodes or passes, you must call this macro.
//!
//! @p moduleName_ is the name of your plugin and is used for debugging purposes.
//!
//! The second argument is optional and points to a callback that will be called when *any other plugin* that also calls
//! @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED is about to be unloaded. The purpose of the callback is to give *this*
//! module a chance to remove any references to objects that contain code that is about to be unloaded. The signature
//! of the callback is `void(void)`. See @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::addClearCallback for more details.
#define OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED(moduleName_, ...) \
try \
{ \
OMNI_GRAPH_EXEC_ON_MODULE_STARTED(moduleName_); \
omni::kit::exec::core::unstable::detail::_addClearCallback(__VA_ARGS__); \
} \
catch (std::exception & e) \
{ \
CARB_LOG_ERROR("failed to register %s's passes: %s", moduleName_, e.what()); \
}
//! Helper macro to ensure EF features are safely disabled when the current module/plugin unloads.
//!
//! This macro should be called from either @ref carbOnPluginShutdown or @c onUnload.
//!
//! If your module/plugin registers EF nodes or passes, you must call this macro.
#define OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD() \
do \
{ \
OMNI_GRAPH_EXEC_ON_MODULE_UNLOAD(); \
omni::kit::exec::core::unstable::getExecutionControllerFactory()->clear(); \
omni::kit::exec::core::unstable::removeClearCallbacks(); \
} while (0)
| 4,041 | C | 44.41573 | 120 | 0.501856 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IClearCallback.h | // 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.
//
//! @file IClearCallback.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IClearCallback.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
class IClearCallback_abi;
class IClearCallback;
//! Interface wrapping a callback (possibly with storage) called when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear is executed.
class IClearCallback_abi : public omni::core::Inherits<omni::graph::exec::unstable::IBase,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IClearCallback")>
{
protected:
//! Invokes the wrapped function.
virtual void onClear_abi() noexcept = 0;
};
//! Smart pointer managing an instance of @ref IClearCallback.
using ClearCallbackPtr = omni::core::ObjectPtr<IClearCallback>;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IClearCallback.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IClearCallback_abi
class omni::kit::exec::core::unstable::IClearCallback
: public omni::core::Generated<omni::kit::exec::core::unstable::IClearCallback_abi>
{
};
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IClearCallback.gen.h>
| 1,855 | C | 29.426229 | 114 | 0.734771 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionController.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! @ref omni::kit::exec::core::unstable::IExecutionController encapsulates a @ref omni::graph::exec::unstable::IGraph
//! which orchestrates the computation for one of Kit's @c UsdContext.
//!
//! See @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>
: public omni::kit::exec::core::unstable::IExecutionController_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionController")
//! Populates or updates the internal @ref omni::graph::exec::unstable::IGraph.
void compile();
//! Searches for the @ref omni::graph::exec::unstable::IDef and executes it. Useful for on-demand execution.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
bool executeDefinition(omni::core::ObjectParam<omni::graph::exec::unstable::IDef> execDef);
//! Executes the internal graph at the given time.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
bool execute(double currentTime,
float elapsedSecs,
double absoluteSimTime,
const omni::kit::StageUpdateSettings* updateSettings);
//! Returns the context owned by this controller
//!
//! The returned @ref omni::kit::exec::core::unstable::IExecutionContext will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
omni::kit::exec::core::unstable::IExecutionContext* getContext() noexcept;
//! Returns the graph owned by this controller
//!
//! The returned @ref omni::graph::exec::unstable::IGraph will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
omni::graph::exec::unstable::IGraph* getGraph() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>::compile()
{
OMNI_THROW_IF_FAILED(compile_abi());
}
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>::executeDefinition(
omni::core::ObjectParam<omni::graph::exec::unstable::IDef> execDef)
{
OMNI_THROW_IF_ARG_NULL(execDef);
bool outExecuted;
OMNI_THROW_IF_FAILED(executeDefinition_abi(execDef.get(), &outExecuted));
return outExecuted;
}
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>::execute(
double currentTime, float elapsedSecs, double absoluteSimTime, const omni::kit::StageUpdateSettings* updateSettings)
{
bool outExecuted;
OMNI_THROW_IF_FAILED(execute_abi(currentTime, elapsedSecs, absoluteSimTime, updateSettings, &outExecuted));
return outExecuted;
}
inline omni::kit::exec::core::unstable::IExecutionContext* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionController_abi>::getContext() noexcept
{
return getContext_abi();
}
inline omni::graph::exec::unstable::IGraph* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionController_abi>::getGraph() noexcept
{
return getGraph_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,516 | C | 37.606837 | 120 | 0.711913 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionControllerFactory.h | // 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.
//
//! @file IExecutionControllerFactory.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IClearCallback;
class IExecutionController;
class IExecutionControllerFactory;
class IExecutionControllerFactory_abi;
//! Factory for creating instances of @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! This interface also stores the "default" @ref omni::kit::exec::core::unstable::IExecutionController, which is
//! associated with Kit's "default" @c UsdContext.
//!
//! The factory is a singleton. Access the singleton with @ref
//! omni::kit::exec::core::unstable::getExecutionControllerFactory().
class IExecutionControllerFactory_abi
: public omni::core::Inherits<graph::exec::unstable::IBase,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionControllerFactory")>
{
protected:
//! Creates an @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! The given name should match the name of the @c UsdContext.
//!
//! Throws an exception on all errors.
virtual OMNI_ATTR("throw_result") omni::core::Result
createExecutionController_abi(OMNI_ATTR("not_null, throw_if_null, c_str") const char* name,
OMNI_ATTR("out, *return") IExecutionController** out) noexcept = 0;
//! Sets the "default" @ref omni::kit::exec::core::unstable::IExecutionController which should be owned by Kit's
//! "default"
//! @c UsdContext.
//!
//! Throws an exception if the controller has already been set.
//!
//! Throws an exception on all errors.
virtual OMNI_ATTR("throw_result") omni::core::Result
setDefaultExecutionController_abi(OMNI_ATTR("not_null, throw_if_null")
IExecutionController* controller) noexcept = 0;
//! Returns the "default" @ref omni::kit::exec::core::unstable::IExecutionController associated with the "default"
//! @c UsdContext.
//!
//! The returned pointer may be @c nullptr.
//!
//! Prefer calling @ref getDefaultExecutionController() rather than directly calling this method.
virtual IExecutionController* getDefaultExecutionController_abi() noexcept = 0;
//! Attempts to release references to all objects when unloading DLLs.
//!
//! State managed by controllers may store references to objects emanating from many DLLs. As long as a controller
//! stores a reference to an object, it will not be destructed. This causes a problem when unloading DLLs. If a
//! controller's graph/context stores a reference to an object created by "foo.dll" and "foo.dll" is unloaded, when
//! the controller later releases its reference to the object, the object's @c release() method will call into
//! unloaded code, causing a crash.
//!
//! The fix for this disastrous scenario is ensure that no outstanding references to objects created in "foo.dll"
//! are present in the process. This method attempts to do just that by releasing *all* references stored within
//! all controllers/graphs/contexts.
//!
//! A plugin may choose to store references to execution framework objects originating from other modules. In such
//! a case, the plugin can be notified when this @c clear() method is called by invoking @ref
//! omni::kit::exec::core::unstable::addClearCallback when the plugin/module is loaded.
//!
//! Upon completion of this method, pointers to controllers created by this factory will remain valid, though
//! references within the controllers to objects potentially created by other DLLs will have been released.
//!
//! This method is not thread safe.
virtual void clear_abi() noexcept = 0;
//! Adds a callback that will be invoked when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called.
//!
//! @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called when a .dll/.so providing
//! execution framework functionality is unloaded (e.g. a plugin that provides a pass or node definition). The
//! purpose of the given callback is to provide the plugin calling this method an opportunity to remove pointers to
//! code that may be unloaded. For example, OmniGraph uses this callback to remove any @ref
//! omni::graph::exec::unstable::IDef pointers in its plugins.
//!
//! Do not call this method directly. Rather, call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED in either a plugin's
//! @ref carbOnPluginStartup or @c onStarted.
virtual void addClearCallback_abi(OMNI_ATTR("not_null") IClearCallback* callback) noexcept = 0;
//! Removes a callback registered with @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::addClearCallback.
//!
//! If @p callback is @c nullptr or was not registered, this function silently fails.
//!
//! This method should not be explicitly called, rather call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD during
//! plugin/module shutdown.
virtual void removeClearCallback_abi(OMNI_ATTR("not_null") IClearCallback* callback) noexcept = 0;
};
//! Smart pointer for @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
using ExecutionControllerFactoryPtr = omni::core::ObjectPtr<IExecutionControllerFactory>;
//! Returns the singleton @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
//!
//! May return @c nullptr if the *omni.kit.exec.core* extension has not been loaded.
//!
//! The returned pointer does not have @ref omni::core::IObject::acquire() called on it.
inline IExecutionControllerFactory* getExecutionControllerFactory() noexcept;
//! Returns the "default" @ref omni::kit::exec::core::unstable::IExecutionController associated with the "default" @c
//! UsdContext.
//!
//! The returned pointer may be @c nullptr.
inline omni::core::ObjectPtr<IExecutionController> getDefaultExecutionController() noexcept;
//! Adds a callback that will be invoked when @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear()
//! is called.
//!
//! @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called when a .dll/.so providing
//! execution framework functionality is unloaded (e.g. a plugin that provides a pass or node definition). The purpose
//! of the given callback is to provide the plugin calling @ref addClearCallback an opportunity to remove pointers to
//! code that may be unloaded. For example, OmniGraph uses this callback to remove any @ref
//! omni::graph::exec::unstable::IDef pointers in its plugins.
//!
//! Do not call this method directly. Rather, call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED in either a plugin's
//! @ref carbOnPluginStartup or @c onStarted.
//!
//! The callback will be removed/unregistered by @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD.
template <typename Fn>
inline void addClearCallback(Fn&& fn) noexcept;
//! Removes any @ref omni::kit::exec::core::unstable::IExecutionControllerFactory clear callback registered by the
//! plugin/module. This method should not be explicitly called, rather call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD
//! during plugin/module shutdown.
inline void removeClearCallbacks() noexcept;
#ifndef DOXYGEN_BUILD
namespace detail
{
inline std::vector<IClearCallback*>& getClearCallbacks()
{
// we store raw pointers rather than ObjectPtr to avoid static destruction issues
static std::vector<IClearCallback*> sCallbacks;
return sCallbacks;
}
} // namespace detail
#endif // DOXYGEN_BUILD
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IExecutionControllerFactory.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IExecutionControllerFactory_abi
//!
//! @ingroup groupOmniKitExecCoreInterfaces
class omni::kit::exec::core::unstable::IExecutionControllerFactory
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>
{
};
inline omni::kit::exec::core::unstable::IExecutionControllerFactory* omni::kit::exec::core::unstable::
getExecutionControllerFactory() noexcept
{
// createType() always calls acquire() and returns an ObjectPtr to make sure release() is called. we don't want to
// hold a ref here to avoid static destruction issues. here we allow the returned ObjectPtr to destruct (after
// calling get()) to release our ref. we know the DLL in which the singleton was created is maintaining a ref and
// will keep the singleton alive for the lifetime of the DLL.
static auto sSingleton = omni::core::createType<IExecutionControllerFactory>().get();
return sSingleton;
}
inline omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> omni::kit::exec::core::unstable::
getDefaultExecutionController() noexcept
{
return getExecutionControllerFactory()->getDefaultExecutionController();
}
// additional headers needed for API implementation
#include <omni/kit/exec/core/unstable/IClearCallback.h>
#include <omni/kit/exec/core/unstable/IExecutionController.h>
template <typename Fn>
inline void omni::kit::exec::core::unstable::addClearCallback(Fn&& fn) noexcept
{
class Callback : public graph::exec::unstable::Implements<IClearCallback>
{
public:
Callback(Fn&& fn) : m_fn(std::move(fn))
{
}
protected:
void onClear_abi() noexcept override
{
m_fn();
}
Fn m_fn;
};
Callback* callback = new Callback(std::forward<Fn>(fn));
detail::getClearCallbacks().emplace_back(callback);
getExecutionControllerFactory()->addClearCallback(callback);
}
inline void omni::kit::exec::core::unstable::removeClearCallbacks() noexcept
{
auto factory = getExecutionControllerFactory();
auto& callbacks = detail::getClearCallbacks();
while (!callbacks.empty())
{
auto callback = callbacks.back();
factory->removeClearCallback(callback);
callback->release();
callbacks.pop_back();
}
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IExecutionControllerFactory.gen.h>
| 11,037 | C | 43.329317 | 120 | 0.721392 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IClearCallback.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Interface wrapping a callback (possibly with storage) called when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear is executed.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IClearCallback_abi>
: public omni::kit::exec::core::unstable::IClearCallback_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IClearCallback")
//! Invokes the wrapped function.
void onClear() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void omni::core::Generated<omni::kit::exec::core::unstable::IClearCallback_abi>::onClear() noexcept
{
onClear_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 1,536 | C | 27.999999 | 106 | 0.735677 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/TbbSchedulerState.h | // 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.
//
//! @file TbbSchedulerState.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::TbbSchedulerState.
#pragma once
#include <tbb/concurrent_queue.h>
#include <tbb/enumerable_thread_specific.h>
#include <tbb/recursive_mutex.h>
#include <tbb/task.h>
#include <atomic>
#include <thread>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
//! Implementation details for the TBB based task scheduler state singleton.
//!
//! Will be replaced.
struct TbbSchedulerState
{
tbb::concurrent_queue<tbb::task*> queueParallel; //!< Queue of parallel tasks. Allows concurrent insertion.
tbb::concurrent_queue<tbb::task*> queueSerial; //!< Queue of serial tasks. Allows concurrent insertion.
tbb::concurrent_queue<tbb::task*> queueIsolate; //!< Queue of isolate tasks. Allows concurrent insertion.
std::atomic<int> totalTasksInFlight{ 0 }; //!< Track total number of serial and parallel tasks. Used for isolation.
tbb::enumerable_thread_specific<int> tasksExecutingPerThread{ 0 }; //!< Track execution per thread to know if
//!< waiting on a task contributed to a total
//!< tasks in flight.
std::atomic<std::thread::id> serialThreadId; //!< Thread currently processing serial tasks.
std::atomic<std::thread::id> isolateThreadId; //!< Thread currently processing isolate tasks.
tbb::recursive_mutex executingThreadMutex; //!< Mutex used to serialize the processing of all context threads
//!< (i.e., all threads which kickstarted execution from a any
//!< given ExecutionContexts). This ensures that up to a single context
//!< thread is computing at any given moment, regardless of the number
//!< of threads that kickstarted execution from a given context OR the
//!< number of different ExecutionContexts that began executing
//!< concurrently (assuming that the user is utilizing the provided
//!< ParallelScheduler for those contexts, otherwise they will need to
//!< manage the synchronization on their own), which is important because
//!< serial and isolate tasks are scheduled to run on a context thread,
//!< so allowing multiple context threads to evaluate concurrently would
//!< break the promise that serial and isolate tasks cannot be executed
//!< in multiple threads simultaneously.
};
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
| 3,522 | C | 48.619718 | 120 | 0.601363 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionContext.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! @ref omni::kit::exec::core::unstable::IExecutionContext inherits all of the functionality of @ref
//! omni::graph::exec::unstable::IExecutionContext but adds information related to Kit.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionContext_abi>
: public omni::kit::exec::core::unstable::IExecutionContext_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionContext")
//! Returns Kit's timing parameters for the current execution.
const omni::kit::exec::core::unstable::ExecutionContextTime* getTime() noexcept;
//! Returns Kit's update settings for the current execution.
const omni::kit::StageUpdateSettings* getUpdateSettings() noexcept;
//! Schedule given function to execute at the end of current execution.
void schedulePostTask(omni::core::ObjectParam<graph::exec::unstable::IScheduleFunction> fn) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline const omni::kit::exec::core::unstable::ExecutionContextTime* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionContext_abi>::getTime() noexcept
{
return getTime_abi();
}
inline const omni::kit::StageUpdateSettings* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionContext_abi>::getUpdateSettings() noexcept
{
return getUpdateSettings_abi();
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionContext_abi>::schedulePostTask(
omni::core::ObjectParam<graph::exec::unstable::IScheduleFunction> fn) noexcept
{
schedulePostTask_abi(fn.get());
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
static_assert(std::is_standard_layout<omni::kit::exec::core::unstable::ExecutionContextTime>::value,
"omni::kit::exec::core::unstable::ExecutionContextTime must be standard layout to be used in ONI ABI");
| 2,703 | C | 35.54054 | 117 | 0.741028 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionControllerFactory.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Factory for creating instances of @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! This interface also stores the "default" @ref omni::kit::exec::core::unstable::IExecutionController, which is
//! associated with Kit's "default" @c UsdContext.
//!
//! The factory is a singleton. Access the singleton with @ref
//! omni::kit::exec::core::unstable::getExecutionControllerFactory().
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>
: public omni::kit::exec::core::unstable::IExecutionControllerFactory_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionControllerFactory")
//! Creates an @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! The given name should match the name of the @c UsdContext.
//!
//! Throws an exception on all errors.
omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> createExecutionController(const char* name);
//! Sets the "default" @ref omni::kit::exec::core::unstable::IExecutionController which should be owned by Kit's
//! "default"
//! @c UsdContext.
//!
//! Throws an exception if the controller has already been set.
//!
//! Throws an exception on all errors.
void setDefaultExecutionController(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IExecutionController> controller);
//! Returns the "default" @ref omni::kit::exec::core::unstable::IExecutionController associated with the "default"
//! @c UsdContext.
//!
//! The returned pointer may be @c nullptr.
//!
//! Prefer calling @ref getDefaultExecutionController() rather than directly calling this method.
omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> getDefaultExecutionController() noexcept;
//! Attempts to release references to all objects when unloading DLLs.
//!
//! State managed by controllers may store references to objects emanating from many DLLs. As long as a controller
//! stores a reference to an object, it will not be destructed. This causes a problem when unloading DLLs. If a
//! controller's graph/context stores a reference to an object created by "foo.dll" and "foo.dll" is unloaded, when
//! the controller later releases its reference to the object, the object's @c release() method will call into
//! unloaded code, causing a crash.
//!
//! The fix for this disastrous scenario is ensure that no outstanding references to objects created in "foo.dll"
//! are present in the process. This method attempts to do just that by releasing *all* references stored within
//! all controllers/graphs/contexts.
//!
//! A plugin may choose to store references to execution framework objects originating from other modules. In such
//! a case, the plugin can be notified when this @c clear() method is called by invoking @ref
//! omni::kit::exec::core::unstable::addClearCallback when the plugin/module is loaded.
//!
//! Upon completion of this method, pointers to controllers created by this factory will remain valid, though
//! references within the controllers to objects potentially created by other DLLs will have been released.
//!
//! This method is not thread safe.
void clear() noexcept;
//! Adds a callback that will be invoked when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called.
//!
//! @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called when a .dll/.so providing
//! execution framework functionality is unloaded (e.g. a plugin that provides a pass or node definition). The
//! purpose of the given callback is to provide the plugin calling this method an opportunity to remove pointers to
//! code that may be unloaded. For example, OmniGraph uses this callback to remove any @ref
//! omni::graph::exec::unstable::IDef pointers in its plugins.
//!
//! Do not call this method directly. Rather, call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED in either a plugin's
//! @ref carbOnPluginStartup or @c onStarted.
void addClearCallback(omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept;
//! Removes a callback registered with @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::addClearCallback.
//!
//! If @p callback is @c nullptr or was not registered, this function silently fails.
//!
//! This method should not be explicitly called, rather call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD during
//! plugin/module shutdown.
void removeClearCallback(omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::createExecutionController(const char* name)
{
OMNI_THROW_IF_ARG_NULL(name);
omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> out;
OMNI_THROW_IF_FAILED(createExecutionController_abi(name, out.put()));
return out;
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::setDefaultExecutionController(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IExecutionController> controller)
{
OMNI_THROW_IF_ARG_NULL(controller);
OMNI_THROW_IF_FAILED(setDefaultExecutionController_abi(controller.get()));
}
inline omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::getDefaultExecutionController() noexcept
{
return omni::core::steal(getDefaultExecutionController_abi());
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::clear() noexcept
{
clear_abi();
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::addClearCallback(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept
{
addClearCallback_abi(callback.get());
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::removeClearCallback(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept
{
removeClearCallback_abi(callback.get());
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 7,550 | C | 46.791139 | 131 | 0.726225 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionContext.h | // 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.
//
//! @file IExecutionContext.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionContext.
#pragma once
#include <omni/graph/exec/unstable/IExecutionContext.h>
namespace omni
{
namespace kit
{
struct StageUpdateSettings;
namespace exec
{
namespace core
{
namespace unstable
{
//! ABI-safe struct containing time information for graph execution.
struct ExecutionContextTime
{
double currentTime; //!< Current execution time (within application timeline)
double absoluteSimTime; //!< Absolute simulation time (from start of simulation)
float elapsedSecs; //!< Time elapsed since last execution
bool timeChanged; //!< Is this execution triggered by a time change
char _padding; //!< Padding
char _padding1; //!< Padding
char _padding2; //!< Padding
};
static_assert(std::is_standard_layout<ExecutionContextTime>::value, "ExecutionContextTime is not ABI-safe");
static_assert(offsetof(ExecutionContextTime, currentTime) == 0, "unexpected offset");
static_assert(offsetof(ExecutionContextTime, absoluteSimTime) == 8, "unexpected offset");
static_assert(offsetof(ExecutionContextTime, elapsedSecs) == 16, "unexpected offset");
static_assert(offsetof(ExecutionContextTime, timeChanged) == 20, "unexpected offset");
static_assert(24 == sizeof(ExecutionContextTime), "unexpected size");
// forward declarations needed by interface declaration
class IExecutionContext;
class IExecutionContext_abi;
class IScheduleFunction;
//! @ref omni::kit::exec::core::unstable::IExecutionContext inherits all of the functionality of @ref
//! omni::graph::exec::unstable::IExecutionContext but adds information related to Kit.
class IExecutionContext_abi : public omni::core::Inherits<omni::graph::exec::unstable::IExecutionContext,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionContext")>
{
protected:
//! Returns Kit's timing parameters for the current execution.
virtual const ExecutionContextTime* getTime_abi() noexcept = 0;
//! Returns Kit's update settings for the current execution.
virtual const omni::kit::StageUpdateSettings* getUpdateSettings_abi() noexcept = 0;
//! Schedule given function to execute at the end of current execution.
virtual void schedulePostTask_abi(OMNI_ATTR("not_null") graph::exec::unstable::IScheduleFunction* fn) noexcept = 0;
};
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "IExecutionContext.gen.h"
//! @copydoc omni::kit::exec::core::unstable::IExecutionContext_abi
class omni::kit::exec::core::unstable::IExecutionContext
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionContext_abi>
{
public:
//! Schedule given function to execute at the end of current execution.
//!
//! This inline implementation wraps lambda into IScheduleFunction.
//!
//! The supplied function should have the signature of `void()`.
//!
//! Returns true if function was scheduled. False when context is currently not executing and function won't be
//! scheduled.
template <typename FN>
inline bool schedulePostTask(FN&& callback);
};
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/IScheduleFunction.h>
template <typename FN>
inline bool omni::kit::exec::core::unstable::IExecutionContext::schedulePostTask(FN&& callback)
{
class Forwarder : public graph::exec::unstable::Implements<graph::exec::unstable::IScheduleFunction>
{
public:
Forwarder(FN&& fn) : m_fn(std::move(fn))
{
}
protected:
graph::exec::unstable::Status invoke_abi() noexcept override
{
m_fn();
return graph::exec::unstable::Status::eSuccess;
}
FN m_fn;
};
if (inExecute())
{
schedulePostTask_abi(omni::core::steal(new Forwarder(std::forward<FN>(callback))).get());
return true;
}
else
{
return false;
}
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "IExecutionContext.gen.h"
| 4,659 | C | 33.518518 | 120 | 0.716892 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionController.h | // 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.
//
//! @file IExecutionController.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionController.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
#include <omni/kit/IStageUpdate.h> // StageUpdateSettings
//! @defgroup groupOmniKitExecCoreInterfaces API Interfaces
//!
//! @brief Convenience interfaces backed by a stable ABI.
namespace omni
{
namespace graph
{
namespace exec
{
namespace unstable
{
class IDef;
class IGraph;
} // namespace unstable
} // namespace exec
} // namespace graph
namespace kit
{
namespace exec
{
//! Main namespace for Kit's integration of @ref omni::graph::exec.
namespace core
{
//! In-development interfaces for Kit's integration with Execution Framework.
//! Do not take dependencies on any code in this namespace.
namespace unstable
{
// forward declarations needed by interface declaration
class IExecutionContext;
class IExecutionController;
class IExecutionController_abi;
//! @ref omni::kit::exec::core::unstable::IExecutionController encapsulates a @ref omni::graph::exec::unstable::IGraph
//! which orchestrates the computation for one of Kit's @c UsdContext.
//!
//! See @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
class IExecutionController_abi
: public omni::core::Inherits<graph::exec::unstable::IBase, OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionController")>
{
protected:
//! Populates or updates the internal @ref omni::graph::exec::unstable::IGraph.
virtual OMNI_ATTR("throw_result") omni::core::Result compile_abi() noexcept = 0;
//! Searches for the @ref omni::graph::exec::unstable::IDef and executes it. Useful for on-demand execution.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
virtual OMNI_ATTR("throw_result") omni::core::Result
executeDefinition_abi(OMNI_ATTR("not_null, throw_if_null") omni::graph::exec::unstable::IDef* execDef,
OMNI_ATTR("out, not_null, throw_if_null, *return") bool* outExecuted) noexcept = 0;
//! Executes the internal graph at the given time.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
virtual OMNI_ATTR("throw_result") omni::core::Result
execute_abi(double currentTime,
float elapsedSecs,
double absoluteSimTime,
OMNI_ATTR("in") const omni::kit::StageUpdateSettings* updateSettings,
OMNI_ATTR("out, not_null, throw_if_null, *return") bool* outExecuted) noexcept = 0;
//! Returns the context owned by this controller
//!
//! The returned @ref omni::kit::exec::core::unstable::IExecutionContext will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
virtual OMNI_ATTR("no_acquire") IExecutionContext* getContext_abi() noexcept = 0;
//! Returns the graph owned by this controller
//!
//! The returned @ref omni::graph::exec::unstable::IGraph will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
virtual OMNI_ATTR("no_acquire") omni::graph::exec::unstable::IGraph* getGraph_abi() noexcept = 0;
};
//! Smart pointer for @ref omni::kit::exec::core::unstable::IExecutionController.
using ExecutionControllerPtr = omni::core::ObjectPtr<IExecutionController>;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IExecutionController.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IExecutionController_abi
//!
//! @ingroup groupOmniKitExecCoreInterfaces
class omni::kit::exec::core::unstable::IExecutionController
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>
{
};
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/IDef.h>
#include <omni/graph/exec/unstable/IGraph.h>
#include <omni/kit/exec/core/unstable/IExecutionContext.h>
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IExecutionController.gen.h>
| 5,112 | C | 36.050724 | 129 | 0.717723 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionGraphSettings.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Interface for accessing global execution graph settings.
//!
//! This interface is a singleton. The settings are applied to all graphs.
//!
//! Access the singleton with @ref omni::kit::exec::core::unstable::getExecutionGraphSettings().
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>
: public omni::kit::exec::core::unstable::IExecutionGraphSettings_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionGraphSettings")
//! If @c true all tasks will skip the scheduler and be executed immediately.
bool shouldForceSerial() noexcept;
//! If @c true all tasks will be given to the scheduler and marked as being able to execute in parallel.
bool shouldForceParallel() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>::shouldForceSerial() noexcept
{
return shouldForceSerial_abi();
}
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>::shouldForceParallel() noexcept
{
return shouldForceParallel_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 2,061 | C | 31.21875 | 127 | 0.745754 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/ITbbSchedulerState.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Returns a global scheduler state based on TBB.
//!
//! This object is a singleton. Access it with @ref omni::kit::exec::core::unstable::getTbbSchedulerState().
//!
//! Use of this object should be transparent to the user as it is an implementation detail of
//! @ref omni::kit::exec::core::unstable::ParallelSpawner.
//!
//! Temporary interface. Will be replaced with something more generic.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::ITbbSchedulerState_abi>
: public omni::kit::exec::core::unstable::ITbbSchedulerState_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::ITbbSchedulerState")
//! Returns the needed data to access the serial task queue.
omni::kit::exec::core::unstable::TbbSchedulerState* geState() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::kit::exec::core::unstable::TbbSchedulerState* omni::core::Generated<
omni::kit::exec::core::unstable::ITbbSchedulerState_abi>::geState() noexcept
{
return geState_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 1,923 | C | 31.066666 | 109 | 0.733229 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/ITbbSchedulerState.h | // 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.
//
//! @file ITbbSchedulerState.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::ITbbSchedulerState.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
struct TbbSchedulerState;
// forward declarations needed by interface declaration
class ITbbSchedulerState;
class ITbbSchedulerState_abi;
//! Returns a global scheduler state based on TBB.
//!
//! This object is a singleton. Access it with @ref omni::kit::exec::core::unstable::getTbbSchedulerState().
//!
//! Use of this object should be transparent to the user as it is an implementation detail of
//! @ref omni::kit::exec::core::unstable::ParallelSpawner.
//!
//! Temporary interface. Will be replaced with something more generic.
class ITbbSchedulerState_abi
: public omni::core::Inherits<graph::exec::unstable::IBase, OMNI_TYPE_ID("omni.kit.exec.core.unstable.ITbbSchedulerState")>
{
protected:
//! Returns the needed data to access the serial task queue.
virtual TbbSchedulerState* geState_abi() noexcept = 0;
};
//! Returns the singleton @ref omni::kit::exec::core::unstable::ITbbSchedulerState.
//!
//! May return @c nullptr if the *omni.kit.exec.core* extension has not been loaded.
//!
//! The returned pointer does not have @ref omni::core::IObject::acquire() called on it.
inline ITbbSchedulerState* getTbbSchedulerState() noexcept;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/ITbbSchedulerState.gen.h>
//! @copydoc omni::kit::exec::core::unstable::ITbbSchedulerState_abi
class omni::kit::exec::core::unstable::ITbbSchedulerState
: public omni::core::Generated<omni::kit::exec::core::unstable::ITbbSchedulerState_abi>
{
};
inline omni::kit::exec::core::unstable::ITbbSchedulerState* omni::kit::exec::core::unstable::getTbbSchedulerState() noexcept
{
// createType() always calls acquire() and returns an ObjectPtr to make sure release() is called. we don't want to
// hold a ref here to avoid static destruction issues. here we allow the returned ObjectPtr to destruct (after
// calling get()) to release our ref. we know the DLL in which the singleton was created is maintaining a ref and
// will keep the singleton alive for the lifetime of the DLL.
static auto sSingleton = omni::core::createType<ITbbSchedulerState>().get();
return sSingleton;
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/ITbbSchedulerState.gen.h>
| 3,116 | C | 35.244186 | 127 | 0.751284 |
omniverse-code/kit/include/omni/kit/actions/core/IAction.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/IObject.h>
#include <carb/variant/IVariant.h>
#include <carb/variant/VariantUtils.h>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Pure virtual action interface.
*/
class IAction : public carb::IObject
{
public:
/**
* Function prototype to execute an action.
*
* @param args Variable positional argument (optional).
* Maybe a VariantArray with multiple args.
* @param kwargs Variable keyword arguments (optional).
*
* @return An arbitrary variant object (could be empty).
*/
using ExecuteFunctionType = carb::variant::Variant (*)(const carb::variant::Variant& /*args*/,
const carb::dictionary::Item* /*kwargs*/);
/**
* Called when something wants to execute this action.
*
* @param args Variable positional argument (optional).
* Maybe a VariantArray with multiple args.
* @param kwargs Variable keyword arguments (optional).
*
* @return An arbitrary variant object (could be empty).
*/
virtual carb::variant::Variant execute(const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) = 0;
/**
* Invalidate this action so that executing it will not do anything.
* This can be called if it is no longer safe to execute the action,
* and by default is called when deregistering an action (optional).
*/
virtual void invalidate() = 0;
/**
* Is this an instance of the derived PythonAction class?
*
* @return True if this an instance of the derived PythonAction class, false otherwise.
*/
virtual bool isPythonAction() const = 0;
/**
* Get the id of the source extension which registered this action.
*
* @return Id of the source extension which registered this action.
*/
virtual const char* getExtensionId() const = 0;
/**
* Get the id of this action, unique to the extension that registered it.
*
* @return Id of this action, unique to the extension that registered it.
*/
virtual const char* getActionId() const = 0;
/**
* Get the display name of this action.
*
* @return Display name of this action.
*/
virtual const char* getDisplayName() const = 0;
/**
* Get the description of this action.
*
* @return Description of this action.
*/
virtual const char* getDescription() const = 0;
/**
* Get the URL of the icon used to represent this action.
*
* @return URL of the icon used to represent this action.
*/
virtual const char* getIconUrl() const = 0;
/**
* Get the tag that this action is grouped with.
*
* @return Tag that this action is grouped with.
*/
virtual const char* getTag() const = 0;
};
using IActionPtr = carb::ObjectPtr<IAction>;
inline bool operator==(const carb::ObjectPtr<IAction>& left, const carb::ObjectPtr<IAction>& right) noexcept
{
return (left.get() == right.get());
}
}
}
}
}
| 3,591 | C | 28.68595 | 108 | 0.641047 |
omniverse-code/kit/include/omni/kit/actions/core/IActionRegistry.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/kit/actions/core/IAction.h>
#include <carb/Interface.h>
#include <vector>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Defines the interface for the ActionRegistry.
*/
class IActionRegistry
{
public:
/// @private
CARB_PLUGIN_INTERFACE("omni::kit::actions::core::IActionRegistry", 1, 0);
/**
* Register an action.
*
* @param action The action to register.
*/
virtual void registerAction(carb::ObjectPtr<IAction>& action) = 0;
/**
* Create and register an action that calls a function object when executed.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param function The function object to call when the action is executed.
* @param displayName The name of the action for display purposes.
* @param description A brief description of what the action does.
* @param iconUrl The URL of an image which represents the action.
* @param tag Arbitrary tag used to group sets of related actions.
*
* @return The action that was created.
*/
virtual carb::ObjectPtr<IAction> registerAction(const char* extensionId,
const char* actionId,
IAction::ExecuteFunctionType function,
const char* displayName = "",
const char* description = "",
const char* iconUrl = "",
const char* tag = "") = 0;
/**
* Deregister an action.
*
* @param action The action to deregister.
* @param invalidate Should the action be invalidated so executing does nothing?
*/
virtual void deregisterAction(carb::ObjectPtr<IAction>& action, bool invalidate = true) = 0;
/**
* Find and deregister an action.
*
* @param extensionId The id of the source extension that registered the action.
* @param actionId Id of the action, unique to the extension that registered it.
* @param invalidate Should the action be invalidated so executing does nothing?
*
* @return The action if it exists and was deregistered, an empty ObjectPtr otherwise.
*/
virtual carb::ObjectPtr<IAction> deregisterAction(const char* extensionId,
const char* actionId,
bool invalidate = true) = 0;
/**
* Deregister all actions that were registered by the specified extension.
*
* @param extensionId The id of the source extension that registered the actions.
* @param invalidate Should the actions be invalidated so executing does nothing?
*/
virtual void deregisterAllActionsForExtension(const char* extensionId, bool invalidate = true) = 0;
/**
* Find and execute an action.
*
* @param extensionId The id of the source extension that registered the action.
* @param actionId Id of the action, unique to the extension that registered it.
* @param args Variable positional argument (optional).
* Maybe a VariantArray with multiple args.
* @param kwargs Variable keyword arguments (optional).
*
* @return An arbitrary variant object (could be empty).
*/
virtual carb::variant::Variant executeAction(const char* extensionId,
const char* actionId,
const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) const = 0;
/**
* Get an action.
*
* @param extensionId The id of the source extension that registered the action.
* @param actionId Id of the action, unique to the extension that registered it.
*
* @return The action if it exists, an empty ObjectPtr otherwise.
*/
virtual carb::ObjectPtr<IAction> getAction(const char* extensionId, const char* actionId) const = 0;
/**
* Get the total number of registered actions.
*
* @return Total number of registered actions.
*/
virtual size_t getActionCount() const = 0;
/**
* Callback function used by @ref IActionRegistry::walkAllActions.
*
* @param action The current action being visited by @ref IActionRegistry::walkAllActions.
* @param context Any user defined data that was passed to @ref IActionRegistry::walkAllActions.
*
* @return True if we should continue walking through all registered actions, false otherwise.
*/
using WalkActionsCallbackFn = bool(*)(carb::ObjectPtr<IAction> action, void* context);
/**
* Walks through all registered actions and calls a callback function for each.
*
* @param callbackFn The callback function to call for each registered action,
* until all actions have been visited or the callback function returns false.
* @param context User defined data that will be passed to callback function.
*
* @return The number of actions that were visited.
*/
virtual size_t walkAllActions(WalkActionsCallbackFn callbackFn, void* context) const = 0;
/**
* Walks through all actions that were registered by the specified extension.
*
* @param callbackFn The callback function to call for each registered action,
* until all actions have been visited or the callback function returns false.
* @param context User defined data that will be passed to callback function.
* @param extensionId The id of the extension which registered the actions.
*
* @return The number of actions that were visited.
*/
virtual size_t walkAllActionsRegisteredByExtension(WalkActionsCallbackFn callbackFn,
void* context,
const char* extensionId) const = 0;
/**
* Get all registered actions.
*
* @return All registered actions.
*/
std::vector<carb::ObjectPtr<IAction>> getAllActions() const
{
std::vector<carb::ObjectPtr<IAction>> actions;
const size_t numActionsWalked = walkAllActions(
[](carb::ObjectPtr<IAction> action, void* context) {
auto actionsPtr = static_cast<std::vector<carb::ObjectPtr<IAction>>*>(context);
actionsPtr->push_back(action);
return true;
},
&actions);
CARB_ASSERT(numActionsWalked == actions.size());
CARB_UNUSED(numActionsWalked);
return actions;
}
/**
* Get all actions that were registered by the specified extension.
*
* @param extensionId Id of the extension which registered the actions.
*
* @return All actions that were registered by the specified extension.
*/
std::vector<carb::ObjectPtr<IAction>> getAllActionsForExtension(const char* extensionId) const
{
std::vector<carb::ObjectPtr<IAction>> actions;
const size_t numActionsWalked = walkAllActionsRegisteredByExtension(
[](carb::ObjectPtr<IAction> action, void* context) {
auto actionsPtr = static_cast<std::vector<carb::ObjectPtr<IAction>>*>(context);
actionsPtr->push_back(action);
return true;
},
&actions, extensionId);
CARB_ASSERT(numActionsWalked == actions.size());
CARB_UNUSED(numActionsWalked);
return actions;
}
};
}
}
}
}
| 8,260 | C | 38.526316 | 107 | 0.624092 |
omniverse-code/kit/include/omni/kit/actions/core/Action.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/kit/actions/core/IAction.h>
#include <carb/ObjectUtils.h>
#include <omni/String.h>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Abstract action base class providing the core functionaly common to all actions.
*/
class Action : public IAction
{
public:
/**
* Struct containing all optional data that can be associated with any action.
*/
struct MetaData
{
omni::string displayName; //!< The name of the action for display purposes.
omni::string description; //!< A brief description of what the action does.
omni::string iconUrl; //!< The URL of an image which represents the action.
omni::string tag; //!< Arbitrary tag used to group sets of related actions.
};
/**
* Constructor.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param metaData Pointer to a meta data struct associated with the action.
*/
Action(const char* extensionId, const char* actionId, const MetaData* metaData = nullptr)
: m_extensionId(extensionId ? extensionId : ""), m_actionId(actionId ? actionId : "")
{
if (metaData)
{
m_metaData = *metaData;
}
}
/**
* Destructor.
*/
~Action() override = default;
/**
* @ref IAction::isPythonAction
*/
bool isPythonAction() const override
{
return false;
}
/**
* @ref IAction::getExtensionId
*/
const char* getExtensionId() const override
{
return m_extensionId.c_str();
}
/**
* @ref IAction::getActionId
*/
const char* getActionId() const override
{
return m_actionId.c_str();
}
/**
* @ref IAction::getDisplayName
*/
const char* getDisplayName() const override
{
return m_metaData.displayName.c_str();
}
/**
* @ref IAction::getDescription
*/
const char* getDescription() const override
{
return m_metaData.description.c_str();
}
/**
* @ref IAction::getIconUrl
*/
const char* getIconUrl() const override
{
return m_metaData.iconUrl.c_str();
}
/**
* @ref IAction::getTag
*/
const char* getTag() const override
{
return m_metaData.tag.c_str();
}
protected:
omni::string m_extensionId; //!< The id of the source extension that registered the action.
omni::string m_actionId; //!< Id of the action, unique to the extension that registered it.
MetaData m_metaData; //!< Struct containing all the meta data associated with this action.
private:
CARB_IOBJECT_IMPL
};
}
}
}
}
| 3,224 | C | 23.24812 | 95 | 0.635546 |
omniverse-code/kit/include/omni/kit/actions/core/LambdaAction.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <omni/kit/actions/core/Action.h>
#include <carb/thread/Mutex.h>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Concrete action class that can be used to create an action from C++ which calls a supplied lambda/function.
*/
class LambdaAction : public Action
{
public:
/**
* Factory.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param metaData Pointer to a meta data struct associated with the action.
* @param function The function object to call when the action is executed.
*
* @return The action that was created.
*/
static carb::ObjectPtr<IAction> create(const char* extensionId,
const char* actionId,
const MetaData* metaData,
ExecuteFunctionType function)
{
// Note: It is important to construct the handler using ObjectPtr<T>::InitPolicy::eSteal,
// otherwise we end up incresing the reference count by one too many during construction,
// resulting in a carb::ObjectPtr<IAction> whose object instance will never be destroyed.
return carb::stealObject<IAction>(new LambdaAction(extensionId, actionId, metaData, function));
}
/**
* Constructor.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param metaData Pointer to a meta data struct associated with the action.
* @param function The function object to call when the action is executed.
*/
LambdaAction(const char* extensionId, const char* actionId, const MetaData* metaData, ExecuteFunctionType function)
: Action(extensionId, actionId, metaData), m_function(function)
{
}
/**
* Destructor.
*/
~LambdaAction() override = default;
/**
* @ref IAction::execute
*/
carb::variant::Variant execute(const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) override
{
std::lock_guard<carb::thread::mutex> lock(m_mutex);
return m_function ? m_function(args, kwargs) : carb::variant::Variant();
}
/**
* @ref IAction::invalidate
*/
void invalidate() override
{
std::lock_guard<carb::thread::mutex> lock(m_mutex);
m_function = nullptr;
}
private:
ExecuteFunctionType m_function; //!< The function object to call when the action is executed.
carb::thread::mutex m_mutex; //!< Mutex to lock for thread safety when calling the function.
};
}
}
}
}
| 3,270 | C | 32.721649 | 119 | 0.657187 |
omniverse-code/kit/include/omni/kit/xr/XRBootstrap.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/settings/ISettings.h>
#include <carb/settings/SettingsUtils.h>
#include <vector>
#include <string>
#include <set>
namespace omni
{
namespace kit
{
namespace xr
{
/**
* @brief Gets a list of (Vulkan) extensions, which is overridable and has default values
*
* @param path a settings path to store an overridable copy of this list
* @param hardCodedExtensions pre-loaded list of (vk) extensions
* @return std::vector<std::string> list of (vk) extensions to use
*/
inline std::vector<std::string> getExtensions(const char* path, const std::vector<std::string>& hardCodedExtensions)
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "XRContext::getExtensions");
// This provides a way of other plugins/extensions to list additional extensions to load for
// an instance or device:
// This code scans the settings dictionaries under:
// /renderer/vulkan/deviceExtensions and /renderer/vulkan/instanceExtensions and will check if the items
// found contain an array, if they do the array is parsed and it's contents is added to the
// list of extensions to load
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
carb::dictionary::IDictionary* dictionary = carb::getCachedInterface<carb::dictionary::IDictionary>();
auto type = settings->getItemType(path);
std::set<std::string> extensions;
extensions.insert(hardCodedExtensions.begin(), hardCodedExtensions.end());
if (type == carb::dictionary::ItemType::eDictionary)
{
auto item = settings->getSettingsDictionary(path);
size_t count = dictionary->getItemChildCount(item);
for (size_t idx = 0; idx < count; idx++)
{
auto child = dictionary->getItemChildByIndex(item, idx);
auto childType = dictionary->getItemType(child);
if (childType == carb::dictionary::ItemType::eString)
{
std::string extension = dictionary->getStringBuffer(child);
extensions.insert(extension);
}
else if (childType == carb::dictionary::ItemType::eDictionary)
{
if (dictionary->isAccessibleAsArrayOf(carb::dictionary::ItemType::eString, child))
{
size_t arrLength = dictionary->getArrayLength(child);
for (size_t arrIdx = 0; arrIdx < arrLength; ++arrIdx)
{
std::string ext = dictionary->getStringBufferAt(child, arrIdx);
extensions.insert(ext);
}
}
}
}
}
std::vector<std::string> result;
result.insert(result.begin(), extensions.begin(), extensions.end());
return result;
}
/**
* @brief Ensure compatibility with XR
*
* Various XR plugins (especially SteamVR) require certain renderer options.
* Ensure those options are set before an XRSystem is initialized.
*/
inline void bootstrapXR()
{
auto settings = carb::getCachedInterface<carb::settings::ISettings>();
// If an XR extension is enabled disable the validation layer for now
if (settings->getAsBool("/xr/debug"))
{
// This one breaks openvr
settings->setBool("/renderer/debug/validation/enabled", false);
}
#if CARB_PLATFORM_WINDOWS
std::vector<std::string> instanceExtensions =
getExtensions("/persistent/xr/vulkanInstanceExtensions",
{ "VK_NV_external_memory_capabilities", "VK_KHR_external_memory_capabilities",
"VK_KHR_get_physical_device_properties2" });
std::vector<std::string> deviceExtensions = getExtensions(
"/persistent/xr/vulkanDeviceExtensions", { "VK_NV_dedicated_allocation", "VK_NV_external_memory",
"VK_NV_external_memory_win32", "VK_NV_win32_keyed_mutex" });
#elif CARB_PLATFORM_LINUX
std::vector<std::string> instanceExtensions =
getExtensions("/persistent/xr/vulkanInstanceExtensions",
{ "VK_KHR_external_memory_capabilities", "VK_KHR_get_physical_device_properties2",
"VK_KHR_external_semaphore_capabilities" });
std::vector<std::string> deviceExtensions = getExtensions(
"/persistent/xr/vulkanDeviceExtensions",
{ "VK_KHR_external_memory", "VK_KHR_external_semaphore", "VK_KHR_dedicated_allocation",
"VK_KHR_get_memory_requirements2", "VK_KHR_external_memory_fd", "VK_KHR_external_semaphore_fd" });
#elif CARB_PLATFORM_MACOS
// FIXME!! do some actual checks here. MacOS doesn't natively support Vulkan and only
// supports it by using MoltenVK. The set of available extensions may differ
// as a result so we don't want to make any assumptions here yet.
std::vector<std::string> instanceExtensions;
std::vector<std::string> deviceExtensions;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
carb::settings::setStringArray(
settings, "/renderer/vulkan/instanceExtensions/omni.kit.xr.plugin", instanceExtensions);
carb::settings::setStringArray(
settings, "/renderer/vulkan/deviceExtensions/omni.kit.xr.plugin", deviceExtensions);
}
} // namespace xr
} // namespace kit
} // namespace omni
| 5,783 | C | 39.166666 | 116 | 0.662805 |
omniverse-code/kit/include/omni/kit/raycast/query/RaycastQueryUtils.h | // 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.
//
#pragma once
#include <omni/math/linalg/vec.h>
#include <carb/settings/ISettings.h>
namespace omni
{
namespace kit
{
namespace raycastquery
{
inline void adjustRayToSection(Ray& ray)
{
static constexpr char kSectionEnabledSettingPath[] = "/rtx/sectionPlane/enabled";
static constexpr char kSectionPlaneSettingPath[] = "/rtx/sectionPlane/plane";
auto settings = carb::getCachedInterface<carb::settings::ISettings>();
if (!settings->get<bool>(kSectionEnabledSettingPath))
{
return;
}
using namespace omni::math::linalg;
vec4<float> plane;
settings->getAsFloatArray(kSectionPlaneSettingPath, &plane[0], 4);
vec3 const planeNormal(plane[0], plane[1], plane[2]);
vec4 const rayOrigin4(ray.origin.x, ray.origin.y, ray.origin.z, 1.f);
vec3 const rayDir(ray.direction.x, ray.direction.y, ray.direction.z);
float const originPlaneDistance = -rayOrigin4.Dot(plane);
bool const originCulled = originPlaneDistance > 0.f;
float const dirNormalCos = rayDir.Dot(planeNormal);
bool const sameNormalDirection = dirNormalCos > 0.f;
float const rayDist = (dirNormalCos != 0) ? (originPlaneDistance / dirNormalCos) : ray.maxT;
if (originCulled)
{
if (sameNormalDirection)
{
// move minT so it's starting from the section plane.
ray.minT = ray.minT > rayDist ? ray.minT : rayDist;
}
else
{
// the entire ray is culled.
ray.minT = ray.maxT = std::numeric_limits<float>::infinity();
}
}
else
{
if (sameNormalDirection)
{
// the entire ray is within non-culled section, no adjustment needed
}
else
{
// move maxT so it ends on the section plane
ray.maxT = ray.maxT < rayDist ? ray.maxT : rayDist;
}
}
}
}
}
}
| 2,312 | C | 27.9125 | 96 | 0.66263 |
omniverse-code/kit/include/omni/kit/raycast/query/IRaycastQuery.h | // Copyright (c) 2019-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.
//
//! @file
//!
//! @brief Carbonite Interface for IRaycastQuery.
#pragma once
#include <carb/Interface.h>
#include <carb/events/IEvents.h>
#include <rtx/raytracing/RaycastQueryTypes.h>
namespace omni
{
namespace kit
{
namespace raycastquery
{
using RaycastSequenceId = uint32_t;
using Ray = rtx::raytracing::RaycastQueryRay;
using RayQueryResult = rtx::raytracing::RaycastQueryResult;
enum class Result : int32_t
{
eSuccess = 0, // No error
eInvalidParameter, // One of the given parameters is not valid
eParameterIsNull, // One of the given parameters is null, which is not expected
eRaycastSequenceDoesNotExist, // Raycast sequence requested does not exist
eRaycastQueryManagerDoesNotExist, // Raycast query manager does not exist, raycast queries disabled
eRaycastSequenceAdditionFailed, // Raycast sequence addition failed
};
struct RaycastQueryOp
{
size_t(CARB_ABI* getQueryCount)(RaycastQueryOp* op);
Ray*(CARB_ABI* getQueryRays)(RaycastQueryOp* op);
RayQueryResult*(CARB_ABI* getQueryResults)(RaycastQueryOp* op);
void(CARB_ABI* callback)(RaycastQueryOp* op);
void(CARB_ABI* destroy)(RaycastQueryOp* op);
};
class IRaycastQuery
{
public:
CARB_PLUGIN_INTERFACE("omni::rtx::IRaycastQuery", 1, 0)
/**
* @brief This function adds a raycast query operation in the current scene.
*
* @param raycastOp operation that describes a query that needs to be executed
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result submitRaycastQuery(RaycastQueryOp* raycastOp) = 0;
/**
* @brief Add a sequence of raycast queries that maintains last valid value
* and will execute raycast on current scene.
*
* @param sequenceId (out) sequence id (needed for removal)
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result addRaycastSequence(RaycastSequenceId& sequenceId) = 0;
/**
* @brief Remove a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result removeRaycastSequence(RaycastSequenceId sequence) = 0;
/**
* @brief Submit a new ray request to a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result submitRayToRaycastSequence(RaycastSequenceId sequence, const Ray& ray) = 0;
/**
* @brief Get latest result from a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param ray latest ray that was resolved
* @param result result of the ray request
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result getLatestResultFromRaycastSequence(RaycastSequenceId sequence,
Ray& ray,
RayQueryResult& result) = 0;
/**
* @brief Set the size of the raycast sequence.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param size number of ray casts in sequence
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result setRaycastSequenceArraySize(RaycastSequenceId sequence, size_t size) = 0;
/**
* @brief Submit a new ray request to a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param ray pointer to list of rays
* @param size length of the ray array
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result submitRayToRaycastSequenceArray(RaycastSequenceId sequence, Ray* ray, size_t size) = 0;
/**
* @brief Get latest result from a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param ray latest ray that was resolved
* @param result result of the ray request
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result getLatestResultFromRaycastSequenceArray(RaycastSequenceId sequence,
Ray* ray,
RayQueryResult* result,
size_t size) = 0;
};
template <typename RaycastQueryOpLambdaType>
class RaycastQueryTemplate final : public RaycastQueryOp
{
public:
RaycastQueryTemplate(const Ray& queryRay, RaycastQueryOpLambdaType&& raycastOpLambda)
: m_raycastOpLambda(static_cast<RaycastQueryOpLambdaType&&>(raycastOpLambda)), m_queryRay(queryRay)
{
m_queryResult = {};
RaycastQueryOp::getQueryCount = RaycastQueryTemplate<RaycastQueryOpLambdaType>::getQueryCount;
RaycastQueryOp::getQueryRays = RaycastQueryTemplate<RaycastQueryOpLambdaType>::getQueryRays;
RaycastQueryOp::getQueryResults = RaycastQueryTemplate<RaycastQueryOpLambdaType>::getQueryResults;
RaycastQueryOp::callback = RaycastQueryTemplate<RaycastQueryOpLambdaType>::callback;
RaycastQueryOp::destroy = RaycastQueryTemplate<RaycastQueryOpLambdaType>::destroy;
}
~RaycastQueryTemplate()
{
}
static size_t CARB_ABI getQueryCount(RaycastQueryOp* op)
{
return 1;
}
static Ray* CARB_ABI getQueryRays(RaycastQueryOp* op)
{
RaycastQueryTemplate<RaycastQueryOpLambdaType>* typedOp = (RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op;
return &(typedOp->m_queryRay);
}
static RayQueryResult* CARB_ABI getQueryResults(RaycastQueryOp* op)
{
RaycastQueryTemplate<RaycastQueryOpLambdaType>* typedOp = (RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op;
return &(typedOp->m_queryResult);
}
static void CARB_ABI destroy(RaycastQueryOp* op)
{
delete ((RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op);
}
static void CARB_ABI callback(RaycastQueryOp* op)
{
RaycastQueryTemplate<RaycastQueryOpLambdaType>* typedOp = (RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op;
typedOp->m_raycastOpLambda(typedOp->m_queryRay, typedOp->m_queryResult);
}
private:
RaycastQueryOpLambdaType m_raycastOpLambda;
Ray m_queryRay;
RayQueryResult m_queryResult;
};
/**
* @brief This function adds a raycast query operation in the current scene
*
* @param ray the ray to submit
* @param callback the callback lambda function to execute when resolved
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
template <typename RaycastOpLambdaType>
inline void submitRaycastQueryLambda(IRaycastQuery* raycastQuery, const Ray& ray, RaycastOpLambdaType&& callback)
{
auto raycastOp = new RaycastQueryTemplate<RaycastOpLambdaType>(ray, static_cast<RaycastOpLambdaType&&>(callback));
raycastQuery->submitRaycastQuery(raycastOp);
}
}
}
}
| 7,988 | C | 32.426778 | 118 | 0.677266 |
omniverse-code/kit/include/omni/kit/ui/Common.h | // 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.
//
#pragma once
#include <carb/events/EventsUtils.h>
#include <carb/imgui/ImGui.h>
#include <omni/kit/KitUtils.h>
#include <omni/ui/Font.h>
#include <omni/ui/IGlyphManager.h>
#include <cmath>
#include <functional>
#include <memory>
namespace omni
{
namespace kit
{
namespace ui
{
class Widget;
using WidgetRef = std::shared_ptr<Widget>;
struct Mat44
{
carb::Double4 rows[4];
};
enum class ClippingType
{
eNone,
eEllipsisLeft,
eEllipsisRight,
eWrap,
eCount
};
enum class DraggingType
{
eStarted,
eStopped
};
enum class UnitType
{
ePixel,
ePercent
};
struct Length
{
float value;
UnitType unit;
};
struct Percent : public Length
{
explicit Percent(float v) : Length{ v, UnitType::ePercent }
{
}
};
struct Pixel : public Length
{
explicit Pixel(float v) : Length{ v, UnitType::ePixel }
{
}
};
inline float calculateWidth(const Length& length, const float usedWidth = 0.0f)
{
if (length.unit == UnitType::ePercent)
return length.value * 0.01f * (getImGui()->getWindowContentRegionWidth() - usedWidth);
return length.value;
}
inline float calculateHeight(const Length& length)
{
if (length.unit == UnitType::ePercent)
return length.value * 0.01f * getImGui()->getWindowContentRegionWidth();
return length.value;
}
inline const char* getCustomGlyphCode(const char* glyphFilePath, omni::ui::FontStyle fontStyle)
{
return getGlyphManager()->getGlyphInfo(glyphFilePath, fontStyle).code;
}
inline bool clipText(ClippingType clipType, std::string& text, float& clippingWidth, const float itemWidth, size_t maxLength)
{
carb::imgui::ImGui* imgui = getImGui();
using OnClipText = std::function<std::string(const std::string& str, float itemWidth)>;
auto clipFn = [&text, &clippingWidth, itemWidth, imgui](OnClipText onClipText) {
// only re-build m_clippedText when the column is re-sized
if (itemWidth != clippingWidth)
{
std::string fullText = text;
carb::Float2 textWidth = imgui->calcTextSize(text.c_str(), nullptr, false, -1.0f);
if (textWidth.x > itemWidth && itemWidth > 0.0f)
{
text = onClipText(fullText, itemWidth);
}
clippingWidth = itemWidth;
return true;
}
return false;
};
switch (clipType)
{
case ClippingType::eEllipsisLeft:
return clipFn([maxLength, imgui](const std::string& fullText, float itemWidth) {
size_t index = 0;
std::string text = fullText;
while (++index < fullText.length())
{
text = "..." + fullText.substr(index);
carb::Float2 textWidth = imgui->calcTextSize(text.c_str(), nullptr, false, -1.0f);
if (textWidth.x < itemWidth || text.length() == maxLength - 1)
break;
}
return text;
});
case ClippingType::eEllipsisRight:
return clipFn([maxLength, imgui](const std::string& fullText, float itemWidth) {
int64_t index = static_cast<int64_t>(fullText.length());
std::string text = fullText;
while (--index > 0)
{
text = fullText.substr(0, index) + "...";
carb::Float2 textWidth = imgui->calcTextSize(text.c_str(), nullptr, false, -1.0f);
if (textWidth.x < itemWidth || text.length() == maxLength - 1)
break;
}
return text;
});
case ClippingType::eWrap:
// not supported
default:
break;
}
return false;
}
inline bool handleDragging(const std::function<void(WidgetRef, DraggingType)>& draggedFn, WidgetRef widget, bool isDragging)
{
carb::imgui::ImGui* imgui = getImGui();
bool dragging = imgui->isMouseDragging(0, -1.0f);
if (draggedFn != nullptr)
{
// dragging handling
if (dragging == true && isDragging == false)
draggedFn(widget, DraggingType::eStarted);
else if (dragging == false && isDragging == true)
draggedFn(widget, DraggingType::eStopped);
}
return dragging;
}
inline void handleDragDrop(std::function<void(WidgetRef, const char*)>& dragDropFn,
const char* dragDropPayloadName,
WidgetRef widget)
{
carb::imgui::ImGui* imgui = getImGui();
// handle drag-drop callback
if (dragDropFn != nullptr && (dragDropPayloadName != nullptr && dragDropPayloadName[0] != 0) &&
imgui->beginDragDropTarget())
{
const carb::imgui::Payload* payload = imgui->acceptDragDropPayload(dragDropPayloadName, 0);
if (payload && payload->isDelivery())
{
dragDropFn(widget, reinterpret_cast<const char*>(payload->data));
}
imgui->endDragDropTarget();
}
}
template <class T>
inline bool almostEqual(T a, T b)
{
return a == b;
}
static constexpr float kDefaultEpsilonF = 0.001f;
static constexpr double kDefaultEpsilonD = 0.0001;
inline bool almostEqual(double a, double b, double epsilon = kDefaultEpsilonD)
{
return std::abs(a - b) < epsilon;
}
inline bool almostEqual(float a, float b, float epsilon = std::numeric_limits<float>::epsilon())
{
return std::abs(a - b) < epsilon;
}
inline bool almostEqual(carb::ColorRgb a, carb::ColorRgb b, float epsilon = kDefaultEpsilonF)
{
return almostEqual(a.r, b.r, epsilon) && almostEqual(a.g, b.g, epsilon) && almostEqual(a.b, b.b, epsilon);
}
inline bool almostEqual(carb::ColorRgba a, carb::ColorRgba b, float epsilon = kDefaultEpsilonF)
{
return almostEqual(a.r, b.r, epsilon) && almostEqual(a.g, b.g, epsilon) && almostEqual(a.b, b.b, epsilon) &&
almostEqual(a.a, b.a, epsilon);
}
inline bool almostEqual(carb::Float3 a, carb::Float3 b, float epsilon = kDefaultEpsilonF)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon) && almostEqual(a.z, b.z, epsilon);
}
inline bool almostEqual(carb::Double2 a, carb::Double2 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon);
}
inline bool almostEqual(carb::Double3 a, carb::Double3 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon) && almostEqual(a.z, b.z, epsilon);
}
inline bool almostEqual(carb::Double4 a, carb::Double4 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon) && almostEqual(a.z, b.z, epsilon) &&
almostEqual(a.w, b.w, epsilon);
}
inline bool almostEqual(ui::Mat44 a, ui::Mat44 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.rows[0], b.rows[0], epsilon) && almostEqual(a.rows[1], b.rows[1], epsilon) &&
almostEqual(a.rows[2], b.rows[2], epsilon) && almostEqual(a.rows[3], b.rows[3], epsilon);
}
inline bool almostEqual(carb::Int2 a, carb::Int2 b)
{
return (a.x == b.x) && (a.y == b.y);
}
}
}
}
| 7,500 | C | 27.85 | 125 | 0.6364 |
omniverse-code/kit/include/omni/kit/ui/Drag.h | // 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.
//
#pragma once
#include "ValueWidget.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a input drag.
*
* Usage:
* Drag<int, int>
* Drag<carb::Int2, int>
* Drag<double>
* Drag<carb::Double2>
* Drag<carb::Double3>
* Drag<carb::Double4>
*/
template <class T, class RangeT = double>
class OMNI_KIT_UI_CLASS_API Drag : public SimpleValueWidget<T>
{
public:
static const WidgetType kType;
OMNI_KIT_UI_API explicit Drag(
const char* text = "", T value = {}, RangeT min = {}, RangeT max = {}, float valueDragSpeed = 1.0f);
OMNI_KIT_UI_API ~Drag();
RangeT min;
RangeT max;
std::string format;
float dragSpeed;
OMNI_KIT_UI_API WidgetType getType() override;
protected:
bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) override;
};
#if CARB_POSIX && !CARB_TOOLCHAIN_CLANG
extern template class OMNI_KIT_UI_API Drag<int, int>;
extern template class OMNI_KIT_UI_API Drag<uint32_t, uint32_t>;
extern template class OMNI_KIT_UI_API Drag<carb::Int2, int>;
extern template class OMNI_KIT_UI_API Drag<double>;
extern template class OMNI_KIT_UI_API Drag<carb::Double2>;
extern template class OMNI_KIT_UI_API Drag<carb::Double3>;
extern template class OMNI_KIT_UI_API Drag<carb::Double4>;
#endif
using DragInt = Drag<int, int>;
using DragUInt = Drag<uint32_t, uint32_t>;
using DragInt2 = Drag<carb::Int2, int>;
using DragDouble = Drag<double>;
using DragDouble2 = Drag<carb::Double2>;
using DragDouble3 = Drag<carb::Double3>;
using DragDouble4 = Drag<carb::Double4>;
}
}
}
| 1,981 | C | 25.783783 | 108 | 0.717819 |
omniverse-code/kit/include/omni/kit/ui/Label.h | // 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.
//
#pragma once
#include "Widget.h"
#include <functional>
#include <memory>
#include <string>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a label.
*/
class OMNI_KIT_UI_CLASS_API Label : public Widget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Label);
/**
* Constructor.
*
* @param text The text for the label to use.
*/
OMNI_KIT_UI_API explicit Label(const char* text);
/**
* Constructor.
*
* @param text The text for the label to use.
* @param copyToClipboard when true, can be copied to clipboard via context menu
*/
OMNI_KIT_UI_API Label(const char* text, bool copyToClipboard, ClippingType clipping, omni::ui::FontStyle fontStyle);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~Label() override;
/**
* Gets the text of the label.
*
* @return The text of the label.
*/
OMNI_KIT_UI_API const char* getText() const;
/**
* Sets the text of the label.
*
* @param text The text of the label.
*/
OMNI_KIT_UI_API virtual void setText(const char* text);
/**
* Sets the color of the label text.
*
* @param textColor
*/
OMNI_KIT_UI_API virtual void setTextColor(const carb::ColorRgba& textColor);
/**
* Resets the color of the label text.
*
* @param textColor
*/
OMNI_KIT_UI_API virtual void resetTextColor();
/**
* Sets the callback function when the label is clicked.
*
* fn The callback function when the label is clicked.
*/
OMNI_KIT_UI_API void setClickedFn(const std::function<void(WidgetRef)>& fn);
/**
* @see Widget::getType
*/
OMNI_KIT_UI_API WidgetType getType() override;
/**
* @see Widget::draw
*/
void draw(float elapsedTime) override;
std::shared_ptr<Widget> tooltip;
void setPaddingX(float px)
{
m_paddingX = px;
}
protected:
std::string m_text;
bool m_customColor = false;
carb::ColorRgba m_textColor = { 1.f, 1.f, 1.f, 1.f };
std::function<void(WidgetRef)> m_clickedFn;
std::string m_clippedText;
float m_clippingWidth;
float m_paddingX = 0.0f;
bool m_copyToClipboard;
ClippingType m_clippingMode = ClippingType::eNone;
};
}
}
}
| 2,753 | C | 22.338983 | 120 | 0.63785 |
omniverse-code/kit/include/omni/kit/ui/BroadcastModel.h | // Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include "Api.h"
#include "Model.h"
namespace omni
{
namespace kit
{
namespace ui
{
class OMNI_KIT_UI_CLASS_API BroadcastModel : public Model
{
public:
using TargetId = uint32_t;
OMNI_KIT_UI_API virtual TargetId addTarget(const std::shared_ptr<Model>& model,
const std::string& pathPrefixOrigin,
const std::string& pathPrefixNew) = 0;
OMNI_KIT_UI_API virtual void removeTarget(TargetId) = 0;
};
OMNI_KIT_UI_API std::unique_ptr<BroadcastModel> createBroadcastModel();
}
}
}
| 1,044 | C | 23.302325 | 85 | 0.685824 |
omniverse-code/kit/include/omni/kit/ui/Api.h | // 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.
//
#pragma once
#if defined _WIN32
# ifdef OMNI_KIT_UI_EXPORTS
# define OMNI_KIT_UI_API __declspec(dllexport)
# define OMNI_KIT_UI_CLASS_API
# else
# define OMNI_KIT_UI_API __declspec(dllimport)
# define OMNI_KIT_UI_CLASS_API
# endif
#else
# ifdef OMNI_KIT_UI_EXPORTS
# define OMNI_KIT_UI_API __attribute__((visibility("default")))
# define OMNI_KIT_UI_CLASS_API __attribute__((visibility("default")))
# else
# define OMNI_KIT_UI_API
# define OMNI_KIT_UI_CLASS_API
# endif
#endif
| 987 | C | 34.285713 | 77 | 0.698075 |
omniverse-code/kit/include/omni/kit/ui/HotkeyUtils.h | // 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.
//
#pragma once
#include <carb/InterfaceUtils.h>
#include <carb/imgui/ImGui.h>
#include <carb/input/IInput.h>
#include <carb/input/InputUtils.h>
#include <imgui/imgui.h>
#include <string>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Classical keyboard Hotkey (modifier + key). Can be polled, works nicely with imgui windows.
*/
class Hotkey
{
public:
void initialize(carb::input::KeyboardModifierFlags mod, carb::input::KeyboardInput key, std::string displayName = "")
{
m_key = key;
m_mod = mod;
m_displayName = displayName;
m_shortcut = carb::input::getModifierFlagsString(mod);
if (!m_shortcut.empty())
m_shortcut += " + ";
m_shortcut += carb::input::getKeyboardInputString(key);
}
bool isPressedInCurrentWindow(carb::imgui::ImGui* imgui, carb::input::Keyboard* keyboard) const
{
return imgui->isWindowFocused(carb::imgui::kFocusedFlagRootAndChildWindows) && isPressed(keyboard, m_mod, m_key);
}
bool isPressed(carb::input::Keyboard* keyboard) const
{
return isPressed(keyboard, m_mod, m_key);
}
static bool isPressed(carb::input::Keyboard* keyboard,
carb::input::KeyboardModifierFlags mod,
carb::input::KeyboardInput key)
{
using namespace carb::input;
if ((uint32_t)key >= (uint32_t)carb::input::KeyboardInput::eCount)
{
return false;
}
// TODO: That's not correct to use ImGui directly here. It's better to add this functionality to
// carb::imgui::ImGui, but it's not possible to update it at this moment because physxui that is also using
// carb::imgui::ImGui is blocked. The only way to access WantCaptureKeyboard is using directly ImGui.
::ImGuiIO& io = ::ImGui::GetIO();
if (io.WantCaptureKeyboard)
{
// When wantCaptureKeyboard is true, ImGui is using the keyboard input exclusively, and it's not necessary
// to dispatch the input to the application. (e.g. InputText active, or an ImGui window is focused and
// navigation is enabled, etc.).
return false;
}
carb::input::IInput* input = carb::getCachedInterface<carb::input::IInput>();
const auto isKeyPressed = [input, keyboard](KeyboardInput key) {
return (input->getKeyboardButtonFlags(keyboard, key) & kButtonFlagTransitionDown);
};
const auto isUp = [input, keyboard](KeyboardInput key) {
return (input->getKeyboardButtonFlags(keyboard, key) & kButtonFlagStateUp);
};
const auto isDown = [input, keyboard](KeyboardInput key) {
return (input->getKeyboardButtonFlags(keyboard, key) & kButtonFlagStateDown);
};
if (!isKeyPressed(key))
return false;
if (!(mod & kKeyboardModifierFlagShift) &&
(isDown(KeyboardInput::eLeftShift) || isDown(KeyboardInput::eRightShift)))
return false;
if (!(mod & kKeyboardModifierFlagControl) &&
(isDown(KeyboardInput::eLeftControl) || isDown(KeyboardInput::eRightControl)))
return false;
if (!(mod & kKeyboardModifierFlagAlt) && (isDown(KeyboardInput::eLeftAlt) || isDown(KeyboardInput::eRightAlt)))
return false;
if ((mod & kKeyboardModifierFlagShift) && isUp(KeyboardInput::eLeftShift) && isUp(KeyboardInput::eRightShift))
return false;
if ((mod & kKeyboardModifierFlagControl) && isUp(KeyboardInput::eLeftControl) &&
isUp(KeyboardInput::eRightControl))
return false;
if ((mod & kKeyboardModifierFlagAlt) && isUp(KeyboardInput::eLeftAlt) && isUp(KeyboardInput::eRightAlt))
return false;
if ((mod & kKeyboardModifierFlagSuper) && isUp(KeyboardInput::eLeftSuper) && isUp(KeyboardInput::eRightSuper))
return false;
if ((mod & kKeyboardModifierFlagCapsLock) && isUp(KeyboardInput::eCapsLock))
return false;
if ((mod & kKeyboardModifierFlagNumLock) && isUp(KeyboardInput::eNumLock))
return false;
return true;
}
const char* getDisplayName() const
{
return m_displayName.c_str();
}
const char* getShortcut() const
{
return m_shortcut.c_str();
}
carb::input::KeyboardInput getKey() const
{
return m_key;
}
carb::input::KeyboardModifierFlags getModifiers() const
{
return m_mod;
}
private:
carb::input::KeyboardInput m_key = carb::input::KeyboardInput::eCount;
carb::input::KeyboardModifierFlags m_mod = 0;
std::string m_shortcut;
std::string m_displayName;
};
}
}
}
| 5,179 | C | 35.223776 | 121 | 0.644912 |
omniverse-code/kit/include/omni/kit/ui/PopupDialog.h | // 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.
//
#pragma once
#include <carb/imgui/ImGui.h>
#include <string>
#include <utility>
#include <vector>
namespace carb
{
namespace imgui
{
struct ImGui;
}
}
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines an PopupDialog class that draws popup dialogbox.
*/
class PopupDialog
{
public:
/**
* Constructor.
*
* @param title Title of the popup dialog.
* @param message Message of the popup dialog.
* @modal True to create a modal popup.
*/
PopupDialog(const char* title, const char* message, bool modal) : m_title(title), m_message(message), m_modal(modal)
{
}
/**
* Adds option button to the dialog.
*
* @param name Name of the option button.
* @param tooltop Tooltip of the option button.
*/
void addOptionButton(const char* name, const char* tooltip)
{
m_options.emplace_back(name, tooltip);
}
/**
* Gets the selected option button index.
*
* @param index The selected index.
* @return True if the index is valid. False if none selected.
*/
bool getSelectedOption(size_t& index) const
{
if (m_selectedIndex != kInvalidSelection)
{
index = m_selectedIndex;
return true;
}
return false;
}
/**
* Draws the popup window.
*
* @param The imgui instance.
*/
void draw(carb::imgui::ImGui* imgui)
{
using namespace carb::imgui;
imgui->openPopup(m_title.c_str());
if (m_modal ? imgui->beginPopupModal(m_title.c_str(), nullptr, kWindowFlagAlwaysAutoResize) :
imgui->beginPopup(m_title.c_str(), kWindowFlagAlwaysAutoResize))
{
imgui->text(m_message.c_str());
m_selectedIndex = kInvalidSelection;
for (size_t i = 0; i < m_options.size(); i++)
{
if (imgui->button(m_options[i].first.c_str()))
{
m_selectedIndex = i;
}
if (imgui->isItemHovered(0) && m_options[i].second.length())
{
imgui->setTooltip(m_options[i].second.c_str());
}
imgui->sameLine();
}
imgui->endPopup();
}
}
private:
static const size_t kInvalidSelection = SIZE_MAX;
std::string m_title;
std::string m_message;
bool m_modal;
std::vector<std::pair<std::string, std::string>> m_options;
size_t m_selectedIndex = kInvalidSelection;
};
}
}
}
| 2,988 | C | 24.330508 | 120 | 0.592704 |
omniverse-code/kit/include/omni/kit/ui/Window.h | // Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/events/EventsUtils.h>
#include <omni/kit/ui/Common.h>
#include <omni/kit/ui/Menu.h>
#include <omni/ui/windowmanager/IWindowCallbackManager.h>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace omni
{
namespace kit
{
namespace ui
{
class Container;
enum class WindowEventType : uint32_t
{
eVisibilityChange,
eUpdate
};
/**
* Defines a window.
*/
class OMNI_KIT_UI_CLASS_API Window
{
public:
typedef uint32_t Flags;
static constexpr Flags kWindowFlagNone = 0;
static constexpr Flags kWindowFlagNoTitleBar = (1 << 0);
static constexpr Flags kWindowFlagNoResize = (1 << 1);
static constexpr Flags kWindowFlagNoMove = (1 << 2);
static constexpr Flags kWindowFlagNoScrollbar = (1 << 3);
static constexpr Flags kWindowFlagNoCollapse = (1 << 4);
static constexpr Flags kWindowFlagNoSavedSettings = (1 << 5);
static constexpr Flags kWindowFlagShowHorizontalScrollbar = (1 << 7);
static constexpr Flags kWindowFlagForceVerticalScrollbar = (1 << 8);
static constexpr Flags kWindowFlagForceHorizontalScrollbar = (1 << 9);
static constexpr Flags kWindowFlagNoFocusOnAppearing = (1 << 10);
static constexpr Flags kWindowFlagNoClose = (1 << 11);
static constexpr Flags kWindowFlagModal = (1 << 12);
/**
* Constructor.
*
* @param title The window title.
* @param width The window default width.
* @param height The window default height.
*/
OMNI_KIT_UI_API explicit Window(
const char* title,
uint32_t width = 640,
uint32_t height = 480,
bool open = true,
bool addToMenu = true,
const std::string& menuPath = "",
bool isToggleMenu = true,
omni::ui::windowmanager::DockPreference dockPreference = omni::ui::windowmanager::DockPreference::eLeftBottom,
Flags flags = kWindowFlagNone);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~Window();
/**
* Gets the title of the window.
*
* @return The title of the window.
*/
OMNI_KIT_UI_API const char* getTitle() const;
/**
* Sets the title for the window.
*
* @param title The title of the window.
*/
OMNI_KIT_UI_API void setTitle(const char* title);
/**
* Gets the width of the window.
*
* @return The width of the window.
*/
OMNI_KIT_UI_API uint32_t getWidth() const;
/**
* Sets the width of the window.
*
* @param width The width of the window.
*/
OMNI_KIT_UI_API void setWidth(uint32_t width);
/**
* Gets the height of the window.
*
* @return The height of the window.
*/
OMNI_KIT_UI_API uint32_t getHeight() const;
/**
* Sets the height of the window.
*
* @param height The height of the window.
*/
OMNI_KIT_UI_API void setHeight(uint32_t height);
/**
* Sets the size of the window.
*
* @param width The width of the window.
* @param height The height of the window.
*/
OMNI_KIT_UI_API void setSize(uint32_t width, uint32_t height);
/**
* Sets the flags for the window.
*
* @param fkags The flags for the window.
*/
void setFlags(Flags flags)
{
m_flags = flags;
}
/**
* Gets the flags for the window
*
* @param flags The flags for the window.
*/
Flags getFlags() const
{
return m_flags;
}
/**
* Sets the alpha value (transparency) of the window.
*
* @param alpha The alpha value of the window.
*/
OMNI_KIT_UI_API void setAlpha(float alpha);
/**
* Gets the layout for the window.
*
* @return The layout for the window.
*/
OMNI_KIT_UI_API std::shared_ptr<Container> getLayout() const;
/**
* Sets the layout for the window.
*
* @return The layout for the window.
*/
OMNI_KIT_UI_API void setLayout(std::shared_ptr<Container> layout);
/**
* Determines if the window is visible.
*
* @return true if the window is visible.
*/
OMNI_KIT_UI_API bool isVisible() const;
/**
* Determines if the window has modal popup.
*
* @return true if the window has modal popup.
*/
OMNI_KIT_UI_API bool isModal() const;
/**
* Shows a window and sets it to visible.
*/
OMNI_KIT_UI_API void show();
/**
* Hides a window and sets it to not visible.
*/
OMNI_KIT_UI_API void hide();
/**
*
*/
OMNI_KIT_UI_API void setUpdateFn(const std::function<void(float)>& fn);
OMNI_KIT_UI_API void setVisibilityChangedFn(const std::function<void(bool)>& fn);
OMNI_KIT_UI_API void setVisible(bool visible);
carb::events::IEventStream* getEventStream() const
{
return m_stream.get();
}
std::shared_ptr<Menu> menu;
carb::Float2 currentMousePos;
carb::Float2 windowPos;
bool windowPosValid = false;
private:
Window() = default;
void updateWindow(float elapsedTime);
carb::events::IEventStreamPtr m_stream;
omni::ui::windowmanager::IWindowCallbackPtr m_handle;
carb::events::ISubscriptionPtr m_updateSubId;
std::string m_title;
std::string m_menuPath;
uint32_t m_width = 0;
uint32_t m_height = 0;
float m_alpha = 1.0f;
bool m_visible = false;
std::shared_ptr<Container> m_layout = nullptr;
std::function<void(float)> m_updateFn;
std::function<void(bool)> m_visibilityChangedFn;
bool m_addToMenu;
bool m_menuTogglable;
bool m_autoResize = false;
omni::ui::windowmanager::DockPreference m_dock;
Flags m_flags;
};
}
}
}
| 6,128 | C | 24.326446 | 118 | 0.631527 |
omniverse-code/kit/include/omni/kit/ui/ValueWidget.h | // 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.
//
#pragma once
#include "Button.h"
#include "ModelWidget.h"
namespace omni
{
namespace kit
{
namespace ui
{
template <class T>
class OMNI_KIT_UI_CLASS_API ValueWidget : public ModelWidget
{
public:
ValueWidget(T value) : ModelWidget(), m_value(value)
{
this->text = text;
auto model = createSimpleValueModel(Model::getNodeTypeForT<T>());
model->setValue(m_modelRoot.c_str(), "", value);
setModel(std::move(model), "");
}
void setValue(const T& v)
{
_setValue(v);
}
const T& getValue() const
{
return m_value;
}
bool isValueAmbiguous() const
{
return m_valueAmbiguous;
}
void setValueAmbiguous(bool state)
{
ModelChangeInfo info = { m_sender, false };
m_valueAmbiguous = state;
if (m_valueAmbiguous)
m_model->setType(m_modelRoot.c_str(), "", ModelNodeType::eUnknown, info);
}
bool leftHanded;
std::string text;
std::function<void(const T&)> onChangedFn;
std::function<void(const ValueWidget<T>*)> onRightClickFn;
std::shared_ptr<Widget> tooltip;
protected:
virtual void _onValueChange(){};
void rightClickHandler()
{
carb::imgui::ImGui* imgui = getImGui();
if (imgui->isItemHovered(0) && imgui->isMouseReleased(1))
{
if (onRightClickFn)
onRightClickFn(this);
}
}
void _setValue(const T& value, bool transient = false, bool force = false)
{
if (!almostEqual(value, m_value) || force || m_valueAmbiguous)
{
m_value = value;
m_valueAmbiguous = false;
this->_onValueChange();
ModelChangeInfo info = { m_sender, transient };
m_model->setValue(m_modelRoot.c_str(), "", m_value, 0, m_isTimeSampled, m_timeCode, info);
if (onChangedFn)
onChangedFn(m_value);
}
}
virtual void _onModelValueChange() override
{
ModelValue<T> newValue = m_model->getValue<T>(m_modelRoot.c_str(), "", 0, m_isTimeSampled, m_timeCode);
if (!almostEqual(newValue.value, m_value) || newValue.ambiguous != m_valueAmbiguous)
{
m_value = newValue.value;
m_valueAmbiguous = newValue.ambiguous;
this->_onValueChange();
if (onChangedFn)
onChangedFn(m_value);
}
}
T m_value;
bool m_valueAmbiguous;
};
template <class T>
class OMNI_KIT_UI_CLASS_API SimpleValueWidget : public ValueWidget<T>
{
public:
SimpleValueWidget(const std::string& text, T value) : ValueWidget<T>(value), leftHanded(false), m_wasActive(false)
{
this->text = text;
}
bool leftHanded;
std::string text;
std::shared_ptr<Widget> tooltip;
void draw(float dt) override
{
this->_processModelEvents();
if (!this->m_visible)
return;
carb::imgui::ImGui* imgui = getImGui();
carb::imgui::Font* font = this->m_font;
if (font)
imgui->pushFont(font);
imgui->pushItemFlag(carb::imgui::kItemFlagDisabled, !this->m_enabled);
imgui->pushStyleVarFloat(carb::imgui::StyleVar::eAlpha, this->m_enabled ? 1.0f : .6f);
if (this->leftHanded)
{
_drawWidget(imgui, dt);
_drawText(imgui);
}
else
{
_drawText(imgui);
_drawWidget(imgui, dt);
}
this->rightClickHandler();
imgui->popStyleVar();
imgui->popItemFlag();
if (font)
imgui->popFont();
}
protected:
virtual bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) = 0;
virtual bool _isTransientChangeSupported() const
{
return true;
}
private:
void _drawWidget(carb::imgui::ImGui* imgui, float dt)
{
if (this->m_label.empty())
{
this->m_label = "##hidelabel";
this->m_label += this->m_uniqueId;
}
if (m_wasActive)
{
processImguiInputEvents();
}
predictActiveProcessImguiInput(this->m_label.c_str());
float uiScale = imgui->getWindowDpiScale();
imgui->pushItemWidth(calculateWidth(this->width) * uiScale);
const bool isTransientChangeSupported = this->_isTransientChangeSupported();
T v = this->getValue();
if (this->_drawImGuiWidget(imgui, v))
{
this->_setValue(v, isTransientChangeSupported);
}
imgui->popItemWidth();
m_wasActive = imgui->isItemActive();
if (m_wasActive || this->m_isDragging)
this->m_isDragging = handleDragging(this->m_draggedFn, Widget::shared_from_this(), this->m_isDragging);
// Just finished editing -> force notify value with undo
if (imgui->isItemDeactivatedAfterEdit() && isTransientChangeSupported)
{
this->_setValue(v, false, true);
}
if (this->tooltip && imgui->isItemHovered(0))
{
imgui->beginTooltip();
this->tooltip->draw(dt);
imgui->endTooltip();
}
}
void _drawText(carb::imgui::ImGui* imgui)
{
if (this->text.size() > 0)
{
if (this->leftHanded)
imgui->sameLine();
imgui->text(this->text.c_str());
if (!this->leftHanded)
imgui->sameLine();
}
}
bool m_wasActive;
};
}
}
}
| 5,948 | C | 23.891213 | 118 | 0.575488 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.