file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/include/carb/logging/Logger.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. // //! @file //! @brief carb.logging Logger definition #pragma once #include "../Defines.h" #include <cstdint> // example-begin Logger namespace carb { //! Namespace for logging interfaces and utilities namespace logging { /** * Defines an extension interface for logging backends to register with the ILogging system. * * @see ILogging::addLogger * @see ILogging::removeLogger */ struct Logger { /** * Handler for a formatted log message. * * This function is called by @ref ILogging if the Logger has * been registered via @ref ILogging::addLogger(), log level passes the threshold (for module or * globally if not set for module), and logging is enabled (for module or globally if not set * for module). * * @param logger The logger interface - can be nullptr if not used by handleMessage * @param source The source of the message in UTF8 character encoding - commonly plugin name * @param level The severity level of the message * @param filename The file name where the message originated from. * @param functionName The name of the function where the message originated from. * @param lineNumber The line number where the message originated from * @param message The formatted message in UTF8 character encoding * * @thread_safety this function will potentially be called simultaneously from multiple threads. */ void(CARB_ABI* handleMessage)(Logger* logger, const char* source, int32_t level, const char* filename, const char* functionName, int lineNumber, const char* message); // NOTE: This interface, because it is inherited from, is CLOSED and may not have any additional functions added // without an ILogging major version increase. }; } // namespace logging } // namespace carb // example-end
omniverse-code/kit/include/carb/logging/ILogging.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. // //! @file //! @brief carb.logging interface definition #pragma once #include "../Interface.h" #include "../IObject.h" #include "StandardLogger2.h" namespace carb { namespace logging { struct StandardLogger; class StandardLogger2; struct Logger; /** * Defines a callback type for setting log level for every source. */ typedef void(CARB_ABI* SetLogLevelFn)(int32_t logLevel); /** * Defines a log setting behavior. */ enum class LogSettingBehavior { eInherit, eOverride }; /** * Function pointer typedef for a logging function * * @note Typically this is not used directly. It exists solely for \ref g_carbLogFn and represents the type of * \ref carb::logging::ILogging::log(). * @param source The log source (typically client or plugin) * @param level The log level, such as \ref kLevelInfo * @param fileName The name of the source file that generated the log message (typically from `__FILE__`) * @param functionName The name of the source function that generated the log message (such as via * \ref CARB_PRETTY_FUNCTION) * @param lineNumber The line number of \p filename that generated the log message (typically from `__LINE__`) * @param fmt A printf format string * @param ... varargs for \p fmt */ typedef void (*LogFn)(const char* source, int32_t level, const char* fileName, const char* functionName, int lineNumber, const char* fmt, ...); /** * Defines the log system that is associated with the Framework. * * This interface defines the log system, which is a singleton object. It can be used at any moment, including * before the startup of the Framework and after the Framework was shutdown. It allows a user to setup the logging * behavior in advance and allows the Framework to log during its initialization. * * Logger - is an interface for logging backend. ILogging can contain multiple Loggers and every message will be passed * to every logger. There is one implementation of a Logger provided - StandardLogger. It can log into file, console and * debug window. ILogging starts up with one instance of \ref StandardLogger2, which can be retrieved by calling * getDefaultLogger(). It is added by default, but can be removed with * `getLogging()->removeLogger(getLogging()->getDefaultLogger()->getLogger())`. * * ILogging supports multiple sources of log messages. Source is just a name to differentiate the origins of a message. * Every plugin, application and Framework itself are different sources. However user can add more custom sources if * needed. * * Use the logging macros from Log.h for all logging in applications and plugins. * * There are 2 log settings: log level (to control log severity threshold) and log enabled (to toggle whole logging). * Both of them can be set globally and per source. */ struct ILogging { CARB_PLUGIN_INTERFACE("carb::logging::ILogging", 1, 1) /** * Logs a formatted message to the specified log source and log level. * * This API is used primarily by the CARB_LOG_XXXX macros. * * @param source The log source to log the message to. * @param level The level to log the message at. * @param fileName The file name to log to. * @param functionName The name of the function where the message originated from. * @param lineNumber The line number * @param fmt The print formatted message. * @param ... The variable arguments for the formatted message variables. */ void(CARB_ABI* log)(const char* source, int32_t level, const char* fileName, const char* functionName, int lineNumber, const char* fmt, ...) CARB_PRINTF_FUNCTION(6, 7); /** * Sets global log level threshold. Messages below this threshold will be dropped. * * @param level The log level to set. */ void(CARB_ABI* setLevelThreshold)(int32_t level); /** * Gets global log level threshold. Messages below this threshold will be dropped. * * @return Global log level. */ int32_t(CARB_ABI* getLevelThreshold)(); /** * Sets global log enabled setting. * * @param enabled Global log enabled setting. */ void(CARB_ABI* setLogEnabled)(bool enabled); /** * If global log is enabled. * * @return Global log enabled. */ bool(CARB_ABI* isLogEnabled)(); /** * Sets log level threshold for the specified source. Messages below this threshold will be dropped. * Per source log settings can either inherit global or override it, it is configured with * LogSettingBehavior::eInherit and LogSettingBehavior::eOverride accordingly. * * @param source The source to set log level setting for. Must not be nullptr. * @param behavior The log setting behavior for the source. * @param level The log level to set. This param is ignored if behavior is set to LogSettingBehavior::eInherit. */ void(CARB_ABI* setLevelThresholdForSource)(const char* source, LogSettingBehavior behavior, int32_t level); /** * Sets log enabled setting for the specified source. * Per source log settings can either inherit global or override it, it is configured with * LogSettingBehavior::eInherit and LogSettingBehavior::eOverride accordingly. * * @param source The source to set log enabled setting for. Must not be nullptr. * @param behavior The log setting behavior for the source. * @param enabled The log enabled setting. This param is ignored if behavior is set to LogSettingBehavior::eInherit. */ void(CARB_ABI* setLogEnabledForSource)(const char* source, LogSettingBehavior behavior, bool enabled); /** * Reset all log settings set both globally and per source. * Log system resets to the defaults: log is enabled and log level is 'warn'. */ void(CARB_ABI* reset)(); /** * Adds a logger to the ILogging. * @see StandardLogger2::getLogger() * @param logger The logger to be added. */ void(CARB_ABI* addLogger)(Logger* logger); /** * Removes the logger from the ILogging. * @see StandardLogger2::getLogger() * @param logger The logger to be removed. */ void(CARB_ABI* removeLogger)(Logger* logger); /** * Accesses the default logger. * * This logger can be disabled by passing it to \ref removeLogger(). This logger is owned by the logging system and * cannot be destroyed by passing it to \ref destroyStandardLoggerOld(). * * @rst * .. deprecated:: 156.0 * Use getDefaultLogger() instead * @endrst * * @returns the default logger. */ CARB_DEPRECATED("Use getDefaultLogger() instead") StandardLogger*(CARB_ABI* getDefaultLoggerOld)(); /** * Creates a new \ref StandardLogger instance. * * Use this method to create additional \ref StandardLogger instances. This can be useful when you want to log * to multiple output destinations but want different configuration for each. Use \ref addLogger() to make it * active. When finished with the \ref StandardLogger pass it to \ref destroyStandardLoggerOld(). * * @rst * .. deprecated:: 156.0 * Use createStandardLogger() instead * @endrst * * @returns A new \ref StandardLogger. */ CARB_DEPRECATED("Use createStandardLogger() instead") StandardLogger*(CARB_ABI* createStandardLoggerOld)(); /** * Use this method to destroy a \ref StandardLogger that was created via \ref createStandardLogger(). * * @rst * .. deprecated:: 156.0 * The ``StandardLogger2`` that replaces ``StandardLogger`` can be destroyed by calling ``release()``. * @endrst * * @param logger The logger to be destroyed. */ CARB_DEPRECATED("Use StandardLogger2::release() instead") void(CARB_ABI* destroyStandardLoggerOld)(StandardLogger* logger); /** * Register new logging source. * This function is mainly automatically used by plugins, application and the Framework itself to create * their own logging sources. * * Custom logging source can also be created if needed. It is the user's responsibility to call * ILogging::unregisterSource in that case. * * It is the source responsibility to track its log level. The reason is that it allows to filter out * logging before calling into the logging system, thus making the performance cost for the disabled logging * negligible. It is done by providing a callback `setLevelThreshold` to be called by ILogging when any setting * which influences this source is changed. * * @param source The source name. Must not be nullptr. * @param setLevelThreshold The callback to be called to update log level. ILogging::unregisterSource must be called * when the callback is no longer valid. */ void(CARB_ABI* registerSource)(const char* source, SetLogLevelFn setLevelThreshold); /** * Unregister logging source. * * @param source The source name. Must not be nullptr. */ void(CARB_ABI* unregisterSource)(const char* source); /** * Instructs the logging system to deliver all log messages to the Logger backends asynchronously. Async logging is * OFF by default. * * This causes log() calls to be buffered so that log() may return as quickly as possible. A background thread then * issues these buffered log messages to the registered Logger backend objects. * * @param logAsync True to use async logging; false to disable async logging. * @return true if was previously using async logging; false if was previously using synchronous logging. */ bool(CARB_ABI* setLogAsync)(bool logAsync); /** * Returns whether the ILogging system is using async logging. * @return true if currently using async logging; false if currently using synchronous logging */ bool(CARB_ABI* getLogAsync)(); /** * When ILogging is in async mode, wait until all log messages have flushed out to the various loggers. */ void(CARB_ABI* flushLogs)(); /** * Retrieves the extended StandardLogger2 interface from an old \ref StandardLogger instance. * @param logger The logger to retrieve the instance from. If `nullptr` then `nullptr` will be returned. * @returns The \ref StandardLogger2 interface for \p logger, or `nullptr`. */ StandardLogger2*(CARB_ABI* getStandardLogger2)(StandardLogger* logger); /** * Accesses the default logger. * * This logger can be disabled by passing the underlying logger (from \ref StandardLogger2::getLogger()) to * \ref removeLogger(). This logger is owned by the logging system and calling \ref StandardLogger2::release() has * no effect. * * @returns the default \ref StandardLogger2. */ StandardLogger2*(CARB_ABI* getDefaultLogger)(); //! @private StandardLogger2*(CARB_ABI* createStandardLoggerInternal)(); /** * Creates a new \ref StandardLogger2 instance. * * Use this method to create additional \ref StandardLogger2 instances. This can be useful when you want to log * to multiple output destinations but want different configuration for each. Pass the value from * \ref StandardLogger2::getLogger() to \ref addLogger() to make it active. When finished with the * \ref StandardLogger2 call \ref StandardLogger2::release(). * * @returns A new \ref StandardLogger2. */ ObjectPtr<StandardLogger2> createStandardLogger() { using Ptr = ObjectPtr<StandardLogger2>; return Ptr(createStandardLoggerInternal(), Ptr::InitPolicy::eSteal); } }; } // namespace logging } // namespace carb
omniverse-code/kit/include/carb/logging/LoggingUtils.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 Utilities for carb.logging #pragma once #include "Log.h" #if CARB_ASSERT_ENABLED # include "../thread/Util.h" #endif namespace carb { namespace logging { /** * A class that pauses logging to a file when constructed and resumes logging to a file when destroyed. */ class ScopedFilePause { public: /** * RAII Constructor. * * @param inst The StandardLogger to pause file logging for. */ CARB_DEPRECATED("Use StandardLogger2 instead") ScopedFilePause(StandardLogger* inst) : ScopedFilePause(g_carbLogging->getStandardLogger2(inst)) { } /** * RAII Constructor. * * @param inst The \ref StandardLogger2 to pause file logging for. */ ScopedFilePause(StandardLogger2* inst) : m_inst(inst) { if (m_inst) { m_inst->addRef(); m_inst->pauseFileLogging(); } } /** * RAII Destructor. * * Restarts file logging on the StandardLogger that was given to the constructor. */ ~ScopedFilePause() { if (m_inst) { m_inst->resumeFileLogging(); m_inst->release(); } } CARB_PREVENT_COPY_AND_MOVE(ScopedFilePause); private: StandardLogger2* m_inst; }; /** * A RAII object for overriding a thread's log level for a given type in \ref StandardLogger while in scope. * * When this object is constructed, \ref StandardLogger2::setLevelThresholdThreadOverride() is called as long as the * given logger object is not `nullptr`. Upon destruction, \ref StandardLogger2::clearLevelThresholdThreadOverride() is * called. */ class ScopedLevelThreadOverride { public: /** * Converting constructor for StandardLogger. * @warning It is not recommended to use this from within a \a carb.tasking task across context switches. * @param logger The \ref StandardLogger instance to override. If `nullptr` no action is taken. * @param type The \ref OutputType to override. * @param level The overriding \ref loglevel. */ CARB_DEPRECATED("Use StandardLogger2 instead") ScopedLevelThreadOverride(StandardLogger* logger, OutputType type, int32_t level) : ScopedLevelThreadOverride(g_carbLogging->getStandardLogger2(logger), type, level) { } /** * Constructor for overriding a log level for the calling thread. * @warning It is not recommended to use this from within a \a carb.tasking task across context switches. * @param logger The \ref StandardLogger2 instance to override. If `nullptr` no action is taken. * @param type The \ref OutputType to override. * @param level The overriding \ref loglevel. */ ScopedLevelThreadOverride(StandardLogger2* logger, OutputType type, int32_t level) : m_logger(logger), m_type(type) #if CARB_ASSERT_ENABLED , m_threadId(carb::this_thread::getId()) #endif { if (m_logger) { m_logger->addRef(); m_logger->setLevelThresholdThreadOverride(m_type, level); } } /** * Destructor which clears the override for the current thread. */ ~ScopedLevelThreadOverride() { // Make sure we are on the same thread CARB_ASSERT(m_threadId == carb::this_thread::getId()); if (m_logger) { m_logger->clearLevelThresholdThreadOverride(m_type); m_logger->release(); } } CARB_PREVENT_COPY_AND_MOVE(ScopedLevelThreadOverride); private: StandardLogger2* m_logger; OutputType m_type; #if CARB_ASSERT_ENABLED thread::ThreadId m_threadId; #endif }; } // namespace logging } // namespace carb
omniverse-code/kit/include/carb/logging/Log.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. // //! @file //! @brief carb.logging utilities #pragma once #include "../Framework.h" #include "ILogging.h" #include "../../omni/log/ILog.h" #include <cctype> #include <cstdint> #include <cstdio> // example-begin Log levels namespace carb { namespace logging { //! \defgroup loglevel Log Levels //! @{ /** * Verbose level, this is for detailed diagnostics messages. Expect to see some verbose messages on every frame under * certain conditions. */ const int32_t kLevelVerbose = -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. */ const int32_t kLevelInfo = -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 (default as zero). */ const int32_t kLevelWarn = 0; /** * Error level, this is for error messages. An error has occurred but the program can continue. */ const int32_t kLevelError = 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. */ const int32_t kLevelFatal = 2; //! @} } // namespace logging } // namespace carb // example-end //! A global weak variable representing the current log level. //! @note This variable is registered by \ref carb::logging::registerLoggingForClient() and is updated whenever the //! logging level changes. //! @warning If \ref carb::logging::deregisterLoggingForClient() is not called before a module is unloaded, changing the //! log level can result in a crash since \ref carb::logging::ILogging retains a pointer to this variable. CARB_WEAKLINK int32_t g_carbLogLevel = carb::logging::kLevelWarn; //! A global weak variable cache of the logging function. //! //! This variable is initialized by \ref carb::logging::registerLoggingForClient() and stores a pointer to //! \ref carb::logging::ILogging::log() for performance, so that the interface does not have to constantly be acquired //! (even via \ref carb::getCachedInterface()). CARB_WEAKLINK carb::logging::LogFn g_carbLogFn CARB_PRINTF_FUNCTION(6, 7); //! A global weak variable cache of the logging interface. //! //! This variable is initialized by \ref carb::logging::registerLoggingForClient(). As \ref carb::logging::ILogging is a //! built-in interface from the Carbonite Framework, this variable can be safely cached without //! \ref carb::getCachedInterface(). CARB_WEAKLINK carb::logging::ILogging* g_carbLogging; #if CARB_COMPILER_GNUC || defined(DOXYGEN_BUILD) /** * A printf that will never be executed but allows the compiler to test if there are format errors. * * This is a no-op on GCC and Clang because they support `__attribute__((format))`. * @param fmt The printf format specifier * @param ... Optional arguments */ # define CARB_FAKE_PRINTF(fmt, ...) \ do \ { \ } while (0) #else # define CARB_FAKE_PRINTF(fmt, ...) \ do \ { \ if (false) \ ::printf(fmt, ##__VA_ARGS__); \ } while (0) #endif //! \defgroup logmacros Logging Macros //! @{ //! Logging macro if the level is dynamic. //! //! Prefer using @ref CARB_LOG_VERBOSE, @ref CARB_LOG_INFO, etc. if the level is static. //! @param level The \ref loglevel //! @param fmt The printf format specifier string //! @param ... Optional arguments #define CARB_LOG(level, fmt, ...) \ do \ { \ auto lvl = (level); \ if (g_carbLogFn && g_carbLogLevel <= lvl) \ { \ CARB_FAKE_PRINTF(fmt, ##__VA_ARGS__); \ g_carbLogFn(g_carbClientName, lvl, __FILE__, __func__, __LINE__, fmt, ##__VA_ARGS__); \ } \ } while (0) //! Logging macro for static log level. //! @param fmt The printf format specifier string //! @param ... Optional arguments #define CARB_LOG_VERBOSE(fmt, ...) CARB_LOG(carb::logging::kLevelVerbose, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE #define CARB_LOG_INFO(fmt, ...) CARB_LOG(carb::logging::kLevelInfo, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE #define CARB_LOG_WARN(fmt, ...) CARB_LOG(carb::logging::kLevelWarn, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE #define CARB_LOG_ERROR(fmt, ...) CARB_LOG(carb::logging::kLevelError, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE #define CARB_LOG_FATAL(fmt, ...) CARB_LOG(carb::logging::kLevelFatal, fmt, ##__VA_ARGS__) //! Single-time logging macro if the level is dynamic. //! //! Prefer using @ref CARB_LOG_VERBOSE_ONCE, @ref CARB_LOG_INFO_ONCE, etc. if the level is static. //! @note This logs a single time by using `static` initialization. //! @param level The \ref loglevel //! @param fmt The print format specifier string //! @param ... Optional arguments #define CARB_LOG_ONCE(level, fmt, ...) \ do \ { \ static bool CARB_JOIN(logged_, __LINE__) = \ (g_carbLogFn && g_carbLogLevel <= (level)) ? \ (false ? \ (::printf(fmt, ##__VA_ARGS__), true) : \ (g_carbLogFn(g_carbClientName, (level), __FILE__, __func__, __LINE__, fmt, ##__VA_ARGS__), true)) : \ false; \ CARB_UNUSED(CARB_JOIN(logged_, __LINE__)); \ } while (0) //! Single-time logging macro for static log level. //! @note This logs a single time by using `static` initialization. //! @param fmt The print format specifier string //! @param ... Optional arguments #define CARB_LOG_VERBOSE_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelVerbose, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE_ONCE #define CARB_LOG_INFO_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelInfo, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE_ONCE #define CARB_LOG_WARN_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelWarn, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE_ONCE #define CARB_LOG_ERROR_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelError, fmt, ##__VA_ARGS__) //! @copydoc CARB_LOG_VERBOSE_ONCE #define CARB_LOG_FATAL_ONCE(fmt, ...) CARB_LOG_ONCE(carb::logging::kLevelFatal, fmt, ##__VA_ARGS__) //! @} //! Placeholder macro for any globals that must be declared for the logging system. //! @note This is typically not used as it is included in the @ref CARB_GLOBALS_EX macro. #define CARB_LOG_GLOBALS() namespace carb { namespace logging { //! Accessor for logging interface. //! @returns \ref ILogging interface as read from \ref g_carbLogging inline ILogging* getLogging() { return g_carbLogging; } //! Acquires the default ILogging interface and registers log channels. //! //! This acquires the \ref ILogging interface and assigns it to a special \ref g_carbLogging variable. The //! \ref g_carbLogLevel variable is registered with \ref ILogging so that it is kept up to date when log level changes. //! The \ref g_carbLogFn variable is also initialized. Finally \ref omni::log::addModulesChannels() is called to //! register log channels. //! @note It is typically not necessary to call this function. It is automatically called for plugins by //! \ref carb::pluginInitialize() (in turn called by \ref CARB_PLUGIN_IMPL). For script bindings it is called by //! \ref carb::acquireFrameworkForBindings(). For applications it is called by //! \ref carb::acquireFrameworkAndRegisterBuiltins() (typically called by \ref OMNI_CORE_INIT). //! @see deregisterLoggingForClient() inline void registerLoggingForClient() noexcept { g_carbLogging = getFramework()->tryAcquireInterface<ILogging>(); if (g_carbLogging) { g_carbLogging->registerSource(g_carbClientName, [](int32_t logLevel) { g_carbLogLevel = logLevel; }); g_carbLogFn = g_carbLogging->log; } omni::log::addModulesChannels(); } //! Unregisters the log channels and the logger interface. //! //! @note It is typically not necessary to call this function as it is automatically called in similar situations to //! those described in @ref registerLoggingForClient(). inline void deregisterLoggingForClient() noexcept { omni::log::removeModulesChannels(); if (g_carbLogging) { g_carbLogFn = nullptr; if (getFramework() && getFramework()->verifyInterface<ILogging>(g_carbLogging)) { g_carbLogging->unregisterSource(g_carbClientName); } g_carbLogging = nullptr; } } //! A struct that describes level name to integer value struct StringToLogLevelMapping { const char* name; //!< Log level name int32_t level; //!< Log level integer value (see \ref loglevel) }; //! A mapping of log level names to integer value //! @see loglevel const StringToLogLevelMapping kStringToLevelMappings[] = { { "verbose", kLevelVerbose }, { "info", kLevelInfo }, { "warning", kLevelWarn }, { "error", kLevelError }, { "fatal", kLevelFatal } }; //! The number of items in \ref kStringToLevelMappings. const size_t kStringToLevelMappingsCount = CARB_COUNTOF(kStringToLevelMappings); /** * Convert a given string to a log level. * * Compares the given \p levelString against \ref kStringToLevelMappings to find a match. Only the first character is * checked in a case insensitive manner. * @param levelString A string representing the name of a log level. `nullptr` is interpreted as \ref kLevelFatal. Only * the first character of the string is checked in a case insensitive manner. * @returns The integer \ref loglevel determined from \p levelString. If a level could not be determined, * \ref kLevelFatal is returned after an error log is issued. */ inline int32_t stringToLevel(const char* levelString) { const int32_t kFallbackLevel = kLevelFatal; if (!levelString) return kFallbackLevel; // Since our log level identifiers start with different characters, we're allowed to just compare the first one. // However, whether the need arises, it is worth making a score-based system, where full match will win over // partial match, if there are similarly starting log levels. int lcLevelChar = tolower((int)levelString[0]); for (size_t lm = 0; lm < kStringToLevelMappingsCount; ++lm) { int lcMappingChar = tolower((int)kStringToLevelMappings[lm].name[0]); if (lcLevelChar == lcMappingChar) return kStringToLevelMappings[lm].level; } // Ideally, this should never happen if level string is valid. CARB_ASSERT(false); CARB_LOG_ERROR("Unknown log level string: %s", levelString); return kFallbackLevel; } } // namespace logging } // namespace carb
omniverse-code/kit/include/carb/simplegui/ISimpleGui.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 *carb.simplegui* interface definition file. #pragma once #include "SimpleGuiTypes.h" #include "../Interface.h" namespace carb { //! Namespace for *carb.simplegui* plugin. namespace simplegui { /** * Defines the simplegui interface. * * Based on: ImGui 1.70 */ struct ISimpleGui { CARB_PLUGIN_INTERFACE("carb::simplegui::ISimpleGui", 1, 2) /** * Creates a new immediate mode GUI context. * * @param desc Context descriptor. * @return The context used for the current state of the GUI. */ Context*(CARB_ABI* createContext)(const ContextDesc& desc); /** * Destroys an immediate mode GUI context. * * @param ctx The context to be destroyed. */ void(CARB_ABI* destroyContext)(Context* ctx); /** * Sets the current immediate mode GUI context to be used. */ void(CARB_ABI* setCurrentContext)(Context* ctx); /** * Gets the current immediate mode GUI context that is used. * @return returns current immediate GUI mode context. */ Context*(CARB_ABI* getCurrentContext)(); /** * Start rendering a new immediate mode GUI frame. */ void(CARB_ABI* newFrame)(); /** * Render the immediate mode GUI frame. * * @param elapsedTime The amount of elapsed time since the last render() call. */ void(CARB_ABI* render)(float elapsedTime); /** * Sets the display size. * * @param size The display size to be set. */ void(CARB_ABI* setDisplaySize)(Float2 size); /** * Gets the display size. * * @return The display size. */ Float2(CARB_ABI* getDisplaySize)(); /** * Gets the style struct. * * @return The style struct. */ Style*(CARB_ABI* getStyle)(); /** * Shows a demo window of all features supported. * * @param open Is window opened, can be changed after the call. */ void(CARB_ABI* showDemoWindow)(bool* open); /** * Create metrics window. * * Display simplegui internals: draw commands (with individual draw calls and vertices), window list, basic internal * state, etc. * * @param open Is window opened, can be changed after the call. */ void(CARB_ABI* showMetricsWindow)(bool* open); /** * Add style editor block (not a window). * * You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default * style) * * @param style Style to edit. Pass nullptr to edit the default one. */ void(CARB_ABI* showStyleEditor)(Style* style); /** * Add style selector block (not a window). * * Essentially a combo listing the default styles. * * @param label Label. */ bool(CARB_ABI* showStyleSelector)(const char* label); /** * Add font selector block (not a window). * * Essentially a combo listing the loaded fonts. * * @param label Label. */ void(CARB_ABI* showFontSelector)(const char* label); /** * Add basic help/info block (not a window): how to manipulate simplegui as a end-user (mouse/keyboard controls). */ void(CARB_ABI* showUserGuide)(); /** * Get underlying ImGui library version string. * * @return The version string e.g. "1.70". */ const char*(CARB_ABI* getImGuiVersion)(); /** * Set style colors from one of the predefined presets: * * @param style Style to change. Pass nullptr to change the default one. * @param preset Colors preset. */ void(CARB_ABI* setStyleColors)(Style* style, StyleColorsPreset preset); /** * Begins defining a new immediate mode GUI (window). * * @param label The window label. * @param open Returns if the window was active. * @param windowFlags The window flags to be used. * @return return false to indicate the window is collapsed or fully clipped, * so you may early out and omit submitting anything to the window. */ bool(CARB_ABI* begin)(const char* label, bool* open, WindowFlags flags); /** * Ends defining a immediate mode. */ void(CARB_ABI* end)(); /** * Begins a scrolling child region. * * @param strId The string identifier for the child region. * @param size The size of the region. * size==0.0f: use remaining window size, size<0.0f: use remaining window. * @param border Draw border. * @param flags Sets any WindowFlags for the dialog. * @return true if the region change, false if not. */ bool(CARB_ABI* beginChild)(const char* strId, Float2 size, bool border, WindowFlags flags); /** * Begins a scrolling child region. * * @param id The identifier for the child region. * @param size The size of the region. * size==0.0f: use remaining window size, size<0.0f: use remaining window. * @param border Draw border. * @param flags Sets any WindowFlags for the dialog. * @return true if the region change, false if not. */ bool(CARB_ABI* beginChildId)(uint32_t id, Float2 size, bool border, WindowFlags flags); /** * Ends a child region. */ void(CARB_ABI* endChild)(); /** * Is window appearing? * * @return true if window is appearing, false if not. */ bool(CARB_ABI* isWindowAppearing)(); /** * Is window collapsed? * * @return true if window is collapsed, false is not. */ bool(CARB_ABI* isWindowCollapsed)(); /** * Is current window focused? or its root/child, depending on flags. see flags for options. * * @param flags The focused flags to use. * @return true if window is focused, false if not. */ bool(CARB_ABI* isWindowFocused)(FocusedFlags flags); /** * Is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. * * If you are trying to check whether your mouse should be dispatched to simplegui or to your app, you should use * the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! * * @param flags The hovered flags to use. * @return true if window is currently hovered over, false if not. */ bool(CARB_ABI* isWindowHovered)(HoveredFlags flags); /** * Get the draw list associated to the window, to append your own drawing primitives. * * @return The draw list associated to the window, to append your own drawing primitives. */ DrawList*(CARB_ABI* getWindowDrawList)(); /** * Gets the DPI scale currently associated to the current window's viewport. * * @return The DPI scale currently associated to the current window's viewport. */ float(CARB_ABI* getWindowDpiScale)(); /** * Get current window position in screen space * * This is useful if you want to do your own drawing via the DrawList API. * * @return The current window position in screen space. */ Float2(CARB_ABI* getWindowPos)(); /** * Gets the current window size. * * @return The current window size */ Float2(CARB_ABI* getWindowSize)(); /** * Gets the current window width. * * @return The current window width. */ float(CARB_ABI* getWindowWidth)(); /** * Gets the current window height. * * @return The current window height. */ float(CARB_ABI* getWindowHeight)(); /** * Gets the current content boundaries. * * This is typically window boundaries including scrolling, * or current column boundaries, in windows coordinates. * * @return The current content boundaries. */ Float2(CARB_ABI* getContentRegionMax)(); /** * Gets the current content region available. * * This is: getContentRegionMax() - getCursorPos() * * @return The current content region available. */ Float2(CARB_ABI* getContentRegionAvail)(); /** * Gets the width of the current content region available. * * @return The width of the current content region available. */ float(CARB_ABI* ContentRegionAvailWidth)(); /** * Content boundaries min (roughly (0,0)-Scroll), in window coordinates */ Float2(CARB_ABI* getWindowContentRegionMin)(); /** * Gets the maximum content boundaries. * * This is roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), * in window coordinates. * * @return The maximum content boundaries. */ Float2(CARB_ABI* getWindowContentRegionMax)(); /** * Content region width. */ float(CARB_ABI* getWindowContentRegionWidth)(); /** * Sets the next window position. * * Call before begin(). use pivot=(0.5f,0.5f) to center on given point, etc. * * @param position The position to set. * @param pivot The offset pivot. */ void(CARB_ABI* setNextWindowPos)(Float2 position, Condition cond, Float2 pivot); /** * Set next window size. * * Set axis to 0.0f to force an auto-fit on this axis. call before begin() * * @param size The next window size. */ void(CARB_ABI* setNextWindowSize)(Float2 size, Condition cond); /** * Set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply * non-trivial programmatic constraints. */ void(CARB_ABI* setNextWindowSizeConstraints)(const Float2& sizeMin, const Float2& sizeMax); /** * Set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, * menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin() */ void(CARB_ABI* setNextWindowContentSize)(const Float2& size); /** * Set next window collapsed state. call before Begin() */ void(CARB_ABI* setNextWindowCollapsed)(bool collapsed, Condition cond); /** * Set next window to be focused / front-most. call before Begin() */ void(CARB_ABI* setNextWindowFocus)(); /** * Set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. */ void(CARB_ABI* setNextWindowBgAlpha)(float alpha); /** * Set font scale. Adjust IO.FontGlobalScale if you want to scale all windows */ void(CARB_ABI* setWindowFontScale)(float scale); /** * Set named window position. */ void(CARB_ABI* setWindowPos)(const char* name, const Float2& pos, Condition cond); /** * Set named window size. set axis to 0.0f to force an auto-fit on this axis. */ void(CARB_ABI* setWindowSize)(const char* name, const Float2& size, Condition cond); /** * Set named window collapsed state */ void(CARB_ABI* setWindowCollapsed)(const char* name, bool collapsed, Condition cond); /** * Set named window to be focused / front-most. use NULL to remove focus. */ void(CARB_ABI* setWindowFocus)(const char* name); /** * Get scrolling amount [0..GetScrollMaxX()] */ float(CARB_ABI* getScrollX)(); /** * Get scrolling amount [0..GetScrollMaxY()] */ float(CARB_ABI* getScrollY)(); /** * Get maximum scrolling amount ~~ ContentSize.X - WindowSize.X */ float(CARB_ABI* getScrollMaxX)(); /** * Get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y */ float(CARB_ABI* getScrollMaxY)(); /** * Set scrolling amount [0..GetScrollMaxX()] */ void(CARB_ABI* setScrollX)(float scrollX); /** * Set scrolling amount [0..GetScrollMaxY()] */ void(CARB_ABI* setScrollY)(float scrollY); /** * Adjust scrolling amount to make current cursor position visible. * * @param centerYRatio Center y ratio: 0.0: top, 0.5: center, 1.0: bottom. */ void(CARB_ABI* setScrollHereY)(float centerYRatio); /** * Adjust scrolling amount to make given position valid. use getCursorPos() or getCursorStartPos()+offset to get * valid positions. default: centerYRatio = 0.5f */ void(CARB_ABI* setScrollFromPosY)(float posY, float centerYRatio); /** * Use NULL as a shortcut to push default font */ void(CARB_ABI* pushFont)(Font* font); /** * Pop font from the stack */ void(CARB_ABI* popFont)(); /** * Pushes and applies a style color for the current widget. * * @param styleColorIndex The style color index. * @param color The color to be applied for the style color being pushed. */ void(CARB_ABI* pushStyleColor)(StyleColor styleColorIndex, Float4 color); /** * Pops off and stops applying the style color for the current widget. */ void(CARB_ABI* popStyleColor)(); /** * Pushes a style variable(property) with a float value. * * @param styleVarIndex The style variable(property) index. * @param value The value to be applied. */ void(CARB_ABI* pushStyleVarFloat)(StyleVar styleVarIndex, float value); /** * Pushes a style variable(property) with a Float2 value. * * @param styleVarIndex The style variable(property) index. * @param value The value to be applied. */ void(CARB_ABI* pushStyleVarFloat2)(StyleVar styleVarIndex, Float2 value); /** * Pops off and stops applying the style variable(property) for the current widget. */ void(CARB_ABI* popStyleVar)(); /** * Retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use * GetColorU32() to get style color with style alpha baked in. */ const Float4&(CARB_ABI* getStyleColorVec4)(StyleColor colorIndex); /** * Get current font */ Font*(CARB_ABI* getFont)(); /** * Get current font size (= height in pixels) of current font with current scale applied */ float(CARB_ABI* getFontSize)(); /** * Get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API */ Float2(CARB_ABI* getFontTexUvWhitePixel)(); /** * Retrieve given style color with style alpha applied and optional extra alpha multiplier */ uint32_t(CARB_ABI* getColorU32StyleColor)(StyleColor colorIndex, float alphaMul); /** * Retrieve given color with style alpha applied */ uint32_t(CARB_ABI* getColorU32Vec4)(Float4 color); /** * Retrieve given color with style alpha applied */ uint32_t(CARB_ABI* getColorU32)(uint32_t color); /** * Push an item width for next widgets. * In pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of * window (so -1.0f always align width to the right side). * * @param width The width. */ void(CARB_ABI* pushItemWidth)(float width); /** * Pops an item width. */ void(CARB_ABI* popItemWidth)(); /** * Size of item given pushed settings and current cursor position * NOTE: This is not the same as calcItemWidth */ carb::Float2(CARB_ABI* calcItemSize)(carb::Float2 size, float defaultX, float defaultY); /** * Width of item given pushed settings and current cursor position */ float(CARB_ABI* calcItemWidth)(); //! @private Unknown/Undocumented void(CARB_ABI* pushItemFlag)(ItemFlags option, bool enabled); //! @private Unknown/Undocumented void(CARB_ABI* popItemFlag)(); /** * Word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at * 'wrapPosX' position in window local space */ void(CARB_ABI* pushTextWrapPos)(float wrapPosX); /** * Pop text wrap pos form the stack */ void(CARB_ABI* popTextWrapPos)(); /** * Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets */ void(CARB_ABI* pushAllowKeyboardFocus)(bool allow); /** * Pop allow keyboard focus */ void(CARB_ABI* popAllowKeyboardFocus)(); /** * In 'repeat' mode, Button*() functions return repeated true in a typematic manner (using * io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if * the button is held in the current frame. */ void(CARB_ABI* pushButtonRepeat)(bool repeat); /** * Pop button repeat */ void(CARB_ABI* popButtonRepeat)(); /** * Adds a widget separator. */ void(CARB_ABI* separator)(); /** * Tell the widget to stay on the same line. */ void sameLine(); /** * Tell the widget to stay on the same line with parameters. */ void(CARB_ABI* sameLineEx)(float posX, float spacingW); /** * Undo sameLine() */ void(CARB_ABI* newLine)(); /** * Adds widget spacing. */ void(CARB_ABI* spacing)(); /** * Adds a dummy element of a given size * * @param size The size of a dummy element. */ void(CARB_ABI* dummy)(Float2 size); /** * Indents. */ void(CARB_ABI* indent)(); /** * Indents with width indent spacing. */ void(CARB_ABI* indentEx)(float indentWidth); /** * Undo indent. */ void(CARB_ABI* unindent)(); /** * Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or * layout primitives such as () on whole group, etc.) */ void(CARB_ABI* beginGroup)(); /** * End group */ void(CARB_ABI* endGroup)(); /** * Cursor position is relative to window position */ Float2(CARB_ABI* getCursorPos)(); //! @private Unknown/Undocumented float(CARB_ABI* getCursorPosX)(); //! @private Unknown/Undocumented float(CARB_ABI* getCursorPosY)(); //! @private Unknown/Undocumented void(CARB_ABI* setCursorPos)(const Float2& localPos); //! @private Unknown/Undocumented void(CARB_ABI* setCursorPosX)(float x); //! @private Unknown/Undocumented void(CARB_ABI* setCursorPosY)(float y); /** * Initial cursor position */ Float2(CARB_ABI* getCursorStartPos)(); /** * Cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) */ Float2(CARB_ABI* getCursorScreenPos)(); /** * Cursor position in absolute screen coordinates [0..io.DisplaySize] */ void(CARB_ABI* setCursorScreenPos)(const Float2& pos); /** * Vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed * items (call if you have text on a line before a framed item) */ void(CARB_ABI* alignTextToFramePadding)(); /** * ~ FontSize */ float(CARB_ABI* getTextLineHeight)(); /** * ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) */ float(CARB_ABI* getTextLineHeightWithSpacing)(); /** * ~ FontSize + style.FramePadding.y * 2 */ float(CARB_ABI* getFrameHeight)(); /** * ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of * framed widgets) */ float(CARB_ABI* getFrameHeightWithSpacing)(); /** * Push a string id for next widgets. * * If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop * index) so simplegui can differentiate them. popId() must be called later. * @param id The string id. */ void(CARB_ABI* pushIdString)(const char* id); /** * Push a string id for next widgets. * * If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop * index) so simplegui can differentiate them. popId() must be called later. * @param id The string id. */ void(CARB_ABI* pushIdStringBeginEnd)(const char* idBegin, const char* idEnd); /** * Push an integer id for next widgets. * * If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop * index) so simplegui can differentiate them. popId() must be called later. * @param id The integer id. */ void(CARB_ABI* pushIdInt)(int id); /** * Push pointer id for next widgets. */ void(CARB_ABI* pushIdPtr)(const void* id); /** * Pops an id. */ void(CARB_ABI* popId)(); /** * Calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage * yourself. */ uint32_t(CARB_ABI* getIdString)(const char* id); /** * Calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage * yourself. */ uint32_t(CARB_ABI* getIdStringBeginEnd)(const char* idBegin, const char* idEnd); //! @private Unknown/Undocumented uint32_t(CARB_ABI* getIdPtr)(const void* id); /** * Shows a text widget, without text formatting. Faster version, use for big texts. * * @param text The null terminated text string. */ void(CARB_ABI* textUnformatted)(const char* text); /** * Shows a text widget. * * @param fmt The formatted label for the text. * @param ... The variable arguments for the label. */ void(CARB_ABI* text)(const char* fmt, ...); /** * Shows a colored text widget. * * @param fmt The formatted label for the text. * @param ... The variable arguments for the label. */ void(CARB_ABI* textColored)(const Float4& color, const char* fmt, ...); /** * Shows a disabled text widget. * * @param fmt The formatted label for the text. * @param ... The variable arguments for the label. */ void(CARB_ABI* textDisabled)(const char* fmt, ...); /** * Shows a wrapped text widget. * * @param fmt The formatted label for the text. * @param ... The variable arguments for the label. */ void(CARB_ABI* textWrapped)(const char* fmt, ...); /** * Display text+label aligned the same way as value+label widgets. */ void(CARB_ABI* labelText)(const char* label, const char* fmt, ...); /** * Shortcut for Bullet()+Text() */ void(CARB_ABI* bulletText)(const char* fmt, ...); /** * Shows a button widget. * * @param label The label for the button. * @return true if the button was pressed, false if not. */ bool(CARB_ABI* buttonEx)(const char* label, const Float2& size); //! @private Unknown/Undocumented bool button(const char* label); /** * Shows a smallButton widget. * * @param label The label for the button. * @return true if the button was pressed, false if not. */ bool(CARB_ABI* smallButton)(const char* label); /** * Button behavior without the visuals. * * Useful to build custom behaviors using the public api (along with isItemActive, isItemHovered, etc.) */ bool(CARB_ABI* invisibleButton)(const char* id, const Float2& size); /** * Arrow-like button with specified direction. */ bool(CARB_ABI* arrowButton)(const char* id, Direction dir); /** * Image with user texture id * defaults: * uv0 = Float2(0,0) * uv1 = Float2(1,1) * tintColor = Float4(1,1,1,1) * borderColor = Float4(0,0,0,0) */ void(CARB_ABI* image)(TextureId userTextureId, const Float2& size, const Float2& uv0, const Float2& uv1, const Float4& tintColor, const Float4& borderColor); /** * Image as a button. <0 framePadding uses default frame padding settings. 0 for no padding * defaults: * uv0 = Float2(0,0) * uv1 = Float2(1,1) * framePadding = -1 * bgColor = Float4(0,0,0,0) * tintColor = Float4(1,1,1,1) */ bool(CARB_ABI* imageButton)(TextureId userTextureId, const Float2& size, const Float2& uv0, const Float2& uv1, int framePadding, const Float4& bgColor, const Float4& tintColor); /** * Adds a checkbox widget. * * @param label The checkbox label. * @param value The current value of the checkbox * * @return true if the checkbox was pressed, false if not. */ bool(CARB_ABI* checkbox)(const char* label, bool* value); /** * Flags checkbox */ bool(CARB_ABI* checkboxFlags)(const char* label, uint32_t* flags, uint32_t flagsValue); /** * Radio button */ bool(CARB_ABI* radioButton)(const char* label, bool active); /** * Radio button */ bool(CARB_ABI* radioButtonEx)(const char* label, int* v, int vButton); /** * Adds a progress bar widget. * * @param fraction The progress value (0-1). * @param size The widget size. * @param overlay The text overlay, if nullptr the default with percents is displayed. */ void(CARB_ABI* progressBar)(float fraction, Float2 size, const char* overlay); /** * Draws a small circle. */ void(CARB_ABI* bullet)(); /** * The new beginCombo()/endCombo() api allows you to manage your contents and selection state however you want it. * The old Combo() api are helpers over beginCombo()/endCombo() which are kept available for convenience purpose. */ bool(CARB_ABI* beginCombo)(const char* label, const char* previewValue, ComboFlags flags); /** * only call endCombo() if beginCombo() returns true! */ void(CARB_ABI* endCombo)(); /** * Adds a combo box widget. * * @param label The label for the combo box. * @param currentItem The current (selected) element index. * @param items The array of items. * @param itemCount The number of items. * * @return true if the selected item value has changed, false if not. */ bool(CARB_ABI* combo)(const char* label, int* currentItem, const char* const* items, int itemCount); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). If vMin >= vMax we have no bound. For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of * every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a * way to document the number of elements that are expected to be accessible. You can pass address of your first * element out of a contiguous set, e.g. &myvector.x. Speed are per-pixel of mouse movement (vSpeed=0.2f: mouse * needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(vSpeed, * minimum_step_at_given_precision). Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const * char* displayFormat = "%.3f", float power = 1.0f) */ bool(CARB_ABI* dragFloat)( const char* label, float* v, float vSpeed, float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds) Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat = * "%.3f", float power = 1.0f) */ bool(CARB_ABI* dragFloat2)( const char* label, float v[2], float vSpeed, float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds) Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat = * "%.3f", float power = 1.0f) */ bool(CARB_ABI* dragFloat3)( const char* label, float v[3], float vSpeed, float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds) Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat = * "%.3f", float power = 1.0f) */ bool(CARB_ABI* dragFloat4)( const char* label, float v[4], float vSpeed, float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: float vSpeed = 1.0f, float vMin = 0.0f, float vMax = 0.0f, const char* displayFormat = * "%.3f", const char* displayFormatMax = NULL, float power = 1.0f */ bool(CARB_ABI* dragFloatRange2)(const char* label, float* vCurrentMin, float* vCurrentMax, float vSpeed, float vMin, float vMax, const char* displayFormat, const char* displayFormatMax, float power); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). If vMin >= vMax we have no bound.. Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, * const char* displayFormat = "%.0f" */ bool(CARB_ABI* dragInt)(const char* label, int* v, float vSpeed, int vMin, int vMax, const char* displayFormat); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f" */ bool(CARB_ABI* dragInt2)(const char* label, int v[2], float vSpeed, int vMin, int vMax, const char* displayFormat); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f" */ bool(CARB_ABI* dragInt3)(const char* label, int v[3], float vSpeed, int vMin, int vMax, const char* displayFormat); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f" */ bool(CARB_ABI* dragInt4)(const char* label, int v[4], float vSpeed, int vMin, int vMax, const char* displayFormat); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, const char* displayFormat = "%.0f", * const char* displayFormatMax = NULL */ bool(CARB_ABI* dragIntRange2)(const char* label, int* vCurrentMin, int* vCurrentMax, float vSpeed, int vMin, int vMax, const char* displayFormat, const char* displayFormatMax); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). If vMin >= vMax we have no bound.. Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, * const char* displayFormat = "%.0f", power = 1.0f */ bool(CARB_ABI* dragScalar)(const char* label, DataType dataType, void* v, float vSpeed, const void* vMin, const void* vMax, const char* displayFormat, float power); /** * Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can * go off-bounds). If vMin >= vMax we have no bound.. Defaults: float vSpeed = 1.0f, int vMin = 0, int vMax = 0, * const char* displayFormat = "%.0f", power = 1.0f */ bool(CARB_ABI* dragScalarN)(const char* label, DataType dataType, void* v, int components, float vSpeed, const void* vMin, const void* vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Adjust displayFormat to decorate the value with a prefix or a suffix for in-slider labels or unit * display. Use power!=1.0 for logarithmic sliders . Defaults: const char* displayFormat = "%.3f", float power * = 1.0f */ bool(CARB_ABI* sliderFloat)(const char* label, float* v, float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f */ bool(CARB_ABI* sliderFloat2)( const char* label, float v[2], float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f */ bool(CARB_ABI* sliderFloat3)( const char* label, float v[3], float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f */ bool(CARB_ABI* sliderFloat4)( const char* label, float v[4], float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: float vDegreesMin = -360.0f, float vDegreesMax = +360.0f */ bool(CARB_ABI* sliderAngle)(const char* label, float* vRad, float vDegreesMin, float vDegreesMax); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f" */ bool(CARB_ABI* sliderInt)(const char* label, int* v, int vMin, int vMax, const char* displayFormat); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f" */ bool(CARB_ABI* sliderInt2)(const char* label, int v[2], int vMin, int vMax, const char* displayFormat); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f" */ bool(CARB_ABI* sliderInt3)(const char* label, int v[3], int vMin, int vMax, const char* displayFormat); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f" */ bool(CARB_ABI* sliderInt4)(const char* label, int v[4], int vMin, int vMax, const char* displayFormat); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f", power = 1.0f */ bool(CARB_ABI* sliderScalar)(const char* label, DataType dataType, void* v, const void* vMin, const void* vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f", power = 1.0f */ bool(CARB_ABI* sliderScalarN)(const char* label, DataType dataType, void* v, int components, const void* vMin, const void* vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.3f", float power = 1.0f */ bool(CARB_ABI* vSliderFloat)( const char* label, const Float2& size, float* v, float vMin, float vMax, const char* displayFormat, float power); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f" */ bool(CARB_ABI* vSliderInt)(const char* label, const Float2& size, int* v, int vMin, int vMax, const char* displayFormat); /** * Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can * go off-bounds). Defaults: const char* displayFormat = "%.0f", power = 1.0f */ bool(CARB_ABI* vSliderScalar)(const char* label, const Float2& size, DataType dataType, void* v, const void* vMin, const void* vMax, const char* displayFormat, float power); /** * Widgets: Input with Keyboard */ bool(CARB_ABI* inputText)( const char* label, char* buf, size_t bufSize, InputTextFlags flags, TextEditCallback callback, void* userData); /** * Widgets: Input with Keyboard */ bool(CARB_ABI* inputTextMultiline)(const char* label, char* buf, size_t bufSize, const Float2& size, InputTextFlags flags, TextEditCallback callback, void* userData); /** * Widgets: Input with Keyboard. Defaults: float step = 0.0f, float stepFast = 0.0f, int decimalPrecision = -1, * InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputFloat)( const char* label, float* v, float step, float stepFast, int decimalPrecision, InputTextFlags extraFlags); /** * Widgets: Input with Keyboard. Defaults: int decimalPrecision = -1, InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputFloat2)(const char* label, float v[2], int decimalPrecision, InputTextFlags extraFlags); /** * Widgets: Input with Keyboard. Defaults: int decimalPrecision = -1, InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputFloat3)(const char* label, float v[3], int decimalPrecision, InputTextFlags extraFlags); /** * Widgets: Input with Keyboard. Defaults: int decimalPrecision = -1, InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputFloat4)(const char* label, float v[4], int decimalPrecision, InputTextFlags extraFlags); /** * Widgets: Input with Keyboard. Defaults: int step = 1, int stepFast = 100, InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputInt)(const char* label, int* v, int step, int stepFast, InputTextFlags extraFlags); /** * Widgets: Input with Keyboard */ bool(CARB_ABI* inputInt2)(const char* label, int v[2], InputTextFlags extraFlags); /** * Widgets: Input with Keyboard */ bool(CARB_ABI* inputInt3)(const char* label, int v[3], InputTextFlags extraFlags); /** * Widgets: Input with Keyboard */ bool(CARB_ABI* inputInt4)(const char* label, int v[4], InputTextFlags extraFlags); /** * Widgets: Input with Keyboard. Defaults: double step = 0.0f, double stepFast = 0.0f, const char* displayFormat = * "%.6f", InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputDouble)( const char* label, double* v, double step, double stepFast, const char* displayFormat, InputTextFlags extraFlags); /** * Widgets: Input with Keyboard. Defaults: double step = 0.0f, double stepFast = 0.0f, const char* displayFormat = * "%.6f", InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputScalar)(const char* label, DataType dataType, void* v, const void* step, const void* stepFast, const char* displayFormat, InputTextFlags extraFlags); /** * Widgets: Input with Keyboard. Defaults: double step = 0.0f, double stepFast = 0.0f, const char* displayFormat = * "%.6f", InputTextFlags extraFlags = 0 */ bool(CARB_ABI* inputScalarN)(const char* label, DataType dataType, void* v, int components, const void* step, const void* stepFast, const char* displayFormat, InputTextFlags extraFlags); /** * Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be * left-clicked to open a picker, and right-clicked to open an option menu.) */ bool(CARB_ABI* colorEdit3)(const char* label, float col[3], ColorEditFlags flags); /** * Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be * left-clicked to open a picker, and right-clicked to open an option menu.) */ bool(CARB_ABI* colorEdit4)(const char* label, float col[4], ColorEditFlags flags); /** * Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be * left-clicked to open a picker, and right-clicked to open an option menu.) */ bool(CARB_ABI* colorPicker3)(const char* label, float col[3], ColorEditFlags flags); /** * Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be * left-clicked to open a picker, and right-clicked to open an option menu.) */ bool(CARB_ABI* colorPicker4)(const char* label, float col[4], ColorEditFlags flags, const float* refCol); /** * display a colored square/button, hover for details, return true when pressed. */ bool(CARB_ABI* colorButton)(const char* descId, const Float4& col, ColorEditFlags flags, Float2 size); /** * initialize current options (generally on application startup) if you want to select a default format, picker * type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. */ void(CARB_ABI* setColorEditOptions)(ColorEditFlags flags); /** * Tree node. if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible * for calling TreePop(). */ bool(CARB_ABI* treeNode)(const char* label); /** * Tree node with string id. read the FAQ about why and how to use ID. to align arbitrary text at the same level as * a TreeNode() you can use Bullet(). */ bool(CARB_ABI* treeNodeString)(const char* strId, const char* fmt, ...); /** * Tree node with ptr id. */ bool(CARB_ABI* treeNodePtr)(const void* ptrId, const char* fmt, ...); /** * Tree node with flags. */ bool(CARB_ABI* treeNodeEx)(const char* label, TreeNodeFlags flags); /** * Tree node with flags and string id. */ bool(CARB_ABI* treeNodeStringEx)(const char* strId, TreeNodeFlags flags, const char* fmt, ...); /** * Tree node with flags and ptr id. */ bool(CARB_ABI* treeNodePtrEx)(const void* ptrId, TreeNodeFlags flags, const char* fmt, ...); /** * ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for * layout purpose */ void(CARB_ABI* treePushString)(const char* strId); //! @private Unknown/Undocumented void(CARB_ABI* treePushPtr)(const void* ptrId); /** * ~ Unindent()+PopId() */ void(CARB_ABI* treePop)(); /** * Advance cursor x position by GetTreeNodeToLabelSpacing() */ void(CARB_ABI* treeAdvanceToLabelPos)(); /** * Horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) * for a regular unframed TreeNode */ float(CARB_ABI* getTreeNodeToLabelSpacing)(); /** * Set next TreeNode/CollapsingHeader open state. */ void(CARB_ABI* setNextTreeNodeOpen)(bool isOpen, Condition cond); /** * If returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). */ bool(CARB_ABI* collapsingHeader)(const char* label, TreeNodeFlags flags); /** * When 'open' isn't NULL, display an additional small close button on upper right of the header */ bool(CARB_ABI* collapsingHeaderEx)(const char* label, bool* open, TreeNodeFlags flags); /** * Selectable. "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you * can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use * label height, size.y>0.0: specify height. */ bool(CARB_ABI* selectable)(const char* label, bool selected /* = false*/, SelectableFlags flags /* = 0*/, const Float2& size /* = Float2(0,0)*/); /** * Selectable. "bool* selected" point to the selection state (read-write), as a convenient helper. */ bool(CARB_ABI* selectableEx)(const char* label, bool* selected, SelectableFlags flags /* = 0*/, const Float2& size /* = Float2(0,0)*/); /** * ListBox. */ bool(CARB_ABI* listBox)( const char* label, int* currentItem, const char* const items[], int itemCount, int heightInItems /* = -1*/); /** * ListBox. */ bool(CARB_ABI* listBoxEx)(const char* label, int* currentItem, bool (*itemsGetterFn)(void* data, int idx, const char** out_text), void* data, int itemCount, int heightInItems /* = -1*/); /** * ListBox Header. use if you want to reimplement ListBox() will custom data or interactions. make sure to call * ListBoxFooter() afterwards. */ bool(CARB_ABI* listBoxHeader)(const char* label, const Float2& size /* = Float2(0,0)*/); /** * ListBox Header. */ bool(CARB_ABI* listBoxHeaderEx)(const char* label, int itemCount, int heightInItems /* = -1*/); /** * Terminate the scrolling region */ void(CARB_ABI* listBoxFooter)(); /** * Plot * defaults: * valuesOffset = 0 * overlayText = nullptr * scaleMin = FLT_MAX * scaleMax = FLT_MAX * graphSize = Float2(0,0) * stride = sizeof(float) */ void(CARB_ABI* plotLines)(const char* label, const float* values, int valuesCount, int valuesOffset, const char* overlayText, float scaleMin, float scaleMax, Float2 graphSize, int stride); /** * Plot * defaults: * valuesOffset = 0 * overlayText = nullptr * scaleMin = FLT_MAX * scaleMax = FLT_MAX * graphSize = Float2(0,0) */ void(CARB_ABI* plotLinesEx)(const char* label, float (*valuesGetterFn)(void* data, int idx), void* data, int valuesCount, int valuesOffset, const char* overlayText, float scaleMin, float scaleMax, Float2 graphSize); /** * Histogram * defaults: * valuesOffset = 0 * overlayText = nullptr * scaleMin = FLT_MAX * scaleMax = FLT_MAX * graphSize = Float2(0,0) * stride = sizeof(float) */ void(CARB_ABI* plotHistogram)(const char* label, const float* values, int valuesCount, int valuesOffset, const char* overlayText, float scaleMin, float scaleMax, Float2 graphSize, int stride); /** * Histogram * defaults: * valuesOffset = 0 * overlayText = nullptr * scaleMin = FLT_MAX * scaleMax = FLT_MAX * graphSize = Float2(0,0) */ void(CARB_ABI* plotHistogramEx)(const char* label, float (*valuesGetterFn)(void* data, int idx), void* data, int valuesCount, int valuesOffset, const char* overlayText, float scaleMin, float scaleMax, Float2 graphSize); /** * Widgets: Value() Helpers. Output single value in "name: value" format. */ void(CARB_ABI* valueBool)(const char* prefix, bool b); /** * Widgets: Value() Helpers. Output single value in "name: value" format. */ void(CARB_ABI* valueInt)(const char* prefix, int v); /** * Widgets: Value() Helpers. Output single value in "name: value" format. */ void(CARB_ABI* valueUInt32)(const char* prefix, uint32_t v); /** * Widgets: Value() Helpers. Output single value in "name: value" format. */ void(CARB_ABI* valueFloat)(const char* prefix, float v, const char* floatFormat /* = nullptr*/); /** * Create and append to a full screen menu-bar. */ bool(CARB_ABI* beginMainMenuBar)(); /** * Only call EndMainMenuBar() if BeginMainMenuBar() returns true! */ void(CARB_ABI* endMainMenuBar)(); /** * Append to menu-bar of current window (requires WindowFlags_MenuBar flag set on parent window). */ bool(CARB_ABI* beginMenuBar)(); /** * Only call EndMenuBar() if BeginMenuBar() returns true! */ void(CARB_ABI* endMenuBar)(); /** * Create a sub-menu entry. only call EndMenu() if this returns true! */ bool(CARB_ABI* beginMenu)(const char* label, bool enabled /* = true*/); /** * Only call EndMenu() if BeginMenu() returns true! */ void(CARB_ABI* endMenu)(); /** * Return true when activated. shortcuts are displayed for convenience but not processed by simplegui at the moment */ bool(CARB_ABI* menuItem)(const char* label, const char* shortcut /* = NULL*/, bool selected /* = false*/, bool enabled /* = true*/); /** * Return true when activated + toggle (*pSelected) if pSelected != NULL */ bool(CARB_ABI* menuItemEx)(const char* label, const char* shortcut, bool* pSelected, bool enabled /* = true*/); /** * Set text tooltip under mouse-cursor, typically use with ISimpleGui::IsItemHovered(). Overrides any previous call * to SetTooltip(). */ void(CARB_ABI* setTooltip)(const char* fmt, ...); /** * Begin/append a tooltip window. to create full-featured tooltip (with any kind of contents). */ void(CARB_ABI* beginTooltip)(); /** * End tooltip */ void(CARB_ABI* endTooltip)(); /** * Call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if * CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are * calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup * needs to be at the same level). */ void(CARB_ABI* openPopup)(const char* strId); /** * Return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() * returns true! */ bool(CARB_ABI* beginPopup)(const char* strId, WindowFlags flags /* = 0*/); /** * Helper to open and begin popup when clicked on last item. if you can pass a NULL strId only if the previous item * had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID * here. read comments in .cpp! */ bool(CARB_ABI* beginPopupContextItem)(const char* strId /* = NULL*/, int mouseButton /* = 1*/); /** * Helper to open and begin popup when clicked on current window. */ bool(CARB_ABI* beginPopupContextWindow)(const char* strId /* = NULL*/, int mouseButton /* = 1*/, bool alsoOverItems /* = true*/); /** * Helper to open and begin popup when clicked in void (where there are no simplegui windows). */ bool(CARB_ABI* beginPopupContextVoid)(const char* strId /* = NULL*/, int mouseButton /* = 1*/); /** * Modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal * window by clicking outside) */ bool(CARB_ABI* beginPopupModal)(const char* name, bool* open /* = NULL*/, WindowFlags flags /* = 0*/); /** * Only call EndPopup() if BeginPopupXXX() returns true! */ void(CARB_ABI* endPopup)(); /** * Helper to open popup when clicked on last item. return true when just opened. */ bool(CARB_ABI* openPopupOnItemClick)(const char* strId /* = NULL*/, int mouseButton /* = 1*/); /** * Return true if the popup is open */ bool(CARB_ABI* isPopupOpen)(const char* strId); /** * Close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current * popup. */ void(CARB_ABI* closeCurrentPopup)(); /** * Columns. You can also use SameLine(pos_x) for simplified columns. The columns API is still work-in-progress and * rather lacking. */ void(CARB_ABI* columns)(int count /* = 1*/, const char* id /* = NULL*/, bool border /* = true*/); /** * Next column, defaults to current row or next row if the current row is finished */ void(CARB_ABI* nextColumn)(); /** * Get current column index */ int(CARB_ABI* getColumnIndex)(); /** * Get column width (in pixels). pass -1 to use current column */ float(CARB_ABI* getColumnWidth)(int columnIndex /* = -1*/); /** * Set column width (in pixels). pass -1 to use current column */ void(CARB_ABI* setColumnWidth)(int columnIndex, float width); /** * Get position of column line (in pixels, from the left side of the contents region). pass -1 to use current * column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f */ float(CARB_ABI* getColumnOffset)(int columnIndex /* = -1*/); /** * Set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column */ void(CARB_ABI* setColumnOffset)(int columnIndex, float offsetX); /** * Columns count. */ int(CARB_ABI* getColumnsCount)(); /** * Create and append into a TabBar. * defaults: * flags = 0 */ bool(CARB_ABI* beginTabBar)(const char* strId, TabBarFlags flags); /** * End TabBar. */ void(CARB_ABI* endTabBar)(); /** * Create a Tab. Returns true if the Tab is selected. * defaults: * open = nullptr * flags = 0 */ bool(CARB_ABI* beginTabItem)(const char* label, bool* open, TabItemFlags flags); /** * Only call endTabItem() if beginTabItem() returns true! */ void(CARB_ABI* endTabItem)(); /** * Notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable * tab bars). For tab-bar: call after beginTabBar() and before Tab submissions. Otherwise call with a window name. */ void(CARB_ABI* setTabItemClosed)(const char* tabOrDockedWindowLabel); /** * defaults: * size = Float2(0, 0), * flags = 0, * windowClass = nullptr */ void(CARB_ABI* dockSpace)(uint32_t id, const Float2& size, DockNodeFlags flags, const WindowClass* windowClass); /** * defaults: * viewport = nullptr, * dockspaceFlags = 0, * windowClass = nullptr */ uint32_t(CARB_ABI* dockSpaceOverViewport)(Viewport* viewport, DockNodeFlags dockspaceFlags, const WindowClass* windowClass); /** * Set next window dock id (FIXME-DOCK). */ void(CARB_ABI* setNextWindowDockId)(uint32_t dockId, Condition cond); /** * Set next window user type (docking filters by same user_type). */ void(CARB_ABI* setNextWindowClass)(const WindowClass* windowClass); /** * Get window dock Id. */ uint32_t(CARB_ABI* getWindowDockId)(); /** * Return is window Docked. */ bool(CARB_ABI* isWindowDocked)(); /** * Call when the current item is active. If this return true, you can call setDragDropPayload() + * endDragDropSource() */ bool(CARB_ABI* beginDragDropSource)(DragDropFlags flags); /** * Type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for simplegui * internal types. Data is copied and held by simplegui. Defaults: cond = 0 */ bool(CARB_ABI* setDragDropPayload)(const char* type, const void* data, size_t size, Condition cond); /** * Only call endDragDropSource() if beginDragDropSource() returns true! */ void(CARB_ABI* endDragDropSource)(); /** * Call after submitting an item that may receive a payload. If this returns true, you can call * acceptDragDropPayload() + endDragDropTarget() */ bool(CARB_ABI* beginDragDropTarget)(); /** * Accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload * before the mouse button is released. */ const Payload*(CARB_ABI* acceptDragDropPayload)(const char* type, DragDropFlags flags); /** * Only call endDragDropTarget() if beginDragDropTarget() returns true! */ void(CARB_ABI* endDragDropTarget)(); /** * Peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for * the payload type. */ const Payload*(CARB_ABI* getDragDropPayload)(); /** * Clipping. */ void(CARB_ABI* pushClipRect)(const Float2& clipRectMin, const Float2& clipRectMax, bool intersectWithCurrentClipRect); /** * Clipping. */ void(CARB_ABI* popClipRect)(); /** * Make last item the default focused item of a window. Please use instead of "if (IsWindowAppearing()) * SetScrollHere()" to signify "default item". */ void(CARB_ABI* setItemDefaultFocus)(); /** * Focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. * Use -1 to access previous widget. */ void(CARB_ABI* setKeyboardFocusHere)(int offset /* = 0*/); /** * Clears the active element id in the internal state. */ void(CARB_ABI* clearActiveId)(); /** * Is the last item hovered? (and usable, aka not blocked by a popup, etc.). See HoveredFlags for more options. */ bool(CARB_ABI* isItemHovered)(HoveredFlags flags /* = 0*/); /** * Is the last item active? (e.g. button being held, text field being edited- items that don't interact will always * return false) */ bool(CARB_ABI* isItemActive)(); /** * Is the last item focused for keyboard/gamepad navigation? */ bool(CARB_ABI* isItemFocused)(); /** * Is the last item clicked? (e.g. button/node just clicked on) */ bool(CARB_ABI* isItemClicked)(int mouseButton /* = 0*/); /** * Is the last item visible? (aka not out of sight due to clipping/scrolling.) */ bool(CARB_ABI* isItemVisible)(); /** * Is the last item visible? (items may be out of sight because of clipping/scrolling) */ bool(CARB_ABI* isItemEdited)(); /** * Was the last item just made inactive (item was previously active). * * Useful for Undo/Redo patterns with widgets that requires continuous editing. */ bool(CARB_ABI* isItemDeactivated)(); /** * Was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). * * Useful for Undo/Redo patterns with widgets that requires continuous editing. * Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). */ bool(CARB_ABI* isItemDeactivatedAfterEdit)(); //! @private Unknown/Undocumented bool(CARB_ABI* isAnyItemHovered)(); //! @private Unknown/Undocumented bool(CARB_ABI* isAnyItemActive)(); //! @private Unknown/Undocumented bool(CARB_ABI* isAnyItemFocused)(); /** * Is specific item active? */ bool(CARB_ABI* isItemIdActive)(uint32_t id); /** * Get bounding rectangle of last item, in screen space */ Float2(CARB_ABI* getItemRectMin)(); //! @private Unknown/Undocumented Float2(CARB_ABI* getItemRectMax)(); /** * Get size of last item, in screen space */ Float2(CARB_ABI* getItemRectSize)(); /** * Allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. * to catch unused area. */ void(CARB_ABI* setItemAllowOverlap)(); /** * Test if rectangle (of given size, starting from cursor position) is visible / not clipped. */ bool(CARB_ABI* isRectVisible)(const Float2& size); /** * Test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. */ bool(CARB_ABI* isRectVisibleEx)(const Float2& rectMin, const Float2& rectMax); /** * Time. */ float(CARB_ABI* getTime)(); /** * Frame Count. */ int(CARB_ABI* getFrameCount)(); /** * This draw list will be the last rendered one, useful to quickly draw overlays shapes/text */ DrawList*(CARB_ABI* getOverlayDrawList)(); //! @private Unknown/Undocumented const char*(CARB_ABI* getStyleColorName)(StyleColor color); //! @private Unknown/Undocumented Float2(CARB_ABI* calcTextSize)(const char* text, const char* textEnd /* = nullptr*/, bool hideTextAfterDoubleHash /* = false*/, float wrap_width /* = -1.0f*/); /** * Calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level * helper if you can. */ void(CARB_ABI* calcListClipping)(int itemCount, float itemsHeight, int* outItemsDisplayStart, int* outItemsDisplayEnd); /** * Helper to create a child window / scrolling region that looks like a normal widget frame */ bool(CARB_ABI* beginChildFrame)(uint32_t id, const Float2& size, WindowFlags flags /* = 0*/); /** * Always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped * window) */ void(CARB_ABI* endChildFrame)(); //! @private Unknown/Undocumented Float4(CARB_ABI* colorConvertU32ToFloat4)(uint32_t in); //! @private Unknown/Undocumented uint32_t(CARB_ABI* colorConvertFloat4ToU32)(const Float4& in); //! @private Unknown/Undocumented void(CARB_ABI* colorConvertRGBtoHSV)(float r, float g, float b, float& outH, float& outS, float& outV); //! @private Unknown/Undocumented void(CARB_ABI* colorConvertHSVtoRGB)(float h, float s, float v, float& outR, float& outG, float& outB); /** * Map ImGuiKey_* values into user's key index. == io.KeyMap[key] */ int(CARB_ABI* getKeyIndex)(int imguiKey); /** * Is key being held. == io.KeysDown[userKeyIndex]. note that simplegui doesn't know the semantic of each entry of * io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]! */ bool(CARB_ABI* isKeyDown)(int userKeyIndex); /** * Was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate */ bool(CARB_ABI* isKeyPressed)(int userKeyIndex, bool repeat /* = true*/); /** * Was key released (went from Down to !Down). */ bool(CARB_ABI* isKeyReleased)(int userKeyIndex); /** * Uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough * that DeltaTime > RepeatRate */ int(CARB_ABI* getKeyPressedAmount)(int keyIndex, float repeatDelay, float rate); /** * Gets the key modifiers for each frame. * * Shortcut to bitwise modifier from ImGui::GetIO().KeyCtrl + .KeyShift + .KeyAlt + .KeySuper * * @return The key modifiers for each frame. */ KeyModifiers(CARB_ABI* getKeyModifiers)(); /** * Is mouse button held */ bool(CARB_ABI* isMouseDown)(int button); /** * Is any mouse button held */ bool(CARB_ABI* isAnyMouseDown)(); /** * Did mouse button clicked (went from !Down to Down) */ bool(CARB_ABI* isMouseClicked)(int button, bool repeat /* = false*/); /** * Did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. */ bool(CARB_ABI* isMouseDoubleClicked)(int button); /** * Did mouse button released (went from Down to !Down) */ bool(CARB_ABI* isMouseReleased)(int button); /** * Is mouse dragging. if lockThreshold < -1.0f uses io.MouseDraggingThreshold */ bool(CARB_ABI* isMouseDragging)(int button /* = 0*/, float lockThreshold /* = -1.0f*/); /** * Is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of * consideration of focus/window ordering/blocked by a popup. */ bool(CARB_ABI* isMouseHoveringRect)(const Float2& rMin, const Float2& rMax, bool clip /* = true*/); //! @private Unknown/Undocumented bool(CARB_ABI* isMousePosValid)(const Float2* mousePos /* = nullptr*/); /** * Shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls */ Float2(CARB_ABI* getMousePos)(); /** * Retrieve backup of mouse position at the time of opening popup we have BeginPopup() into */ Float2(CARB_ABI* getMousePosOnOpeningCurrentPopup)(); /** * Dragging amount since clicking. if lockThreshold < -1.0f uses io.MouseDraggingThreshold */ Float2(CARB_ABI* getMouseDragDelta)(int button /* = 0*/, float lockThreshold /* = -1.0f*/); //! @private Unknown/Undocumented void(CARB_ABI* resetMouseDragDelta)(int button /* = 0*/); /** * Gets the mouse wheel delta for each frame. * * Shortcut to ImGui::GetIO().MouseWheel + .MouseWheelH. * * @return The mouse wheel delta for each frame. */ carb::Float2(CARB_ABI* getMouseWheel)(); /** * Get desired cursor type, reset in ISimpleGui::newFrame(), this is updated during the frame. valid before * Render(). If you use software rendering by setting io.MouseDrawCursor simplegui will render those for you */ MouseCursor(CARB_ABI* getMouseCursor)(); /** * Set desired cursor type */ void(CARB_ABI* setMouseCursor)(MouseCursor type); /** * Manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to * handle). e.g. force capture keyboard when your widget is being hovered. */ void(CARB_ABI* captureKeyboardFromApp)(bool capture /* = true*/); /** * Manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to * handle). */ void(CARB_ABI* captureMouseFromApp)(bool capture /* = true*/); /** * Used to capture text data to the clipboard. * * @return The text captures from the clipboard */ const char*(CARB_ABI* getClipboardText)(); /** * Used to apply text into the clipboard. * * @param text The text to be set into the clipboard. */ void(CARB_ABI* setClipboardText)(const char* text); /** * Shortcut to ImGui::GetIO().WantSaveIniSettings provided by user, to be consistent with other calls */ bool(CARB_ABI* getWantSaveIniSettings)(); /** * Shortcut to ImGui::GetIO().WantSaveIniSettings provided by user, to be consistent with other calls */ void(CARB_ABI* setWantSaveIniSettings)(bool wantSaveIniSettings); /** * Manually load the previously saved setting from memory loaded from an .ini settings file. * * @param iniData The init data to be loaded. * @param initSize The size of the ini data to be loaded. */ void(CARB_ABI* loadIniSettingsFromMemory)(const char* iniData, size_t iniSize); /** * Manually save settings to a ini memory as a string. * * @param iniSize[out] The ini size of memory to be saved. * @return The memory */ const char*(CARB_ABI* saveIniSettingsToMemory)(size_t* iniSize); /** * Main viewport. Same as GetPlatformIO().MainViewport == GetPlatformIO().Viewports[0] */ Viewport*(CARB_ABI* getMainViewport)(); /** * Associates a windowName to a dock node id. * * @param windowName The name of the window. * @param nodeId The dock node id. */ void(CARB_ABI* dockBuilderDockWindow)(const char* windowName, uint32_t nodeId); /** * DO NOT HOLD ON ImGuiDockNode* pointer, will be invalided by any split/merge/remove operation. */ DockNode*(CARB_ABI* dockBuilderGetNode)(uint32_t nodeId); /** * Defaults: * flags = 0 */ void(CARB_ABI* dockBuilderAddNode)(uint32_t nodeId, DockNodeFlags flags); /** * Remove node and all its child, undock all windows */ void(CARB_ABI* dockBuilderRemoveNode)(uint32_t nodeId); /** * Defaults: * clearPersistentDockingReferences = true */ void(CARB_ABI* dockBuilderRemoveNodeDockedWindows)(uint32_t nodeId, bool clearPersistentDockingReferences); /** * Remove all split/hierarchy. All remaining docked windows will be re-docked to the root. */ void(CARB_ABI* dockBuilderRemoveNodeChildNodes)(uint32_t nodeId); /** * Dock building split node. */ uint32_t(CARB_ABI* dockBuilderSplitNode)( uint32_t nodeId, Direction splitDir, float sizeRatioForNodeAtDir, uint32_t* outIdDir, uint32_t* outIdOther); /** * Dock building finished. */ void(CARB_ABI* dockBuilderFinish)(uint32_t nodeId); /** * Adds a font from a given font config. * @param fontConfig The font config struct. * @returns A valid font, or `nullptr` if an error occurred. */ Font*(CARB_ABI* addFont)(const FontConfig* fontConfig); /** * Adds a default font from a given font config. * @param fontConfig The font config struct. * @returns A valid font, or `nullptr` if an error occurred. */ Font*(CARB_ABI* addFontDefault)(const FontConfig* fontConfig /* = NULL */); /** * Adds a TTF font from a file. * @param filename The path to the file. * @param sizePixels The size of the font in pixels. * @param fontCfg (Optional) The font config struct. * @param glyphRanges (Optional) The range of glyphs. * @returns A valid font, or `nullptr` if an error occurred. */ Font*(CARB_ABI* addFontFromFileTTF)(const char* filename, float sizePixels, const FontConfig* fontCfg /*= NULL */, const Wchar* glyphRanges /*= NULL*/); /** * Adds a TTF font from a memory region. * @param fontData The font data in memory. * @param fontSize The number of bytes of the font data in memory. * @param sizePixels The size of the font in pixels. * @param fontCfg (Optional) The font config struct. * @param glyphRanges (Optional) The range of glyphs. * @returns A valid font, or `nullptr` if an error occurred. */ Font*(CARB_ABI* addFontFromMemoryTTF)(void* fontData, int fontSize, float sizePixels, const FontConfig* fontCfg /* = NULL */, const Wchar* glyphRanges /* = NULL */); /** * Adds a compressed TTF font from a memory region. * @param compressedFontData The font data in memory. * @param compressedFontSize The number of bytes of the font data in memory. * @param sizePixels The size of the font in pixels. * @param fontCfg (Optional) The font config struct. * @param glyphRanges (Optional) The range of glyphs. * @returns A valid font, or `nullptr` if an error occurred. */ Font*(CARB_ABI* addFontFromMemoryCompressedTTF)(const void* compressedFontData, int compressedFontSize, float sizePixels, const FontConfig* fontCfg /* = NULL */, const Wchar* glyphRanges /*= NULL */); /** * Adds a compressed base-85 TTF font from a memory region. * @param compressedFontDataBase85 The font data in memory. * @param sizePixels The size of the font in pixels. * @param fontCfg (Optional) The font config struct. * @param glyphRanges (Optional) The range of glyphs. * @returns A valid font, or `nullptr` if an error occurred. */ Font*(CARB_ABI* addFontFromMemoryCompressedBase85TTF)(const char* compressedFontDataBase85, float sizePixels, const FontConfig* fontCfg /* = NULL */, const Wchar* glyphRanges /* = NULL */); /** * Add a custom rect glyph that can be built into the font atlas. Call buildFont after. * * @param font The font to add to. * @param id The Unicode point to add for. * @param width The width of the glyph. * @param height The height of the glyph * @param advanceX The advance x for the glyph. * @param offset The glyph offset. * @return The glyph index. */ int(CARB_ABI* addFontCustomRectGlyph)( Font* font, Wchar id, int width, int height, float advanceX, const carb::Float2& offset /* (0, 0) */); /** * Gets the font custom rect by glyph index. * * @param index The glyph index to get the custom rect information for. * @return The font glyph custom rect information. */ const FontCustomRect*(CARB_ABI* getFontCustomRectByIndex)(int index); /** * Builds the font atlas. * * @return true if the font atlas was built successfully. */ bool(CARB_ABI* buildFont)(); /** * Determines if changes have been made to font atlas * * @return true if the font atlas is built. */ bool(CARB_ABI* isFontBuilt)(); /** * Gets the font texture data. * * @param outPixel The pixel texture data in A8 format. * @param outWidth The texture width. * @param outPixel The texture height. */ void(CARB_ABI* getFontTexDataAsAlpha8)(unsigned char** outPixels, int* outWidth, int* outHeight); /** * Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used * to build the texture and fonts. */ void(CARB_ABI* clearFontInputData)(); /** * Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. */ void(CARB_ABI* clearFontTexData)(); /** * Clear output font data (glyphs storage, UV coordinates). */ void(CARB_ABI* clearFonts)(); /** * Clear all input and output. */ void(CARB_ABI* clearFontInputOutput)(); /** * Basic Latin, Extended Latin */ const Wchar*(CARB_ABI* getFontGlyphRangesDefault)(); /** * Default + Korean characters */ const Wchar*(CARB_ABI* getFontGlyphRangesKorean)(); /** * Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs */ const Wchar*(CARB_ABI* getFontGlyphRangesJapanese)(); /** * Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs */ const Wchar*(CARB_ABI* getFontGlyphRangesChineseFull)(); /** * Default + Half-Width + Japanese Hiragana/Katakana + set * of 2500 CJK Unified Ideographs for common simplified Chinese */ const Wchar*(CARB_ABI* getGlyphRangesChineseSimplifiedCommon)(); /** * Default + about 400 Cyrillic characters */ const Wchar*(CARB_ABI* getFontGlyphRangesCyrillic)(); /** * Default + Thai characters */ const Wchar*(CARB_ABI* getFontGlyphRangesThai)(); /** * set Global Font Scale */ void(CARB_ABI* setFontGlobalScale)(float scale); /** * Shortcut for getWindowDrawList() + DrawList::AddCallback() */ void(CARB_ABI* addWindowDrawCallback)(DrawCallback callback, void* userData); /** * Adds a line to the draw list. */ void(CARB_ABI* addLine)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, uint32_t col, float thickness); /** * Adds a rect to the draw list. * * @param a Upper-left. * @param b Lower-right. * @param col color. * @param rounding Default = 0.f; * @param roundingCornersFlags 4-bits corresponding to which corner to round. Default = kDrawCornerFlagAll * @param thickness Default = 1.0f */ void(CARB_ABI* addRect)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, uint32_t col, float rounding, DrawCornerFlags roundingCornersFlags, float thickness); /** * Adds a filled rect to the draw list. * * @param a Upper-left. * @param b Lower-right. * @param col color. * @param rounding Default = 0.f; * @param roundingCornersFlags 4-bits corresponding to which corner to round. Default = kDrawCornerFlagAll */ void(CARB_ABI* addRectFilled)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, uint32_t col, float rounding, DrawCornerFlags roundingCornersFlags); /** * Adds a filled multi-color rect to the draw list. */ void(CARB_ABI* addRectFilledMultiColor)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, uint32_t colUprLeft, uint32_t colUprRight, uint32_t colBotRight, uint32_t colBotLeft); /** * Adds a quad to the draw list. * Default: thickness = 1.0f. */ void(CARB_ABI* addQuad)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, const carb::Float2& c, const carb::Float2& d, uint32_t col, float thickness); /** * Adds a filled quad to the draw list. */ void(CARB_ABI* addQuadFilled)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, const carb::Float2& c, const carb::Float2& d, uint32_t col); /** * Adds a triangle to the draw list. * Defaults: thickness = 1.0f. */ void(CARB_ABI* addTriangle)(DrawList* drawList, const carb::Float2& a, const carb::Float2& b, const carb::Float2& c, uint32_t col, float thickness); /** * Adds a filled triangle to the draw list. */ void(CARB_ABI* addTriangleFilled)( DrawList* drawList, const carb::Float2& a, const carb::Float2& b, const carb::Float2& c, uint32_t col); /** * Adds a circle to the draw list. * Defaults: numSegments = 12, thickness = 1.0f. */ void(CARB_ABI* addCircle)( DrawList* drawList, const carb::Float2& centre, float radius, uint32_t col, int32_t numSegments, float thickness); /** * Adds a filled circle to the draw list. * Defaults: numSegments = 12, thickness = 1.0f. */ void(CARB_ABI* addCircleFilled)( DrawList* drawList, const carb::Float2& centre, float radius, uint32_t col, int32_t numSegments); /** * Adds text to the draw list. */ void(CARB_ABI* addText)( DrawList* drawList, const carb::Float2& pos, uint32_t col, const char* textBegin, const char* textEnd); /** * Adds text to the draw list. * Defaults: textEnd = nullptr, wrapWidth = 0.f, cpuFineClipRect = nullptr. */ void(CARB_ABI* addTextEx)(DrawList* drawList, const Font* font, float fontSize, const carb::Float2& pos, uint32_t col, const char* textBegin, const char* textEnd, float wrapWidth, const carb::Float4* cpuFineClipRect); /** * Adds an image to the draw list. */ void(CARB_ABI* addImage)(DrawList* drawList, TextureId textureId, const carb::Float2& a, const carb::Float2& b, const carb::Float2& uvA, const carb::Float2& uvB, uint32_t col); /** * Adds an image quad to the draw list. * defaults: uvA = (0, 0), uvB = (1, 0), uvC = (1, 1), uvD = (0, 1), col = 0xFFFFFFFF. */ void(CARB_ABI* addImageQuad)(DrawList* drawList, TextureId textureId, const carb::Float2& a, const carb::Float2& b, const carb::Float2& c, const carb::Float2& d, const carb::Float2& uvA, const carb::Float2& uvB, const carb::Float2& uvC, const carb::Float2& uvD, uint32_t col); /** * Adds an rounded image to the draw list. * defaults: roundingCorners = kDrawCornerFlagAll */ void(CARB_ABI* addImageRounded)(DrawList* drawList, TextureId textureId, const carb::Float2& a, const carb::Float2& b, const carb::Float2& uvA, const carb::Float2& uvB, uint32_t col, float rounding, DrawCornerFlags roundingCorners); /** * Adds a polygon line to the draw list. */ void(CARB_ABI* addPolyline)(DrawList* drawList, const carb::Float2* points, const int32_t numPoints, uint32_t col, bool closed, float thickness); /** * Adds a filled convex polygon to draw list. * Note: Anti-aliased filling requires points to be in clockwise order. */ void(CARB_ABI* addConvexPolyFilled)(DrawList* drawList, const carb::Float2* points, const int32_t numPoints, uint32_t col); /** * Adds a Bezier curve to draw list. * defaults: numSegments = 0. */ void(CARB_ABI* addBezierCurve)(DrawList* drawList, const carb::Float2& pos0, const carb::Float2& cp0, const carb::Float2& cp1, const carb::Float2& pos1, uint32_t col, float thickness, int32_t numSegments); /** * Creates a ListClipper to clip large list of items. * * @param itemsCount Number of items to clip. Use INT_MAX if you don't know how many items you have (in which case * the cursor won't be advanced in the final step) * @param float itemsHeight Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance * between your items, typically getTextLineHeightWithSpacing() or getFrameHeightWithSpacing(). * * @return returns the created ListClipper instance. */ ListClipper*(CARB_ABI* createListClipper)(int32_t itemsCount, float itemsHeight); /** * Call until it returns false. The displayStart/displayEnd fields will be set and you can process/draw those items. * * @param listClipper The listClipper instance to advance. */ bool(CARB_ABI* stepListClipper)(ListClipper* listClipper); /** * Destroys a listClipper instance. * * @param listClipper The listClipper instance to destroy. */ void(CARB_ABI* destroyListClipper)(ListClipper* listClipper); /** * Feed the keyboard event into the simplegui. * * @param ctx The context to be fed input event to. * @param event Keyboard event description. */ bool(CARB_ABI* feedKeyboardEvent)(Context* ctx, const input::KeyboardEvent& event); /** * Feed the mouse event into the simplegui. * * @param ctx The context to be fed input event to. * @param event Mouse event description. */ bool(CARB_ABI* feedMouseEvent)(Context* ctx, const input::MouseEvent& event); /** * Walks all of the currently loaded fonts and calls a callback for each. * @param func The function to call for each loaded font. * @param user The user data to pass to \p func. */ void(CARB_ABI* enumerateFonts)(FontEnumFn func, void* user); /** * Returns the name of a loaded font. * @param font The font to retrieve the name of. * @returns The font name, or "<unknown>" if not known. */ const char*(CARB_ABI* getFontName)(const Font* font); /** * Returns the default font for the current context. * @returns The default font for the current context. */ Font*(CARB_ABI* getDefaultFont)(); /** * Sets the default font for the current context. * @param font The font to use as the default. * @returns The previous default font. */ Font*(CARB_ABI* setDefaultFont)(Font* font); }; inline void ISimpleGui::sameLine() { sameLineEx(0, -1.0f); } inline bool ISimpleGui::button(const char* label) { return buttonEx(label, { 0, 0 }); } } // namespace simplegui } // namespace carb
omniverse-code/kit/include/carb/simplegui/SimpleGuiTypes.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 carb.simplegui type definitions. #pragma once #include "../Types.h" namespace carb { //! Namespace for Carbonite Input system. namespace input { struct Keyboard; struct Mouse; struct Gamepad; struct KeyboardEvent; struct MouseEvent; } // namespace input //! Namespace for Carbonite Windowing system. namespace windowing { struct Window; } namespace simplegui { //! An opaque type representing a SimpleGui "context," or instance of a GUI. struct Context; //! An opaque type representing a SimpleGui font. struct Font; //! An opaque type returned by ISimpleGui::dockBuilderGetNode(). struct DockNode; /** * Defines a descriptor for simplegui context. */ struct ContextDesc { Float2 displaySize; //!< The display size. windowing::Window* window; //!< The Window to use. input::Keyboard* keyboard; //!< The Keyboard to listen for events. Can be nullptr. input::Mouse* mouse; //!< The Mouse to listen for events. Can be nullptr. input::Gamepad* gamepad; //!< The Gamepad to listen for events. Can be nullptr. }; /** * Key modifiers returned by ISimpleGui::getKeyModifiers(). */ typedef uint32_t KeyModifiers; const KeyModifiers kKeyModifierNone = 0; //!< Indicates no key modifiers. const KeyModifiers kKeyModifierCtrl = 1 << 0; //!< Indicates CTRL is held. const KeyModifiers kKeyModifierShift = 1 << 1; //!< Indicates SHIFT is held. const KeyModifiers kKeyModifierAlt = 1 << 2; //!< Indicates ALT is held. const KeyModifiers kKeyModifierSuper = 1 << 3; //!< Indicates a "super key" is held (Cmd/Windows/etc.). /** * Defines window flags for simplegui::begin() */ typedef uint32_t WindowFlags; const WindowFlags kWindowFlagNone = 0; //!< Indicates the absence of all other window flags. const WindowFlags kWindowFlagNoTitleBar = 1 << 0; //!< Window Flag to disable the title bar. const WindowFlags kWindowFlagNoResize = 1 << 1; //!< Window Flag to disable user resizing with the lower-right grip. const WindowFlags kWindowFlagNoMove = 1 << 2; //!< Window Flag to disable user moving the window. const WindowFlags kWindowFlagNoScrollbar = 1 << 3; //!< Window Flag to disable user moving the window. const WindowFlags kWindowFlagNoScrollWithMouse = 1 << 4; //!< Window Flag to disable user vertically scrolling with //!< mouse wheel. On child window, mouse wheel will be //!< forwarded to the parent unless NoScrollbar is also set.. const WindowFlags kWindowFlagNoCollapse = 1 << 5; //!< Window Flag to disable user collapsing window by double-clicking //!< on it. const WindowFlags kWindowFlagAlwaysAutoResize = 1 << 6; //!< Window Flag to resize every window to its content every //!< frame. const WindowFlags kWindowFlagNoBackground = 1 << 7; //!< Window Flag to disable drawing background color (WindowBg, //!< etc.) and outside border. Similar as using //!< SetNextWindowBgAlpha(0.0f). const WindowFlags kWindowFlagNoSavedSettings = 1 << 8; //!< Window Flag to never load/save settings in .ini file const WindowFlags kWindowFlagNoMouseInputs = 1 << 9; //!< Window Flag to disable catching mouse, hovering test with pass //!< through. const WindowFlags kWindowFlagMenuBar = 1 << 10; //!< Window Flag to state that this has a menu-bar. const WindowFlags kWindowFlagHorizontalScrollbar = 1 << 11; //!< Window Flag to allow horizontal scrollbar to appear //!< (off by default). You may use //!< `SetNextWindowContentSize(Float2(width,0.0f))`, prior //!< to calling Begin() to specify width. const WindowFlags kWindowFlagNoFocusOnAppearing = 1 << 12; //!< Window Flag to disable taking focus when transitioning //!< from hidden to visible state. const WindowFlags kWindowFlagNoBringToFrontOnFocus = 1 << 13; //!< Window Flag to disable bringing window to front when //!< taking focus. (Ex. clicking on it or programmatically //!< giving it focus). const WindowFlags kWindowFlagAlwaysVerticalScrollbar = 1 << 14; //!< Window Flag to always show vertical scrollbar (even //!< if content Size.y < Size.y). const WindowFlags kWindowFlagAlwaysHorizontalScrollbar = 1 << 15; //!< Window Flag to always show horizontal scrollbar //!< (even if content Size.x < Size.x). const WindowFlags kWindowFlagAlwaysUseWindowPadding = 1 << 16; //!< Window Flag to ensure child windows without border //!< uses style.WindowPadding. Ignored by default for //!< non-bordered child windows, because more convenient. const WindowFlags kWindowFlagNoNavInputs = 1 << 18; //!< No gamepad/keyboard navigation within the window const WindowFlags kWindowFlagNoNavFocus = 1 << 19; //!< No focusing toward this window with gamepad/keyboard navigation //!< (e.g. skipped by CTRL+TAB) const WindowFlags kWindowFlagUnsavedDocument = 1 << 20; //!< Append '*' to title without affecting the ID, as a //!< convenience to avoid using the ### operator. When used in a //!< tab/docking context, tab is selected on closure and closure //!< is deferred by one frame to allow code to cancel the //!< closure (with a confirmation popup, etc.) without flicker. const WindowFlags kWindowFlagNoDocking = 1 << 21; //!< Disable docking of this window //! Special composed Window Flag to disable navigation. const WindowFlags kWindowFlagNoNav = kWindowFlagNoNavInputs | kWindowFlagNoNavFocus; //! Special composed Window Flag to disable all decorative elements. const WindowFlags kWindowFlagNoDecoration = kWindowFlagNoTitleBar | kWindowFlagNoResize | kWindowFlagNoScrollbar | kWindowFlagNoCollapse; //! Special composed Window Flag to disable input. const WindowFlags kWindowFlagNoInput = kWindowFlagNoMouseInputs | kWindowFlagNoNavInputs | kWindowFlagNoNavFocus; /** * Defines item flags for simplegui::pushItemFlags(). * * Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first * Begin(). */ typedef uint32_t ItemFlags; const ItemFlags kItemFlagDefault = 0; //!< Absence of other item flags. const ItemFlags kItemFlagsNoTabStop = 1 << 0; //!< No tab stop. const ItemFlags kItemFlagButtonRepeat = 1 << 1; //!< Button repeat. const ItemFlags kItemFlagDisabled = 1 << 2; //!< Disable interactions. const ItemFlags kItemFlagNoNav = 1 << 3; //!< No Navigation const ItemFlags kItemFlagNoNavDefaultFocus = 1 << 4; //!< No Navigation Default Focus. const ItemFlags kItemFlagSelectableDontClosePopup = 1 << 5; //!< MenuItem/Selectable() automatically closes current //!< Popup window. /** * Defines input text flags for simplegui::inputText() */ typedef uint32_t InputTextFlags; const InputTextFlags kInputTextFlagNone = 0; //!< Absence of other input text flags. const InputTextFlags kInputTextFlagCharsDecimal = 1 << 0; //!< Allow `0123456789.+-*/` const InputTextFlags kInputTextFlagCharsHexadecimal = 1 << 1; //!< Allow `0123456789ABCDEFabcdef` const InputTextFlags kInputTextFlagCharsUppercase = 1 << 2; //!< Turn `a..z` into `A..Z` const InputTextFlags kInputTextFlagCharsNoBlank = 1 << 3; //!< Filter out spaces, tabs const InputTextFlags kInputTextFlagAutoSelectAll = 1 << 4; //!< Select entire text when first taking mouse focus const InputTextFlags kInputTextFlagEnterReturnsTrue = 1 << 5; //!< Return 'true' when Enter is pressed (as opposed to //!< when the value was modified) const InputTextFlags kInputTextFlagCallbackCompletion = 1 << 6; //!< Call user function on pressing TAB (for completion //!< handling) const InputTextFlags kInputTextFlagCallbackHistory = 1 << 7; //!< Call user function on pressing Up/Down arrows (for //!< history handling) const InputTextFlags kInputTextFlagCallbackAlways = 1 << 8; //!< Call user function every time. User code may query //!< cursor position, modify text buffer. const InputTextFlags kInputTextFlagCallbackCharFilter = 1 << 9; //!< Call user function to filter character. Modify //!< data->EventChar to replace/filter input, or return //!< 1 to discard character. const InputTextFlags kInputTextFlagAllowTabInput = 1 << 10; //!< Pressing TAB input a `\t` character into the text field const InputTextFlags kInputTextFlagCtrlEnterForNewLine = 1 << 11; //!< In multi-line mode, unfocus with Enter, add new //!< line with Ctrl+Enter (default is opposite: //!< unfocus with Ctrl+Enter, add line with Enter). const InputTextFlags kInputTextFlagNoHorizontalScroll = 1 << 12; //!< Disable following the cursor horizontally const InputTextFlags kInputTextFlagAlwaysInsertMode = 1 << 13; //!< Insert mode const InputTextFlags kInputTextFlagReadOnly = 1 << 14; //!< Read-only mode const InputTextFlags kInputTextFlagPassword = 1 << 15; //!< Password mode, display all characters as '*' const InputTextFlags kInputTextFlagNoUndoRedo = 1 << 16; //!< Disable undo/redo. Note that input text owns the text data //!< while active, if you want to provide your own undo/redo //!< stack you need e.g. to call ClearActiveID(). const InputTextFlags kInputTextFlagCharsScientific = 1 << 17; //!< Allow `0123456789.+-*/eE` (Scientific notation input) const InputTextFlags kInputTextFlagCallbackResize = 1 << 18; //!< Callback on buffer capacity changes request (beyond //!< `buf_size` parameter value) /** * Defines tree node flags to be used in simplegui::collapsingHeader(), simplegui::treeNodeEx() */ typedef uint32_t TreeNodeFlags; const TreeNodeFlags kTreeNodeFlagNone = 0; //!< Absence of other tree node flags. const TreeNodeFlags kTreeNodeFlagSelected = 1 << 0; //!< Draw as selected const TreeNodeFlags kTreeNodeFlagFramed = 1 << 1; //!< Full colored frame (e.g. for CollapsingHeader) const TreeNodeFlags kTreeNodeFlagAllowItemOverlap = 1 << 2; //!< Hit testing to allow subsequent widgets to overlap this //!< one const TreeNodeFlags kTreeNodeFlagNoTreePushOnOpen = 1 << 3; //!< Don't do a TreePush() when open (e.g. for //!< CollapsingHeader) = no extra indent nor pushing on ID //!< stack const TreeNodeFlags kTreeNodeFlagNoAutoOpenOnLog = 1 << 4; //!< Don't automatically and temporarily open node when //!< Logging is active (by default logging will automatically //!< open tree nodes) const TreeNodeFlags kTreeNodeFlagDefaultOpen = 1 << 5; //!< Default node to be open const TreeNodeFlags kTreeNodeFlagOpenOnDoubleClick = 1 << 6; //!< Need double-click to open node const TreeNodeFlags kTreeNodeFlagOpenOnArrow = 1 << 7; //!< Only open when clicking on the arrow part. If //!< kTreeNodeFlagOpenOnDoubleClick is also set, single-click //!< arrow or double-click all box to open. const TreeNodeFlags kTreeNodeFlagLeaf = 1 << 8; //!< No collapsing, no arrow (use as a convenience for leaf nodes). const TreeNodeFlags kTreeNodeFlagBullet = 1 << 9; //!< Display a bullet instead of arrow const TreeNodeFlags kTreeNodeFlagFramePadding = 1 << 10; //!< Use FramePadding (even for an unframed text node) to //!< vertically align text baseline to regular widget const TreeNodeFlags kTreeNodeFlagNavLeftJumpsBackHere = 1 << 13; //!< (WIP) Nav: left direction may move to this //!< TreeNode() from any of its child (items submitted //!< between TreeNode and TreePop) //! Composed flag indicating collapsing header. const TreeNodeFlags kTreeNodeFlagCollapsingHeader = kTreeNodeFlagFramed | kTreeNodeFlagNoTreePushOnOpen | kTreeNodeFlagNoAutoOpenOnLog; /** * Defines flags to be used in simplegui::selectable() */ typedef uint32_t SelectableFlags; const SelectableFlags kSelectableFlagNone = 0; //!< Absence of other selectable flags. const SelectableFlags kSelectableFlagDontClosePopups = 1 << 0; //!< Clicking this don't close parent popup window const SelectableFlags kSelectableFlagSpanAllColumns = 1 << 1; //!< Selectable frame can span all columns (text will //!< still fit in current column) const SelectableFlags kSelectableFlagAllowDoubleClick = 1 << 2; //!< Generate press events on double clicks too const SelectableFlags kSelectableFlagDisabled = 1 << 3; //!< Cannot be selected, display grayed out text /** * Defines flags to be used in simplegui::beginCombo() */ typedef uint32_t ComboFlags; const ComboFlags kComboFlagNone = 0; //!< Absence of other combo flags. const ComboFlags kComboFlagPopupAlignLeft = 1 << 0; //!< Align the popup toward the left by default const ComboFlags kComboFlagHeightSmall = 1 << 1; //!< Max ~4 items visible. Tip: If you want your combo popup to be a //!< specific size you can use SetNextWindowSizeConstraints() prior to //!< calling BeginCombo() const ComboFlags kComboFlagHeightRegular = 1 << 2; //!< Max ~8 items visible (default) const ComboFlags kComboFlagHeightLarge = 1 << 3; //!< Max ~20 items visible const ComboFlags kComboFlagHeightLargest = 1 << 4; //!< As many fitting items as possible const ComboFlags kComboFlagNoArrowButton = 1 << 5; //!< Display on the preview box without the square arrow button const ComboFlags kComboFlagNoPreview = 1 << 6; //!< Display only a square arrow button const ComboFlags kComboFlagHeightMask = kComboFlagHeightSmall | kComboFlagHeightRegular | kComboFlagHeightLarge | kComboFlagHeightLargest; //!< Composed //!< flag. /** * Defines flags to be used in simplegui::beginTabBar() */ typedef uint32_t TabBarFlags; const TabBarFlags kTabBarFlagNone = 0; //!< Absence of other tab bar flags. const TabBarFlags kTabBarFlagReorderable = 1 << 0; //!< Allow manually dragging tabs to re-order them + New tabs are //!< appended at the end of list const TabBarFlags kTabBarFlagAutoSelectNewTabs = 1 << 1; //!< Automatically select new tabs when they appear const TabBarFlags kTabBarFlagTabListPopupButton = 1 << 2; //!< Tab list popup button. const TabBarFlags kTabBarFlagNoCloseWithMiddleMouseButton = 1 << 3; //!< Disable behavior of closing tabs (that are //!< submitted with `p_open != NULL`) with middle //!< mouse button. You can still repro this behavior //!< on user's side with if (IsItemHovered() && //!< IsMouseClicked(2)) `*p_open = false`. const TabBarFlags kTabBarFlagNoTabListScrollingButtons = 1 << 4; //!< No scrolling buttons. const TabBarFlags kTabBarFlagNoTooltip = 1 << 5; //!< Disable tooltips when hovering a tab const TabBarFlags kTabBarFlagFittingPolicyResizeDown = 1 << 6; //!< Resize tabs when they don't fit const TabBarFlags kTabBarFlagFittingPolicyScroll = 1 << 7; //!< Add scroll buttons when tabs don't fit const TabBarFlags kTabBarFlagFittingPolicyMask = kTabBarFlagFittingPolicyResizeDown | kTabBarFlagFittingPolicyScroll; //!< Composed flag. const TabBarFlags kTabBarFlagFittingPolicyDefault = kTabBarFlagFittingPolicyResizeDown; //!< Composed flag. /** * Defines flags to be used in simplegui::beginTabItem() */ typedef uint32_t TabItemFlags; const TabItemFlags kTabItemFlagNone = 0; //!< Absence of other tab item flags. const TabItemFlags kTabItemFlagUnsavedDocument = 1 << 0; //!< Append '*' to title without affecting the ID; as a //!< convenience to avoid using the ### operator. Also: tab is //!< selected on closure and closure is deferred by one frame //!< to allow code to undo it without flicker. const TabItemFlags kTabItemFlagSetSelected = 1 << 1; //!< Trigger flag to programmatically make the tab selected when //!< calling BeginTabItem() const TabItemFlags kTabItemFlagNoCloseWithMiddleMouseButton = 1 << 2; //!< Disable behavior of closing tabs (that are //!< submitted with `p_open != NULL`) with middle //!< mouse button. You can still repro this //!< behavior on user's side with if //!< (IsItemHovered() && IsMouseClicked(2)) //!< `*p_open = false`. const TabItemFlags kTabItemFlagNoPushId = 1 << 3; //!< Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() /** * Defines flags to be used in simplegui::dockSpace() */ typedef uint32_t DockNodeFlags; const DockNodeFlags kDockNodeFlagNone = 0; //!< Absence of other dock node flags. const DockNodeFlags kDockNodeFlagKeepAliveOnly = 1 << 0; //!< Don't display the dockspace node but keep it alive. //!< Windows docked into this dockspace node won't be undocked. // const DockNodeFlags kDockNodeFlagNoCentralNode = 1 << 1; //!< Disable Central Node (the node which can stay empty) const DockNodeFlags kDockNodeFlagNoDockingInCentralNode = 1 << 2; //!< Disable docking inside the Central Node, which //!< will be always kept empty. const DockNodeFlags kDockNodeFlagPassthruCentralNode = 1 << 3; //!< Enable passthru dockspace: 1) DockSpace() will //!< render a ImGuiCol_WindowBg background covering //!< everything excepted the Central Node when empty. //!< Meaning the host window should probably use //!< SetNextWindowBgAlpha(0.0f) prior to Begin() when //!< using this. 2) When Central Node is empty: let //!< inputs pass-through + won't display a DockingEmptyBg //!< background. See demo for details. const DockNodeFlags kDockNodeFlagNoSplit = 1 << 4; //!< Disable splitting the node into smaller nodes. Useful e.g. when //!< embedding dockspaces into a main root one (the root one may have //!< splitting disabled to reduce confusion) const DockNodeFlags kDockNodeFlagNoResize = 1 << 5; //!< Disable resizing child nodes using the splitter/separators. //!< Useful with programmatically setup dockspaces. const DockNodeFlags kDockNodeFlagAutoHideTabBar = 1 << 6; //!< Tab bar will automatically hide when there is a single //!< window in the dock node. /** * Defines flags to be used in simplegui::isWindowFocused() */ typedef uint32_t FocusedFlags; const FocusedFlags kFocusedFlagNone = 0; //!< Absence of other focused flags. const FocusedFlags kFocusedFlagChildWindows = 1 << 0; //!< IsWindowFocused(): Return true if any children of the window //!< is focused const FocusedFlags kFocusedFlagRootWindow = 1 << 1; //!< IsWindowFocused(): Test from root window (top most parent of //!< the current hierarchy) const FocusedFlags kFocusedFlagAnyWindow = 1 << 2; //!< IsWindowFocused(): Return true if any window is focused const FocusedFlags kFocusedFlagRootAndChildWindows = kFocusedFlagRootWindow | kFocusedFlagChildWindows; //!< Composed //!< flag. /** * Defines flags to be used in simplegui::isItemHovered(), simplegui::isWindowHovered() */ typedef uint32_t HoveredFlags; const HoveredFlags kHoveredFlagNone = 0; //!< Return true if directly over the item/window, not obstructed by another //!< window, not obstructed by an active popup or modal blocking inputs under //!< them. const HoveredFlags kHoveredFlagChildWindows = 1 << 0; //!< IsWindowHovered() only: Return true if any children of the //!< window is hovered const HoveredFlags kHoveredFlagRootWindow = 1 << 1; //!< IsWindowHovered() only: Test from root window (top most parent //!< of the current hierarchy) const HoveredFlags kHoveredFlagAnyWindow = 1 << 2; //!< IsWindowHovered() only: Return true if any window is hovered const HoveredFlags kHoveredFlagAllowWhenBlockedByPopup = 1 << 3; //!< Return true even if a popup window is normally //!< blocking access to this item/window const HoveredFlags kHoveredFlagAllowWhenBlockedByActiveItem = 1 << 5; //!< Return true even if an active item is //!< blocking access to this item/window. Useful //!< for Drag and Drop patterns. const HoveredFlags kHoveredFlagAllowWhenOverlapped = 1 << 6; //!< Return true even if the position is overlapped by //!< another window const HoveredFlags kHoveredFlagAllowWhenDisabled = 1 << 7; //!< Return true even if the item is disabled const HoveredFlags kHoveredFlagRectOnly = kHoveredFlagAllowWhenBlockedByPopup | kHoveredFlagAllowWhenBlockedByActiveItem | kHoveredFlagAllowWhenOverlapped; //!< Composed flag. const HoveredFlags kHoveredFlagRootAndChildWindows = kHoveredFlagRootWindow | kHoveredFlagChildWindows; //!< Composed //!< flag. /** * Defines flags to be used in simplegui::beginDragDropSource(), simplegui::acceptDragDropPayload() */ typedef uint32_t DragDropFlags; const DragDropFlags kDragDropFlagNone = 0; //!< Absence of other drag/drop flags. // BeginDragDropSource() flags const DragDropFlags kDragDropFlagSourceNoPreviewTooltip = 1 << 0; //!< By default, a successful call to //!< BeginDragDropSource opens a tooltip so you can //!< display a preview or description of the source //!< contents. This flag disable this behavior. const DragDropFlags kDragDropFlagSourceNoDisableHover = 1 << 1; //!< By default, when dragging we clear data so that //!< IsItemHovered() will return true, to avoid //!< subsequent user code submitting tooltips. This flag //!< disable this behavior so you can still call //!< IsItemHovered() on the source item. const DragDropFlags kDragDropFlagSourceNoHoldToOpenOthers = 1 << 2; //!< Disable the behavior that allows to open tree //!< nodes and collapsing header by holding over //!< them while dragging a source item. const DragDropFlags kDragDropFlagSourceAllowNullID = 1 << 3; //!< Allow items such as Text(), Image() that have no //!< unique identifier to be used as drag source, by //!< manufacturing a temporary identifier based on their //!< window-relative position. This is extremely unusual //!< within the simplegui ecosystem and so we made it //!< explicit. const DragDropFlags kDragDropFlagSourceExtern = 1 << 4; //!< External source (from outside of simplegui), won't attempt //!< to read current item/window info. Will always return true. //!< Only one Extern source can be active simultaneously. const DragDropFlags kDragDropFlagSourceAutoExpirePayload = 1 << 5; //!< Automatically expire the payload if the source //!< cease to be submitted (otherwise payloads are //!< persisting while being dragged) // AcceptDragDropPayload() flags const DragDropFlags kDragDropFlagAcceptBeforeDelivery = 1 << 10; //!< AcceptDragDropPayload() will returns true even //!< before the mouse button is released. You can then //!< call IsDelivery() to test if the payload needs to //!< be delivered. const DragDropFlags kDragDropFlagAcceptNoDrawDefaultRect = 1 << 11; //!< Do not draw the default highlight rectangle //!< when hovering over target. const DragDropFlags kDragDropFlagAcceptNoPreviewTooltip = 1 << 12; //!< Request hiding the BeginDragDropSource tooltip //!< from the BeginDragDropTarget site. const DragDropFlags kDragDropFlagAcceptPeekOnly = kDragDropFlagAcceptBeforeDelivery | kDragDropFlagAcceptNoDrawDefaultRect; //!< For peeking ahead and inspecting the //!< payload before delivery. /** * A primary data type */ enum class DataType { eS8, //!< char eU8, //!< unsigned char eS16, //!< short eU16, //!< unsigned short eS32, //!< int eU32, //!< unsigned int eS64, //!< long long, __int64 eU64, //!< unsigned long long, unsigned __int64 eFloat, //!< float eDouble, //!< double eCount //!< Number of items. }; /** * A cardinal direction */ enum class Direction { eNone = -1, //!< None eLeft = 0, //!< Left eRight = 1, //!< Right eUp = 2, //<! Up eDown = 3, //!< Down eCount //!< Number of items. }; /** * Enumeration for pushStyleColor() / popStyleColor() */ enum class StyleColor { eText, //!< Text eTextDisabled, //!< Disabled text eWindowBg, //!< Background of normal windows eChildBg, //!< Background of child windows ePopupBg, //!< Background of popups, menus, tooltips windows eBorder, //!< Border eBorderShadow, //!< Border Shadow eFrameBg, //!< Background of checkbox, radio button, plot, slider, text input eFrameBgHovered, //!< Hovered background eFrameBgActive, //!< Active background eTitleBg, //!< Title background eTitleBgActive, //!< Active title background eTitleBgCollapsed, //!< Collapsed title background eMenuBarBg, //!< Menu bar background eScrollbarBg, //!< Scroll bar background eScrollbarGrab, //!< Grabbed scroll bar eScrollbarGrabHovered, //!< Hovered grabbed scroll bar eScrollbarGrabActive, //!< Active grabbed scroll bar eCheckMark, //!< Check box eSliderGrab, //!< Grabbed slider eSliderGrabActive, //!< Active grabbed slider eButton, //!< Button eButtonHovered, //!< Hovered button eButtonActive, //!< Active button eHeader, //!< Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem eHeaderHovered, //!< Hovered header eHeaderActive, //!< Active header eSeparator, //!< Separator eSeparatorHovered, //!< Hovered separator eSeparatorActive, //!< Active separator eResizeGrip, //!< Resize grip eResizeGripHovered, //!< Hovered resize grip eResizeGripActive, //!< Active resize grip eTab, //!< Tab eTabHovered, //!< Hovered tab eTabActive, //!< Active tab eTabUnfocused, //!< Unfocused tab eTabUnfocusedActive, //!< Active unfocused tab eDockingPreview, //!< Preview overlay color when about to docking something eDockingEmptyBg, //!< Background color for empty node (e.g. CentralNode with no window docked into it) ePlotLines, //!< Plot lines ePlotLinesHovered, //!< Hovered plot lines ePlotHistogram, //!< Histogram ePlotHistogramHovered, //!< Hovered histogram eTableHeaderBg, //!< Table header background eTableBorderStrong, //!< Table outer and header borders (prefer using Alpha=1.0 here) eTableBorderLight, //!< Table inner borders (prefer using Alpha=1.0 here) eTableRowBg, //!< Table row background (even rows) eTableRowBgAlt, //!< Table row background (odd rows) eTextSelectedBg, //!< Selected text background eDragDropTarget, //!< Drag/drop target eNavHighlight, //!< Gamepad/keyboard: current highlighted item eNavWindowingHighlight, //!< Highlight window when using CTRL+TAB eNavWindowingDimBg, //!< Darken/colorize entire screen behind the CTRL+TAB window list, when active eModalWindowDimBg, //!< Darken/colorize entire screen behind a modal window, when one is active eWindowShadow, //!< Window shadows #ifdef IMGUI_NVIDIA eCustomChar, //!< Color to render custom char #endif eCount //!< Number of items }; /** * Defines style variable (properties) that can be used * to temporarily modify UI styles. * * The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During * initialization, feel free to just poke into ImGuiStyle directly. * * @see pushStyleVarFloat * @see pushStyleVarFloat2 * @see popStyleVar */ enum class StyleVar { eAlpha, //!< (float, Style::alpha) eWindowPadding, //!< (Float2, Style::windowPadding) eWindowRounding, //!< (float, Style::windowRounding) eWindowBorderSize, //!< (float, Style::windowBorderSize) eWindowMinSize, //!< (Float2, Style::windowMinSize) eWindowTitleAlign, //!< (Float2, Style::windowTitleAlign) eChildRounding, //!< (float, Style::childRounding) eChildBorderSize, //!< (float, Style::childBorderSize) ePopupRounding, //!< (float, Style::popupRounding) ePopupBorderSize, //!< (float, Style::popupBorderSize) eFramePadding, //!< (Float2, Style::framePadding) eFrameRounding, //!< (float, Style::frameRounding) eFrameBorderSize, //!< (float, Style::frameBorderSize) eItemSpacing, //!< (Float2, Style::itemSpacing) eItemInnerSpacing, //!< (Float2, Style::itemInnerSpacing) eIndentSpacing, //!< (float, Style::indentSpacing) eCellPadding, //!< (Float2, Style::cellPadding) eScrollbarSize, //!< (float, Style::scrollbarSize) eScrollbarRounding, //!< (float, Style::scrollbarRounding) eGrabMinSize, //!< (float, Style::grabMinSize) eGrabRounding, //!< (float, Style::grabRounding) eTabRounding, //!< (float, Style::tabRounding) eButtonTextAlign, //!< (Float2, Style::buttonTextAlign) eSelectableTextAlign, //!< (Float2, Style::selectableTextAlign) #ifdef IMGUI_NVIDIA eDockSplitterSize, //!< (float, Style::dockSplitterSize) #endif eCount //!< Number of items }; /** * Defines flags to be used in colorEdit3() / colorEdit4() / colorPicker3() / colorPicker4() / colorButton() */ typedef uint32_t ColorEditFlags; const ColorEditFlags kColorEditFlagNone = 0; //!< Absence of other color edit flags. const ColorEditFlags kColorEditFlagNoAlpha = 1 << 1; //!< ColorEdit, ColorPicker, ColorButton: ignore Alpha component //!< (read 3 components from the input pointer). const ColorEditFlags kColorEditFlagNoPicker = 1 << 2; //!< ColorEdit: disable picker when clicking on colored square. const ColorEditFlags kColorEditFlagNoOptions = 1 << 3; //!< ColorEdit: disable toggling options menu when right-clicking //!< on inputs/small preview. const ColorEditFlags kColorEditFlagNoSmallPreview = 1 << 4; //!< ColorEdit, ColorPicker: disable colored square preview //!< next to the inputs. (e.g. to show only the inputs) const ColorEditFlags kColorEditFlagNoInputs = 1 << 5; //!< ColorEdit, ColorPicker: disable inputs sliders/text widgets //!< (e.g. to show only the small preview colored square). const ColorEditFlags kColorEditFlagNoTooltip = 1 << 6; //!< ColorEdit, ColorPicker, ColorButton: disable tooltip when //!< hovering the preview. const ColorEditFlags kColorEditFlagNoLabel = 1 << 7; //!< ColorEdit, ColorPicker: disable display of inline text label //!< (the label is still forwarded to the tooltip and picker). const ColorEditFlags kColorEditFlagNoSidePreview = 1 << 8; //!< ColorPicker: disable bigger color preview on right side //!< of the picker, use small colored square preview instead. // User Options (right-click on widget to change some of them). You can set application defaults using // SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user // choose and/or call SetColorEditOptions() during startup. const ColorEditFlags kColorEditFlagAlphaBar = 1 << 9; //!< ColorEdit, ColorPicker: show vertical alpha bar/gradient in //!< picker. const ColorEditFlags kColorEditFlagAlphaPreview = 1 << 10; //!< ColorEdit, ColorPicker, ColorButton: display preview as //!< a transparent color over a checkerboard, instead of //!< opaque. const ColorEditFlags kColorEditFlagAlphaPreviewHalf = 1 << 11; //!< ColorEdit, ColorPicker, ColorButton: display half //!< opaque / half checkerboard, instead of opaque. const ColorEditFlags kColorEditFlagHDR = 1 << 12; //!< (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA //!< edition (note: you probably want to use ImGuiColorEditFlags_Float //!< flag as well). const ColorEditFlags kColorEditFlagRGB = 1 << 13; //!< [Inputs] ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: //!< choose any combination using RGB/HSV/HEX. const ColorEditFlags kColorEditFlagHSV = 1 << 14; //!< [Inputs] const ColorEditFlags kColorEditFlagHEX = 1 << 15; //!< [Inputs] const ColorEditFlags kColorEditFlagUint8 = 1 << 16; //!< [DataType] ColorEdit, ColorPicker, ColorButton: _display_ //!< values formatted as 0..255. const ColorEditFlags kColorEditFlagFloat = 1 << 17; //!< [DataType] ColorEdit, ColorPicker, ColorButton: _display_ //!< values formatted as 0.0f..1.0f floats instead of 0..255 //!< integers. No round-trip of value via integers. const ColorEditFlags kColorEditFlagPickerHueBar = 1 << 18; //!< [PickerMode] // ColorPicker: bar for Hue, rectangle for //!< Sat/Value. const ColorEditFlags kColorEditFlagPickerHueWheel = 1 << 19; //!< [PickerMode] // ColorPicker: wheel for Hue, triangle //!< for Sat/Value. /** * Defines DrawCornerFlags. */ typedef uint32_t DrawCornerFlags; const DrawCornerFlags kDrawCornerFlagTopLeft = 1 << 0; //!< Top left const DrawCornerFlags kDrawCornerFlagTopRight = 1 << 1; //!< Top right const DrawCornerFlags kDrawCornerFlagBotLeft = 1 << 2; //!< Bottom left const DrawCornerFlags kDrawCornerFlagBotRight = 1 << 3; //!< Bottom right const DrawCornerFlags kDrawCornerFlagTop = kDrawCornerFlagTopLeft | kDrawCornerFlagTopRight; //!< Top const DrawCornerFlags kDrawCornerFlagBot = kDrawCornerFlagBotLeft | kDrawCornerFlagBotRight; //!< Bottom const DrawCornerFlags kDrawCornerFlagLeft = kDrawCornerFlagTopLeft | kDrawCornerFlagBotLeft; //!< Left const DrawCornerFlags kDrawCornerFlagRight = kDrawCornerFlagTopRight | kDrawCornerFlagBotRight; //!< Right const DrawCornerFlags kDrawCornerFlagAll = 0xF; //!< All corners /** * Enumeration for GetMouseCursor() * User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors * that are marked unused here */ enum class MouseCursor { eNone = -1, //!< No mouse cursor. eArrow = 0, //!< Arrow eTextInput, //!< When hovering over InputText, etc. eResizeAll, //!< Unused by simplegui functions eResizeNS, //!< When hovering over an horizontal border eResizeEW, //!< When hovering over a vertical border or a column eResizeNESW, //!< When hovering over the bottom-left corner of a window eResizeNWSE, //!< When hovering over the bottom-right corner of a window eHand, //!< Unused by simplegui functions. Use for e.g. hyperlinks eNotAllowed, //!< When hovering something with disallowed interaction. Usually a crossed circle. eCount //!< Number of items }; /** * Condition for simplegui::setWindow***(), setNextWindow***(), setNextTreeNode***() functions */ enum class Condition { eAlways = 1 << 0, //!< Set the variable eOnce = 1 << 1, //!< Set the variable once per runtime session (only the first call with succeed) eFirstUseEver = 1 << 2, //!< Set the variable if the object/window has no persistently saved data (no entry in .ini //!< file) eAppearing = 1 << 3, //!< Set the variable if the object/window is appearing after being hidden/inactive (or the //!< first time) }; /** * Struct with all style variables * * You may modify the simplegui::getStyle() main instance during initialization and before newFrame(). * During the frame, use simplegui::pushStyleVar()/popStyleVar() to alter the main style values, and * simplegui::pushStyleColor()/popStyleColor() for colors. */ struct Style { float alpha; //!< Global alpha applies to everything in simplegui. Float2 windowPadding; //!< Padding within a window. float windowRounding; //!< Radius of window corners rounding. Set to 0.0f to have rectangular windows. float windowBorderSize; //!< Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are //!< not well tested and more CPU/GPU costly). Float2 windowMinSize; //!< Minimum window size. This is a global setting. If you want to constraint individual //!< windows, use SetNextWindowSizeConstraints(). Float2 windowTitleAlign; //!< Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically //!< centered. Direction windowMenuButtonPosition; //!< Side of the collapsing/docking button in the title bar (None/Left/Right). //!< Defaults to ImGuiDir_Left. float childRounding; //!< Radius of child window corners rounding. Set to 0.0f to have rectangular windows. float childBorderSize; //!< Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values //!< are not well tested and more CPU/GPU costly). float popupRounding; //!< Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) float popupBorderSize; //!< Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other //!< values are not well tested and more CPU/GPU costly). Float2 framePadding; //!< Padding within a framed rectangle (used by most widgets). float frameRounding; //!< Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most //!< widgets). float frameBorderSize; //!< Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not //!< well tested and more CPU/GPU costly). Float2 itemSpacing; //!< Horizontal and vertical spacing between widgets/lines. Float2 itemInnerSpacing; //!< Horizontal and vertical spacing between within elements of a composed widget (e.g. a //!< slider and its label). Float2 cellPadding; //!< Padding within a table cell Float2 touchExtraPadding; //!< Expand reactive bounding box for touch-based system where touch position is not //!< accurate enough. Unfortunately we don't sort widgets so priority on overlap will //!< always be given to the first widget. So don't grow this too much! float indentSpacing; //!< Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + //!< FramePadding.x*2). float columnsMinSpacing; //!< Minimum horizontal spacing between two columns. float scrollbarSize; //!< Width of the vertical scrollbar, Height of the horizontal scrollbar. float scrollbarRounding; //!< Radius of grab corners for scrollbar. float grabMinSize; //!< Minimum width/height of a grab box for slider/scrollbar. float grabRounding; //!< Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float tabRounding; //!< Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float tabBorderSize; //!< Thickness of border around tabs. float tabMinWidthForUnselectedCloseButton; //!< Minimum width for close button to appears on an unselected tab when //!< hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to //!< never show close button unless selected. Direction colorButtonPosition; //!< Side of the color button in the ColorEdit4 widget (left/right). Defaults to //!< ImGuiDir_Right. Float2 buttonTextAlign; //!< Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for //!< horizontally+vertically centered. Float2 selectableTextAlign; //!< Alignment of selectable text when selectable is larger than text. Defaults to //!< (0.0f, 0.0f) (top-left aligned). Float2 displayWindowPadding; //!< Window positions are clamped to be visible within the display area by at least //!< this amount. Only covers regular windows. Float2 displaySafeAreaPadding; //!< If you cannot see the edge of your screen (e.g. on a TV) increase the safe area //!< padding. Covers popups/tooltips as well regular windows. float mouseCursorScale; //!< Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be //!< removed later. bool antiAliasedLines; //!< Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool antiAliasedFill; //!< Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float curveTessellationTol; //!< Tessellation tolerance when using PathBezierCurveTo() without a specific number of //!< segments. Decrease for highly tessellated curves (higher quality, more polygons), //!< increase to reduce quality. float circleSegmentMaxError; //!< Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or //!< drawing rounded corner rectangles with no explicit segment count specified. //!< Decrease for higher quality but more geometry. float windowShadowSize; //!< Size (in pixels) of window shadows. Set this to zero to disable shadows. float windowShadowOffsetDist; //!< Offset distance (in pixels) of window shadows from casting window. float windowShadowOffsetAngle; //!< Offset angle of window shadows from casting window (0.0f = left, 0.5f*PI = //!< bottom, 1.0f*PI = right, 1.5f*PI = top). Float4 colors[(size_t)StyleColor::eCount]; //!< Color by style. #ifdef IMGUI_NVIDIA float dockSplitterSize; //!< Thickness of border around docking window. Set to 0.0f to no splitter. uint16_t customCharBegin; //!< Code of first custom char. Custom char will be rendered with ImGuiCol_CustomChar. //!< 0xFFFF means no custom char. #endif //! Constructor. Style() { } }; /** * Predefined Style Colors presets. */ enum class StyleColorsPreset { eNvidiaDark, //!< NVIDIA Dark colors. eNvidiaLight, //!< NVIDIA Light colors. eDark, //!< New Dear ImGui style eLight, //!< Best used with borders and a custom, thicker font eClassic, //!< Classic Dear ImGui style eCount //!< Number of items. }; struct DrawCommand; struct DrawData; /** * User data to identify a texture. */ typedef void* TextureId; /** * Draw callbacks for advanced uses. */ typedef void (*DrawCallback)(const DrawData* drawData, const DrawCommand* cmd); /** * Font enumeration function. * * A return of \c false stops iteration. */ typedef bool (*FontEnumFn)(Font* font, void* user); /** * Defines a drawing command. */ struct DrawCommand { /** * The number of indices (multiple of 3) to be rendered as triangles. * The vertices are stored in the callee DrawList::vertexBuffer array, * indices in IdxBuffer. */ uint32_t elementCount; /** * The clipping rectangle (x1, y1, x2, y2). */ carb::Float4 clipRect; /** * User provided texture ID. */ TextureId textureId; /** * If != NULL, call the function instead of rendering the vertices. */ DrawCallback userCallback; /** * The draw callback code can access this. */ void* userCallbackData; }; /** * Defines a vertex used for drawing lists. */ struct DrawVertex { Float2 position; //!< Position Float2 texCoord; //!< Texture Coordinate uint32_t color; //!< Color }; /** * Defines a list of draw commands. */ struct DrawList { uint32_t commandBufferCount; //!< The number of command in the command buffers. DrawCommand* commandBuffers; //!< Draw commands. (Typically 1 command = 1 GPU draw call) uint32_t indexBufferSize; //!< The number of index buffers. uint32_t* indexBuffer; //!< The index buffers. (Each command consumes command) uint32_t vertexBufferSize; //!< The number of vertex buffers. DrawVertex* vertexBuffer; //!< The vertex buffers. }; /** * Defines the data used for drawing back-ends */ struct DrawData { uint32_t commandListCount; //!< Number of command lists DrawList* commandLists; //!< Command lists uint32_t vertexCount; //!< Count of vertexes. uint32_t indexCount; //!< Count of indexes. }; //! SimpleGui-specific definition of a wide character. typedef unsigned short Wchar; /** * Structure defining the configuration for a font. */ struct FontConfig { void* fontData; //!< TTF/OTF data int fontDataSize; //!< TTF/OTF data size bool fontDataOwnedByAtlas; //!< `true` - TTF/OTF data ownership taken by the container ImFontAtlas (will delete //!< memory itself). int fontNo; //!< 0 - Index of font within TTF/OTF file float sizePixels; //!< Size in pixels for rasterizer (more or less maps to the resulting font height). int oversampleH; //!< 3 - Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on //!< the Y axis. int oversampleV; //!< 1 - Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on //!< the Y axis. bool pixelSnapH; //!< false - Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel //!< aligned font with the default font. If enabled, you can set OversampleH/V to 1. Float2 glyphExtraSpacing; //!< 0, 0 - Extra spacing (in pixels) between glyphs. Only X axis is supported for now. Float2 glyphOffset; //!< 0, 0 - Offset all glyphs from this font input. const Wchar* glyphRanges; //!< NULL - Pointer to a user-provided list of Unicode range (2 value per range, values //!< are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE //!< FONT IS ALIVE. float glyphMinAdvanceX; //!< 0 - Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to //!< enforce mono-space font float glyphMaxAdvanceX; //!< FLT_MAX - Maximum AdvanceX for glyphs bool mergeMode; //!< false - Merge into previous ImFont, so you can combine multiple inputs font into one ImFont //!< (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font //!< of different heights. uint32_t rasterizerFlags; //!< 0x00 - Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you //!< aren't using one. float rasterizerMultiply; //!< 1.0f - Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be //!< a good workaround to make them more readable. char name[40]; //!< (internal) Name (strictly to ease debugging) Font* dstFont; //!< (internal) //! Constructor. FontConfig() { fontData = nullptr; fontDataSize = 0; fontDataOwnedByAtlas = true; fontNo = 0; sizePixels = 0.0f; oversampleH = 3; oversampleV = 1; pixelSnapH = false; glyphExtraSpacing = Float2{ 0.0f, 0.0f }; glyphOffset = Float2{ 0.0f, 0.0f }; glyphRanges = nullptr; glyphMinAdvanceX = 0.0f; glyphMaxAdvanceX = CARB_FLOAT_MAX; mergeMode = false; rasterizerFlags = 0x00; rasterizerMultiply = 1.0f; memset(name, 0, sizeof(name)); dstFont = nullptr; } }; /** * Structure of a custom rectangle for a font definition. */ struct FontCustomRect { uint32_t id; //!< [input] User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom //!< texture data. uint16_t width; //!< [input] Desired rectangle dimension uint16_t height; //!< [input] Desired rectangle dimension uint16_t x; //!< [output] Packed position in Atlas uint16_t y; //!< [output] Packed position in Atlas float glyphAdvanceX; //!< [input] For custom font glyphs only (ID<0x10000): glyph xadvance carb::Float2 glyphOffset; //!< [input] For custom font glyphs only (ID<0x10000): glyph display offset Font* font; //!< [input] For custom font glyphs only (ID<0x10000): target font //! Constructor. FontCustomRect() { id = 0xFFFFFFFF; width = height = 0; x = y = 0xFFFF; glyphAdvanceX = 0.0f; glyphOffset = { 0.0f, 0.0f }; font = nullptr; } //! Checks if the font custom rect is packed or not. //! @returns `true` if the font is packed; `false` otherwise. bool isPacked() const { return x != 0xFFFF; } }; /** * Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the * corresponding callback is triggered. */ struct TextEditCallbackData { InputTextFlags eventFlag; //!< One of ImGuiInputTextFlags_Callback* - Read-only InputTextFlags flags; //!< What user passed to InputText() - Read-only void* userData; //!< What user passed to InputText() - Read-only uint16_t eventChar; //!< Character input - Read-write (replace character or set to zero) int eventKey; //!< Key pressed (Up/Down/TAB) - Read-only char* buf; //!< Current text buffer - Read-write (pointed data only, can't replace the actual pointer) int bufTextLen; //!< Current text length in bytes - Read-write int bufSize; //!< Maximum text length in bytes - Read-only bool bufDirty; //!< Set if you modify Buf/BufTextLen - Write int cursorPos; //!< Read-write int selectionStart; //!< Read-write (== to SelectionEnd when no selection) int selectionEnd; //!< Read-write }; //! Definition of callback from InputText(). typedef int (*TextEditCallback)(TextEditCallbackData* data); /** * Data payload for Drag and Drop operations: acceptDragDropPayload(), getDragDropPayload() */ struct Payload { // Members void* data; //!< Data (copied and owned by simplegui) int dataSize; //!< Data size // [Internal] uint32_t sourceId; //!< Source item id uint32_t sourceParentId; //!< Source parent id (if available) int dataFrameCount; //!< Data timestamp char dataType[32 + 1]; //!< Data type tag (short user-supplied string, 32 characters max) bool preview; //!< Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: //!< handle overlapping drag targets) bool delivery; //!< Set when AcceptDragDropPayload() was called and mouse button is released over the target item. //! Constructor. Payload() { clear(); } //! Resets the state to cleared. void clear() { sourceId = sourceParentId = 0; data = nullptr; dataSize = 0; memset(dataType, 0, sizeof(dataType)); dataFrameCount = -1; preview = delivery = false; } //! Checks if the Payload matches the given type. //! @param type The type that should be checked against the `dataType` member. //! @returns `true` if the type matches `dataType`; `false` otherwise. bool isDataType(const char* type) const { return dataFrameCount != -1 && strcmp(type, dataType) == 0; } //! Returns the state of the `preview` member. //! @returns The state of the `preview` member. bool isPreview() const { return preview; } //! Returns the state of the `delivery` member. //! @returns The state of the `delivery` member. bool isDelivery() const { return delivery; } }; /** * Flags stored in ImGuiViewport::Flags, giving indications to the platform back-ends */ typedef uint32_t ViewportFlags; const ViewportFlags kViewportFlagNone = 0; //!< Absence of other viewport flags. const ViewportFlags kViewportFlagNoDecoration = 1 << 0; //!< Platform Window: Disable platform decorations: title bar; //!< borders; etc. const ViewportFlags kViewportFlagNoTaskBarIcon = 1 << 1; //!< Platform Window: Disable platform task bar icon (for //!< popups; menus; or all windows if //!< ImGuiConfigFlags_ViewportsNoTaskBarIcons if set) const ViewportFlags kViewportFlagNoFocusOnAppearing = 1 << 2; //!< Platform Window: Don't take focus when created. const ViewportFlags kViewportFlagNoFocusOnClick = 1 << 3; //!< Platform Window: Don't take focus when clicked on. const ViewportFlags kViewportFlagNoInputs = 1 << 4; //!< Platform Window: Make mouse pass through so we can drag this //!< window while peaking behind it. const ViewportFlags kViewportFlagNoRendererClear = 1 << 5; //!< Platform Window: Renderer doesn't need to clear the //!< framebuffer ahead. const ViewportFlags kViewportFlagTopMost = 1 << 6; //!< Platform Window: Display on top (for tooltips only) /** * The viewports created and managed by simplegui. The role of the platform back-end is to create the platform/OS * windows corresponding to each viewport. */ struct Viewport { uint32_t id; //!< Unique identifier. ViewportFlags flags; //!< Flags describing this viewport. Float2 pos; //!< Position of viewport both in simplegui space and in OS desktop/native space Float2 size; //!< Size of viewport in pixel Float2 workOffsetMin; //!< Work Area: Offset from Pos to top-left corner of Work Area. Generally (0,0) or //!< (0,+main_menu_bar_height). Work Area is Full Area but without menu-bars/status-bars (so //!< WorkArea always fit inside Pos/Size!) Float2 workOffsetMax; //!< Work Area: Offset from Pos+Size to bottom-right corner of Work Area. Generally (0,0) or //!< (0,-status_bar_height). float dpiScale; //!< 1.0f = 96 DPI = No extra scale DrawData* drawData; //!< The ImDrawData corresponding to this viewport. Valid after Render() and until the next call //!< to NewFrame(). uint32_t parentViewportId; //!< (Advanced) 0: no parent. Instruct the platform back-end to setup a parent/child //!< relationship between platform windows. void* rendererUserData; //!< void* to hold custom data structure for the renderer (e.g. swap chain, frame-buffers //!< etc.) void* platformUserData; //!< void* to hold custom data structure for the platform (e.g. windowing info, render //!< context) void* platformHandle; //!< void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle //!< such as HWND, GlfwWindow*, SDL_Window*) void* platformHandleRaw; //!< void* to hold lower-level, platform-native window handle (e.g. the HWND) when using an //!< abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*) bool platformRequestMove; //!< Platform window requested move (e.g. window was moved by the OS / host window //!< manager, authoritative position will be OS window position) bool platformRequestResize; //!< Platform window requested resize (e.g. window was resized by the OS / host window //!< manager, authoritative size will be OS window size) bool platformRequestClose; //!< Platform windows requested closure (e.g. window was moved by the OS / host window //!< manager, e.g. pressing ALT-F4) //! Constructor. Viewport() { id = 0; flags = 0; dpiScale = 0.0f; drawData = NULL; parentViewportId = 0; rendererUserData = platformUserData = platformHandle = platformHandleRaw = nullptr; platformRequestMove = platformRequestResize = platformRequestClose = false; } //! Destructor. ~Viewport() { CARB_ASSERT(platformUserData == nullptr && rendererUserData == nullptr); } }; //! [BETA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. //! Provide hints to the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, //! etc.) and OS level parent/child relationships. struct WindowClass { uint32_t classId; //!< User data. 0 = Default class (unclassed) uint32_t parentViewportId; //!< Hint for the platform back-end. If non-zero, the platform back-end can create a //!< parent<>child relationship between the platform windows. Not conforming back-ends //!< are free to e.g. parent every viewport to the main viewport or not. ViewportFlags viewportFlagsOverrideSet; //!< Viewport flags to set when a window of this class owns a viewport. This //!< allows you to enforce OS decoration or task bar icon, override the //!< defaults on a per-window basis. ViewportFlags viewportFlagsOverrideClear; //!< Viewport flags to clear when a window of this class owns a viewport. //!< This allows you to enforce OS decoration or task bar icon, override //!< the defaults on a per-window basis. DockNodeFlags dockNodeFlagsOverrideSet; //!< [EXPERIMENTAL] Dock node flags to set when a window of this class is //!< hosted by a dock node (it doesn't have to be selected!) DockNodeFlags dockNodeFlagsOverrideClear; //!< [EXPERIMENTAL] bool dockingAlwaysTabBar; //!< Set to true to enforce single floating windows of this class always having their own //!< docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) bool dockingAllowUnclassed; //!< Set to true to allow windows of this class to be docked/merged with an unclassed //!< window. // FIXME-DOCK: Move to DockNodeFlags override? //! Constructor. WindowClass() { classId = 0; parentViewportId = 0; viewportFlagsOverrideSet = viewportFlagsOverrideClear = 0x00; dockNodeFlagsOverrideSet = dockNodeFlagsOverrideClear = 0x00; dockingAlwaysTabBar = false; dockingAllowUnclassed = true; } }; /** * Helper: Manually clip large list of items. * If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse * clipping based on visibility to save yourself from processing those items at all. The clipper calculates the range of * visible items and advance the cursor to compensate for the non-visible items we have skipped. */ struct ListClipper { float startPosY; //!< Start Y coordinate position; float itemsHeight; //!< Height of items. int32_t itemsCount; //!< Number of items. int32_t stepNo; //!< Stepping int32_t displayStart; //!< Display start index. int32_t displayEnd; //!< Display end index. }; } // namespace simplegui } // namespace carb
omniverse-code/kit/include/carb/simplegui/SimpleGuiBindingsPython.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "../BindingsPythonUtils.h" #include "../BindingsPythonTypes.h" #include "ISimpleGui.h" #include <algorithm> #include <string> #include <vector> namespace carb { namespace simplegui { inline void definePythonModule(py::module& m) { using namespace carb; using namespace carb::simplegui; m.doc() = "pybind11 carb.simplegui bindings"; py::enum_<Condition>(m, "Condition") .value("ALWAYS", Condition::eAlways) .value("APPEARING", Condition::eAppearing) .value("FIRST_USE_EVER", Condition::eFirstUseEver) .value("ONCE", Condition::eOnce); defineInterfaceClass<ISimpleGui>(m, "ISimpleGui", "acquire_simplegui") //.def("create_context", wrapInterfaceFunction(&ISimpleGui::createContext)) //.def("destroy_context", wrapInterfaceFunction(&ISimpleGui::destroyContext)) //.def("set_current_context", wrapInterfaceFunction(&ISimpleGui::setCurrentContext)) //.def("new_frame", wrapInterfaceFunction(&ISimpleGui::newFrame)) //.def("render", wrapInterfaceFunction(&ISimpleGui::render)) .def("set_display_size", wrapInterfaceFunction(&ISimpleGui::setDisplaySize)) .def("get_display_size", wrapInterfaceFunction(&ISimpleGui::getDisplaySize)) .def("show_demo_window", wrapInterfaceFunction(&ISimpleGui::showDemoWindow)) .def("set_next_window_pos", wrapInterfaceFunction(&ISimpleGui::setNextWindowPos)) .def("set_next_window_size", wrapInterfaceFunction(&ISimpleGui::setNextWindowSize)) .def("begin", [](const ISimpleGui* iface, const char* label, bool opened, carb::simplegui::WindowFlags flags) { bool visible = iface->begin(label, &opened, flags); return py::make_tuple(visible, opened); }) .def("end", wrapInterfaceFunction(&ISimpleGui::end)) .def("collapsing_header", wrapInterfaceFunction(&ISimpleGui::collapsingHeader)) .def("text", [](const ISimpleGui* iface, const char* text) { iface->text(text); }) .def("text_unformatted", wrapInterfaceFunction(&ISimpleGui::textUnformatted)) .def("text_wrapped", [](const ISimpleGui* iface, const char* text) { iface->textWrapped(text); }) .def("button", &ISimpleGui::button) .def("small_button", wrapInterfaceFunction(&ISimpleGui::smallButton)) .def("same_line", &ISimpleGui::sameLine) .def("same_line_ex", wrapInterfaceFunction(&ISimpleGui::sameLineEx), py::arg("pos_x") = 0.0f, py::arg("spacing_w") = -1.0f) .def("separator", wrapInterfaceFunction(&ISimpleGui::separator)) .def("spacing", wrapInterfaceFunction(&ISimpleGui::spacing)) .def("indent", wrapInterfaceFunction(&ISimpleGui::indent)) .def("unindent", wrapInterfaceFunction(&ISimpleGui::unindent)) .def("dummy", wrapInterfaceFunction(&ISimpleGui::dummy)) .def("bullet", wrapInterfaceFunction(&ISimpleGui::bullet)) .def("checkbox", [](const ISimpleGui* iface, const char* label, bool value) { bool clicked = iface->checkbox(label, &value); return py::make_tuple(clicked, value); }) .def("input_float", [](const ISimpleGui* iface, const char* label, float value, float step) { bool clicked = iface->inputFloat(label, &value, step, 0.0f, -1, 0); return py::make_tuple(clicked, value); }) .def("input_int", [](const ISimpleGui* iface, const char* label, int value, int step) { bool clicked = iface->inputInt(label, &value, step, 0, 0); return py::make_tuple(clicked, value); }) .def("input_text", [](const ISimpleGui* iface, const char* label, const std::string& str, size_t size) { std::vector<char> buf(str.begin(), str.end()); buf.resize(size); bool clicked = iface->inputText(label, buf.data(), size, 0, nullptr, nullptr); return py::make_tuple(clicked, buf.data()); }) .def("slider_float", [](const ISimpleGui* iface, const char* label, float value, float vMin, float vMax) { bool clicked = iface->sliderFloat(label, &value, vMin, vMax, "%.3f", 1.0f); return py::make_tuple(clicked, value); }) .def("slider_int", [](const ISimpleGui* iface, const char* label, int value, int vMin, int vMax) { bool clicked = iface->sliderInt(label, &value, vMin, vMax, "%.0f"); return py::make_tuple(clicked, value); }) .def("combo", [](const ISimpleGui* iface, const char* label, int selectedItem, std::vector<std::string> items) { std::vector<const char*> itemPtrs(items.size()); std::transform( items.begin(), items.end(), itemPtrs.begin(), [](const std::string& s) { return s.c_str(); }); bool clicked = iface->combo(label, &selectedItem, itemPtrs.data(), (int)itemPtrs.size()); return py::make_tuple(clicked, selectedItem); }) .def("progress_bar", wrapInterfaceFunction(&ISimpleGui::progressBar)) .def("color_edit3", [](const ISimpleGui* iface, const char* label, Float3 color) { bool clicked = iface->colorEdit3(label, &color.x, 0); return py::make_tuple(clicked, color); }) .def("color_edit4", [](const ISimpleGui* iface, const char* label, Float4 color) { bool clicked = iface->colorEdit4(label, &color.x, 0); return py::make_tuple(clicked, color); }) .def("push_id_string", wrapInterfaceFunction(&ISimpleGui::pushIdString)) .def("push_id_int", wrapInterfaceFunction(&ISimpleGui::pushIdInt)) .def("pop_id", wrapInterfaceFunction(&ISimpleGui::popId)) .def("push_item_width", wrapInterfaceFunction(&ISimpleGui::pushItemWidth)) .def("pop_item_width", wrapInterfaceFunction(&ISimpleGui::popItemWidth)) .def("tree_node_ptr", [](const ISimpleGui* iface, int64_t id, const char* text) { return iface->treeNodePtr((void*)id, text); }) .def("tree_pop", wrapInterfaceFunction(&ISimpleGui::treePop)) .def("begin_child", wrapInterfaceFunction(&ISimpleGui::beginChild)) .def("end_child", wrapInterfaceFunction(&ISimpleGui::endChild)) .def("set_scroll_here_y", wrapInterfaceFunction(&ISimpleGui::setScrollHereY)) .def("open_popup", wrapInterfaceFunction(&ISimpleGui::openPopup)) .def("begin_popup_modal", wrapInterfaceFunction(&ISimpleGui::beginPopupModal)) .def("end_popup", wrapInterfaceFunction(&ISimpleGui::endPopup)) .def("close_current_popup", wrapInterfaceFunction(&ISimpleGui::closeCurrentPopup)) .def("push_style_color", wrapInterfaceFunction(&ISimpleGui::pushStyleColor)) .def("pop_style_color", wrapInterfaceFunction(&ISimpleGui::popStyleColor)) .def("push_style_var_float", wrapInterfaceFunction(&ISimpleGui::pushStyleVarFloat)) .def("push_style_var_float2", wrapInterfaceFunction(&ISimpleGui::pushStyleVarFloat2)) .def("pop_style_var", wrapInterfaceFunction(&ISimpleGui::popStyleVar)) .def("menu_item_ex", [](const ISimpleGui* iface, const char* label, const char* shortcut, bool selected, bool enabled) { bool activated = iface->menuItemEx(label, shortcut, &selected, enabled); return py::make_tuple(activated, selected); }) .def("dock_builder_dock_window", wrapInterfaceFunction(&ISimpleGui::dockBuilderDockWindow)) .def("plot_lines", [](const ISimpleGui* self, const char* label, const std::vector<float>& values, int valuesCount, int valuesOffset, const char* overlayText, float scaleMin, float scaleMax, Float2 graphSize, int stride) { self->plotLines( label, values.data(), valuesCount, valuesOffset, overlayText, scaleMin, scaleMax, graphSize, stride); }); m.attr("WINDOW_FLAG_NO_TITLE_BAR") = py::int_(kWindowFlagNoTitleBar); m.attr("WINDOW_FLAG_NO_RESIZE") = py::int_(kWindowFlagNoResize); m.attr("WINDOW_FLAG_NO_MOVE") = py::int_(kWindowFlagNoMove); m.attr("WINDOW_FLAG_NO_SCROLLBAR") = py::int_(kWindowFlagNoScrollbar); m.attr("WINDOW_FLAG_NO_SCROLL_WITH_MOUSE") = py::int_(kWindowFlagNoScrollWithMouse); m.attr("WINDOW_FLAG_NO_COLLAPSE") = py::int_(kWindowFlagNoCollapse); m.attr("WINDOW_FLAG_ALWAYS_AUTO_RESIZE") = py::int_(kWindowFlagAlwaysAutoResize); m.attr("WINDOW_FLAG_NO_BACKGROUND") = py::int_(kWindowFlagNoBackground); m.attr("WINDOW_FLAG_NO_SAVED_SETTINGS") = py::int_(kWindowFlagNoSavedSettings); m.attr("WINDOW_FLAG_NO_MOUSE_INPUTS") = py::int_(kWindowFlagNoMouseInputs); m.attr("WINDOW_FLAG_MENU_BAR") = py::int_(kWindowFlagMenuBar); m.attr("WINDOW_FLAG_HORIZONTAL_SCROLLBAR") = py::int_(kWindowFlagHorizontalScrollbar); m.attr("WINDOW_FLAG_NO_FOCUS_ON_APPEARING") = py::int_(kWindowFlagNoFocusOnAppearing); m.attr("WINDOW_FLAG_NO_BRING_TO_FRONT_ON_FOCUS") = py::int_(kWindowFlagNoBringToFrontOnFocus); m.attr("WINDOW_FLAG_ALWAYS_VERTICAL_SCROLLBAR") = py::int_(kWindowFlagAlwaysVerticalScrollbar); m.attr("WINDOW_FLAG_ALWAYS_HORIZONTAL_SCROLLBAR") = py::int_(kWindowFlagAlwaysHorizontalScrollbar); m.attr("WINDOW_FLAG_ALWAYS_USE_WINDOW_PADDING") = py::int_(kWindowFlagAlwaysUseWindowPadding); m.attr("WINDOW_FLAG_NO_NAV_INPUTS") = py::int_(kWindowFlagNoNavFocus); m.attr("WINDOW_FLAG_NO_NAV_FOCUS") = py::int_(kWindowFlagNoNavInputs); m.attr("WINDOW_FLAG_UNSAVED_DOCUMENT") = py::int_(kWindowFlagUnsavedDocument); m.attr("WINDOW_FLAG_NO_DOCKING") = py::int_(kWindowFlagNoDocking); } } // namespace simplegui } // namespace carb
omniverse-code/kit/include/carb/scripting/IScripting.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "../Interface.h" namespace carb { namespace scripting { /** * Defines a scripting return code. */ enum class ExecutionErrorCode { eOk, eError }; using OutputFlags = uint32_t; const OutputFlags kOutputFlagCaptureStdout = 1; const OutputFlags kOutputFlagCaptureStderr = (1 << 1); struct ExecutionError { ExecutionErrorCode code; const char* message; }; /** * Scripting plugin description */ struct ScriptingDesc { const char* languageName; const char* const* fileExtensions; ///! File extensions list, each prefixed with period. E.g. ".py" size_t fileExtensionCount; }; /** * Context of execution. * * Context keeps all shared data between executions. For example global state (variables, functions etc.) in python. */ struct Context; /** * Script is an execution unit. * * By making a Script from a code you give an opportunity to plugin to preload and compile the code once. */ struct Script; /** * Opaque container to pass and retrieve data with Scripting interface. */ struct Object; /** * Defines a generic scripting interface. * * Specific implementations such as Python realize this simple interface * and allow access to the Carbonite framework through run-time scripts and not * just compiled code. */ struct IScripting { CARB_PLUGIN_INTERFACE("carb::scripting::IScripting", 1, 0) /** * Add raw module search path, this path will be added to the list unmodified, potentially requiring * language-specific search patterns. */ void(CARB_ABI* addSearchPath)(const char* path); /** * Remove raw module search path. */ void(CARB_ABI* removeSearchPath)(const char* path); /** * Create an execution context. * * Context: * 1. Keeps execution result: errors, stdout, stderr. * 2. Stores globals between execution calls. */ Context*(CARB_ABI* createContext)(); /** * Destroy an execution context. */ void(CARB_ABI* destroyContext)(Context* context); /** * Get a global execution context. * This context uses interpreter global state for globals. */ Context*(CARB_ABI* getGlobalContext)(); /** * Execute code from a file on a Context. * * @return false iff execution produced an error. Use getLastExecutionError(context) to get more details. */ bool(CARB_ABI* executeFile)(Context* context, const char* path, OutputFlags outputCaptureFlags); /** * Execute a string of code on a Context. * * @param sourceFile Set as __file__ in python. Can be nullptr, will default to executable name then. * * @return false iff execution produced an error. Use getLastExecutionError(context) to get more details. */ bool(CARB_ABI* executeString)(Context* context, const char* str, OutputFlags outputCaptureFlags, const char* sourceFile); /** * Execute a Script on a Context. * * @return false iff execution produced an error. Use getLastExecutionError(context) to get more details. */ bool(CARB_ABI* executeScript)(Context* context, Script* script, OutputFlags outputCaptureFlags); /** * Execute a Script with arguments on a Context. * * @return false iff execution produced an error. Use getLastExecutionError(context) to get more details. */ bool(CARB_ABI* executeScriptWithArgs)( Context* context, Script* script, const char* const* argv, size_t argc, OutputFlags outputCaptureFlags); /** * Check if context has a function. */ bool(CARB_ABI* hasFunction)(Context* context, const char* functionName); /** * Execute a function on a Context. * * @param returnObject Pass an object to store returned data, if any. Can be nullptr. * @return false iff execution produced an error. Use getLastExecutionError(context) to get more details. */ bool(CARB_ABI* executeFunction)(Context* context, const char* functionName, Object* returnObject, OutputFlags outputCaptureFlags); /** * Check if object has a method */ bool(CARB_ABI* hasMethod)(Context* context, Object* self, const char* methodName); /** * Execute Object method on a Context. * * @param returnObject Pass an object to store returned data, if any. Can be nullptr. * @return false iff execution produced an error. Use getLastExecutionError(context) to get more details. */ bool(CARB_ABI* executeMethod)( Context* context, Object* self, const char* methodName, Object* returnObject, OutputFlags outputCaptureFlags); /** * Get last stdout, if stdout from the execute within the given context. */ const char*(CARB_ABI* getLastStdout)(Context* context); /** * Get last stderr, if stdout from the execute within the given context. */ const char*(CARB_ABI* getLastStderr)(Context* context); /** * Get last execution error from last execute within the given context call if any. */ const ExecutionError&(CARB_ABI* getLastExecutionError)(Context* context); /** * Create a script instance from an explicit string. * * @param str The full script as a string. * @return The script. */ Script*(CARB_ABI* createScriptFromString)(const char* str); /** * Create a script instance from a file path. * * @param path The file path such as "assets/scripts/hello.py" * @return The script. */ Script*(CARB_ABI* createScriptFromFile)(const char* path); /** * Destroys the script and releases all resources from a previously created script. * * @param script The previously created script. */ void(CARB_ABI* destroyScript)(Script* script); /** * Create an object to hold scripting data. */ Object*(CARB_ABI* createObject)(); /** * Destroy an object. */ void(CARB_ABI* destroyObject)(Object* object); /** * Is object empty? */ bool(CARB_ABI* isObjectNone)(Object* object); /** * Get a object data as string. * * Returned string is internally buffered and valid until next call. * If an object is not of a string type, nullptr is returned. */ const char*(CARB_ABI* getObjectAsString)(Object* object); /** * Get a object data as integer. * * If an object is not of an int type, 0 is returned. */ int(CARB_ABI* getObjectAsInt)(Object* object); /** * Gets the Scripting plugin desc. * * @return The desc. */ const ScriptingDesc&(CARB_ABI* getDesc)(); /** * Collects all plugin folders (by asking the Framework), appends language specific subfolder and adds them to * search path. */ void(CARB_ABI* addPluginBindingFoldersToSearchPath)(); /** * Temp helper to scope control GIL */ void(CARB_ABI* releaseGIL)(); void(CARB_ABI* acquireGIL)(); }; } // namespace scripting } // namespace carb
omniverse-code/kit/include/carb/messaging/MessagingTypes.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 <cstdint> namespace carb { namespace messaging { struct Channel; /** * Defines type on message. */ enum class Type { eError, eMessage, eHello, eJoin, eLeft, eDeleted, }; /** * Response results for messaging. */ enum class Status { eOk, eErrorUnknown }; /** * Callback return type. */ enum class CallbackReturnType : uint64_t { eContinue = 0, ///! Continue callback subscription. eStop = 1 ///! Stop callback subscription. }; /** * Description of Listen channel parameters. */ struct ListenChannelDesc { void* connection; ///! Native connection handle for message channel. const char* path; ///! Path of message channel to listen to. }; /** * Defines a message body. */ struct MessageResult { carb::messaging::Status status; ///! Status of the message const char* statusDescription; ///! Status in a more descriptive string. Channel* channel; ///! Channel where the message is received from. const char* from; ///! The sender id of this message. const uint8_t* ptr; ///! Payload of the message. uint64_t size; ///! Size of the payload. Type type; ///! Type of message. }; /** * Description of message to be sent. */ struct SendMessageDesc { Channel* channel; ///! Channel to send this message to. const char* to; ///! Recipient of the message. use nullptr to broadcast. const uint8_t* ptr; ///! Payload of the message. A copy will be made internally. uint64_t size; ///! Size of the message. bool waitForAnswer; ///! Whether to wait for answer or not. }; /** * Callback function when a message is sent or received. * * @param result The message body. * @param userPtr The custom user data to be passed into callback function. * @return if to continue or stop callback subscription. */ typedef CallbackReturnType (*OnMessageFn)(const MessageResult* result, void* userPtr); } }
omniverse-code/kit/include/carb/messaging/IMessaging.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 "MessagingTypes.h" #include <carb/Interface.h> namespace carb { namespace messaging { /** * Defines a messaging interface. */ struct IMessaging { CARB_PLUGIN_INTERFACE("carb::messaging::IMessaging", 0, 3) /** * Listens to a channel and keep receiving message from it until @ref stopChannel is called. * This also creates the channel, if it doesn't already exist. * * @param desc The description of listen settings. * @param onMessage Callback function to be called when a message is received. * @param userData Custom user data to be passed back in callback function. * @return the channel joined. */ Channel*(CARB_ABI* joinChannel)(const ListenChannelDesc* desc, OnMessageFn onMessage, void* userData); /** * Stops listening to a channel. * * @param channel The Channel to stop listening to. * @param connectionLost Whether the stop request is due to a connection lose. */ void(CARB_ABI* leaveChannel)(const Channel* channel, bool connectionLost); /** * Sends a message. * * @param desc The description of the message. * @param onMessage Callback function to be called when a message is sent. * @param userData Custom user data to be passed back in callback function. */ void(CARB_ABI* sendMessage)(const SendMessageDesc* desc, OnMessageFn onMessage, void* userData); }; } }
omniverse-code/kit/include/usdrt/gf/vec.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once //! @file //! //! @brief TODO #include <carb/Defines.h> #include <usdrt/gf/half.h> #include <usdrt/gf/math.h> #include <cmath> #include <initializer_list> #include <stdint.h> #include <type_traits> #ifndef __CUDACC__ # define CUDA_SAFE_ASSERT(cond, ...) CARB_ASSERT(cond, ##__VA_ARGS__) # define CUDA_CALLABLE #else # define CUDA_SAFE_ASSERT(cond, ...) # define CUDA_CALLABLE __device__ __host__ #endif namespace omni { namespace math { namespace linalg { // Forward declaration, just for the using statements, below. class half; template <typename T, size_t N> class base_vec { public: // Some standard types, similar to std::array and std::vector. using value_type = T; using size_type = size_t; using difference_type = ptrdiff_t; using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; using const_pointer = const value_type*; using iterator = pointer; using const_iterator = const_pointer; // static constexpr variable to be able to refer to the tuple size from the type, // from outside this class definition. static constexpr size_t tuple_size = N; using ScalarType = T; static const size_t dimension = N; base_vec() = default; constexpr base_vec(const base_vec<T, N>&) = default; constexpr explicit CUDA_CALLABLE base_vec(T value) : v{} { for (size_t i = 0; i < N; ++i) { v[i] = value; } } // NOTE: The static_cast is to avoid issues with other not being accepted as being the // base class type, presumably because of the base class type conversion constructor // being marked as explicit. template <typename OTHER_T> constexpr explicit CUDA_CALLABLE base_vec(const base_vec<OTHER_T, N>& other) : v{} { for (size_t i = 0; i < N; ++i) { v[i] = T(other[i]); } } template <typename OTHER_T0, typename OTHER_T1, typename... Args> constexpr CUDA_CALLABLE base_vec(OTHER_T0 a, OTHER_T1 b, Args... args) noexcept : v{} { v[0] = a; initHelper<1>(b, args...); } template <typename OTHER_T> CUDA_CALLABLE base_vec(const std::initializer_list<OTHER_T>& other) noexcept : v{} { CUDA_SAFE_ASSERT(other.size() == N); for (size_t i = 0; i < N && i < other.size(); ++i) { // NOTE: This intentionally doesn't have an explicit cast, so that // the compiler will warn on invalid implicit casts, since this // constructor isn't marked explicit. v[i] = other.begin()[i]; } } // Access a single component of this base_vec. constexpr CUDA_CALLABLE T& operator[](size_t i) noexcept { // Ensure that this type is a POD type if T is a POD type. // This check is unrelated to this operator, but the static_assert // must be inside some function that is likely to be called. static_assert(std::is_pod<base_vec<T, N>>::value == std::is_pod<T>::value, "base_vec<T,N> should be a POD type iff T is a POD type."); CUDA_SAFE_ASSERT(i < N); return v[i]; } constexpr CUDA_CALLABLE const T& operator[](size_t i) const noexcept { CUDA_SAFE_ASSERT(i < N); return v[i]; } // Get a pointer to the data of this tuple. constexpr CUDA_CALLABLE T* data() noexcept { return v; } constexpr CUDA_CALLABLE const T* data() const noexcept { return v; } static CUDA_CALLABLE base_vec<T, N> Axis(size_t axis) { base_vec<T, N> v(T(0)); if (axis < dimension) { v[axis] = T(1); } return v; } const CUDA_CALLABLE T* GetArray() const { return data(); } constexpr CUDA_CALLABLE T Dot(const base_vec<T, N>& other) const { T d = v[0] * other[0]; for (size_t i = 1; i < N; ++i) { d += v[i] * other[i]; } return d; } constexpr CUDA_CALLABLE T GetLengthSq() const { return this->Dot(*this); } CUDA_CALLABLE auto GetLength() const { return std::sqrt(GetLengthSq()); } CUDA_CALLABLE auto Normalize() { const T length2 = GetLengthSq(); decltype(std::sqrt(length2)) length; decltype(length) scale; if (length2 != T(0)) { length = std::sqrt(length2); scale = T(1) / length; } else { // If close enough to zero that the length squared is zero, // make it exactly zero, for consistency. length = 0; scale = 0; } (*this) *= scale; return length; } #ifndef DOXYGEN_BUILD CUDA_CALLABLE base_vec<T, N> GetNormalized() const { base_vec<T, N> copy(*this); copy.Normalize(); return copy; } #endif // DOXYGEN_BUILD // NOTE: This is the dot product, NOT the component-wise product! constexpr CUDA_CALLABLE T operator*(const base_vec<T, N>& other) const { return Dot(other); } constexpr CUDA_CALLABLE base_vec<T, N>& operator+=(const base_vec<T, N>& that) noexcept { for (size_t i = 0; i < N; ++i) { v[i] += that[i]; } return *this; } constexpr CUDA_CALLABLE base_vec<T, N>& operator-=(const base_vec<T, N>& that) noexcept { for (size_t i = 0; i < N; ++i) { v[i] -= that[i]; } return *this; } constexpr CUDA_CALLABLE base_vec<T, N>& operator*=(const T that) noexcept { for (size_t i = 0; i < N; ++i) { v[i] *= that; } return *this; } constexpr CUDA_CALLABLE base_vec<T, N>& operator/=(const T that) noexcept { for (size_t i = 0; i < N; ++i) { v[i] /= that; } return *this; } #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE base_vec<T, N> operator*(const T& multiplier, base_vec<T, N> rhs) { rhs *= multiplier; return rhs; } friend CUDA_CALLABLE base_vec<T, N> operator*(base_vec<T, N> lhs, const T& multiplier) { lhs *= multiplier; return lhs; } friend CUDA_CALLABLE base_vec<T, N> operator/(base_vec<T, N> lhs, const T& divisor) { lhs /= divisor; return lhs; } friend CUDA_CALLABLE base_vec<T, N> operator+(base_vec<T, N> lhs, const base_vec<T, N>& rhs) { lhs += rhs; return lhs; } friend CUDA_CALLABLE base_vec<T, N> operator-(base_vec<T, N> lhs, const base_vec<T, N>& rhs) { lhs -= rhs; return lhs; } #endif protected: T v[N]; private: template <size_t i, typename OTHER_T> constexpr CUDA_CALLABLE void initHelper(OTHER_T a) { static_assert(i == N - 1, "Variadic constructor of base_vec<T, N> requires N arguments"); v[i] = T(a); } template <size_t i, typename OTHER_T, typename... Args> constexpr CUDA_CALLABLE void initHelper(OTHER_T a, Args... args) { v[i] = T(a); initHelper<i + 1>(args...); } }; template <typename T, size_t N> CUDA_CALLABLE T GfDot(const base_vec<T, N>& a, const base_vec<T, N>& b) { return a.Dot(b); } template <typename T, size_t N> CUDA_CALLABLE auto GfGetLength(const base_vec<T, N>& v) { return v.GetLength(); } template <typename T, size_t N> CUDA_CALLABLE auto GfNormalize(base_vec<T, N>* p) { return p->Normalize(); } template <typename T, size_t N> CUDA_CALLABLE bool GfIsClose(const base_vec<T, N>& a, const base_vec<T, N>& b, double tolerance) { auto distanceSq = (a - b).GetLengthSq(); return distanceSq <= tolerance * tolerance; } #ifndef DOXYGEN_BUILD template <> inline auto base_vec<half, 2>::GetLength() const { return std::sqrt((float)GetLengthSq()); } template <> inline auto base_vec<half, 2>::Normalize() { const float length2 = (float)GetLengthSq(); float length; float scale; if (length2 != 0.0) { length = std::sqrt(length2); scale = 1.0f / length; } else { // If close enough to zero that the length squared is zero, // make it exactly zero, for consistency. length = 0; scale = 0; } (*this) *= scale; return length; } template <> inline auto base_vec<half, 3>::GetLength() const { return std::sqrt((float)GetLengthSq()); } template <> inline auto base_vec<half, 3>::Normalize() { const float length2 = (float)GetLengthSq(); float length; float scale; if (length2 != 0.0) { length = std::sqrt(length2); scale = 1.0f / length; } else { // If close enough to zero that the length squared is zero, // make it exactly zero, for consistency. length = 0; scale = 0; } (*this) *= scale; return length; } template <> inline auto base_vec<half, 4>::GetLength() const { return std::sqrt((float)GetLengthSq()); } template <> inline auto base_vec<half, 4>::Normalize() { const float length2 = (float)GetLengthSq(); float length; float scale; if (length2 != 0.0) { length = std::sqrt(length2); scale = 1.0f / length; } else { // If close enough to zero that the length squared is zero, // make it exactly zero, for consistency. length = 0; scale = 0; } (*this) *= scale; return length; } #endif // DOXYGEN_BUILD template <typename T> class vec2 : public base_vec<T, 2> { public: using base_type = base_vec<T, 2>; using this_type = vec2<T>; using base_type::operator[]; using base_type::data; using base_type::operator+=; using base_type::operator-=; using base_type::operator*=; using base_type::operator/=; using base_type::GetArray; using base_type::GetLength; using base_type::GetLengthSq; using base_type::Normalize; using ScalarType = T; using base_type::dimension; vec2() = default; constexpr vec2(const vec2<T>&) = default; // Implicit conversion from base class, to avoid issues on that front. constexpr CUDA_CALLABLE vec2(const base_type& other) : base_type(other) { } constexpr explicit CUDA_CALLABLE vec2(T value) : base_type(value, value) { } constexpr CUDA_CALLABLE vec2(T v0, T v1) : base_type(v0, v1) { } template <typename OTHER_T> constexpr explicit CUDA_CALLABLE vec2(const OTHER_T* p) : base_type(p[0], p[1]) { } template <typename OTHER_T> explicit CUDA_CALLABLE vec2(const vec2<OTHER_T>& other) : base_type(other) { } template <typename OTHER_T> explicit CUDA_CALLABLE vec2(const base_vec<OTHER_T, 2>& other) : base_type(other) { } template <typename OTHER_T> CUDA_CALLABLE vec2(const std::initializer_list<OTHER_T>& other) : base_type(other) { } static constexpr CUDA_CALLABLE vec2<T> XAxis() { return vec2<T>(T(1), T(0)); } static constexpr CUDA_CALLABLE vec2<T> YAxis() { return vec2<T>(T(0), T(1)); } static CUDA_CALLABLE vec2<T> Axis(size_t axis) { return base_type::Axis(axis); } CUDA_CALLABLE this_type& Set(T v0, T v1) { v[0] = v0; v[1] = v1; return *this; } CUDA_CALLABLE this_type& Set(T* p) { return Set(p[0], p[1]); } // NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here. template <typename OTHER_T> CUDA_CALLABLE bool operator==(const vec2<OTHER_T>& other) const { return (v[0] == other[0]) && (v[1] == other[1]); } template <typename OTHER_T> CUDA_CALLABLE bool operator!=(const vec2<OTHER_T>& other) const { return !(*this == other); } // Returns the portion of this that is parallel to unitVector. // NOTE: unitVector must have length 1 for this to produce a meaningful result. CUDA_CALLABLE this_type GetProjection(const this_type& unitVector) const { return unitVector * (this->Dot(unitVector)); } // Returns the portion of this that is orthogonal to unitVector. // NOTE: unitVector must have length 1 for this to produce a meaningful result. CUDA_CALLABLE this_type GetComplement(const this_type& unitVector) const { return *this - GetProjection(unitVector); } CUDA_CALLABLE this_type GetNormalized() const { return base_type::GetNormalized(); } private: using base_type::v; }; template <typename T> CUDA_CALLABLE vec2<T> operator-(const vec2<T>& v) { return vec2<T>(-v[0], -v[1]); } template <typename T> CUDA_CALLABLE vec2<T> GfCompMult(const vec2<T>& a, const vec2<T>& b) { return vec2<T>(a[0] * b[0], a[1] * b[1]); } template <typename T> CUDA_CALLABLE vec2<T> GfCompDiv(const vec2<T>& a, const vec2<T>& b) { return vec2<T>(a[0] / b[0], a[1] / b[1]); } template <typename T> CUDA_CALLABLE vec2<T> GfGetNormalized(const vec2<T>& v) { return v.GetNormalized(); } template <typename T> CUDA_CALLABLE vec2<T> GfGetProjection(const vec2<T>& v, const vec2<T>& unitVector) { return v.GetProjection(unitVector); } template <typename T> CUDA_CALLABLE vec2<T> GfGetComplement(const vec2<T>& v, const vec2<T>& unitVector) { return v.GetComplement(unitVector); } template <typename T> class vec3 : public base_vec<T, 3> { public: using base_type = base_vec<T, 3>; using this_type = vec3<T>; using base_type::operator[]; using base_type::data; using base_type::operator+=; using base_type::operator-=; using base_type::operator*=; using base_type::operator/=; using base_type::GetArray; using base_type::GetLength; using base_type::GetLengthSq; using base_type::Normalize; using ScalarType = T; using base_type::dimension; vec3() = default; constexpr vec3(const this_type&) = default; // Implicit conversion from base class, to avoid issues on that front. constexpr CUDA_CALLABLE vec3(const base_type& other) : base_type(other) { } constexpr explicit CUDA_CALLABLE vec3(T value) : base_type(value, value, value) { } constexpr CUDA_CALLABLE vec3(T v0, T v1, T v2) : base_type(v0, v1, v2) { } template <typename OTHER_T> constexpr explicit CUDA_CALLABLE vec3(const OTHER_T* p) : base_type(p[0], p[1], p[2]) { } template <typename OTHER_T> explicit CUDA_CALLABLE vec3(const vec3<OTHER_T>& other) : base_type(other) { } template <typename OTHER_T> explicit CUDA_CALLABLE vec3(const base_vec<OTHER_T, 3>& other) : base_type(other) { } template <typename OTHER_T> CUDA_CALLABLE vec3(const std::initializer_list<OTHER_T>& other) : base_type(other) { } static constexpr CUDA_CALLABLE vec3<T> XAxis() { return vec3<T>(T(1), T(0), T(0)); } static constexpr CUDA_CALLABLE vec3<T> YAxis() { return vec3<T>(T(0), T(1), T(0)); } static constexpr CUDA_CALLABLE vec3<T> ZAxis() { return vec3<T>(T(0), T(0), T(1)); } static CUDA_CALLABLE vec3<T> Axis(size_t axis) { return base_type::Axis(axis); } CUDA_CALLABLE this_type& Set(T v0, T v1, T v2) { v[0] = v0; v[1] = v1; v[2] = v2; return *this; } CUDA_CALLABLE this_type& Set(T* p) { return Set(p[0], p[1], p[2]); } // NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here. template <typename OTHER_T> CUDA_CALLABLE bool operator==(const vec3<OTHER_T>& other) const { return (v[0] == other[0]) && (v[1] == other[1]) && (v[2] == other[2]); } template <typename OTHER_T> CUDA_CALLABLE bool operator!=(const vec3<OTHER_T>& other) const { return !(*this == other); } // Returns the portion of this that is parallel to unitVector. // NOTE: unitVector must have length 1 for this to produce a meaningful result. CUDA_CALLABLE this_type GetProjection(const this_type& unitVector) const { return unitVector * (this->Dot(unitVector)); } // Returns the portion of this that is orthogonal to unitVector. // NOTE: unitVector must have length 1 for this to produce a meaningful result. CUDA_CALLABLE this_type GetComplement(const this_type& unitVector) const { return *this - GetProjection(unitVector); } CUDA_CALLABLE this_type GetNormalized() const { return base_type::GetNormalized(); } static CUDA_CALLABLE bool OrthogonalizeBasis(vec3<T>* pa, vec3<T>* pb, vec3<T>* pc, bool normalize = true); CUDA_CALLABLE void BuildOrthonormalFrame(vec3<T>* v1, vec3<T>* v2, float eps = 1e-10) const; private: using base_type::v; }; template <typename T> CUDA_CALLABLE vec3<T> operator-(const vec3<T>& v) { return vec3<T>(-v[0], -v[1], -v[2]); } template <typename T> CUDA_CALLABLE vec3<T> GfCompMult(const vec3<T>& a, const vec3<T>& b) { return vec3<T>(a[0] * b[0], a[1] * b[1], a[2] * b[2]); } template <typename T> CUDA_CALLABLE vec3<T> GfCompDiv(const vec3<T>& a, const vec3<T>& b) { return vec3<T>(a[0] / b[0], a[1] / b[1], a[2] / b[2]); } template <typename T> CUDA_CALLABLE vec3<T> GfGetNormalized(const vec3<T>& v) { return v.GetNormalized(); } template <typename T> CUDA_CALLABLE vec3<T> GfGetProjection(const vec3<T>& v, const vec3<T>& unitVector) { return v.GetProjection(unitVector); } template <typename T> CUDA_CALLABLE vec3<T> GfGetComplement(const vec3<T>& v, const vec3<T>& unitVector) { return v.GetComplement(unitVector); } template <typename T> CUDA_CALLABLE vec3<T> GfRadiansToDegrees(const vec3<T>& radians) { return radians * T(180.0 / M_PI); } template <typename T> CUDA_CALLABLE vec3<T> GfDegreesToRadians(const vec3<T>& degrees) { return degrees * T(M_PI / 180.0); } template <typename T> CUDA_CALLABLE vec3<T> GfCross(const base_vec<T, 3>& a, const base_vec<T, 3>& b) { return vec3<T>(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]); } // NOTE: This is the cross product, NOT the XOR operator! template <typename T> CUDA_CALLABLE vec3<T> operator^(const vec3<T>& a, const vec3<T>& b) { return GfCross(a, b); } template <typename T> class vec4 : public base_vec<T, 4> { public: using base_type = base_vec<T, 4>; using this_type = vec4<T>; using base_type::operator[]; using base_type::data; using base_type::operator+=; using base_type::operator-=; using base_type::operator*=; using base_type::operator/=; using base_type::GetArray; using base_type::GetLength; using base_type::GetLengthSq; using base_type::Normalize; using ScalarType = T; using base_type::dimension; vec4() = default; constexpr vec4(const vec4<T>&) = default; // Implicit conversion from base class, to avoid issues on that front. constexpr CUDA_CALLABLE vec4(const base_type& other) : base_type(other) { } constexpr explicit CUDA_CALLABLE vec4(T value) : base_type(value, value, value, value) { } constexpr CUDA_CALLABLE vec4(T v0, T v1, T v2, T v3) : base_type(v0, v1, v2, v3) { } template <typename OTHER_T> constexpr explicit CUDA_CALLABLE vec4(const OTHER_T* p) : base_type(p[0], p[1], p[2], p[3]) { } template <typename OTHER_T> explicit CUDA_CALLABLE vec4(const vec4<OTHER_T>& other) : base_type(other) { } template <typename OTHER_T> explicit CUDA_CALLABLE vec4(const base_vec<OTHER_T, 4>& other) : base_type(other) { } template <typename OTHER_T> CUDA_CALLABLE vec4(const std::initializer_list<OTHER_T>& other) : base_type(other) { } static constexpr CUDA_CALLABLE vec4<T> XAxis() { return vec4<T>(T(1), T(0), T(0), T(0)); } static constexpr CUDA_CALLABLE vec4<T> YAxis() { return vec4<T>(T(0), T(1), T(0), T(0)); } static constexpr CUDA_CALLABLE vec4<T> ZAxis() { return vec4<T>(T(0), T(0), T(1), T(0)); } static constexpr CUDA_CALLABLE vec4<T> WAxis() { return vec4<T>(T(0), T(0), T(0), T(1)); } static CUDA_CALLABLE vec4<T> Axis(size_t axis) { return base_type::Axis(axis); } CUDA_CALLABLE this_type& Set(T v0, T v1, T v2, T v3) { v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3; return *this; } CUDA_CALLABLE this_type& Set(T* p) { return Set(p[0], p[1], p[2], p[3]); } // NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here. template <typename OTHER_T> CUDA_CALLABLE bool operator==(const vec4<OTHER_T>& other) const { return (v[0] == other[0]) && (v[1] == other[1]) && (v[2] == other[2]) && (v[3] == other[3]); } template <typename OTHER_T> CUDA_CALLABLE bool operator!=(const vec4<OTHER_T>& other) const { return !(*this == other); } // Returns the portion of this that is parallel to unitVector. // NOTE: unitVector must have length 1 for this to produce a meaningful result. CUDA_CALLABLE this_type GetProjection(const this_type& unitVector) const { return unitVector * (this->Dot(unitVector)); } // Returns the portion of this that is orthogonal to unitVector. // NOTE: unitVector must have length 1 for this to produce a meaningful result. CUDA_CALLABLE this_type GetComplement(const this_type& unitVector) const { return *this - GetProjection(unitVector); } CUDA_CALLABLE this_type GetNormalized() const { return base_type::GetNormalized(); } CUDA_CALLABLE vec3<T> Project() const { T w = v[3]; w = (w != T(0)) ? T(1) / w : T(1); return w * vec3<T>(v[0], v[1], v[2]); } private: using base_type::v; }; template <typename T> CUDA_CALLABLE vec4<T> operator-(const vec4<T>& v) { return vec4<T>(-v[0], -v[1], -v[2], -v[3]); } template <typename T> CUDA_CALLABLE vec4<T> GfCompMult(const vec4<T>& a, const vec4<T>& b) { return vec4<T>(a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]); } template <typename T> CUDA_CALLABLE vec4<T> GfCompDiv(const vec4<T>& a, const vec4<T>& b) { return vec4<T>(a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]); } template <typename T> CUDA_CALLABLE vec4<T> GfGetNormalized(const vec4<T>& v) { return v.GetNormalized(); } template <typename T> CUDA_CALLABLE vec4<T> GfGetProjection(const vec4<T>& v, const vec4<T>& unitVector) { return v.GetProjection(unitVector); } template <typename T> CUDA_CALLABLE vec4<T> GfGetComplement(const vec4<T>& v, const vec4<T>& unitVector) { return v.GetComplement(unitVector); } template <typename T> CUDA_CALLABLE bool GfOrthogonalizeBasis(vec3<T>* pa, vec3<T>* pb, vec3<T>* pc, bool normalize = true) { // Compute using at least single-precision, to avoid issues with half-precision floating-point values. using S = typename std::conditional<std::is_same<T, float>::value || std::is_same<T, double>::value, T, float>::type; vec3<S> a(pa->GetNormalized()); vec3<S> b(pb->GetNormalized()); vec3<S> c(pc->GetNormalized()); if (normalize) { pa->Normalize(); pb->Normalize(); pc->Normalize(); } // This is an arbitrary tolerance that's about 8 ulps in single-precision floating-point. const double tolerance = 4.8e-7; const double toleranceSq = tolerance * tolerance; // This max iteration count is also somewhat arbitrary. const size_t maxIterations = 32; size_t iteration; for (iteration = 0; iteration < maxIterations; ++iteration) { vec3<S> newA(a.GetComplement(b)); newA = newA.GetComplement(c); vec3<S> newB(b.GetComplement(c)); newB = newB.GetComplement(a); vec3<S> newC(c.GetComplement(a)); newC = newC.GetComplement(b); if (iteration == 0) { // Should only need to check for coplanar vectors on the first iteration. auto lengthSqA = newA.GetLengthSq(); auto lengthSqB = newB.GetLengthSq(); auto lengthSqC = newC.GetLengthSq(); // The unusual condition form is to catch NaNs. if (!(lengthSqA >= toleranceSq) || !(lengthSqB >= toleranceSq) || !(lengthSqC >= toleranceSq)) { return false; } } // Only move a half-step at a time, to avoid instability and improve convergence. newA = S(0.5) * (a + newA); newB = S(0.5) * (b + newB); newC = S(0.5) * (c + newC); if (normalize) { newA.Normalize(); newB.Normalize(); newC.Normalize(); } S changeSq = (newA - a).GetLengthSq() + (newB - b).GetLengthSq() + (newC - c).GetLengthSq(); if (changeSq < toleranceSq) { break; } a = newA; b = newB; c = newC; *pa = vec3<T>(a); *pb = vec3<T>(b); *pc = vec3<T>(c); if (!normalize) { a.Normalize(); b.Normalize(); c.Normalize(); } } return iteration < maxIterations; } template <typename T> CUDA_CALLABLE void GfBuildOrthonormalFrame(const vec3<T>& v0, vec3<T>* v1, vec3<T>* v2, float eps) { float length = v0.GetLength(); if (length == 0) { *v1 = vec3<T>(0); *v2 = vec3<T>(0); } else { vec3<T> unitDir = v0 / length; *v1 = GfCross(vec3<T>::XAxis(), unitDir); if (v1->GetLengthSq() < 1e-8) { *v1 = GfCross(vec3<T>::YAxis(), unitDir); } GfNormalize(v1); *v2 = GfCross(unitDir, *v1); if (length < eps) { double desiredLen = length / eps; *v1 *= desiredLen; *v2 *= desiredLen; } } } template <typename T> CUDA_CALLABLE bool vec3<T>::OrthogonalizeBasis(vec3<T>* pa, vec3<T>* pb, vec3<T>* pc, bool normalize) { return GfOrthogonalizeBasis(pa, pb, pc, normalize); } template <typename T> CUDA_CALLABLE void vec3<T>::BuildOrthonormalFrame(vec3<T>* v1, vec3<T>* v2, float eps) const { return GfBuildOrthonormalFrame(*this, v1, v2, eps); } template <typename T, size_t N> CUDA_CALLABLE base_vec<T, N> GfSlerp(const base_vec<T, N>& a, const base_vec<T, N>& b, double t) { const base_vec<double, N> ad(a); base_vec<double, N> bd(b); double d = ad.Dot(bd); const double arbitraryThreshold = (1.0 - 1e-5); if (d < arbitraryThreshold) { const double angle = t * acos(d); base_vec<double, N> complement; if (d > -arbitraryThreshold) { // Common case: large enough angle between a and b for stable angle from acos and stable complement complement = bd - d * ad; } else { // Angle is almost 180 degrees, so pick an arbitrary vector perpendicular to ad size_t minAxis = 0; for (size_t axis = 1; axis < N; ++axis) minAxis = (abs(ad[axis]) < abs(ad[minAxis])) ? axis : minAxis; base_vec<double, N> complement(0.0); complement[minAxis] = 1; complement -= ad.Dot(complement) * ad; } complement.Normalize(); return base_vec<T, N>(cos(angle) * ad + sin(angle) * complement); } // For small angles, just linearly interpolate. return base_vec<T, N>(ad + t * (bd - ad)); } template <typename T> CUDA_CALLABLE vec2<T> GfSlerp(const vec2<T>& a, const vec2<T>& b, double t) { return vec2<T>(GfSlerp((const base_vec<T, 2>&)a, (const base_vec<T, 2>&)b, t)); } template <typename T> CUDA_CALLABLE vec3<T> GfSlerp(const vec3<T>& a, const vec3<T>& b, double t) { const vec3<double> ad(a); vec3<double> bd(b); double d = ad.Dot(bd); const double arbitraryThreshold = (1.0 - 1e-5); if (d < arbitraryThreshold) { const double angle = t * acos(d); vec3<double> complement; if (d > -arbitraryThreshold) { // Common case: large enough angle between a and b for stable angle from acos and stable complement complement = bd - d * ad; } else { // Angle is almost 180 degrees, so pick an arbitrary vector perpendicular to ad vec3<double> ofa(0); vec3<double> unit = ad / ad.GetLength(); vec3<double> xaxis(0); xaxis[0] = 1; ofa = GfCross(xaxis, unit); if (ofa.GetLength() < 1e-8) { vec3<double> yaxis(0); yaxis[1] = 1; ofa = GfCross(yaxis, unit); } ofa.Normalize(); return vec3<T>(cos(t * M_PI) * ad + sin(t * M_PI) * ofa); } complement.Normalize(); return vec3<T>(cos(angle) * ad + sin(angle) * complement); } // For small angles, just linearly interpolate. return vec3<T>(ad + t * (bd - ad)); } template <typename T> CUDA_CALLABLE vec4<T> GfSlerp(const vec4<T>& a, const vec4<T>& b, double t) { return vec4<T>(GfSlerp((const base_vec<T, 4>&)a, (const base_vec<T, 4>&)b, t)); } // Different parameter order, for compatibility. template <typename VECTOR_T> CUDA_CALLABLE VECTOR_T GfSlerp(double t, const VECTOR_T& a, const VECTOR_T& b) { return GfSlerp(a, b, t); } using vec2h = vec2<half>; using vec2f = vec2<float>; using vec2d = vec2<double>; using vec2i = vec2<int>; using vec3h = vec3<half>; using vec3f = vec3<float>; using vec3d = vec3<double>; using vec3i = vec3<int>; using vec4h = vec4<half>; using vec4f = vec4<float>; using vec4d = vec4<double>; using vec4i = vec4<int>; } } } namespace usdrt { using omni::math::linalg::GfBuildOrthonormalFrame; using omni::math::linalg::GfCompDiv; using omni::math::linalg::GfCompMult; using omni::math::linalg::GfCross; using omni::math::linalg::GfDot; using omni::math::linalg::GfGetComplement; using omni::math::linalg::GfGetLength; using omni::math::linalg::GfGetNormalized; using omni::math::linalg::GfGetProjection; using omni::math::linalg::GfIsClose; using omni::math::linalg::GfNormalize; using omni::math::linalg::GfOrthogonalizeBasis; using omni::math::linalg::GfSlerp; using GfVec2d = omni::math::linalg::vec2<double>; using GfVec2f = omni::math::linalg::vec2<float>; using GfVec2h = omni::math::linalg::vec2<omni::math::linalg::half>; using GfVec2i = omni::math::linalg::vec2<int>; using GfVec3d = omni::math::linalg::vec3<double>; using GfVec3f = omni::math::linalg::vec3<float>; using GfVec3h = omni::math::linalg::vec3<omni::math::linalg::half>; using GfVec3i = omni::math::linalg::vec3<int>; using GfVec4d = omni::math::linalg::vec4<double>; using GfVec4f = omni::math::linalg::vec4<float>; using GfVec4h = omni::math::linalg::vec4<omni::math::linalg::half>; using GfVec4i = omni::math::linalg::vec4<int>; }
omniverse-code/kit/include/usdrt/gf/defines.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 //! @file //! //! @brief TODO #ifndef __CUDACC__ # define CUDA_SAFE_ASSERT(cond, ...) CARB_ASSERT(cond, ##__VA_ARGS__) # define CUDA_CALLABLE #else # define CUDA_SAFE_ASSERT(cond, ...) # define CUDA_CALLABLE __device__ __host__ #endif
omniverse-code/kit/include/usdrt/gf/half.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. // #pragma once //! @file //! //! @brief TODO #include <usdrt/gf/defines.h> #include <stdint.h> #include <type_traits> namespace omni { namespace math { namespace linalg { class half { public: half() noexcept = default; constexpr half(const half&) noexcept = default; constexpr half& operator=(const half&) noexcept = default; // TODO: Change this to be explicit, once OGN default value code supports explicit conversions. // Converting to half-precision can be dangerous if unintentional, so make sure it's intentional. CUDA_CALLABLE half(float f) noexcept : v(floatToHalf(f)) { static_assert(std::is_pod<half>::value, "half should be a POD type."); } // NOTE: This is two roundings, so could occasionally produce a suboptimal rounded value. explicit CUDA_CALLABLE half(double f) noexcept : v(floatToHalf(float(f))) { } explicit CUDA_CALLABLE half(int i) noexcept : v(floatToHalf(float(i))) { } explicit CUDA_CALLABLE operator float() const noexcept { return halfToFloat(v); } explicit CUDA_CALLABLE operator double() const noexcept { return double(halfToFloat(v)); } explicit CUDA_CALLABLE operator int() const noexcept { return int(halfToFloat(v)); } CUDA_CALLABLE bool operator<(const half& rhs) const noexcept { return halfToFloat(v) < halfToFloat(rhs.bits()); } CUDA_CALLABLE bool operator<=(const half& rhs) const noexcept { return halfToFloat(v) <= halfToFloat(rhs.bits()); } CUDA_CALLABLE bool operator>(const half& rhs) const noexcept { return halfToFloat(v) > halfToFloat(rhs.bits()); } CUDA_CALLABLE bool operator>=(const half& rhs) const noexcept { return halfToFloat(v) >= halfToFloat(rhs.bits()); } CUDA_CALLABLE bool operator==(const half& rhs) const noexcept { return bits() == rhs.bits(); } CUDA_CALLABLE bool operator!=(const half& rhs) const noexcept { return bits() != rhs.bits(); } CUDA_CALLABLE half operator-() const noexcept { half result(-halfToFloat(v)); return result; } CUDA_CALLABLE half& operator+=(const half& rhs) noexcept { v = floatToHalf(halfToFloat(v) + halfToFloat(rhs.bits())); return *this; } CUDA_CALLABLE half& operator-=(const half& rhs) noexcept { v = floatToHalf(halfToFloat(v) - halfToFloat(rhs.bits())); return *this; } CUDA_CALLABLE half& operator*=(const half& rhs) noexcept { v = floatToHalf(halfToFloat(v) * halfToFloat(rhs.bits())); return *this; } CUDA_CALLABLE half& operator/=(const half& rhs) noexcept { v = floatToHalf(halfToFloat(v) / halfToFloat(rhs.bits())); return *this; } #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE half operator+(half lhs, const half& rhs) { lhs += rhs; return lhs; } friend CUDA_CALLABLE half operator-(half lhs, const half& rhs) { lhs -= rhs; return lhs; } friend CUDA_CALLABLE half operator*(half lhs, const half& rhs) { lhs *= rhs; return lhs; } friend CUDA_CALLABLE half operator/(half lhs, const half& rhs) { lhs /= rhs; return lhs; } #endif // DOXYGEN_BUILD CUDA_CALLABLE uint16_t& bits() noexcept { return v; } CUDA_CALLABLE const uint16_t& bits() const noexcept { return v; } #ifndef DOXYGEN_BUILD constexpr static uint32_t s_floatMantissaBitCount = 23; constexpr static uint32_t s_floatMantissaMask = (uint32_t(1) << s_floatMantissaBitCount) - 1; constexpr static uint32_t s_floatExponentBitCount = 8; constexpr static uint32_t s_floatShiftedExponentMask = (uint32_t(1) << s_floatExponentBitCount) - 1; constexpr static uint32_t s_floatExponentExcess = 0x7F; constexpr static uint32_t s_floatInfExpWithExcess = s_floatShiftedExponentMask; constexpr static uint16_t s_halfMantissaBitCount = 10; constexpr static uint16_t s_halfMantissaMask = (uint16_t(1) << s_halfMantissaBitCount) - 1; constexpr static uint16_t s_halfExponentBitCount = 5; constexpr static uint16_t s_halfShiftedExponentMask = (uint16_t(1) << s_halfExponentBitCount) - 1; constexpr static uint16_t s_halfExponentExcess = 0xF; constexpr static uint16_t s_halfInfExpWithExcess = s_halfShiftedExponentMask; constexpr static uint32_t s_mantissaBitCountDiff = s_floatMantissaBitCount - s_halfMantissaBitCount; constexpr static uint32_t s_exponentExcessDiff = s_floatExponentExcess - s_halfExponentExcess; #endif // DOXYGEN_BUILD static CUDA_CALLABLE float halfToFloat(uint16_t i) noexcept { // Extract parts uint32_t sign = uint32_t(i >> 15); uint16_t exponent = (i >> s_halfMantissaBitCount) & s_halfShiftedExponentMask; uint16_t mantissa = (i & s_halfMantissaMask); // Shift parts uint32_t newExponent = (uint32_t(exponent) + s_exponentExcessDiff); uint32_t newMantissa = (mantissa << s_mantissaBitCountDiff); if (exponent == s_halfInfExpWithExcess) { // Infinity or NaN newExponent = s_floatInfExpWithExcess; } else if (exponent == 0) { // Denormal if (mantissa == 0) { // Zero newExponent = 0; } else { // Non-zero denormal ++newExponent; do { newMantissa <<= 1; --newExponent; } while (!(newMantissa & (s_floatMantissaMask + 1))); newMantissa &= s_floatMantissaMask; } } uint32_t result = (sign << 31) | (newExponent << s_floatMantissaBitCount) | newMantissa; static_assert(sizeof(uint32_t) == sizeof(float), "The following union requires that uint32_t and float are the same size."); union { uint32_t result_i; float result_f; }; result_i = result; return result_f; } static CUDA_CALLABLE uint16_t floatToHalf(float f) noexcept { static_assert(sizeof(uint32_t) == sizeof(float), "The following union requires that uint32_t and float are the same size."); union { uint32_t input_i; float input_f; }; input_f = f; uint32_t i = input_i; // Extract parts uint32_t sign = uint32_t(i >> 31); uint32_t exponent = (i >> s_floatMantissaBitCount) & s_floatShiftedExponentMask; uint32_t mantissa = (i & s_floatMantissaMask); bool atLeastHalf = false; bool nonZeroLowBits = false; uint16_t newExponent; uint16_t newMantissa; if (exponent >= (s_exponentExcessDiff + s_halfInfExpWithExcess)) { // New value will be infinity or NaN newExponent = s_halfInfExpWithExcess; if (exponent == s_floatInfExpWithExcess) { // Old value was infinity or NaN newMantissa = (mantissa >> s_mantissaBitCountDiff); if (mantissa != 0 && newMantissa == 0) { // Preserve NaN newMantissa = 1; } } else { // New infinity newMantissa = 0; } } // NOTE: s_exponentExcessDiff is the smallest half-precision exponent with single-precision's excess. else if (exponent <= s_exponentExcessDiff) { // New value will be denormal (unless rounded up to normal) newExponent = 0; if (exponent < (s_exponentExcessDiff - s_halfMantissaBitCount)) { // Zero newMantissa = 0; } else { // Non-zero denormal mantissa += (s_floatMantissaMask + 1); std::size_t shift = (s_exponentExcessDiff + 1) + s_mantissaBitCountDiff - exponent; newMantissa = (mantissa >> shift); atLeastHalf = ((mantissa >> (shift - 1)) & 1); nonZeroLowBits = (mantissa & ((1 << (shift - 1)) - 1)) != 0; } } else { // New value will be normal (unless rounded up to infinity) newMantissa = (mantissa >> s_mantissaBitCountDiff); newExponent = exponent - s_exponentExcessDiff; atLeastHalf = ((mantissa >> (s_mantissaBitCountDiff - 1)) & 1); nonZeroLowBits = (mantissa & ((1 << (s_mantissaBitCountDiff - 1)) - 1)) != 0; } // Round half to even bool odd = (newMantissa & 1); newMantissa += atLeastHalf && (nonZeroLowBits || odd); if (newMantissa == (s_halfMantissaMask + 1)) { newMantissa = 0; ++newExponent; } uint16_t result = (sign << 15) | (newExponent << s_halfMantissaBitCount) | newMantissa; return result; } private: uint16_t v; }; } } } namespace usdrt { using GfHalf = omni::math::linalg::half; }
omniverse-code/kit/include/usdrt/gf/quat.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once //! @file //! //! @brief TODO #include <usdrt/gf/defines.h> #include <usdrt/gf/math.h> #include <usdrt/gf/vec.h> #include <initializer_list> namespace omni { namespace math { namespace linalg { // Forward declaration, just for the using statement, below. class half; template <typename T> class quat : private base_vec<T, 4> { public: using base_type = base_vec<T, 4>; // usdrt edit using typename base_type::const_iterator; using typename base_type::const_pointer; using typename base_type::const_reference; using typename base_type::difference_type; using typename base_type::iterator; using typename base_type::pointer; using typename base_type::reference; using typename base_type::size_type; using typename base_type::value_type; // end usdrt edit using ScalarType = T; using ImaginaryType = vec3<T>; #ifndef DOXYGEN_BUILD constexpr static size_t dimension = 4; constexpr static size_t real_index = 3; constexpr static size_t imaginary_index = 0; #endif // DOXYGEN_BUILD quat() = default; constexpr quat(const quat<T>&) = default; // Explicit conversion from base class, to avoid issues on that front. constexpr explicit CUDA_CALLABLE quat(const base_type& other) : base_type(other) { } // NOTE: This usually only makes sense for real being -1, 0, or 1. constexpr explicit CUDA_CALLABLE quat(T real) : base_type(T(0), T(0), T(0), real) { } // NOTE: The order of the arguments is different from the order in memory! constexpr CUDA_CALLABLE quat(T real, T i, T j, T k) : base_type(i, j, k, real) { } // NOTE: The order of the arguments is different from the order in memory! constexpr CUDA_CALLABLE quat(T real, vec3<T> imaginary) : base_type(imaginary[0], imaginary[1], imaginary[2], real) { } template <typename OTHER_T> explicit CUDA_CALLABLE quat(const quat<OTHER_T>& other) : quat(T(other.GetReal()), vec3<T>(other.GetImaginary())) { } // NOTE: The order of the arguments is different from the order in memory, // so we can't delegate directly to the base class constructor. template <typename OTHER_T> CUDA_CALLABLE quat(const std::initializer_list<OTHER_T>& other) noexcept : base_type(T(0), T(0), T(0), T(0)) { CUDA_SAFE_ASSERT(other.size() == 4); if (other.size() != 4) return; // Order change as above base_type::operator[](0) = other.begin()[1]; base_type::operator[](1) = other.begin()[2]; base_type::operator[](2) = other.begin()[3]; base_type::operator[](3) = other.begin()[0]; } static CUDA_CALLABLE quat<T> GetIdentity() { return quat<T>(T(1)); } CUDA_CALLABLE T GetReal() const { return base_type::operator[](real_index); } CUDA_CALLABLE void SetReal(T real) { base_type::operator[](real_index) = real; } CUDA_CALLABLE vec3<T> GetImaginary() const { return vec3<T>(base_type::operator[](imaginary_index), base_type::operator[](imaginary_index + 1), base_type::operator[](imaginary_index + 2)); } CUDA_CALLABLE void SetImaginary(const vec3<T>& imaginary) { base_type::operator[](imaginary_index) = imaginary[0]; base_type::operator[](imaginary_index + 1) = imaginary[1]; base_type::operator[](imaginary_index + 2) = imaginary[2]; } CUDA_CALLABLE void SetImaginary(T i, T j, T k) { base_type::operator[](imaginary_index) = i; base_type::operator[](imaginary_index + 1) = j; base_type::operator[](imaginary_index + 2) = k; } constexpr CUDA_CALLABLE T Dot(const quat<T>& other) const { return base_type::Dot(other); // return GetImaginary().Dot(other.GetImaginary()) + GetReal() * other.GetReal(); } using base_type::data; using base_type::GetLength; using base_type::GetLengthSq; using base_type::Normalize; #ifndef DOXYGEN_BUILD CUDA_CALLABLE quat<T> GetNormalized() const { return quat<T>(base_type::GetNormalized()); } #endif // DOXYGEN_BUILD CUDA_CALLABLE quat<T> GetConjugate() const { return quat<T>(GetReal(), -GetImaginary()); } CUDA_CALLABLE quat<T> GetInverse() const { return GetConjugate() / GetLengthSq(); } CUDA_CALLABLE vec3<T> Transform(const vec3<T>& point) const { const auto& cosTheta = GetReal(); const T cosTheta2 = GetReal() * GetReal(); const vec3<T> sinThetas = GetImaginary(); const T sinTheta2 = sinThetas.GetLengthSq(); const T length2 = cosTheta2 + sinTheta2; const T cos2Theta = cosTheta2 - sinTheta2; return (cos2Theta * point + ((2 * GfDot(sinThetas, point)) * sinThetas + (2 * cosTheta) * GfCross(sinThetas, point))) / length2; } // NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here. CUDA_CALLABLE quat<T> operator-() const { return quat<T>(-GetReal(), -GetImaginary()); } CUDA_CALLABLE bool operator==(const quat<T>& other) const { return (GetImaginary() == other.GetImaginary()) && (GetReal() == other.GetReal()); } CUDA_CALLABLE bool operator!=(const quat<T>& other) const { return !(*this == other); } CUDA_CALLABLE quat<T>& operator*=(const quat<T>& other) { const T r0 = GetReal(); const T r1 = other.GetReal(); const vec3<T> i0 = GetImaginary(); const vec3<T> i1 = other.GetImaginary(); // TODO: This isn't the most efficient way to multiply two quaternions. SetImaginary(r0 * i1 + r1 * i0 + GfCross(i0, i1)); SetReal(r0 * r1 - i0.Dot(i1)); return *this; } CUDA_CALLABLE quat<T>& operator*=(T scalar) { base_type::operator*=(scalar); return *this; } CUDA_CALLABLE quat<T>& operator/=(T scalar) { base_type::operator/=(scalar); return *this; } CUDA_CALLABLE quat<T>& operator+=(const quat<T>& other) { base_type::operator+=(other); return *this; } CUDA_CALLABLE quat<T>& operator-=(const quat<T>& other) { base_type::operator-=(other); return *this; } #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE quat<T> operator+(const quat<T>& a, const quat<T>& b) { return quat<T>(((const base_type&)a) + ((const base_type&)b)); } friend CUDA_CALLABLE quat<T> operator-(const quat<T>& a, const quat<T>& b) { return quat<T>(((const base_type&)a) - ((const base_type&)b)); } friend CUDA_CALLABLE quat<T> operator*(const quat<T>& a, const quat<T>& b) { quat<T> product(a); product *= b; return product; } friend CUDA_CALLABLE quat<T> operator*(const quat<T>& q, T scalar) { return quat<T>(((const base_type&)q) * scalar); } friend CUDA_CALLABLE quat<T> operator*(T scalar, const quat<T>& q) { return quat<T>(((const base_type&)q) * scalar); } friend CUDA_CALLABLE quat<T> operator/(const quat<T>& q, T scalar) { return quat<T>(((const base_type&)q) / scalar); } #endif }; template <typename T> CUDA_CALLABLE T GfDot(const quat<T>& a, const quat<T>& b) { return a.Dot(b); } template <typename T> CUDA_CALLABLE bool GfIsClose(const quat<T>& a, const quat<T>& b, double tolerance) { auto distanceSq = (a - b).GetLengthSq(); return distanceSq <= tolerance * tolerance; } template <typename T> CUDA_CALLABLE quat<T> GfSlerp(const quat<T>& a, const quat<T>& b, double t) { const quat<double> ad(a); quat<double> bd(b); double d = ad.Dot(bd); // NOTE: Although a proper slerp wouldn't flip b on negative dot, this flips b // for compatibility. Quaternions cover the space of orientations twice, so this // avoids interpolating between orientations that are more than 180 degrees apart. if (d < 0) { bd = -bd; d = -d; } const double arbitraryThreshold = (1.0 - 1e-5); if (d < arbitraryThreshold) { // Common case: large enough angle between a and b for stable angle from acos and stable complement const double angle = t * std::acos(d); quat<double> complement = bd - d * ad; complement.Normalize(); return quat<T>(std::cos(angle) * ad + std::sin(angle) * complement); } // For small angles, just linearly interpolate. return quat<T>(ad + t * (bd - ad)); } using quath = quat<half>; using quatf = quat<float>; using quatd = quat<double>; // Alphabetical order (same order as pxr::UsdGeomXformCommonAPI::RotationOrder) enum class EulerRotationOrder { XYZ, XZY, YXZ, YZX, ZXY, ZYX }; static constexpr size_t s_eulerRotationOrderAxes[6][3] = { { 0, 1, 2 }, // XYZ { 0, 2, 1 }, // XZY { 1, 0, 2 }, // YXZ { 1, 2, 0 }, // YZX { 2, 0, 1 }, // ZXY { 2, 1, 0 } // ZYX }; // eulerAngles is in radians. You can use GfDegreesToRadians to convert. template <typename T> CUDA_CALLABLE quatd eulerAnglesToQuaternion(const vec3<T>& eulerAngles, EulerRotationOrder order) { // There's almost certainly a more efficient way to do this, but this should work, // (unless the quaternion order is backward from what's needed, but then // choosing the reverse rotation order should address that.) // Quaternions are applied "on both sides", so each contains half the rotation, // or at least that's a mnemonic to remember to half it. const vec3d halfAngles = 0.5 * vec3d(eulerAngles); const double cx = std::cos(halfAngles[0]); const double sx = std::sin(halfAngles[0]); const double cy = std::cos(halfAngles[1]); const double sy = std::sin(halfAngles[1]); const double cz = std::cos(halfAngles[2]); const double sz = std::sin(halfAngles[2]); const quatd qs[3] = { quatd(cx, vec3d(sx, 0, 0)), quatd(cy, vec3d(0, sy, 0)), quatd(cz, vec3d(0, 0, sz)) }; // Apply the quaternions in the specified order // NOTE: Even though USD matrix transformations are applied to row vectors from left to right, // quaternions are still applied from right to left, like standard quaternions. const size_t* const orderAxes = s_eulerRotationOrderAxes[size_t(order)]; const quatd q = qs[orderAxes[2]] * qs[orderAxes[1]] * qs[orderAxes[0]]; return q; } } } } namespace usdrt { using omni::math::linalg::GfDot; using omni::math::linalg::GfIsClose; using omni::math::linalg::GfSlerp; using GfQuatd = omni::math::linalg::quat<double>; using GfQuatf = omni::math::linalg::quat<float>; using GfQuath = omni::math::linalg::quat<omni::math::linalg::half>; }
omniverse-code/kit/include/usdrt/gf/rect.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once //! @file //! //! @brief TODO #include <carb/Defines.h> #include <usdrt/gf/vec.h> #include <float.h> namespace usdrt { struct GfRect2i { public: // In order to make GfRect2i a POD type we need to give up on non-default constructor // pxr::GfRect2i initializes to empty, so we're not 100% compatible here! GfRect2i() = default; constexpr GfRect2i(const GfRect2i&) = default; /// Helper typedef. using MinMaxType = GfVec2i; static const size_t dimension = MinMaxType::dimension; using ScalarType = MinMaxType::ScalarType; /// Constructs a rectangle with \p min and \p max corners. constexpr GfRect2i(const GfVec2i& min, const GfVec2i& max) : _min(min), _max(max) { } /// Constructs a rectangle with \p min corner and the indicated \p width /// and \p height. GfRect2i(const GfVec2i& min, int width, int height) : _min(min), _max(min + GfVec2i(width - 1, height - 1)) { } /// Returns true if the rectangle is a null rectangle. /// /// A null rectangle has both the width and the height set to 0, that is /// \code /// GetMaxX() == GetMinX() - 1 /// \endcode /// and /// \code /// GetMaxY() == GetMinY() - 1 /// \endcode /// Remember that if \c GetMinX() and \c GetMaxX() return the same value /// then the rectangle has width 1, and similarly for the height. /// /// A null rectangle is both empty, and not valid. bool IsNull() const { return GetWidth() == 0 && GetHeight() == 0; } /// Returns true if the rectangle is empty. /// /// An empty rectangle has one or both of its min coordinates strictly /// greater than the corresponding max coordinate. /// /// An empty rectangle is not valid. bool IsEmpty() const { return GetWidth() <= 0 || GetHeight() <= 0; } /// Return true if the rectangle is valid (equivalently, not empty). bool IsValid() const { return !IsEmpty(); } /// Returns a normalized rectangle, i.e. one that has a non-negative width /// and height. /// /// \c GetNormalized() swaps the min and max x-coordinates to /// ensure a non-negative width, and similarly for the /// y-coordinates. GfRect2i GetNormalized() const { GfVec2i min, max; if (_max[0] < _min[0]) { min[0] = _max[0]; max[0] = _min[0]; } else { min[0] = _min[0]; max[0] = _max[0]; } if (_max[1] < _min[1]) { min[1] = _max[1]; max[1] = _min[1]; } else { min[1] = _min[1]; max[1] = _max[1]; } return GfRect2i(min, max); } /// Returns the min corner of the rectangle. const GfVec2i& GetMin() const { return _min; } /// Returns the max corner of the rectangle. const GfVec2i& GetMax() const { return _max; } /// Return the X value of min corner. /// int GetMinX() const { return _min[0]; } /// Set the X value of the min corner. /// void SetMinX(int x) { _min[0] = x; } /// Return the X value of the max corner. /// int GetMaxX() const { return _max[0]; } /// Set the X value of the max corner void SetMaxX(int x) { _max[0] = x; } /// Return the Y value of the min corner /// int GetMinY() const { return _min[1]; } /// Set the Y value of the min corner. /// void SetMinY(int y) { _min[1] = y; } /// Return the Y value of the max corner int GetMaxY() const { return _max[1]; } /// Set the Y value of the max corner void SetMaxY(int y) { _max[1] = y; } /// Sets the min corner of the rectangle. void SetMin(const GfVec2i& min) { _min = min; } /// Sets the max corner of the rectangle. void SetMax(const GfVec2i& max) { _max = max; } /// Returns the center point of the rectangle. GfVec2i GetCenter() const { return (_min + _max) / 2; } /// Move the rectangle by \p displ. void Translate(const GfVec2i& displacement) { _min += displacement; _max += displacement; } /// Return the area of the rectangle. unsigned long GetArea() const { return (unsigned long)GetWidth() * (unsigned long)GetHeight(); } /// Returns the size of the rectangle as a vector (width,height). GfVec2i GetSize() const { return GfVec2i(GetWidth(), GetHeight()); } /// Returns the width of the rectangle. /// /// \note If the min and max x-coordinates are coincident, the width is /// one. int GetWidth() const { return (_max[0] - _min[0]) + 1; } /// Returns the height of the rectangle. /// /// \note If the min and max y-coordinates are coincident, the height is /// one. int GetHeight() const { return (_max[1] - _min[1]) + 1; } /// Computes the intersection of two rectangles. GfRect2i GetIntersection(const GfRect2i& that) const { if (IsEmpty()) return *this; else if (that.IsEmpty()) return that; else return GfRect2i(GfVec2i(GfMax(_min[0], that._min[0]), GfMax(_min[1], that._min[1])), GfVec2i(GfMin(_max[0], that._max[0]), GfMin(_max[1], that._max[1]))); } /// Computes the intersection of two rectangles. /// \deprecated Use GetIntersection() instead GfRect2i Intersect(const GfRect2i& that) const { return GetIntersection(that); } /// Computes the union of two rectangles. GfRect2i GetUnion(const GfRect2i& that) const { if (IsEmpty()) return that; else if (that.IsEmpty()) return *this; else return GfRect2i(GfVec2i(GfMin(_min[0], that._min[0]), GfMin(_min[1], that._min[1])), GfVec2i(GfMax(_max[0], that._max[0]), GfMax(_max[1], that._max[1]))); } /// Computes the union of two rectangles /// \deprecated Use GetUnion() instead. GfRect2i Union(const GfRect2i& that) const { return GetUnion(that); } /// Returns true if the specified point in the rectangle. bool Contains(const GfVec2i& p) const { return ((p[0] >= _min[0]) && (p[0] <= _max[0]) && (p[1] >= _min[1]) && (p[1] <= _max[1])); } /// Returns true if \p r1 and \p r2 are equal. friend bool operator==(const GfRect2i& r1, const GfRect2i& r2) { return r1._min == r2._min && r1._max == r2._max; } /// Returns true if \p r1 and \p r2 are different. friend bool operator!=(const GfRect2i& r1, const GfRect2i& r2) { return !(r1 == r2); } /// Computes the union of two rectangles. /// \see GetUnion() GfRect2i operator+=(const GfRect2i& that) { *this = GetUnion(that); return *this; } friend GfRect2i operator+(const GfRect2i r1, const GfRect2i& r2) { GfRect2i tmp(r1); tmp += r2; return tmp; } private: GfVec2i _min = { 0, 0 }; GfVec2i _max = { -1, -1 }; }; }
omniverse-code/kit/include/usdrt/gf/math.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once //! @file //! //! @brief TODO #ifdef _MSC_VER // This is for M_PI # define _USE_MATH_DEFINES # include <math.h> #endif #include <usdrt/gf/defines.h> #include <cmath> namespace omni { namespace math { namespace linalg { // WARNING: Non-standard parameter order, for compatibility! template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfLerp(double t, const VALUE_T& a, const VALUE_T& b) { // Always use the difference, so that if a==b, a value equal to both // will be returned, instead of one that might have roundoff error. return a + t * (b - a); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfRadiansToDegrees(VALUE_T radians) { return radians * VALUE_T(180.0 / M_PI); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfDegreesToRadians(VALUE_T degrees) { return degrees * VALUE_T(M_PI / 180.0); } CUDA_CALLABLE inline bool GfIsClose(double a, double b, double epsilon) { return fabs(a - b) < epsilon; } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2) { return (a1 < a2 ? a1 : a2); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2, VALUE_T a3) { return GfMin(GfMin(a1, a2), a3); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4) { return GfMin(GfMin(a1, a2, a3), a4); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMin(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4, VALUE_T a5) { return GfMin(GfMin(a1, a2, a3, a4), a5); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2) { return (a1 < a2 ? a2 : a1); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2, VALUE_T a3) { return GfMax(GfMax(a1, a2), a3); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4) { return GfMax(GfMax(a1, a2, a3), a4); } template <typename VALUE_T> CUDA_CALLABLE VALUE_T GfMax(VALUE_T a1, VALUE_T a2, VALUE_T a3, VALUE_T a4, VALUE_T a5) { return GfMax(GfMax(a1, a2, a3, a4), a5); } template <class VALUE_T> inline double GfSqr(const VALUE_T& x) { return x * x; } } } } namespace usdrt { using omni::math::linalg::GfDegreesToRadians; using omni::math::linalg::GfIsClose; using omni::math::linalg::GfLerp; using omni::math::linalg::GfMax; using omni::math::linalg::GfMin; using omni::math::linalg::GfRadiansToDegrees; using omni::math::linalg::GfSqr; }
omniverse-code/kit/include/usdrt/gf/range.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once //! @file //! //! @brief TODO #include <carb/Defines.h> #include <usdrt/gf/vec.h> namespace omni { namespace math { namespace linalg { // specializing range for 1 dimensions to use float and match GfRange1(d|f) template <typename T> class range1 { public: static const size_t dimension = 1; using MinMaxType = T; using ScalarType = T; using ThisType = range1<T>; /// Sets the range to an empty interval // TODO check whether this can be deprecated. void inline SetEmpty() { _min = std::numeric_limits<ScalarType>::max(); _max = -std::numeric_limits<ScalarType>::max(); } /// The default constructor creates an empty range. range1() = default; constexpr range1(const ThisType&) = default; constexpr explicit range1(ScalarType size) : _min(-size), _max(size) { } /// This constructor initializes the minimum and maximum points. constexpr range1(ScalarType min, ScalarType max) : _min(min), _max(max) { } /// Returns the minimum value of the range. ScalarType GetMin() const { return _min; } /// Returns the maximum value of the range. ScalarType GetMax() const { return _max; } /// Returns the size of the range. ScalarType GetSize() const { return _max - _min; } /// Returns the midpoint of the range, that is, 0.5*(min+max). /// Note: this returns zero in the case of default-constructed ranges, /// or ranges set via SetEmpty(). ScalarType GetMidpoint() const { return static_cast<ScalarType>(0.5) * _min + static_cast<ScalarType>(0.5) * _max; } /// Sets the minimum value of the range. void SetMin(ScalarType min) { _min = min; } /// Sets the maximum value of the range. void SetMax(ScalarType max) { _max = max; } /// Returns whether the range is empty (max < min). bool IsEmpty() const { return _min > _max; } /// Modifies the range if necessary to surround the given value. /// \deprecated Use UnionWith() instead. void ExtendBy(ScalarType point) { UnionWith(point); } /// Modifies the range if necessary to surround the given range. /// \deprecated Use UnionWith() instead. void ExtendBy(const ThisType& range) { UnionWith(range); } /// Returns true if the \p point is located inside the range. As with all /// operations of this type, the range is assumed to include its extrema. bool Contains(const ScalarType& point) const { return (point >= _min && point <= _max); } /// Returns true if the \p range is located entirely inside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. bool Contains(const ThisType& range) const { return Contains(range._min) && Contains(range._max); } /// Returns true if the \p point is located inside the range. As with all /// operations of this type, the range is assumed to include its extrema. /// \deprecated Use Contains() instead. bool IsInside(ScalarType point) const { return Contains(point); } /// Returns true if the \p range is located entirely inside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. /// \deprecated Use Contains() instead. bool IsInside(const ThisType& range) const { return Contains(range); } /// Returns true if the \p range is located entirely outside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. bool IsOutside(const ThisType& range) const { return (range._max < _min || range._min > _max); } /// Returns the smallest \c GfRange1f which contains both \p a and \p b. static ThisType GetUnion(const ThisType& a, const ThisType& b) { auto res = a; _FindMin(res._min, b._min); _FindMax(res._max, b._max); return res; } /// Extend \p this to include \p b. const ThisType& UnionWith(const ThisType& b) { _FindMin(_min, b._min); _FindMax(_max, b._max); return *this; } /// Extend \p this to include \p b. const ThisType& UnionWith(const ScalarType& b) { _FindMin(_min, b); _FindMax(_max, b); return *this; } /// Returns the smallest \c GfRange1f which contains both \p a and \p b /// \deprecated Use GetUnion() instead. static ThisType Union(const ThisType& a, const ThisType& b) { return GetUnion(a, b); } /// Extend \p this to include \p b. /// \deprecated Use UnionWith() instead. const ThisType& Union(const ThisType& b) { return UnionWith(b); } /// Extend \p this to include \p b. /// \deprecated Use UnionWith() instead. const ThisType& Union(ScalarType b) { return UnionWith(b); } /// Returns a \c GfRange1f that describes the intersection of \p a and \p b. static ThisType GetIntersection(const ThisType& a, const ThisType& b) { auto res = a; _FindMax(res._min, b._min); _FindMin(res._max, b._max); return res; } /// Returns a \c GfRange1f that describes the intersection of \p a and \p b. /// \deprecated Use GetIntersection() instead. static ThisType Intersection(const ThisType& a, const ThisType& b) { return GetIntersection(a, b); } /// Modifies this range to hold its intersection with \p b and returns the /// result const ThisType& IntersectWith(const ThisType& b) { _FindMax(_min, b._min); _FindMin(_max, b._max); return *this; } /// Modifies this range to hold its intersection with \p b and returns the /// result. /// \deprecated Use IntersectWith() instead. const ThisType& Intersection(const ThisType& b) { return IntersectWith(b); } /// unary sum. ThisType operator+=(const ThisType& b) { _min += b._min; _max += b._max; return *this; } /// unary difference. ThisType operator-=(const ThisType& b) { _min -= b._max; _max -= b._min; return *this; } /// unary multiply. ThisType operator*=(double m) { if (m > 0) { _min *= m; _max *= m; } else { float tmp = _min; _min = _max * m; _max = tmp * m; } return *this; } /// unary division. ThisType operator/=(double m) { return *this *= (1.0 / m); } /// binary sum. ThisType operator+(const ThisType& b) const { return ThisType(_min + b._min, _max + b._max); } /// binary difference. ThisType operator-(const ThisType& b) const { return ThisType(_min - b._max, _max - b._min); } /// scalar multiply. friend ThisType operator*(double m, const ThisType& r) { return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m)); } /// scalar multiply. friend ThisType operator*(const ThisType& r, double m) { return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m)); } /// scalar divide. friend ThisType operator/(const ThisType& r, double m) { return r * (1.0 / m); } inline bool operator==(const ThisType& other) const { return _min == static_cast<ScalarType>(other.GetMin()) && _max == static_cast<ScalarType>(other.GetMax()); } inline bool operator!=(const ThisType& other) const { return !(*this == other); } /// Compute the squared distance from a point to the range. double GetDistanceSquared(ScalarType p) const { double dist = 0.0; if (p < _min) { // p is left of box dist += GfSqr(_min - p); } else if (p > _max) { // p is right of box dist += GfSqr(p - _max); } return dist; } private: /// Minimum and maximum points. ScalarType _min, _max; /// Extends minimum point if necessary to contain given point. static void _FindMin(ScalarType& dest, ScalarType point) { if (point < dest) { dest = point; } } /// Extends maximum point if necessary to contain given point. static void _FindMax(ScalarType& dest, ScalarType point) { if (point > dest) { dest = point; } } }; template <typename T> class range2 { public: static const size_t dimension = 2; using ScalarType = T; using MinMaxType = omni::math::linalg::vec2<T>; using ThisType = range2<T>; range2() = default; constexpr range2(const ThisType&) = default; constexpr explicit range2(ScalarType size) : _min(-size), _max(size) { } /// Sets the range to an empty interval // TODO check whether this can be deprecated. constexpr void inline SetEmpty() { _min = { std::numeric_limits<ScalarType>::max() }; _max = { -std::numeric_limits<ScalarType>::max() }; } /// This constructor initializes the minimum and maximum points. constexpr range2(const MinMaxType& min, const MinMaxType& max) : _min(min), _max(max) { } /// Returns the minimum value of the range. const MinMaxType& GetMin() const { return _min; } /// Returns the maximum value of the range. const MinMaxType& GetMax() const { return _max; } /// Returns the size of the range. MinMaxType GetSize() const { return _max - _min; } /// Returns the midpoint of the range, that is, 0.5*(min+max). /// Note: this returns zero in the case of default-constructed ranges, /// or ranges set via SetEmpty(). MinMaxType GetMidpoint() const { return static_cast<ScalarType>(0.5) * _min + static_cast<ScalarType>(0.5) * _max; } /// Sets the minimum value of the range. void SetMin(const MinMaxType& min) { _min = min; } /// Sets the maximum value of the range. void SetMax(const MinMaxType& max) { _max = max; } /// Returns whether the range is empty (max < min). bool IsEmpty() const { return _min[0] > _max[0] || _min[1] > _max[1]; } /// Modifies the range if necessary to surround the given value. /// \deprecated Use UnionWith() instead. void ExtendBy(const MinMaxType& point) { UnionWith(point); } /// Modifies the range if necessary to surround the given range. /// \deprecated Use UnionWith() instead. void ExtendBy(const ThisType& range) { UnionWith(range); } /// Returns true if the \p point is located inside the range. As with all /// operations of this type, the range is assumed to include its extrema. bool Contains(const MinMaxType& point) const { return (point[0] >= _min[0] && point[0] <= _max[0] && point[1] >= _min[1] && point[1] <= _max[1]); } /// Returns true if the \p range is located entirely inside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. bool Contains(const ThisType& range) const { return Contains(range._min) && Contains(range._max); } /// Returns true if the \p point is located inside the range. As with all /// operations of this type, the range is assumed to include its extrema. /// \deprecated Use Contains() instead. bool IsInside(const MinMaxType& point) const { return Contains(point); } /// Returns true if the \p range is located entirely inside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. /// \deprecated Use Contains() instead. bool IsInside(const ThisType& range) const { return Contains(range); } /// Returns true if the \p range is located entirely outside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. bool IsOutside(const ThisType& range) const { return ((range._max[0] < _min[0] || range._min[0] > _max[0]) || (range._max[1] < _min[1] || range._min[1] > _max[1])); } /// Returns the smallest \c ThisType which contains both \p a and \p b. static ThisType GetUnion(const ThisType& a, const ThisType& b) { auto res = a; _FindMin(res._min, b._min); _FindMax(res._max, b._max); return res; } /// Extend \p this to include \p b. const ThisType& UnionWith(const ThisType& b) { _FindMin(_min, b._min); _FindMax(_max, b._max); return *this; } /// Extend \p this to include \p b. const ThisType& UnionWith(const MinMaxType& b) { _FindMin(_min, b); _FindMax(_max, b); return *this; } /// Returns the smallest \c ThisType which contains both \p a and \p b /// \deprecated Use GetUnion() instead. static ThisType Union(const ThisType& a, const ThisType& b) { return GetUnion(a, b); } /// Extend \p this to include \p b. /// \deprecated Use UnionWith() instead. const ThisType& Union(const ThisType& b) { return UnionWith(b); } /// Extend \p this to include \p b. /// \deprecated Use UnionWith() instead. const ThisType& Union(const MinMaxType& b) { return UnionWith(b); } /// Returns a \c ThisType that describes the intersection of \p a and \p b. static ThisType GetIntersection(const ThisType& a, const ThisType& b) { auto res = a; _FindMax(res._min, b._min); _FindMin(res._max, b._max); return res; } /// Returns a \c ThisType that describes the intersection of \p a and \p b. /// \deprecated Use GetIntersection() instead. static ThisType Intersection(const ThisType& a, const ThisType& b) { return GetIntersection(a, b); } /// Modifies this range to hold its intersection with \p b and returns the /// result const ThisType& IntersectWith(const ThisType& b) { _FindMax(_min, b._min); _FindMin(_max, b._max); return *this; } /// Modifies this range to hold its intersection with \p b and returns the /// result. /// \deprecated Use IntersectWith() instead. const ThisType& Intersection(const ThisType& b) { return IntersectWith(b); } /// unary sum. ThisType& operator+=(const ThisType& b) { _min += b._min; _max += b._max; return *this; } /// unary difference. ThisType& operator-=(const ThisType& b) { _min -= b._max; _max -= b._min; return *this; } /// unary multiply. ThisType& operator*=(double m) { if (m > 0) { _min *= m; _max *= m; } else { auto tmp = _min; _min = _max * m; _max = tmp * m; } return *this; } /// unary division. ThisType& operator/=(double m) { return *this *= (1.0 / m); } /// binary sum. ThisType operator+(const ThisType& b) const { return ThisType(_min + b._min, _max + b._max); } /// binary difference. ThisType operator-(const ThisType& b) const { return ThisType(_min - b._max, _max - b._min); } /// scalar multiply. friend ThisType operator*(double m, const ThisType& r) { return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m)); } /// scalar multiply. friend ThisType operator*(const ThisType& r, double m) { return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m)); } /// scalar divide. friend ThisType operator/(const ThisType& r, double m) { return r * (1.0 / m); } /// The min and max points must match exactly for equality. bool operator==(const ThisType& b) const { return (_min == b._min && _max == b._max); } bool operator!=(const ThisType& b) const { return !(*this == b); } /// Compute the squared distance from a point to the range. double GetDistanceSquared(const MinMaxType& p) const { double dist = 0.0; if (p[0] < _min[0]) { // p is left of box dist += GfSqr(_min[0] - p[0]); } else if (p[0] > _max[0]) { // p is right of box dist += GfSqr(p[0] - _max[0]); } if (p[1] < _min[1]) { // p is front of box dist += GfSqr(_min[1] - p[1]); } else if (p[1] > _max[1]) { // p is back of box dist += GfSqr(p[1] - _max[1]); } return dist; } /// Returns the ith corner of the range, in the following order: /// SW, SE, NW, NE. MinMaxType GetCorner(size_t i) const { if (i > 3) { return _min; } return MinMaxType((i & 1 ? _max : _min)[0], (i & 2 ? _max : _min)[1]); } /// Returns the ith quadrant of the range, in the following order: /// SW, SE, NW, NE. ThisType GetQuadrant(size_t i) const { if (i > 3) { return {}; } auto a = GetCorner(i); auto b = .5 * (_min + _max); return ThisType( MinMaxType(GfMin(a[0], b[0]), GfMin(a[1], b[1])), MinMaxType(GfMax(a[0], b[0]), GfMax(a[1], b[1]))); } /// The unit square. static constexpr ThisType UnitSquare() { return ThisType(MinMaxType(0), MinMaxType(1)); } private: /// Minimum and maximum points. MinMaxType _min, _max; /// Extends minimum point if necessary to contain given point. static void _FindMin(MinMaxType& dest, const MinMaxType& point) { if (point[0] < dest[0]) { dest[0] = point[0]; } if (point[1] < dest[1]) { dest[1] = point[1]; } } /// Extends maximum point if necessary to contain given point. static void _FindMax(MinMaxType& dest, const MinMaxType& point) { if (point[0] > dest[0]) { dest[0] = point[0]; } if (point[1] > dest[1]) { dest[1] = point[1]; } } }; template <typename T> class range3 { public: static const size_t dimension = 3; using ScalarType = T; using MinMaxType = omni::math::linalg::vec3<T>; using ThisType = range3<T>; range3() = default; constexpr range3(const ThisType&) = default; constexpr explicit range3(ScalarType size) : _min(-size), _max(size) { } /// Sets the range to an empty interval // TODO check whether this can be deprecated. constexpr void inline SetEmpty() { _min = { std::numeric_limits<ScalarType>::max() }; _max = { -std::numeric_limits<ScalarType>::max() }; } /// This constructor initializes the minimum and maximum points. constexpr range3(const MinMaxType& min, const MinMaxType& max) : _min(min), _max(max) { } /// Returns the minimum value of the range. const MinMaxType& GetMin() const { return _min; } /// Returns the maximum value of the range. const MinMaxType& GetMax() const { return _max; } /// Returns the size of the range. MinMaxType GetSize() const { return _max - _min; } /// Returns the midpoint of the range, that is, 0.5*(min+max). /// Note: this returns zero in the case of default-constructed ranges, /// or ranges set via SetEmpty(). MinMaxType GetMidpoint() const { return static_cast<ScalarType>(0.5) * _min + static_cast<ScalarType>(0.5) * _max; } /// Sets the minimum value of the range. void SetMin(const MinMaxType& min) { _min = min; } /// Sets the maximum value of the range. void SetMax(const MinMaxType& max) { _max = max; } /// Returns whether the range is empty (max < min). bool IsEmpty() const { return _min[0] > _max[0] || _min[1] > _max[1] || _min[2] > _max[2]; } /// Modifies the range if necessary to surround the given value. /// \deprecated Use UnionWith() instead. void ExtendBy(const MinMaxType& point) { UnionWith(point); } /// Modifies the range if necessary to surround the given range. /// \deprecated Use UnionWith() instead. void ExtendBy(const ThisType& range) { UnionWith(range); } /// Returns true if the \p point is located inside the range. As with all /// operations of this type, the range is assumed to include its extrema. bool Contains(const MinMaxType& point) const { return (point[0] >= _min[0] && point[0] <= _max[0] && point[1] >= _min[1] && point[1] <= _max[1] && point[2] >= _min[2] && point[2] <= _max[2]); } /// Returns true if the \p range is located entirely inside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. bool Contains(const ThisType& range) const { return Contains(range._min) && Contains(range._max); } /// Returns true if the \p point is located inside the range. As with all /// operations of this type, the range is assumed to include its extrema. /// \deprecated Use Contains() instead. bool IsInside(const MinMaxType& point) const { return Contains(point); } /// Returns true if the \p range is located entirely inside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. /// \deprecated Use Contains() instead. bool IsInside(const ThisType& range) const { return Contains(range); } /// Returns true if the \p range is located entirely outside the range. As /// with all operations of this type, the ranges are assumed to include /// their extrema. bool IsOutside(const ThisType& range) const { return ((range._max[0] < _min[0] || range._min[0] > _max[0]) || (range._max[1] < _min[1] || range._min[1] > _max[1]) || (range._max[2] < _min[2] || range._min[2] > _max[2])); } /// Returns the smallest \c ThisType which contains both \p a and \p b. static ThisType GetUnion(const ThisType& a, const ThisType& b) { ThisType res = a; _FindMin(res._min, b._min); _FindMax(res._max, b._max); return res; } /// Extend \p this to include \p b. const ThisType& UnionWith(const ThisType& b) { _FindMin(_min, b._min); _FindMax(_max, b._max); return *this; } /// Extend \p this to include \p b. const ThisType& UnionWith(const MinMaxType& b) { _FindMin(_min, b); _FindMax(_max, b); return *this; } /// Returns the smallest \c ThisType which contains both \p a and \p b /// \deprecated Use GetUnion() instead. static ThisType Union(const ThisType& a, const ThisType& b) { return GetUnion(a, b); } /// Extend \p this to include \p b. /// \deprecated Use UnionWith() instead. const ThisType& Union(const ThisType& b) { return UnionWith(b); } /// Extend \p this to include \p b. /// \deprecated Use UnionWith() instead. const ThisType& Union(const MinMaxType& b) { return UnionWith(b); } /// Returns a \c ThisType that describes the intersection of \p a and \p b. static ThisType GetIntersection(const ThisType& a, const ThisType& b) { ThisType res = a; _FindMax(res._min, b._min); _FindMin(res._max, b._max); return res; } /// Returns a \c ThisType that describes the intersection of \p a and \p b. /// \deprecated Use GetIntersection() instead. static ThisType Intersection(const ThisType& a, const ThisType& b) { return GetIntersection(a, b); } /// Modifies this range to hold its intersection with \p b and returns the /// result const ThisType& IntersectWith(const ThisType& b) { _FindMax(_min, b._min); _FindMin(_max, b._max); return *this; } /// Modifies this range to hold its intersection with \p b and returns the /// result. /// \deprecated Use IntersectWith() instead. const ThisType& Intersection(const ThisType& b) { return IntersectWith(b); } /// unary sum. ThisType& operator+=(const ThisType& b) { _min += b._min; _max += b._max; return *this; } /// unary difference. ThisType& operator-=(const ThisType& b) { _min -= b._max; _max -= b._min; return *this; } /// unary multiply. ThisType& operator*=(double m) { if (m > 0) { _min *= m; _max *= m; } else { MinMaxType tmp = _min; _min = _max * m; _max = tmp * m; } return *this; } /// unary division. ThisType& operator/=(double m) { return *this *= (1.0 / m); } /// binary sum. ThisType operator+(const ThisType& b) const { return ThisType(_min + b._min, _max + b._max); } /// binary difference. ThisType operator-(const ThisType& b) const { return ThisType(_min - b._max, _max - b._min); } /// scalar multiply. friend ThisType operator*(double m, const ThisType& r) { return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m)); } /// scalar multiply. friend ThisType operator*(const ThisType& r, double m) { return (m > 0 ? ThisType(r._min * m, r._max * m) : ThisType(r._max * m, r._min * m)); } /// scalar divide. friend ThisType operator/(const ThisType& r, double m) { return r * (1.0 / m); } /// The min and max points must match exactly for equality. bool operator==(const ThisType& b) const { return (_min == b._min && _max == b._max); } bool operator!=(const ThisType& b) const { return !(*this == b); } /// Compute the squared distance from a point to the range. double GetDistanceSquared(const MinMaxType& p) const { double dist = 0.0; if (p[0] < _min[0]) { // p is left of box dist += GfSqr(_min[0] - p[0]); } else if (p[0] > _max[0]) { // p is right of box dist += GfSqr(p[0] - _max[0]); } if (p[1] < _min[1]) { // p is front of box dist += GfSqr(_min[1] - p[1]); } else if (p[1] > _max[1]) { // p is back of box dist += GfSqr(p[1] - _max[1]); } if (p[2] < _min[2]) { // p is below of box dist += GfSqr(_min[2] - p[2]); } else if (p[2] > _max[2]) { // p is above of box dist += GfSqr(p[2] - _max[2]); } return dist; } /// Returns the ith corner of the range, in the following order: /// LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF. Where L/R is left/right, /// D/U is down/up, and B/F is back/front. MinMaxType GetCorner(size_t i) const { if (i > 7) { return _min; } return MinMaxType((i & 1 ? _max : _min)[0], (i & 2 ? _max : _min)[1], (i & 4 ? _max : _min)[2]); } /// Returns the ith octant of the range, in the following order: /// LDB, RDB, LUB, RUB, LDF, RDF, LUF, RUF. Where L/R is left/right, /// D/U is down/up, and B/F is back/front. ThisType GetOctant(size_t i) const { if (i > 7) { return {}; } auto a = GetCorner(i); auto b = .5 * (_min + _max); return ThisType(MinMaxType(GfMin(a[0], b[0]), GfMin(a[1], b[1]), GfMin(a[2], b[2])), MinMaxType(GfMax(a[0], b[0]), GfMax(a[1], b[1]), GfMax(a[2], b[2]))); } /// The unit cube. static constexpr const ThisType UnitCube() { return ThisType(MinMaxType(0), MinMaxType(1)); } private: /// Minimum and maximum points. MinMaxType _min, _max; /// Extends minimum point if necessary to contain given point. static void _FindMin(MinMaxType& dest, const MinMaxType& point) { if (point[0] < dest[0]) { dest[0] = point[0]; } if (point[1] < dest[1]) { dest[1] = point[1]; } if (point[2] < dest[2]) { dest[2] = point[2]; } } /// Extends maximum point if necessary to contain given point. static void _FindMax(MinMaxType& dest, const MinMaxType& point) { if (point[0] > dest[0]) { dest[0] = point[0]; } if (point[1] > dest[1]) { dest[1] = point[1]; } if (point[2] > dest[2]) { dest[2] = point[2]; } } }; } } } namespace usdrt { using GfRange1d = omni::math::linalg::range1<double>; using GfRange1f = omni::math::linalg::range1<float>; using GfRange2d = omni::math::linalg::range2<double>; using GfRange2f = omni::math::linalg::range2<float>; using GfRange3d = omni::math::linalg::range3<double>; using GfRange3f = omni::math::linalg::range3<float>; }
omniverse-code/kit/include/usdrt/gf/matrix.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once //! @file //! //! @brief TODO #include <carb/Defines.h> #include <usdrt/gf/defines.h> #include <usdrt/gf/quat.h> #include <usdrt/gf/vec.h> #include <initializer_list> namespace omni { namespace math { namespace linalg { template <typename T, size_t N> class base_matrix { public: using ScalarType = T; static const size_t numRows = N; static const size_t numColumns = N; base_matrix() = default; constexpr base_matrix(const base_matrix<T, N>&) = default; constexpr base_matrix<T, N>& operator=(const base_matrix<T, N>&) = default; // NOTE: Hopefully the compiler can identify that the initializer for v is redundant, // since this constructor is quite useful for constexpr cases. explicit constexpr CUDA_CALLABLE base_matrix(const T m[N][N]) : v{} { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { v[i][j] = m[i][j]; } } } explicit CUDA_CALLABLE base_matrix(T scalar) { SetDiagonal(scalar); } explicit CUDA_CALLABLE base_matrix(const base_vec<T, N>& diagonal) { SetDiagonal(diagonal); } template <typename OTHER_T> explicit CUDA_CALLABLE base_matrix(const base_matrix<OTHER_T, N>& other) { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { v[i][j] = T(other[i][j]); } } } template <typename OTHER_T> CUDA_CALLABLE base_matrix(const std::initializer_list<std::initializer_list<OTHER_T>>& other) : v{} { CUDA_SAFE_ASSERT(other.size() == N); for (size_t i = 0; i < N && i < other.size(); ++i) { CUDA_SAFE_ASSERT(other.begin()[i].size() == N); for (size_t j = 0; j < N && j < other.begin()[i].size(); ++j) { // NOTE: This intentionally doesn't have an explicit cast, so that // the compiler will warn on invalid implicit casts, since this // constructor isn't marked explicit. v[i][j] = other.begin()[i].begin()[j]; } } } CUDA_CALLABLE void SetRow(size_t rowIndex, const base_vec<T, N>& rowValues) { for (size_t col = 0; col < N; ++col) { v[rowIndex][col] = rowValues[col]; } } CUDA_CALLABLE void SetColumn(size_t colIndex, const base_vec<T, N>& colValues) { for (size_t row = 0; row < N; ++row) { v[row][colIndex] = colValues[row]; } } CUDA_CALLABLE base_vec<T, N> GetRow(size_t rowIndex) const { base_vec<T, N> rowValues; for (size_t col = 0; col < N; ++col) { rowValues[col] = v[rowIndex][col]; } return rowValues; } CUDA_CALLABLE base_vec<T, N> GetColumn(size_t colIndex) const { base_vec<T, N> colValues; for (size_t row = 0; row < N; ++row) { colValues[row] = v[row][colIndex]; } return colValues; } CUDA_CALLABLE base_matrix<T, N>& Set(const T m[N][N]) { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { v[i][j] = m[i][j]; } } return *this; } CUDA_CALLABLE base_matrix<T, N>& SetIdentity() { return SetDiagonal(T(1)); } CUDA_CALLABLE base_matrix<T, N>& SetZero() { return SetDiagonal(T(0)); } CUDA_CALLABLE base_matrix<T, N>& SetDiagonal(T scalar) { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { v[i][j] = (i == j) ? scalar : T(0); } } return *this; } CUDA_CALLABLE base_matrix<T, N>& SetDiagonal(const base_vec<T, N>& diagonal) { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { v[i][j] = (i == j) ? diagonal[i] : T(0); } } return *this; } CUDA_CALLABLE T* Get(T m[N][N]) const { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { m[i][j] = v[i][j]; } } return &m[0][0]; } CUDA_CALLABLE T* data() { return &v[0][0]; } CUDA_CALLABLE const T* data() const { return &v[0][0]; } CUDA_CALLABLE T* GetArray() { return &v[0][0]; } CUDA_CALLABLE const T* GetArray() const { return &v[0][0]; } CUDA_CALLABLE T* operator[](size_t row) { return v[row]; } CUDA_CALLABLE const T* operator[](size_t row) const { return v[row]; } // NOTE: To avoid including Boost unless absolutely necessary, hash_value() is not defined here. CUDA_CALLABLE bool operator==(const base_matrix<T, N>& other) const { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { if (v[i][j] != other[i][j]) { return false; } } } return true; } CUDA_CALLABLE bool operator!=(const base_matrix<T, N>& other) const { return !(*this == other); } template <typename OTHER_T> CUDA_CALLABLE bool operator==(const base_matrix<OTHER_T, N>& other) const { for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { if (v[i][j] != other[i][j]) { return false; } } } return true; } template <typename OTHER_T> CUDA_CALLABLE bool operator!=(const base_matrix<OTHER_T, N>& other) const { return !(*this == other); } #ifndef DOXYGEN_BUILD CUDA_CALLABLE base_matrix<T, N> GetTranspose() const { base_matrix<T, N> result; for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { result[i][j] = v[j][i]; } } return result; } #endif // DOXYGEN_BUILD CUDA_CALLABLE base_matrix<T, N>& operator*=(const base_matrix<T, N>& other) { T result[N][N]; for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { T sum = v[row][0] * other[0][col]; for (size_t i = 1; i < N; ++i) { sum += v[row][i] * other[i][col]; } result[row][col] = sum; } } Set(result); return *this; } CUDA_CALLABLE base_matrix<T, N>& operator*=(T scalar) { for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { v[row][col] *= scalar; } } return *this; } #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE base_matrix<T, N> operator*(const base_matrix<T, N>& matrix, T scalar) { base_matrix<T, N> result; for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { result[row][col] = matrix[row][col] * scalar; } } return result; } friend CUDA_CALLABLE base_matrix<T, N> operator*(T scalar, const base_matrix<T, N>& matrix) { return matrix * scalar; } #endif CUDA_CALLABLE base_matrix<T, N>& operator+=(const base_matrix<T, N>& other) { for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { v[row][col] += other[row][col]; } } return *this; } CUDA_CALLABLE base_matrix<T, N>& operator-=(const base_matrix<T, N>& other) { for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { v[row][col] -= other[row][col]; } } return *this; } #ifndef DOXYGEN_BUILD CUDA_CALLABLE base_matrix<T, N> operator-() const { base_matrix<T, N> result; for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { result[row][col] = -v[row][col]; } } return result; } #endif // DOXYGEN_BUILD #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE base_matrix<T, N> operator+(const base_matrix<T, N>& a, const base_matrix<T, N>& b) { base_matrix<T, N> result; for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { result[row][col] = a[row][col] + b[row][col]; } } return result; } friend CUDA_CALLABLE base_matrix<T, N> operator-(const base_matrix<T, N>& a, const base_matrix<T, N>& b) { base_matrix<T, N> result; for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { result[row][col] = a[row][col] - b[row][col]; } } return result; } friend CUDA_CALLABLE base_matrix<T, N> operator*(const base_matrix<T, N>& a, const base_matrix<T, N>& b) { base_matrix<T, N> result(a); result *= b; return result; } // Matrix times column vector friend CUDA_CALLABLE base_vec<T, N> operator*(const base_matrix<T, N>& matrix, const base_vec<T, N>& vec) { base_vec<T, N> result; for (size_t row = 0; row < N; ++row) { T sum = matrix[row][0] * vec[0]; for (size_t col = 1; col < N; ++col) { sum += matrix[row][col] * vec[col]; } result[row] = sum; } return result; } // Row vector times matrix friend CUDA_CALLABLE base_vec<T, N> operator*(const base_vec<T, N>& vec, const base_matrix<T, N>& matrix) { base_vec<T, N> result; T scale = vec[0]; for (size_t col = 0; col < N; ++col) { result[col] = matrix[0][col] * scale; } for (size_t row = 1; row < N; ++row) { T scale = vec[row]; for (size_t col = 0; col < N; ++col) { result[col] += matrix[row][col] * scale; } } return result; } // Matrix times column vector template <typename OTHER_T> friend CUDA_CALLABLE base_vec<OTHER_T, N> operator*(const base_matrix<T, N>& matrix, const base_vec<OTHER_T, N>& vec) { base_vec<OTHER_T, N> result; for (size_t row = 0; row < N; ++row) { OTHER_T sum = matrix[row][0] * vec[0]; for (size_t col = 1; col < N; ++col) { sum += matrix[row][col] * vec[col]; } result[row] = sum; } return result; } // Row vector times matrix template <typename OTHER_T> friend CUDA_CALLABLE base_vec<OTHER_T, N> operator*(const base_vec<OTHER_T, N>& vec, const base_matrix<T, N>& matrix) { base_vec<OTHER_T, N> result; OTHER_T scale = vec[0]; for (size_t col = 0; col < N; ++col) { result[col] = matrix[0][col] * scale; } for (size_t row = 1; row < N; ++row) { OTHER_T scale = vec[row]; for (size_t col = 0; col < N; ++col) { result[col] += matrix[row][col] * scale; } } return result; } #endif protected: T v[N][N]; }; template <typename T, size_t N> CUDA_CALLABLE bool GfIsClose(const base_matrix<T, N>& a, const base_matrix<T, N>& b, double tolerance) { for (size_t row = 0; row < N; ++row) { for (size_t col = 0; col < N; ++col) { const T diff = a[row][col] - b[row][col]; const T absDiff = (diff < T(0)) ? -diff : diff; // NOTE: This condition looks weird, but it's so that NaN values in // either matrix will yield false. if (!(absDiff <= tolerance)) { return false; } } } return true; } template <typename T> class matrix2 : public base_matrix<T, 2> { public: using base_type = base_matrix<T, 2>; using this_type = matrix2<T>; using base_matrix<T, 2>::base_matrix; using base_type::operator[]; using base_type::operator==; using base_type::operator!=; using base_type::data; using base_type::Get; using base_type::GetArray; using base_type::SetColumn; using base_type::SetRow; using ScalarType = T; using base_type::numColumns; using base_type::numRows; matrix2() = default; constexpr matrix2(const this_type&) = default; constexpr this_type& operator=(const this_type&) = default; // Implicit conversion from base_type CUDA_CALLABLE matrix2(const base_type& other) : base_type(other) { } template <typename OTHER_T> explicit CUDA_CALLABLE matrix2(const matrix2<OTHER_T>& other) : base_type(static_cast<const base_matrix<OTHER_T, numRows>&>(other)) { } CUDA_CALLABLE matrix2(T v00, T v01, T v10, T v11) { Set(v00, v01, v10, v11); } CUDA_CALLABLE this_type& Set(const T m[numRows][numColumns]) { base_type::Set(m); return *this; } CUDA_CALLABLE this_type& Set(T v00, T v01, T v10, T v11) { T v[2][2] = { { v00, v01 }, { v10, v11 } }; return Set(v); } CUDA_CALLABLE this_type& SetIdentity() { base_type::SetIdentity(); return *this; } CUDA_CALLABLE this_type& SetZero() { base_type::SetZero(); return *this; } CUDA_CALLABLE this_type& SetDiagonal(T scalar) { base_type::SetDiagonal(scalar); return *this; } CUDA_CALLABLE this_type& SetDiagonal(const base_vec<T, numRows>& diagonal) { base_type::SetDiagonal(diagonal); return *this; } CUDA_CALLABLE this_type GetTranspose() const { return this_type(base_type::GetTranspose()); } CUDA_CALLABLE this_type GetInverse(T* det = nullptr, T epsilon = T(0)) const { T determinant = GetDeterminant(); if (det != nullptr) { *det = determinant; } T absDeterminant = (determinant < 0) ? -determinant : determinant; // This unusual writing of the condition should catch NaNs. if (!(absDeterminant > epsilon)) { // Return the zero matrix, instead of a huge matrix, // so that multiplying by this is less likely to be catastrophic. return this_type(T(0)); } T inverse[2][2] = { { v[1][1] / determinant, -v[0][1] / determinant }, { -v[1][0] / determinant, v[0][0] / determinant } }; return this_type(inverse); } CUDA_CALLABLE T GetDeterminant() const { return v[0][0] * v[1][1] - v[0][1] * v[1][0]; } CUDA_CALLABLE this_type& operator*=(const base_type& other) { base_type::operator*=(other); return *this; } CUDA_CALLABLE this_type& operator*=(T scalar) { base_type::operator*=(scalar); return *this; } CUDA_CALLABLE this_type& operator+=(const base_type& other) { base_type::operator+=(other); return *this; } CUDA_CALLABLE this_type& operator-=(const base_type& other) { base_type::operator-=(other); return *this; } CUDA_CALLABLE this_type operator-() const { return this_type(base_type::operator-()); } #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE this_type operator/(const this_type& a, const this_type& b) { return a * b.GetInverse(); } #endif // DOXYGEN_BUILD private: using base_type::v; }; template <typename T> class matrix3 : public base_matrix<T, 3> { public: using base_type = base_matrix<T, 3>; using this_type = matrix3<T>; using base_matrix<T, 3>::base_matrix; using base_type::operator[]; using base_type::operator==; using base_type::operator!=; using base_type::data; using base_type::Get; using base_type::GetArray; using base_type::SetColumn; using base_type::SetRow; using ScalarType = T; using base_type::numColumns; using base_type::numRows; matrix3() = default; constexpr matrix3(const this_type&) = default; constexpr this_type& operator=(const this_type&) = default; // Implicit conversion from base_type CUDA_CALLABLE matrix3(const base_type& other) : base_type(other) { } template <typename OTHER_T> explicit CUDA_CALLABLE matrix3(const matrix3<OTHER_T>& other) : base_type(static_cast<const base_matrix<OTHER_T, numRows>&>(other)) { } CUDA_CALLABLE matrix3(T v00, T v01, T v02, T v10, T v11, T v12, T v20, T v21, T v22) { Set(v00, v01, v02, v10, v11, v12, v20, v21, v22); } CUDA_CALLABLE this_type& Set(const T m[numRows][numColumns]) { base_type::Set(m); return *this; } CUDA_CALLABLE this_type& Set(T v00, T v01, T v02, T v10, T v11, T v12, T v20, T v21, T v22) { T v[3][3] = { { v00, v01, v02 }, { v10, v11, v12 }, { v20, v21, v22 } }; return Set(v); } CUDA_CALLABLE this_type& SetIdentity() { base_type::SetIdentity(); return *this; } CUDA_CALLABLE this_type& SetZero() { base_type::SetZero(); return *this; } CUDA_CALLABLE this_type& SetDiagonal(T scalar) { base_type::SetDiagonal(scalar); return *this; } CUDA_CALLABLE this_type& SetDiagonal(const base_vec<T, numRows>& diagonal) { base_type::SetDiagonal(diagonal); return *this; } CUDA_CALLABLE this_type GetTranspose() const { return this_type(base_type::GetTranspose()); } CUDA_CALLABLE this_type GetInverse(T* det = nullptr, T epsilon = T(0)) const { T determinant = GetDeterminant(); if (det != nullptr) { *det = determinant; } T absDeterminant = (determinant < 0) ? -determinant : determinant; // This unusual writing of the condition should catch NaNs. if (!(absDeterminant > epsilon)) { // Return the zero matrix, instead of a huge matrix, // so that multiplying by this is less likely to be catastrophic. return this_type(T(0)); } // TODO: If compilers have difficulty optimizing this, inline the calculations. const vec3<T> row0 = GfCross(vec3<T>(v[1]), vec3<T>(v[2])); const vec3<T> row1 = GfCross(vec3<T>(v[2]), vec3<T>(v[0])); const vec3<T> row2 = GfCross(vec3<T>(v[0]), vec3<T>(v[1])); const T recip = T(1) / determinant; return this_type(row0[0], row0[1], row0[2], row1[0], row1[1], row1[2], row2[0], row2[1], row2[2]) * recip; } CUDA_CALLABLE T GetDeterminant() const { // Scalar triple product // TODO: If compilers have difficulty optimizing this, inline the calculations. return vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[2]))); } CUDA_CALLABLE bool Orthonormalize() { vec3<T> rows[3] = { vec3<T>(v[0]), vec3<T>(v[1]), vec3<T>(v[2]) }; bool success = GfOrthogonalizeBasis(&rows[0], &rows[1], &rows[2]); if (success) { // TODO: Should this check for a negative determinant and flip 1 or all 3 axes, // to force this to be a rotation matrix? for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 3; ++j) { v[i][j] = rows[i][j]; } } } return success; } CUDA_CALLABLE this_type GetOrthonormalized() const { this_type result(*this); result.Orthonormalize(); return result; } CUDA_CALLABLE int GetHandedness() const { T det = GetDeterminant(); return (det < T(0)) ? -1 : ((det > T(0)) ? 1 : 0); } CUDA_CALLABLE bool IsRightHanded() const { return GetHandedness() == 1; } CUDA_CALLABLE bool IsLeftHanded() const { return GetHandedness() == -1; } CUDA_CALLABLE this_type& operator*=(const base_type& other) { base_type::operator*=(other); return *this; } CUDA_CALLABLE this_type& operator*=(T scalar) { base_type::operator*=(scalar); return *this; } CUDA_CALLABLE this_type& operator+=(const base_type& other) { base_type::operator+=(other); return *this; } CUDA_CALLABLE this_type& operator-=(const base_type& other) { base_type::operator-=(other); return *this; } CUDA_CALLABLE this_type operator-() const { return this_type(base_type::operator-()); } #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE this_type operator/(const this_type& a, const this_type& b) { return a * b.GetInverse(); } #endif // DOXYGEN_BUILD CUDA_CALLABLE this_type& SetScale(T scale) { return SetDiagonal(scale); } CUDA_CALLABLE this_type& SetScale(const base_vec<T, numRows>& scales) { return SetDiagonal(scales); } // NOTE: The input quaternion must be normalized (length 1). // NOTE: This may or may not represent the rotation matrix for the opposite rotation, // due to interpretations of left-to-right vs. right-to-left multiplication. CUDA_CALLABLE this_type& SetRotate(const quat<double>& rotation) { const double w = rotation.GetReal(); const vec3<double> xyz = rotation.GetImaginary(); const double x = xyz[0]; const double y = xyz[1]; const double z = xyz[2]; const double x2 = x * x; const double y2 = y * y; const double z2 = z * z; const double xy = x * y; const double xz = x * z; const double yz = y * z; const double xw = x * w; const double yw = y * w; const double zw = z * w; const T m[3][3] = { { T(1 - 2 * (y2 + z2)), 2 * T(xy + zw), 2 * T(xz - yw) }, { 2 * T(xy - zw), T(1 - 2 * (x2 + z2)), 2 * T(yz + xw) }, { 2 * T(xz + yw), 2 * T(yz - xw), T(1 - 2 * (x2 + y2)) } }; return Set(m); } // NOTE: This must already be a rotation matrix (i.e. orthonormal rows and columns, // and positive determinant.) // NOTE: This may or may not represent the quaternion for the transpose, // due to interpretations of left-to-right vs. right-to-left multiplication. CUDA_CALLABLE quat<double> ExtractRotation() const { double diag[3] = { v[0][0], v[1][1], v[2][2] }; double trace = diag[0] + diag[1] + diag[2]; double real; vec3d imaginary; if (trace >= 0) { // Non-negative trace corresponds with a rotation of at most 120 degrees. real = 0.5 * sqrt(1.0 + trace); double scale = 0.25 / real; imaginary = scale * vec3d(v[1][2] - v[2][1], v[2][0] - v[0][2], v[0][1] - v[1][0]); } else { // Negative trace corresponds with a rotation of more than 120 degrees. // Use a different approach to reduce instability and risk of dividing by something near or equal zero. // Find the largest diagonal value. size_t index0 = (diag[0] >= diag[1]) ? 0 : 1; index0 = (diag[index0] >= diag[2]) ? index0 : 2; size_t index1 = (index0 == 2) ? 0 : (index0 + 1); size_t index2 = (index1 == 2) ? 0 : (index1 + 1); double large = 0.5 * sqrt(1 + diag[index0] - diag[index1] - diag[index2]); double scale = 0.25 / large; real = scale * (v[index1][index2] - v[index2][index1]); imaginary[index0] = large; imaginary[index1] = scale * (v[index0][index1] + v[index1][index0]); imaginary[index2] = scale * (v[index0][index2] + v[index2][index0]); } return quat<double>(real, imaginary); } private: using base_type::v; }; template <typename T> class matrix4 : public base_matrix<T, 4> { public: using base_type = base_matrix<T, 4>; using this_type = matrix4<T>; using base_matrix<T, 4>::base_matrix; using base_type::operator[]; using base_type::operator==; using base_type::operator!=; using base_type::data; using base_type::Get; using base_type::GetArray; using base_type::SetColumn; using base_type::SetRow; using ScalarType = T; using base_type::numColumns; using base_type::numRows; matrix4() = default; constexpr matrix4(const this_type&) = default; constexpr this_type& operator=(const this_type&) = default; // Implicit conversion from base_type CUDA_CALLABLE matrix4(const base_type& other) : base_type(other) { } template <typename OTHER_T> explicit CUDA_CALLABLE matrix4(const matrix4<OTHER_T>& other) : base_type(static_cast<const base_matrix<OTHER_T, numRows>&>(other)) { } CUDA_CALLABLE matrix4( T v00, T v01, T v02, T v03, T v10, T v11, T v12, T v13, T v20, T v21, T v22, T v23, T v30, T v31, T v32, T v33) { Set(v00, v01, v02, v03, v10, v11, v12, v13, v20, v21, v22, v23, v30, v31, v32, v33); } CUDA_CALLABLE this_type& Set(const T m[numRows][numColumns]) { base_type::Set(m); return *this; } CUDA_CALLABLE this_type& Set( T v00, T v01, T v02, T v03, T v10, T v11, T v12, T v13, T v20, T v21, T v22, T v23, T v30, T v31, T v32, T v33) { T v[4][4] = { { v00, v01, v02, v03 }, { v10, v11, v12, v13 }, { v20, v21, v22, v23 }, { v30, v31, v32, v33 } }; return Set(v); } CUDA_CALLABLE this_type& SetIdentity() { base_type::SetIdentity(); return *this; } CUDA_CALLABLE this_type& SetZero() { base_type::SetZero(); return *this; } CUDA_CALLABLE this_type& SetDiagonal(T scalar) { base_type::SetDiagonal(scalar); return *this; } CUDA_CALLABLE this_type& SetDiagonal(const base_vec<T, numRows>& diagonal) { base_type::SetDiagonal(diagonal); return *this; } CUDA_CALLABLE this_type GetTranspose() const { return this_type(base_type::GetTranspose()); } // TODO: Optimize this. The implementation is not as efficient as it could be. // For example, it computes the 4x4 determinant separately from the rest. CUDA_CALLABLE this_type GetInverse(T* det = nullptr, T epsilon = T(0)) const { T determinant = GetDeterminant(); if (det != nullptr) { *det = determinant; } T absDeterminant = (determinant < 0) ? -determinant : determinant; // This unusual writing of the condition should catch NaNs. if (!(absDeterminant > epsilon)) { // Return the zero matrix, instead of a huge matrix, // so that multiplying by this is less likely to be catastrophic. return this_type(T(0)); } // Compute all 2x2 determinants. // There are only actually 6x6 of them: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3) for row pairs and col pairs. constexpr size_t pairIndices[6][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 2 }, { 1, 3 }, { 2, 3 } }; T det2x2[6][6]; // NOTE: The first 3 row pairs are never used, below, so we can skip computing them. for (size_t rowpair = 3; rowpair < 6; ++rowpair) { const size_t row0 = pairIndices[rowpair][0]; const size_t row1 = pairIndices[rowpair][1]; for (size_t colpair = 0; colpair < 6; ++colpair) { const size_t col0 = pairIndices[colpair][0]; const size_t col1 = pairIndices[colpair][1]; det2x2[rowpair][colpair] = v[row0][col0] * v[row1][col1] - v[row0][col1] * v[row1][col0]; } } // Compute all 3x3 determinants. // There is one for every row-col pair. constexpr size_t oneIndexRemoved4[4][3] = { { 1, 2, 3 }, { 0, 2, 3 }, { 0, 1, 3 }, { 0, 1, 2 } }; constexpr size_t twoIndicesRemovedToPair[4][3] = { { 5, 4, 3 }, { 5, 2, 1 }, { 4, 2, 0 }, { 3, 1, 0 } }; T adjugate[4][4]; for (size_t omittedRow = 0; omittedRow < 4; ++omittedRow) { for (size_t omittedCol = 0; omittedCol < 4; ++omittedCol) { size_t iterationRow = oneIndexRemoved4[omittedRow][0]; // The first entry in each subarray of twoIndicesRemovedToPair is 3, 4, or 5, // regardless of omittedRow, which is why we didn't need to compute det2x2 for // any rowpair less than 3, above. size_t rowpair = twoIndicesRemovedToPair[omittedRow][0]; T sum = T(0); for (size_t subCol = 0; subCol < 3; ++subCol) { size_t iterationCol = oneIndexRemoved4[omittedCol][subCol]; size_t colpair = twoIndicesRemovedToPair[omittedCol][subCol]; const T& factor = v[iterationRow][iterationCol]; T value = factor * det2x2[rowpair][colpair]; sum += (subCol & 1) ? -value : value; } // The adjugate matrix is the transpose of the cofactor matrix, so row and col are swapped here. adjugate[omittedCol][omittedRow] = ((omittedRow ^ omittedCol) & 1) ? -sum : sum; } } // Divide by the 4x4 determinant. for (size_t row = 0; row < 4; ++row) { for (size_t col = 0; col < 4; ++col) { adjugate[row][col] /= determinant; } } return this_type(adjugate); } CUDA_CALLABLE T GetDeterminant() const { T sum = 0; // It's *very* common that the first 3 components of the last column are all zero, // so skip over them. if (v[0][3] != 0) { sum -= v[0][3] * vec3<T>(v[1]).Dot(GfCross(vec3<T>(v[2]), vec3<T>(v[3]))); } if (v[1][3] != 0) { sum += v[1][3] * vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[2]), vec3<T>(v[3]))); } if (v[2][3] != 0) { sum -= v[2][3] * vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[3]))); } if (v[3][3] != 0) { sum += v[3][3] * vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[2]))); } return sum; } CUDA_CALLABLE T GetDeterminant3() const { // Scalar triple product return vec3<T>(v[0]).Dot(GfCross(vec3<T>(v[1]), vec3<T>(v[2]))); } CUDA_CALLABLE int GetHandedness() const { T det = GetDeterminant3(); return (det < T(0)) ? -1 : ((det > T(0)) ? 1 : 0); } CUDA_CALLABLE bool Orthonormalize() { vec3<T> rows[3] = { vec3<T>(v[0][0], v[0][1], v[0][2]), vec3<T>(v[1][0], v[1][1], v[1][2]), vec3<T>(v[2][0], v[2][1], v[2][2]) }; bool success = GfOrthogonalizeBasis(&rows[0], &rows[1], &rows[2]); // TODO: Should this check for a negative determinant and flip 1 or all 3 axes, // to force this to be a rotation matrix? for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 3; ++j) { v[i][j] = rows[i][j]; } } const double minVectorLength = 1e-10; if (v[3][3] != 1.0 && !GfIsClose(v[3][3], 0.0, minVectorLength)) { v[3][0] /= v[3][3]; v[3][1] /= v[3][3]; v[3][2] /= v[3][3]; v[3][3] = 1.0; } return success; } CUDA_CALLABLE this_type GetOrthonormalized() const { this_type result(*this); result.Orthonormalize(); return result; } CUDA_CALLABLE this_type& operator*=(const base_type& other) { base_type::operator*=(other); return *this; } CUDA_CALLABLE this_type& operator*=(T scalar) { base_type::operator*=(scalar); return *this; } CUDA_CALLABLE this_type& operator+=(const base_type& other) { base_type::operator+=(other); return *this; } CUDA_CALLABLE this_type& operator-=(const base_type& other) { base_type::operator-=(other); return *this; } CUDA_CALLABLE this_type operator-() const { return this_type(base_type::operator-()); } #ifndef DOXYGEN_BUILD friend CUDA_CALLABLE this_type operator/(const this_type& a, const this_type& b) { return a * b.GetInverse(); } #endif // DOXYGEN_BUILD CUDA_CALLABLE this_type& SetScale(T scale) { return SetDiagonal(vec4<T>(scale, scale, scale, T(1))); } CUDA_CALLABLE this_type& SetScale(const vec3<T>& scales) { return SetDiagonal(vec4<T>(scales[0], scales[1], scales[2], T(1))); } CUDA_CALLABLE this_type RemoveScaleShear() const { vec3<T> rows[3] = { vec3<T>(v[0]), vec3<T>(v[1]), vec3<T>(v[2]) }; bool success = GfOrthogonalizeBasis(&rows[0], &rows[1], &rows[2]); if (!success) { return *this; } // Scalar triple product is determinant of 3x3 matrix, (which should be about -1 or 1 // after orthonormalizing the vectors.) if (rows[0].Dot(GfCross(rows[1], rows[2])) < 0) { // Negative determinant, so invert one of the axes. // TODO: Is it better to invert all 3 axes? rows[2] = -rows[2]; } return matrix4<T>(rows[0][0], rows[0][1], rows[0][2], 0.0f, rows[1][0], rows[1][1], rows[1][2], 0.0f, rows[2][0], rows[2][1], rows[2][2], 0.0f, v[3][0], v[3][1], v[3][2], 1.0f); } CUDA_CALLABLE this_type& SetRotate(const quat<double>& rotation) { matrix3<T> m3; m3.SetRotate(rotation); return SetRotate(m3); } CUDA_CALLABLE this_type& SetRotateOnly(const quat<double>& rotation) { matrix3<T> m3; m3.SetRotate(rotation); return SetRotateOnly(m3); } // NOTE: Contrary to the name, this sets the full 3x3 portion of the matrix, // i.e. it also sets scales and shears. // NOTE: This clears any translations. CUDA_CALLABLE this_type& SetRotate(const matrix3<T>& m3) { for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 3; ++j) { v[i][j] = m3[i][j]; } v[i][3] = T(0); } v[3][0] = T(0); v[3][1] = T(0); v[3][2] = T(0); v[3][3] = T(1); return *this; } // NOTE: Contrary to the name, this sets the full 3x3 portion of the matrix, // i.e. it also sets scales and shears. // NOTE: This does NOT clear any translations. CUDA_CALLABLE this_type& SetRotateOnly(const matrix3<T>& m3) { for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 3; ++j) { v[i][j] = m3[i][j]; } } return *this; } CUDA_CALLABLE this_type& SetTranslate(const vec3<T>& translation) { for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 4; ++j) { v[i][j] = (i == j) ? T(1) : T(0); } } v[3][0] = translation[0]; v[3][1] = translation[1]; v[3][2] = translation[2]; v[3][3] = T(1); return *this; } CUDA_CALLABLE this_type& SetTranslateOnly(const vec3<T>& translation) { v[3][0] = translation[0]; v[3][1] = translation[1]; v[3][2] = translation[2]; v[3][3] = T(1); return *this; } CUDA_CALLABLE void SetRow3(size_t rowIndex, const vec3<T>& rowValues) { v[rowIndex][0] = rowValues[0]; v[rowIndex][1] = rowValues[1]; v[rowIndex][2] = rowValues[2]; } CUDA_CALLABLE vec3<T> GetRow3(size_t rowIndex) { return vec3<T>(v[rowIndex][0], v[rowIndex][1], v[rowIndex][2]); } CUDA_CALLABLE this_type& SetLookAt(const vec3<T>& cameraPosition, const vec3<T>& focusPosition, const vec3<T>& upDirection) { // NOTE: forward is the negative z direction. vec3<T> forward = (focusPosition - cameraPosition).GetNormalized(); // Force up direction to be orthogonal to forward. // NOTE: up is the positive y direction. vec3<T> up = upDirection.GetComplement(forward).GetNormalized(); // NOTE: right is the positive x direction. vec3<T> right = GfCross(forward, up); // Pre-translation by -cameraPosition vec3<T> translation(-right.Dot(cameraPosition), -up.Dot(cameraPosition), forward.Dot(cameraPosition)); T m[4][4] = { { right[0], up[0], -forward[0], T(0) }, { right[1], up[1], -forward[1], T(0) }, { right[2], up[2], -forward[2], T(0) }, { translation[0], translation[1], translation[2], T(1) } }; return Set(m); } CUDA_CALLABLE this_type& SetLookAt(const vec3<T>& cameraPosition, const quat<double>& orientation) { matrix4<T> translation; translation.SetTranslate(-cameraPosition); matrix4<T> rotation; rotation.SetRotate(orientation.GetInverse()); *this = translation * rotation; return *this; } CUDA_CALLABLE vec3<T> ExtractTranslation() const { return vec3<T>(v[3][0], v[3][1], v[3][2]); } CUDA_CALLABLE quat<double> ExtractRotation() const { return ExtractRotationMatrix().ExtractRotation(); } // NOTE: Contrary to the name, this extracts the full 3x3 portion of the matrix, // i.e. it also includes scales and shears. CUDA_CALLABLE matrix3<T> ExtractRotationMatrix() const { return matrix3<T>(v[0][0], v[0][1], v[0][2], v[1][0], v[1][1], v[1][2], v[2][0], v[2][1], v[2][2]); } template <typename OTHER_T> CUDA_CALLABLE vec3<OTHER_T> Transform(const vec3<OTHER_T>& u) const { return vec3<OTHER_T>(vec4<T>(u[0] * v[0][0] + u[1] * v[1][0] + u[2] * v[2][0] + v[3][0], u[0] * v[0][1] + u[1] * v[1][1] + u[2] * v[2][1] + v[3][1], u[0] * v[0][2] + u[1] * v[1][2] + u[2] * v[2][2] + v[3][2], u[0] * v[0][3] + u[1] * v[1][3] + u[2] * v[2][3] + v[3][3]) .Project()); } template <typename OTHER_T> CUDA_CALLABLE vec3<OTHER_T> TransformDir(const vec3<OTHER_T>& u) const { return vec3<OTHER_T>(OTHER_T(u[0] * v[0][0] + u[1] * v[1][0] + u[2] * v[2][0]), OTHER_T(u[0] * v[0][1] + u[1] * v[1][1] + u[2] * v[2][1]), OTHER_T(u[0] * v[0][2] + u[1] * v[1][2] + u[2] * v[2][2])); } template <typename OTHER_T> CUDA_CALLABLE vec3<OTHER_T> TransformAffine(const vec3<OTHER_T>& u) const { return vec3<OTHER_T>(OTHER_T(u[0] * v[0][0] + u[1] * v[1][0] + u[2] * v[2][0] + v[3][0]), OTHER_T(u[0] * v[0][1] + u[1] * v[1][1] + u[2] * v[2][1] + v[3][1]), OTHER_T(u[0] * v[0][2] + u[1] * v[1][2] + u[2] * v[2][2] + v[3][2])); } private: using base_type::v; }; using matrix2f = matrix2<float>; using matrix2d = matrix2<double>; using matrix3f = matrix3<float>; using matrix3d = matrix3<double>; using matrix4f = matrix4<float>; using matrix4d = matrix4<double>; } } } namespace usdrt { using omni::math::linalg::GfIsClose; using GfMatrix3d = omni::math::linalg::matrix3<double>; using GfMatrix3f = omni::math::linalg::matrix3<float>; using GfMatrix4d = omni::math::linalg::matrix4<double>; using GfMatrix4f = omni::math::linalg::matrix4<float>; }
omniverse-code/kit/include/usdrt/gf/README.md
usdrt::Gf ========= The usdrt::Gf library is a strategic re-namespacing and type aliasing of omni\:\:math\:\:linalg in support of the ongoing Omniverse runtime initiative. This allows us to maintain parity between C++ class names (ex: `usdrt::GfVec3d`) and Python class names (ex: `usdrt.Gf.Vec3d`) for code that integrates the forthcoming USDRT libraries. These are intended to be pin-compatible replacements for their USD equivalents, without the associated overhead (no USD library or other dependencies, no boost). C++ functionality ----------------- These types are aliased in the usdrt namespace: - GfHalf - GfMatrix(3/4)(d/f/h) - GfQuat(d/f/h) - GfVec(2/3/4)(d/f/h/i) - GfRange(1/2/3)(d/f) - GfRect2i These functions are aliased in the usdrt namespace: - GfCompDiv - GfCompMult - GfCross - GfDegreesToRadians - GfDot - GfGetComplement - GfGetLength - GfGetNormalized - GfGetProjection - GfIsClose - GfLerp - GfMax - GfMin - GfNormalize - GfRadiansToDegrees - GfSlerp Note that pointers to usdrt Gf types can be safely reinterpret_cast to pointers of equivalent pxr Gf types and other types with matching memory layouts: ``` pxr::GfVec3d pxrVec(1.0, 2.0, 3.0); usdrt::GfVec3d rtVec(*reinterpret_cast<usdrt::GfVec3d*>(&pxrVec)); assert(rtVec[0] == 1.0); assert(rtVec[1] == 2.0); assert(rtVec[2] == 3.0); ``` pybind11 Python bindings ------------------------ Python bindings using pybind11 for these classes can be found in `source/bindings/python/usdrt.Gf`. The python bindings deliver these classes in the usdrt package: - Gf.Matrix(3/4)(d/f/h) - Gf.Quat(d/f/h) - Gf.Vec(2/3/4)(d/f/h/i) - Gf.Range(1/2/3)(d/f) - Gf.Rect2i Like in USD, usdrt::GfHalf is transparently converted to and from double, which is Python's preferred floating point representation. usdrt.Gf classes implement the python buffer protocol, so they can be initialized from other types that also implement the buffer protocol, including Pixar's Gf types and numpy. ``` import pxr, usdrt pxr_vec = pxr.Gf.Vec3d(1.0, 2.0, 3.0) rt_vec = usdrt.Gf.Vec3d(pxr_vec) assert rt_vec[0] == 1.0 assert rt_vec[1] == 2.0 assert rt_vec[2] == 3.0 ```
omniverse-code/kit/include/omni/StringView.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 Implementation of \ref omni::span #pragma once #include "../carb/cpp/StringView.h" namespace omni { //! @copydoc carb::cpp::string_view using string_view = ::carb::cpp::string_view; //! @copydoc carb::cpp::wstring_view using wstring_view = ::carb::cpp::wstring_view; #if CARB_HAS_CPP20 //! basic_string_view<char8_t> //! @see basic_string_view using u8string_view = ::carb::cpp::u8string_view; #endif //! @copydoc carb::cpp::u16string_view using u16string_view = ::carb::cpp::u16string_view; //! @copydoc carb::cpp::u32string_view using u32string_view = ::carb::cpp::u32string_view; } // namespace omni
omniverse-code/kit/include/omni/Function.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 Implementation of \c omni::function. #pragma once #include <functional> #include "detail/FunctionImpl.h" #include "../carb/detail/NoexceptType.h" namespace omni { //! Thrown when \c function::operator() is called but the function is unbound. using std::bad_function_call; //! \cond DEV template <typename Signature> class function; //! \endcond //! A polymorphic function wrapper which is compatible with \c std::function. //! //! For most usage, it is equivalent to the \c std::function API, but there are a few minor changes for ABI stability //! and C interoperation. //! //! * The \c target and \c target_type functions are not available. These rely on RTTI, which is not required for //! Omniverse builds and is not ABI safe. //! * No support for allocators, as these were removed in C++17. The \c carbReallocate function is used for all memory //! management needs. //! * A local buffer for storing functors. While the C++ Standard encourages this, this implementation keeps the size //! and alignment fixed. //! * An \c omni::function is trivially-relocatable. template <typename TReturn, typename... TArgs> class function<TReturn(TArgs...)> : private ::omni::detail::FunctionData { using base_type = ::omni::detail::FunctionData; using traits = ::omni::detail::FunctionTraits<TReturn(TArgs...)>; public: //! The return type of this function. using result_type = typename traits::result_type; public: //! Create an unbound instance. function(std::nullptr_t) noexcept : base_type(nullptr) { } //! Create an unbound instance. function() noexcept : function(nullptr) { } //! Create an instance as a copy of \a other. //! //! If \a other was bound before the call, then the created instance will be bound to the same target. function(function const& other) = default; //! Create an instance by moving from \a other. //! //! If \a other was bound before the call, then the created instance will be bound to the same target. After this //! call, \a other will be unbound. function(function&& other) noexcept = default; //! Reset this function wrapper to unbound. function& operator=(std::nullptr_t) noexcept { reset(); return *this; } //! Copy the \a other instance into this one. //! //! If copying the function fails, both instances will remain unchanged. function& operator=(function const& other) = default; //! Move the \a other instance into this one. function& operator=(function&& other) noexcept = default; CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE() //! The binding constructor for function, which wraps \a f for invocation. //! //! The created instance will have a "target type" (referred to as \c Target here) of \c std::decay_t<Target> which //! is responsible for invoking the function. The following descriptions use a common set of symbols to describe //! types: //! //! * \c UReturn -- A return type which is the same as or implicitly convertible from \c TReturn. If \c UReturn //! is \c void, then \c TReturn must be implicitly discardable. //! * \c UArgs... -- An argument pack where all arguments are implicitly convertible to \c TArgs... . //! * \c UArg0Obj -- The object type of the possibly-dereferenced first type in the \c TArgs... pack. In other //! words, if \c TArgs... was `{Object*, int}`, then \c UArg0Obj would be \c Object. Any cv-qualifiers follow the //! dereference (e.g.: if \c TArg0 is `Object const*`, then \c UArg0Obj is `Object const`). //! * \c UArg1N... -- Same as \c UArgs... but do not include the first type in the pack. //! //! The \c Target can be one of the following: //! //! 1. A function pointer -- \c UReturn(*)(UArgs...) //! 2. A pointer to a member function -- `UReturn UArg0Obj::*(UArg1N...)` //! 3. A pointer to member data -- `UReturn UArg0Obj::*` when `sizeof(TArgs...) == 1` //! 4. Another `omni::function` -- `omni::function<UReturn(UArgs...)>` where \c UReturn and \c UArgs... are //! different from \c TReturn and \c TArgs... (the exact same type uses a copy or move operation) //! 5. An `std::function` -- `std::function<UReturn(UArgs...)>`, but \c UReturn and \c UArgs... can all match //! \c TReturn and \c TArgs... //! 6. A functor with \c operator() accepting \c UArgs... and returning \c UReturn //! //! If the \c Target does not match any of preceding possibilities, this function does not participate in overload //! resolution in a SFINAE-safe manner. If \c Target is non-copyable, then the program is ill-formed. //! //! For cases 1-5, if `f == nullptr`, then the function is initialized as unbound. Note the quirky case on #6, where //! the composite `omni::function<void()>{std::function<void()>{}}` will create an unbound function. But this is not //! commutative, as `std::function<void()>{omni::function<void()>{}}` will create a bound function which throws when //! called. template <typename F, typename Assigner = ::omni::detail::FunctionAssigner<traits, F>> function(F&& f) : base_type(Assigner{}, std::forward<F>(f)) { } //! Bind this instance to \a f according to the rules in the binding constructor. //! //! If the process of binding a \c function to \a f fails, this instance will remain unchanged. template <typename F, typename Assigner = ::omni::detail::FunctionAssigner<traits, F>> function& operator=(F&& f) { return operator=(function{ std::forward<F>(f) }); } CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE() //! If this function has context it needs to destroy, then perform that cleanup. ~function() noexcept = default; //! Invoke this function with the provided \a args. //! //! If this function is not bound (see `operator bool() const`), the program will throw \c bad_function_call if //! exceptions are enabled or panic if they are not. TReturn operator()(TArgs... args) const { if (m_trampoline == nullptr) ::omni::detail::null_function_call(); auto f = reinterpret_cast<TReturn (*)(::omni::detail::FunctionBuffer const*, TArgs...)>(m_trampoline); return f(&m_buffer, std::forward<TArgs>(args)...); } //! Check that this function is bound. explicit operator bool() const noexcept { return bool(m_trampoline); } //! Swap the contents of \a other with this one. void swap(function& other) noexcept { base_type::swap(other); } }; //! Check if \a func is not activated. template <typename TReturn, typename... TArgs> bool operator==(function<TReturn(TArgs...)> const& func, std::nullptr_t) noexcept { return !func; } //! Check if \a func is not activated. template <typename TReturn, typename... TArgs> bool operator==(std::nullptr_t, function<TReturn(TArgs...)> const& func) noexcept { return !func; } //! Check if \a func is activated. template <typename TReturn, typename... TArgs> bool operator!=(function<TReturn(TArgs...)> const& func, std::nullptr_t) noexcept { return static_cast<bool>(func); } //! Check if \a func is activated. template <typename TReturn, typename... TArgs> bool operator!=(std::nullptr_t, function<TReturn(TArgs...)> const& func) noexcept { return static_cast<bool>(func); } //! Swap \a a and \a b by \c function::swap. template <typename TReturn, typename... TArgs> void swap(function<TReturn(TArgs...)>& a, function<TReturn(TArgs...)>& b) noexcept { a.swap(b); } } // namespace omni
omniverse-code/kit/include/omni/Expected.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 Implementation of \c omni::expected and related functions and structures. #pragma once #include "detail/ExpectedImpl.h" namespace omni { template <typename TValue, typename TError> class expected; //! The unexpected value of an \ref expected monad. This is used as a convenient mechanism to report the error case when //! constructing an \c expected return. //! //! \code //! expected<string, Result> foo(bool x) //! { //! // C++17: TError is deduced as `Result` //! return unexpected(kResultNotImplemented); //! } //! \endcode template <typename TError> class unexpected : public omni::detail::UnexpectedImpl<TError> { using base_impl = omni::detail::UnexpectedImpl<TError>; template <typename UError> friend class unexpected; public: using base_impl::base_impl; //! Swap the contents of this instance with \a other. //! //! If \c TError is \c noexcept swappable or if it is \c void, this operation is also \c noexcept. //! //! \note //! This function only participates in overload resolution if \c TError is swappable or is \c void. template < typename UError, typename IsNoexcept = std::enable_if_t< carb::cpp::conjunction< std::is_same<TError, UError>, typename omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_swappable, UError, std::true_type>::type>::value, typename omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_nothrow_swappable, UError, std::true_type>::type>> constexpr void swap(unexpected& other) noexcept(IsNoexcept::value) { base_impl::swap(static_cast<base_impl&>(other)); } //! Swap the contents of \a lhs with \a rhs. //! //! If \c UError is \c noexcept swappable or if it is \c void, this operation is also \c noexcept. template <typename UError, typename IsNoexcept = std::enable_if_t< omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_swappable, UError, std::true_type>::type::value, typename omni::detail::ExpectedTransformIfNonVoid<carb::cpp::is_nothrow_swappable, UError, std::true_type>::type>> friend constexpr void swap(unexpected& lhs, unexpected<UError>& rhs) noexcept(IsNoexcept::value) { lhs.swap(rhs); } //! If \c TError and \c UError are not \c void, then return `this->error() == other.error()` if they are equality //! comparable (it is a compilation failure if they are not). If both \c TError and \c UError are \c void, then //! return \c true. If one is \c void and the other is not, this is a compilation failure. template <typename UError> constexpr bool operator==(unexpected<UError> const& other) const { static_assert(std::is_void<TError>::value == std::is_void<UError>::value, "Can not compare void and non-void"); return base_impl::operator==(other); } //! If \c TError and \c UError are not \c void, then return `lhs.error() == rhs.error()` if they are equality //! comparable (it is a compilation failure if they are not). If both \c TError and \c UError are \c void, then //! return \c true. If one is \c void and the other is not, this is a compilation failure. template <typename UError> friend constexpr bool operator==(unexpected const& lhs, unexpected<UError> const& rhs) { return lhs.operator==(rhs); } }; #if CARB_HAS_CPP17 //! Allow deduction of \c TError from the `unexpected(t)` expression. template <typename T> unexpected(T) -> unexpected<T>; //! An empty `unexpected()` constructor call implies `TError = void`. unexpected()->unexpected<void>; #endif //! Used in \ref expected constructors to designate that the error type should be constructed. struct unexpect_t; //! A monad which holds either an expected value (the success case) or an unexpected value (the error case). //! //! \tparam TValue The type of expected value, returned in the success case. //! \tparam TError The type of unexpected value, returned in the error case. //! //! Simple use of \c expected instances involve checking if an instance \c has_value() before accessing either the //! \c value() or \c error() member. //! //! \code //! expected<int, string> foo(); //! //! int main() //! { //! auto ex = foo(); //! if (ex) //! std::cout << "Successfully got " << ex.value() << std::endl; //! else //! std::cout << "Error: " << ex.error() << std::endl; //! } //! \endcode //! //! Advanced usage of \c expected involves using the monadic operations, which act on the stored value. This example is //! equivalent to the above: //! //! \code //! expected<int, string> foo(); //! //! int main() //! { //! foo() //! .transform([](int value) { std::cout << "Successfully got " << value << std::endl; }) //! .transform_error([](string const& err) { std::cout << "Error: " << err << std::endl; }); //! } //! \endcode template <typename TValue, typename TError> class CARB_NODISCARD_TYPE expected : public omni::detail::ExpectedImpl<TValue, TError> { private: using base_impl = omni::detail::ExpectedImpl<TValue, TError>; public: //! The type used in success case. using value_type = TValue; //! The type used in error cases. Unlike the C++23 definition of \c std::expected, this is allowed to be \c void to //! match parity with other languages with result monads. using error_type = TError; //! The \c unexpected type which contains this monad's \ref error_type. using unexpected_type = unexpected<error_type>; //! Get an \c expected type with \c UValue as the \ref value_type and the same \ref error_type as this. template <typename UValue> using rebind = expected<UValue, error_type>; public: using base_impl::base_impl; //! Create a valued instance through default construction. //! //! This constructor is only enabled if \ref value_type is default-constructable or \c void. //! //! This function is \c noexcept if \ref value_type has a \c noexcept default constructor or if it is \c void. expected() = default; //! Copy an expected instance from another. After this call, `this->has_value() == src.has_value()` and either the //! \c value or \c error will have been constructed from the \a src instance. //! //! This operation is only enabled if both \ref value_type and \ref error_type are copy-constructible or \c void. //! This operation is trivial if both \ref value_type and \ref error_type have trivial copy constructors or are //! \c void. //! //! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept copy constructors or //! are \c void. //! //! \param src The source to copy from. It will remain unchanged by this operation. expected(expected const& src) = default; //! Move an expected instance from another. After this call, `this->has_value() == src.has_value()` and either the //! \c value or \c error will have been constructed from `std::move(src).value()` or `std::move(src).error()`. Note //! that the \c has_value state is unchanged, but the \a src instance will be moved-from. //! //! This operation is only enabled if both \ref value_type and \ref error_type are move-constructible or \c void. //! This operation is trivial if both \ref value_type and \ref error_type have trivial move constructors or are //! \c void. //! //! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept move constructors or //! are \c void. //! //! \param src The source to move from. While the \ref has_value state will remain unchanged, the active \a src //! instance will have been moved-from. expected(expected&& src) = default; //! Copy-assign this instance from another. After this call, `this->has_value() == src.has_value()`. //! //! Assignment can happen in one of two ways. In the simple case, `this->has_value() == src.has_value()` before the //! call, so the copy assignment operator of the underlying type is used. If `this->has_value() != src.has_value()` //! before the call, then the active instance of \c this gets the destructor called, then the other type is copy //! constructed (generally -- see the "exceptions" section for more info). Note that this destruct-then-construct //! process happens even when \ref value_type and \ref error_type are the same. //! //! This operation is only enabled if both \ref value_type and \ref error_type are copy-assignable or \c void. This //! operation is trivial if both \ref value_type and \ref error_type have trivial copy assignment operators and //! trivial destructors or are \c void. //! //! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept copy constructors, //! copy assignment operators, and \c noexcept destructors or are \c void. //! //! \note //! On type-changing assignment with exceptions enabled, care is taken to ensure the contents of the monad are valid //! for use when exceptions are thrown. The "simple" destruct-then-construct process is only followed when copy //! construction of the type of the created instance is non-throwing. The exact algorithm used depends on the //! available \c noexcept operations (if any), but they involve a stack-based temporary and rollback. Note that a //! new instance \e might be constructed before the destruction of the old, so the ordering of these operations //! should not be relied on. //! //! \param src The source to copy from. It will remain unchanged by this operation. expected& operator=(expected const& src) = default; //! Move-assign this instance from another. After this call, `this->has_value() == src.has_value()`. //! //! Assignment can happen in one of two ways. In the simple case, `this->has_value() == src.has_value()` before the //! call, so the move assignment operator of the underlying type is used. If `this->has_value() != src.has_value()` //! before the call, then the active instance of \c this gets the destructor called, then the other type is move //! constructed (generally -- see the "exceptions" section for more info). Note that this destruct-then-construct //! process happens even when \ref value_type and \ref error_type are the same. //! //! This operation is only enabled if both \ref value_type and \ref error_type are move-assignable or \c void. This //! operation is trivial if both \ref value_type and \ref error_type have trivial move assignment operators and //! trivial destructors or are \c void. //! //! This function is \c noexcept if both \ref value_type and \ref error_type have \c noexcept move constructors, //! move assignment operators, and \c noexcept destructors or are \c void. //! //! \note //! On type-changing assignment with exceptions enabled, care is taken to ensure the contents of the monad are valid //! for use when exceptions are thrown. The "simple" destruct-then-construct process is only followed when move //! construction of the type of the created instance is non-throwing. The exact algorithm used depends on the //! available \c noexcept operations (if any), but they involve a stack-based temporary and rollback. Note that a //! new instance \e might be constructed before the destruction of the old, so the ordering of these operations //! should not be relied on. //! //! \param src The source to move from. While the \ref has_value will remain unchanged, the active \a src instance //! will have been moved-from. expected& operator=(expected&& src) = default; //! Destroy this instance by calling the destructor of the active value. //! //! This operation is trivial if both \ref value_type and \ref error_type are trivially destructible. This function //! is \c noexcept if both \ref value_type and \ref error_type have \c noexcept destructors. ~expected() = default; //! Construct an instance by forwarding \a src to construct the \ref value_type by direct initialization. After this //! call, `this->has_value()` will be true. //! //! This constructor is only enabled when all of the following criteria is met: //! //! 1. \ref value_type is constructible from \c UValue //! 2. \ref value_type is not \c void //! 3. `remove_cvref_t<UValue>` is not \c in_place_t //! 4. `remove_cvref_t<UValue>` is not `expected<TValue, TError>` (the copy or move constructor is used instead) //! 5. `remove_cvref_t<UValue>` is not a specialization of \c unexpected //! 6. if \ref value_type is \c bool, then \c UValue can not be a specialization of \c expected //! //! This constructor is \c explicit if conversion from \c UValue to \ref value_type is \c explicit. template <typename UValue = TValue, std::enable_if_t<omni::detail::IsExpectedDirectConstructibleFrom<UValue, expected>::is_explicit, bool> = true> constexpr explicit expected(UValue&& src) : base_impl(carb::cpp::in_place, std::forward<UValue>(src)) { } #ifndef DOXYGEN_BUILD template <typename UValue = TValue, std::enable_if_t<!omni::detail::IsExpectedDirectConstructibleFrom<UValue, expected>::is_explicit, bool> = false> constexpr expected(UValue&& src) : base_impl(carb::cpp::in_place, std::forward<UValue>(src)) { } #endif //! Convert from \a src by direct initialization from the active element. If `src.has_value()`, then this instance //! will have a value constructed from `src.value()`; otherwise, this instance will have an error constructed from //! `src.error()`. After this call, `this->has_value() == src.has_value()`. //! //! This converting constructor is not \c explicit if conversion from \c UValue to \c TValue and \c UError to //! \c TError are not \c explicit. Conversion from \c void to \c void is also considered a non \c explicit //! conversion. Stated differently, a \c UExpected is implicitly convertible to a \c TExpected if both of its //! components are implicitly convertible. //! //! \note //! The rules for this are almost identical to \c std::expected, but they are expanded to support \c void as the //! \ref error_type. Any case where the C++ Standard makes an exception when \ref value_type is \c void, that same //! exception has been extended to \ref error_type of \c void. template <typename UValue, typename UError, std::enable_if_t<omni::detail::IsExpectedCopyConstructibleFrom<expected<UValue, UError>, expected>::is_explicit, bool> = true> constexpr explicit expected(expected<UValue, UError> const& src) : base_impl(::omni::detail::ExpectedCtorBypass{}, src) { } #ifndef DOXYGEN_BUILD template <typename UValue, typename UError, std::enable_if_t<!omni::detail::IsExpectedCopyConstructibleFrom<expected<UValue, UError>, expected>::is_explicit, bool> = false> constexpr expected(expected<UValue, UError> const& src) : base_impl(::omni::detail::ExpectedCtorBypass{}, src) { } #endif //! Convert from \a src by direct initialization from the active element. If `src.has_value()`, then this instance //! will have a value constructed from `move(src).value()`; otherwise, this instance will have an error constructed //! from `move(src).error()`. After this call, `this->has_value() == src.has_value()`. Note that the contents of //! \a src are moved-from, but not destructed, so the instances is still accessable. //! //! This converting constructor is not \c explicit if conversion from \c UValue to \c TValue and \c UError to //! \c TError are not \c explicit. Conversion from \c void to \c void is also considered a non \c explicit //! conversion. Stated differently, a \c UExpected is implicitly convertible to a \c TExpected if both of its //! components are implicitly convertible. //! //! \note //! The rules for this are almost identical to \c std::expected, but they are expanded to support \c void as the //! \ref error_type. Any case where the C++ Standard makes an exception when \ref value_type is \c void, that same //! exception has been extended to \ref error_type of \c void. template <typename UValue, typename UError, std::enable_if_t<omni::detail::IsExpectedMoveConstructibleFrom<expected<UValue, UError>, expected>::is_explicit, bool> = true> constexpr explicit expected(expected<UValue, UError>&& src) : base_impl(::omni::detail::ExpectedCtorBypass{}, std::move(src)) { } #ifndef DOXYGEN_BUILD template <typename UValue, typename UError, std::enable_if_t<!omni::detail::IsExpectedMoveConstructibleFrom<expected<UValue, UError>, expected>::is_explicit, bool> = false> constexpr expected(expected<UValue, UError>&& src) : base_impl(::omni::detail::ExpectedCtorBypass{}, std::move(src)) { } #endif //! Construct an instance using \a src as the error value. The constructed instance `!this->has_value()` and the //! `this->error()` will have been constructed by `src.error()`. //! //! This constructor is not \c explicit if the conversion from the source \c UError to \c TError is not explicit. //! Stated differently, an `unexpected<UError>` is implicitly convertible to a `expected<TValue, TError>` (of //! arbitrary `TValue`) if `UError` is implicitly convertible to a `TError`. //! //! If \c TError is \c void, then \c UError must also be \c void to construct an instance. template <typename UError, std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError const&>, carb::cpp::negation<std::is_convertible<UError const&, TError>>>::value, bool> = true> constexpr explicit expected(unexpected<UError> const& src) : base_impl(unexpect, src.error()) { } #ifndef DOXYGEN_BUILD template <typename UError, std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError const&>, std::is_convertible<UError const&, TError>>::value, bool> = false> constexpr expected(unexpected<UError> const& src) : base_impl(unexpect, src.error()) { } #endif //! Construct an instance using \a src as the error value. The constructed instance `!this->has_value()` and the //! `this->error()` will have been constructed by `std::move(src).error()`. //! //! This constructor is not \c explicit if the conversion from the source \c UError to \c TError is not explicit. //! Stated differently, an `unexpected<UError>` is implicitly convertible to a `expected<TValue, TError>` (of //! arbitrary `TValue`) if `UError` is implicitly convertible to a `TError`. //! //! If \c TError is \c void, then \c UError must also be \c void to construct an instance. template <typename UError, std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError&&>, carb::cpp::negation<std::is_convertible<UError&&, TError>>>::value, bool> = true> constexpr explicit expected(unexpected<UError>&& src) : base_impl(unexpect, std::move(src).error()) { } #ifndef DOXYGEN_BUILD template <typename UError, std::enable_if_t<carb::cpp::conjunction<std::is_constructible<TError, UError&&>, std::is_convertible<UError&&, TError>>::value, bool> = false> constexpr expected(unexpected<UError>&& src) : base_impl(unexpect, std::move(src).error()) { } #endif //! Test if this instance has a \c value. If this returns \c true, then a call to \c value() will succeed, while a //! call to \c error() would not. If this returns \c false, a call to \c error() will succeed, while a call to //! \c value() would not. constexpr bool has_value() const noexcept { return this->m_state == ::omni::detail::ExpectedState::eSUCCESS; } //! \copydoc expected::has_value() const //! //! \see has_value constexpr explicit operator bool() const noexcept { return this->has_value(); } #ifdef DOXYGEN_BUILD //! If this instance \c has_value(), the value is returned by `&`. //! //! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a //! \c bad_expected_access exception is thrown containing the copied contents of \c error(). If exceptions are //! disabled, then the program will terminate. //! //! \note //! If \ref value_type is \c void, the return type is exactly \c void instead of `void&` (which is illegal). constexpr value_type& value() &; //! If this instance \c has_value(), the value is returned by `const&`. //! //! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a //! \c bad_expected_access exception is thrown containing the copied contents of \c error(). If exceptions are //! disabled, then the program will terminate. //! //! \note //! If \ref value_type is \c void, the return type is exactly \c void instead of `void const&` (which is illegal). constexpr value_type const& value() const&; //! If this instance \c has_value(), the value is returned by `&&`. //! //! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a //! \c bad_expected_access exception is thrown containing the moved contents of \c error(). If exceptions are //! disabled, then the program will terminate. //! //! \note //! If \ref value_type is \c void, the return type is exactly \c void instead of `void&&` (which is illegal). constexpr value_type&& value() &&; //! If this instance \c has_value(), the value is returned by `const&&`. //! //! If this instance does not have a value, this call will not succeed. If exceptions are enabled, then a //! \c bad_expected_access exception is thrown containing the copied contents of \c error(). If exceptions are //! disabled, then the program will terminate. //! //! \note //! If \ref value_type is \c void, the return type is exactly \c void instead of `void const&&` (which is illegal). constexpr value_type const&& value() const&&; //! If this instance \c has_value(), the value is copied and returned; otherwise, a \ref value_type instance is //! constructed from \a default_value. //! //! \note //! If \ref value_type is \c void, this member function does not exist. If \ref value_type is not copy //! constructible, this will fail to compile in the immediate context (not SFINAE-safe). //! //! \tparam UValue Must be convertible to \ref value_type. template <typename UValue> constexpr value_type value_or(UValue&& default_value) const&; //! If this instance \c has_value(), the value is moved and returned; otherwise, a \ref value_type instance is //! constructed from \a default_value. //! //! \note //! If \ref value_type is \c void, this member function does not exist. If \ref value_type is not move //! constructible, this will fail to compile in the immediate context (not SFINAE-safe). //! //! \tparam UValue Must be convertible to \ref value_type. template <typename UValue> constexpr value_type value_or(UValue&& default_value) &&; //! If this instance \c !has_value(), the error is returned by `&`. //! //! \pre //! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate. //! //! \note //! If \ref error_type is \c void, the return type is exactly \c void instead of `void&` (which is illegal). constexpr error_type& error() & noexcept; //! If this instance \c !has_value(), the error is returned by `const&`. //! //! \pre //! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate. //! //! \note //! If \ref error_type is \c void, the return type is exactly \c void instead of `void const&` (which is illegal). constexpr error_type const& error() const& noexcept; //! If this instance \c !has_value(), the error is returned by `&&`. //! //! \pre //! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate. //! //! \note //! If \ref error_type is \c void, the return type is exactly \c void instead of `void&&` (which is illegal). constexpr error_type&& error() && noexcept; //! If this instance \c !has_value(), the error is returned by `const&&`. //! //! \pre //! `!this->has_value()`: if this instance is not in the unexpected state, the program will terminate. //! //! \note //! If \ref error_type is \c void, the return type is exactly \c void instead of `void const&&` (which is illegal). constexpr error_type const&& error() const&& noexcept; //! Access the underlying value instance. If \c has_value() is \c false, the program will terminate. //! //! This function is only available if \ref value_type is not \c void. constexpr value_type* operator->() noexcept; //! \copydoc expected::operator->() constexpr value_type const* operator->() const noexcept; //! If this instance \c has_value(), the value is returned by `&`. //! //! If this instance does not have a value, the program will terminate. //! //! \note //! If \ref value_type is \c void, this overload is not enabled (only the `const&` is accessible). constexpr value_type& operator*() & noexcept; //! If this instance \c has_value(), the value is returned by `const&`. //! //! If this instance does not have a value, the program will terminate. //! //! \note //! If \ref value_type is \c void, the return type is exactly \c void instead of `void const&` (which is illegal). constexpr value_type const& operator*() const& noexcept; //! If this instance \c has_value(), the value is returned by `&&`. //! //! If this instance does not have a value, the program will terminate. //! //! \note //! If \ref value_type is \c void, this overload is not enabled (only the `const&` is accessible). constexpr value_type&& operator*() && noexcept; //! If this instance \c has_value(), the value is returned by `const&&`. //! //! If this instance does not have a value, the program will terminate. //! //! \note //! If \ref value_type is \c void, this overload is not enabled (only the `const&` is accessible). constexpr value_type const&& operator*() const&& noexcept; //! Destroy the current contents of this instance and construct the \ref value_type of this instance through //! direct-initialization. //! //! If \ref value_type is not \c void, this function accepts two overloads: //! //! 1. `template <typename... TArgs> value_type& emplace(TArgs&&... args) noexcept` (only enabled if //! `std::is_nothrow_constructible<value_type, TArgs...>::value` is \c true) //! 2. `template <typename U, typename... TArgs> value_type& emplace(std::initializer_list<U>& il, TArgs&&... args) //! noexcept` (only enabled if `std::is_nothrow_constructible<value_type, std::initializer_list<U>&, //! TArgs...>::value` is \c true) //! //! After calling this function, \c has_value() will return \c true. template <typename... TArgs> value_type& emplace(TArgs&&... args) noexcept; //! If \ref value_type is \c void, then \c emplace is a no argument function that returns \c void. //! //! After calling this function, \c has_value() will return \c true. void emplace() noexcept; #endif //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type const&)`; if //! \ref value_type is \c void, \c F has the signature `UValue ()`. //! //! \returns //! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform(F&& f) const& { return ::omni::detail::ExpectedOpTransform<F, expected, expected const&>::transform(std::forward<F>(f), *this); } //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type&)`; if \ref value_type //! is \c void, \c F has the signature `UValue ()`. //! //! \returns //! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform(F&& f) & { return ::omni::detail::ExpectedOpTransform<F, expected, expected&>::transform(std::forward<F>(f), *this); } //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type&&)`; if \ref value_type //! is \c void, \c F has the signature `UValue ()`. //! //! \returns //! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform(F&& f) && { return ::omni::detail::ExpectedOpTransform<F, expected, expected&&>::transform( std::forward<F>(f), std::move(*this)); } //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature `UValue (value_type const&&)`; if //! \ref value_type is \c void, \c F has the signature `UValue ()`. //! //! \returns //! An `expected<UValue, error_type>`, where the returned value has been transformed by \a f. The \ref value_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform(F&& f) const&& { return ::omni::detail::ExpectedOpTransform<F, expected, expected const&&>::transform( std::forward<F>(f), std::move(*this)); } //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature //! `expected<UValue, UError> (value_type const&)`; if \ref value_type is \c void, \c F has the signature //! `expected<UValue, UError> ()`. In both cases, \c UError must be constructible from \ref error_type or //! \c void. template <typename F> constexpr auto and_then(F&& f) const& { return ::omni::detail::ExpectedOpAndThen<F, expected, expected const&>::and_then(std::forward<F>(f), *this); } //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature `expected<UValue, UError> (value_type&)`; if //! \ref value_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases, //! \c UError must be constructible from \ref error_type or \c void. template <typename F> constexpr auto and_then(F&& f) & { return ::omni::detail::ExpectedOpAndThen<F, expected, expected&>::and_then(std::forward<F>(f), *this); } //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature `expected<UValue, UError> (value_type&&)`; //! if \ref value_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases, //! \c UError must be constructible from \ref error_type or \c void. template <typename F> constexpr auto and_then(F&& f) && { return ::omni::detail::ExpectedOpAndThen<F, expected, expected&&>::and_then(std::forward<F>(f), std::move(*this)); } //! Transform the value by \a f if this \c has_value() or return the error if it does not. //! //! \tparam F If \ref value_type is not \c void, \c F has the signature //! `expected<UValue, UError> (value_type const&&)`; if \ref value_type is \c void, \c F has the signature //! `expected<UValue, UError> ()`. In both cases, \c UError must be constructible from \ref error_type or //! \c void. template <typename F> constexpr auto and_then(F&& f) const&& { return ::omni::detail::ExpectedOpAndThen<F, expected, expected const&&>::and_then( std::forward<F>(f), std::move(*this)); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type const&)`; if //! \ref error_type is \c void, \c F has the signature `UError ()`. //! //! \returns //! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform_error(F&& f) const& { return ::omni::detail::ExpectedOpTransformError<F, expected, expected const&>::transform_error( std::forward<F>(f), *this); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type&)`; if \ref error_type //! is \c void, \c F has the signature `UError ()`. //! //! \returns //! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform_error(F&& f) & { return ::omni::detail::ExpectedOpTransformError<F, expected, expected&>::transform_error( std::forward<F>(f), *this); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type&&)`; if \ref error_type //! is \c void, \c F has the signature `UError ()`. //! //! \returns //! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform_error(F&& f) && { return ::omni::detail::ExpectedOpTransformError<F, expected, expected&&>::transform_error( std::forward<F>(f), std::move(*this)); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature `UError (error_type const&&)`; if //! \ref error_type is \c void, \c F has the signature `UError ()`. //! //! \returns //! An `expected<value_type, UError>`, where the returned error has been transformed by \a f. The \ref error_type of //! the returned instance is the result type of \c F. template <typename F> constexpr auto transform_error(F&& f) const&& { return ::omni::detail::ExpectedOpTransformError<F, expected, expected const&&>::transform_error( std::forward<F>(f), std::move(*this)); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature //! `expected<UValue, UError> (error_type const&)`; if \ref error_type is \c void, \c F has the signature //! `expected<UValue, UError> ()`. In both cases, \c UValue must be constructible from \ref value_type or //! \c void. template <typename F> constexpr auto or_else(F&& f) const& { return ::omni::detail::ExpectedOpOrElse<F, expected, expected const&>::or_else(std::forward<F>(f), *this); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature `expected<UValue, UError> (error_type&)`; if //! \ref error_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases, //! \c UValue must be constructible from \ref value_type or \c void. template <typename F> constexpr auto or_else(F&& f) & { return ::omni::detail::ExpectedOpOrElse<F, expected, expected&>::or_else(std::forward<F>(f), *this); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature `expected<UValue, UError> (error_type&&)`; //! if \ref error_type is \c void, \c F has the signature `expected<UValue, UError> ()`. In both cases, //! \c UValue must be constructible from \ref value_type or \c void. template <typename F> constexpr auto or_else(F&& f) && { return ::omni::detail::ExpectedOpOrElse<F, expected, expected&&>::or_else(std::forward<F>(f), std::move(*this)); } //! Transform the error by \a f if this \c has_value() is \c false or return the value if it does not. //! //! \tparam F If \ref error_type is not \c void, \c F has the signature //! `expected<UValue, UError> (error_type const&&)`; if \ref error_type is \c void, \c F has the signature //! `expected<UValue, UError> ()`. In both cases, \c UValue must be constructible from \ref value_type or //! \c void. template <typename F> constexpr auto or_else(F&& f) const&& { return ::omni::detail::ExpectedOpOrElse<F, expected, expected const&&>::or_else( std::forward<F>(f), std::move(*this)); } }; //! Compare the contents of \c lhs and \c rhs for equality. //! //! 1. If `lhs.has_value() != rhs.has_value()`, then \c false is returned. //! 2. If `lhs.has_value() && rhs.has_value()`, then their `.value()`s are compared; if both are \c void, the //! comparison is always equal. //! 3. If `!lhs.has_value() && !rhs.has_value()`, then their `.error()`s are compared; if they are both \c void, the //! comparison is always equal. //! //! \par Comparability of Template Parameters //! When provided with \p lhs and \p rhs, their \ref expected::value_type and \ref expected::error_type parameters must //! either be equality comparable or \c void. If this is not the case, an error will occur in the immediate context //! (testing for equality comparison of \c expected types is not SFINAE-safe). It is not legal to compare a non-`void` //! type to a \c void type. template <typename TValueLhs, typename TErrorLhs, typename TValueRhs, typename TErrorRhs> constexpr bool operator==(expected<TValueLhs, TErrorLhs> const& lhs, expected<TValueRhs, TErrorRhs> const& rhs) { static_assert(std::is_void<TValueLhs>::value == std::is_void<TValueRhs>::value, "Can not compare expected of non-void `value_type` with one of void `value_type`"); static_assert(std::is_void<TErrorLhs>::value == std::is_void<TErrorRhs>::value, "Can not compare expected of non-void `error_type` with one of void `error_type`"); return ::omni::detail::ExpectedComparer<expected<TValueLhs, TErrorLhs>, expected<TValueRhs, TErrorRhs>>::eq(lhs, rhs); } //! Compare the contents of \a lhs with the non \c expected type \a rhs. //! //! \tparam TValueLhs A value which is comparable to \c TValueRhs. If it is either \c void or a non-comparable type, it //! is an error in the immediate context (not SFINAE-safe). template <typename TValueLhs, typename TErrorLhs, typename TValueRhs> constexpr bool operator==(expected<TValueLhs, TErrorLhs> const& lhs, TValueRhs const& rhs) { static_assert(!std::is_void<TValueLhs>::value, "Can not compare void-valued expected with value"); return lhs.has_value() && static_cast<bool>(lhs.value() == rhs); } //! Compare the error contents of \a lhs with \a rhs. //! //! \returns \c true if `lhs.has_value() && (lhs.error() == rhs.error())`; the second clause is omitted if the error //! type is \c void. template <typename TValueLhs, typename TErrorLhs, typename TErrorRhs> constexpr bool operator==(expected<TValueLhs, TErrorLhs> const& lhs, unexpected<TErrorRhs> const& rhs) { static_assert(!std::is_void<TErrorLhs>::value && std::is_void<TErrorRhs>::value, "Can not compare expected of non-void `error_type` with unexpected<void>"); static_assert(std::is_void<TErrorLhs>::value && !std::is_void<TErrorRhs>::value, "Can not compare expected of void `error_type` with unexpected of non-void `error_type`"); return ::omni::detail::ExpectedUnexpectedComparer<TErrorLhs, TErrorRhs>::eq(lhs, rhs); } } // namespace omni
omniverse-code/kit/include/omni/String.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 ABI safe string implementation #pragma once #include "../carb/Defines.h" #include "detail/PointerIterator.h" #include "../carb/cpp/StringView.h" #include <cstddef> #include <cstdint> #include <initializer_list> #include <istream> #include <iterator> #include <limits> #include <memory> #include <ostream> #include <string> #include <type_traits> #if CARB_HAS_CPP17 # include <string_view> #endif CARB_IGNOREWARNING_MSC_WITH_PUSH(4201) // nonstandard extension used: nameless struct/union. namespace omni { //! A flag type to select the omni::string constructor that allows \c printf style formatting. struct formatted_t { }; //! A flag value to select the omni::string constructor that allows \c printf style formatting. constexpr formatted_t formatted{}; //! A flag type to select the omni::string constructor that allows \c vprintf style formatting. struct vformatted_t { }; //! A flag value to select the omni::string constructor that allows \c vprintf style formatting. constexpr vformatted_t vformatted{}; #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { /** * This struct provides implementations of a subset of the functions found in std::char_traits. It is used to provide * constexpr implementations of the functions because std::char_traits did not become constexpr until C++20. Currently * only the methods used by omni::string are provided. */ struct char_traits { /** * Assigns \p c to \p dest. */ static constexpr void assign(char& dest, const char& c) noexcept; /** * Assigns \p count copies of \p c to \p dest. * * @returns \p dest. */ static constexpr char* assign(char* dest, std::size_t count, char c) noexcept; /** * Copies \p count characters from \p source to \p dest. * * This function performs correctly even if \p dest and \p source overlap. */ static constexpr void move(char* dest, const char* source, std::size_t count) noexcept; /** * Copies \p count characters from \p source to \p dest. * * Behavior of this function is undefined if \p dest and \p source overlap. */ static constexpr void copy(char* dest, const char* source, std::size_t count) noexcept; /** * Lexicographically compares the first \p count characters of \p s1 and \p s2. * * @return Negative value if \p s1 is less than \p s2. * ​0​ if \p s1 is equal to \p s2. * Positive value if \p s1 is greater than \p s2. */ static constexpr int compare(const char* s1, const char* s2, std::size_t count) noexcept; /** * Computes the length of \p s. * * @return The length of \p s. */ static constexpr std::size_t length(const char* s) noexcept; /** * Searches the first \p count characters of \p s for the character \p ch. * * @return A pointer to the first character equal to \p ch, or \c nullptr if no such character exists. */ static constexpr const char* find(const char* s, std::size_t count, char ch) noexcept; }; # if CARB_HAS_CPP17 template <typename T, typename Res = void> using is_sv_convertible = std::enable_if_t<std::conjunction<std::is_convertible<const T&, std::string_view>, std::negation<std::is_convertible<const T&, const char*>>>::value, Res>; # endif } // namespace detail #endif // Handle case where Windows.h may have defined 'max' #pragma push_macro("max") #undef max /** * This class is an ABI safe string implementation. It is meant to be a drop-in replacement for std::string. * * This class is not templated for simplicity and @rstref{ABI safety <abi-compatibility>}. * * Note: If exceptions are not enabled, any function that would throw will terminate the program instead. * * Note: All functions provide a strong exception guarantee. If they throw an exception for any reason, the function * has no effect. */ class CARB_VIZ string { public: /** Char traits type alias. */ #if CARB_HAS_CPP20 using traits_type = std::char_traits<char>; #else using traits_type = detail::char_traits; #endif /** Char type alias. */ using value_type = char; /** Size type alias. */ using size_type = std::size_t; /** Reference type alias. */ using reference = value_type&; /** Const Reference type alias. */ using const_reference = const value_type&; /** Pointer type alias. */ using pointer = value_type*; /** Const Pointer type alias. */ using const_pointer = const value_type*; /** Difference type alias. */ using difference_type = std::pointer_traits<pointer>::difference_type; /** Iterator type alias. */ using iterator = detail::PointerIterator<pointer, string>; /** Const Iterator type alias. */ using const_iterator = detail::PointerIterator<const_pointer, string>; /** Const Reverse Iterator type alias. */ using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** Reverse Iterator type alias. */ using reverse_iterator = std::reverse_iterator<iterator>; /** * Special value normally used to indicate that an operation failed. */ static constexpr size_type npos = std::numeric_limits<size_type>::max(); /** * Default constructor. Constructs empty string. */ string() noexcept; /** * Constructs the string with \p n copies of character \p c. * @param n Number of characters to initialize with. * @param c The character to initialize with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. * */ string(size_type n, value_type c); /** * Constructs the string with a substring `[pos, str.size())` of \p str. * * @param str Another string to use as source to initialize the string with. * @param pos Position of the first character to include. * * @throws std::out_of_range if \p pos is greater than `str.size()`. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(const string& str, size_type pos); /** * Constructs the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the * requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`. * * @param str Another string to use as source to initialize the string with. * @param pos Position of the first character to include. * @param n Number of characters to include. * * @throws std::out_of_range if \p pos is greater than `str.size()`. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(const string& str, size_type pos, size_type n); /** * Constructs the string with the first \p n characters of character string pointed to by \p s. \p s can contain * null characters. The length of the string is \p n. The behavior is undefined if `[s, s + n)` is not * a valid range. * * @param s Pointer to an array of characters to use as source to initialize the string with. * @param n Number of characters to include. * * @throws std::length_error if the string would be larger than max_size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws Allocation This function may throw any exception thrown during allocation. */ string(const value_type* s, size_type n); /** * Constructs the string with the contents initialized with a copy of the null-terminated character string pointed * to by \p s . The length of the string is determined by the first null character. The behavior is undefined if * `[s, s + Traits::length(s))` is not a valid range (for example, if \p s is a null pointer). * * @param s Pointer to an array of characters to use as source to initialize the string with. * * @throws std::length_error if the string would be larger than max_size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws Allocation This function may throw any exception thrown during allocation. */ string(const value_type* s); /** * Constructs the string with the contents of the range `[first, last)`. * * @param begin Start of the range to copy characters from. * @param end End of the range to copy characters from. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename InputIterator> string(InputIterator begin, InputIterator end); /** * Copy constructor. Constructs the string with a copy of the contents of \p str. * * @param str Another string to use as source to initialize the string with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(const string& str); /** * Move constructor. Constructs the string with the contents of \p str using move semantics. \p str is left in * valid, but unspecified state. * * @param str Another string to use as source to initialize the string with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(string&& str) noexcept; /** * Constructs the string with the contents of the initializer list \p ilist. * * @param ilist initializer_list to initialize the string with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(std::initializer_list<value_type> ilist); /** * Constructs the string with the \c printf style format string and additional parameters. * * @param fmt A \c printf style format string. * @param args Additional arguments to the format string. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <class... Args> string(formatted_t, const char* fmt, Args&&... args); /** * Constructs the string with the \c vprintf style format string and additional parameters. * * @param fmt A \c printf style format string. * @param ap A \c va_list as initialized by \c va_start. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(vformatted_t, const char* fmt, va_list ap); /** * Copy constructor. Constructs the string with a copy of the contents of \p str. * * @param str Another string to use as source to initialize the string with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ explicit string(const std::string& str); /** * Constructs the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the * requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`. * * @param str Another string to use as source to initialize the string with. * @param pos Position of the first character to include. * @param n Number of characters to include. * * @throws std::out_of_range if \p pos is greater than `str.size()`. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(const std::string& str, size_type pos, size_type n); /** * Copy constructor. Constructs the string with a copy of the contents of \p sv. * * @param sv String view to use as source to initialize the string with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ explicit string(const carb::cpp::string_view& sv); /** * Constructs the string with a substring `[pos, pos + n)` of \p sv. If `n == npos`, or if the * requested substring lasts past the end of the string, the resulting substring is `[pos, sv.size())`. * * @param sv String view to use as source to initialize the string with. * @param pos Position of the first character to include. * @param n Number of characters to include. * * @throws std::out_of_range if \p pos is greater than `sv.size()`. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string(const carb::cpp::string_view& sv, size_type pos, size_type n); #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and initializes this string with the contents of that * `std::string_view`. This overload participates in overload resolution only if `std::is_convertible_v<const T&, * std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` to initialize with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> explicit string(const T& t); /** * Implicitly converts @p t to type `std::string_view` and initializes this string with a substring `[pos, pos + n)` * of that `string_view`. If `n == npos`, or if the requested substring lasts past the end of the `string_view`, * the resulting substring is `[pos, sv.size())`. This overload participates in overload resolution only if * `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` to initialize with. * @param pos Position of the first character to include. * @param n Number of characters to include. * * @throws std::out_of_range if \p pos is greater than `sv.size()`. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string(const T& t, size_type pos, size_type n); #endif /** * Cannot be constructed from `nullptr`. */ string(std::nullptr_t) = delete; /** * Destroys the string, deallocating internal storage if used. */ ~string() noexcept; /** * Replaces the contents with a copy of \p str. If \c *this and str are the same object, this function has no * effect. * * @param str String to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator=(const string& str); /** * Replaces the contents with those of str using move semantics. str is in a valid but unspecified state afterwards. * * @param str String to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator=(string&& str) noexcept; /** * Replaces the contents with those of null-terminated character string pointed to by \p s. * * @param s Pointer to a null-terminated character string to use as source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator=(const value_type* s); /** * Replaces the contents with character \p c. * * @param c Character to use as source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator=(value_type c); /** * Replaces the contents with those of the initializer list \p ilist. * * @param ilist initializer list to use as source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator=(std::initializer_list<value_type> ilist); /** * Replaces the contents with a copy of \p str. * * @param str String to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator=(const std::string& str); /** * Replaces the contents with a copy of \p sv. * * @param sv String view to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator=(const carb::cpp::string_view& sv); #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and replaces the contents of this string with the contents of * that `std::string_view`. This overload participates in overload resolution only if `std::is_convertible_v<const * T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` to initialize with. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& operator=(const T& t); #endif /** * Cannot be assigned from `nullptr`. */ string& operator=(std::nullptr_t) = delete; /** * Replaces the contents with \p n copies of character \p c. * * @param n Number of characters to initialize with. * @param c Character to use as source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(size_type n, value_type c); /** * Replaces the contents with a copy of \p str. * * @param str String to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const string& str); /** * Replaces the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the * requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`. * * @param str Another string to use as source to initialize the string with. * @param pos Position of the first character to include. * @param n Number of characters to include. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const string& str, size_type pos, size_type n = npos); /** * Replaces the contents with those of str using move semantics. \p str is in a valid but unspecified state * afterwards. * * @param str String to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(string&& str); /** * Replace the string with the first \p n characters of character string pointed to by \p s. \p s can contain * null characters. The length of the string is \p n. The behavior is undefined if `[s, s + n)` is not * a valid range. * * @param s Pointer to an array of characters to use as source to initialize the string with. * @param n Number of characters to include. * @return \c *this. * * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const value_type* s, size_type n); /** * Replaces the contents with those of null-terminated character string pointed to by \p s. * * @param s Pointer to a null-terminated character string to use as source to initialize the string with. * @return \c *this. * * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const value_type* s); /** * Replace the string with the contents of the range `[first, last)`. * * @param first Start of the range to copy characters from. * @param last End of the range to copy characters from. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <class InputIterator> string& assign(InputIterator first, InputIterator last); /** * Replaces the contents with those of the initializer list \p ilist. * * @param ilist initializer list to use as source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(std::initializer_list<value_type> ilist); /** * Replaces the contents with a copy of \p str. * * @param str String to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const std::string& str); /** * Replaces the string with a substring `[pos, pos + n)` of \p str. If `n == npos`, or if the * requested substring lasts past the end of the string, the resulting substring is `[pos, str.size())`. * * @param str Another string to use as source to initialize the string with. * @param pos Position of the first character to include. * @param n Number of characters to include. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const std::string& str, size_type pos, size_type n = npos); /** * Replaces the contents with a copy of \p sv. * * @param sv String view to be used as the source to initialize the string with. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const carb::cpp::string_view& sv); /** * Replaces the string with a substring `[pos, pos + n)` of \p sv. If `n == npos`, or if the * requested substring lasts past the end of the string, the resulting substring is `[pos, sv.size())`. * * @param sv String view to use as source to initialize the string with. * @param pos Position of the first character to include. * @param n Number of characters to include. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign(const carb::cpp::string_view& sv, size_type pos, size_type n = npos); #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and replaces the contents of this string with a substring * `[pos, pos + n)` of that `string_view`. This overload participates in overload resolution only if * `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` to initialize with. * * @throws std::out_of_range if \p pos is greater than `sv.size()`. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& assign(const T& t); /** * Implicitly converts @p t to type `std::string_view` and replaces the contents of this string with a substring * `[pos, pos + n)` of that `string_view`. If `n == npos`, or if the requested substring lasts past the end of * the `string_view`, the resulting substring is `[pos, sv.size())`. This overload participates in overload * resolution only if `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` to initialize with. * @param pos Position of the first character to include. * @param n Number of characters to include. * * @throws std::out_of_range if \p pos is greater than `sv.size()`. * @throws std::length_error if the string would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& assign(const T& t, size_type pos, size_type n = npos); #endif /** * Replaces the contents with those of the \c printf style format string and arguments. * * @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this. * @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign_printf(const char* fmt, ...) CARB_PRINTF_FUNCTION(2, 3); /** * Replaces the contents with those of the \c vprintf style format string and arguments. * * @param fmt \c vprintf style format string to initialize the string with. Must not overlap with \c *this. * @param ap \c va_list as initialized with \c va_start. Arguments must not overlap with \c *this. * @return \c *this. * * @throws std::length_error if the string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& assign_vprintf(const char* fmt, va_list ap); /** * Returns a reference to the character at specified location \p pos. Bounds checking is performed. * * @param pos Position of the character to return. * @return Reference to the character at pos. * * @throws std::out_of_range if \p pos is greater than size(). */ constexpr reference at(size_type pos); /** * Returns a reference to the character at specified location \p pos. Bounds checking is performed. * * @param pos Position of the character to return. * @return Reference to the character at pos. * * @throws std::out_of_range if \p pos is greater than size(). */ constexpr const_reference at(size_type pos) const; /** * Returns a reference to the character at specified location \p pos. No bounds checking is performed. * * @param pos Position of the character to return. * @return Reference to the character at pos. */ constexpr reference operator[](size_type pos); /** * Returns a reference to the character at specified location \p pos. No bounds checking is performed. * * @param pos Position of the character to return. * @return Reference to the character at pos. */ constexpr const_reference operator[](size_type pos) const; /** * Returns a reference to the first character. Behavior is undefined if this string is empty. * * @return Reference to the first character. */ constexpr reference front(); /** * Returns a reference to the first character. Behavior is undefined if this string is empty. * * @return Reference to the first character. */ constexpr const_reference front() const; /** * Returns a reference to the last character. Behavior is undefined if this string is empty. * * @return Reference to the last character. */ constexpr reference back(); /** * Returns a reference to the last character. Behavior is undefined if this string is empty. * * @return Reference to the last character. */ constexpr const_reference back() const; /** * Returns a pointer to the character array of the string. The returned array is null-terminated. * * @return Pointer to the character array of the string. */ constexpr const value_type* data() const noexcept; /** * Returns a pointer to the character array of the string. The returned array is null-terminated. * * @return Pointer to the character array of the string. */ constexpr value_type* data() noexcept; /** * Returns a pointer to the character array of the string. The returned array is null-terminated. * * @return Pointer to the character array of the string. */ constexpr const value_type* c_str() const noexcept; /** * Returns a `carb::cpp::string_view` constructed as if by `carb::cpp::string_view(data(), size())`. * * @return A `carb::cpp::string_view` representing the string. */ constexpr operator carb::cpp::string_view() const noexcept; #if CARB_HAS_CPP17 /** * Returns a `std::string_view` constructed as if by `std::string_view(data(), size())`. * * @return A `std::string_view` representing the string. */ constexpr operator std::string_view() const noexcept; #endif /** * Returns an iterator to the first character in the string. * * @return iterator to the first character in the string. */ constexpr iterator begin() noexcept; /** * Returns a constant iterator to the first character in the string. * * @return iterator to the first character in the string. */ constexpr const_iterator begin() const noexcept; /** * Returns a constant iterator to the first character in the string. * * @return iterator to the first character in the string. */ constexpr const_iterator cbegin() const noexcept; /** * Returns an iterator to the character following the last character of the string. * * @return iterator to the character following the last character of the string. */ constexpr iterator end() noexcept; /** * Returns a constant iterator to the character following the last character of the string. * * @return iterator to the character following the last character of the string. */ constexpr const_iterator end() const noexcept; /** * Returns a constant iterator to the character following the last character of the string. * * @return iterator to the character following the last character of the string. */ constexpr const_iterator cend() const noexcept; /** * Returns a reverse iterator to the first character in the reversed string. This character is the last character in * the non-reversed string. * * @return reverse iterator to the first character in the reversed string. */ reverse_iterator rbegin() noexcept; /** * Returns a constant reverse iterator to the first character in the reversed string. This character is the last * character in the non-reversed string. * * @return reverse iterator to the first character in the reversed string. */ const_reverse_iterator rbegin() const noexcept; /** * Returns a constant reverse iterator to the first character in the reversed string. This character is the last * character in the non-reversed string. * * @return reverse iterator to the first character in the reversed string. */ const_reverse_iterator crbegin() const noexcept; /** * Returns a reverse iterator to the character following the last character in the reversed string. This character * corresponds to character before the first character in the non-reversed string. * * @return reverse iterator to the character following the last character in the reversed string. */ reverse_iterator rend() noexcept; /** * Returns a constant reverse iterator to the character following the last character in the reversed string. This * character corresponds to character before the first character in the non-reversed string. * * @return reverse iterator to the character following the last character in the reversed string. */ const_reverse_iterator rend() const noexcept; /** * Returns a constant reverse iterator to the character following the last character in the reversed string. This * character corresponds to character before the first character in the non-reversed string. * * @return reverse iterator to the character following the last character in the reversed string. */ const_reverse_iterator crend() const noexcept; /** * Checks if the string is empty. * * @return true if the string is empty, false otherwise. */ constexpr bool empty() const noexcept; /** * Returns the number of characters in the string. * * @return the number of characters in the string. */ constexpr size_type size() const noexcept; /** * Returns the number of characters in the string. * * @return the number of characters in the string. */ constexpr size_type length() const noexcept; /** * Returns the maximum number of characters that can be in the string. * * @return the maximum number of characters that can be in the string. */ constexpr size_type max_size() const noexcept; /** * Attempt to change the capacity of the string. * * If \p new_cap is greater than the current capacity(), the string will allocate a new buffer equal to or * larger than \p new_cap. * * If \p new_cap is less than the current capacity(), the string may shrink the buffer. * * If \p new_cap is less that the current size(), the string will shrink the buffer to fit the current * size() as if by calling shrink_to_fit(). * * If reallocation takes place, all pointers, references, and iterators are invalidated. * * @return none. * * @throws std::length_error if \p new_cap is larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ void reserve(size_type new_cap); /** * Reduce the capacity of the string as if by calling shrink_to_fit(). * * If reallocation takes place, all pointers, references, and iterators are invalidated. * * @return none. * * @throws Allocation This function may throw any exception thrown during allocation. */ void reserve(); // deprecated in C++20 /** * Returns the number of characters that can fit in the current storage array. * * @return the number of characters that can fit in the current storage array. */ constexpr size_type capacity() const noexcept; /** * Reduce capacity() to size(). * * If reallocation takes place, all pointers, references, and iterators are invalidated. * * @return none. * * @throws Allocation This function may throw any exception thrown during allocation. */ void shrink_to_fit(); /** * Clears the contents of the string. capacity() is not changed by this function. * * All pointers, references, and iterators are invalidated. * * @return none. */ constexpr void clear() noexcept; /** * Inserts \p n copies of character \p c at position \p pos. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos Position to insert characters. * @param n Number of characters to insert. * @param c Character to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::length_error if `n + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos, size_type n, value_type c); /** * Inserts the string pointed to by \p s at position \p pos. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos Position to insert characters. * @param s String to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if `Traits::length(s) + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos, const value_type* s); /** * Inserts the first \p n characters of the string pointed to by \p s at position \p pos. The range can contain null * characters. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos Position to insert characters. * @param s String to insert. * @param n Number of characters to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if `n + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos, const value_type* s, size_type n); /** * Inserts the string \p str at position \p pos. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos Position to insert characters. * @param str String to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::length_error if `str.size() + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos, const string& str); /** * Inserts the substring `str.substr(pos2, n)` at position \p pos1. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos1 Position to insert characters. * @param str String to insert. * @param pos2 Position in \p str to copy characters from. * @param n Number of characters to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`. * @throws std::length_error if `n + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos1, const string& str, size_type pos2, size_type n = npos); /** * Inserts the character \p c before the character pointed to by \p p. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param p Iterator to the position the character should be inserted before. * @param c Character to insert. * * @return Iterator to the inserted character, or \p p if no character was inserted. * * @throws std::out_of_range if \p p is not in the range [begin(), end()]. * @throws std::length_error if `1 + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ iterator insert(const_iterator p, value_type c); /** * Inserts \p n copies of the character \p c before the character pointed to by \p p. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param p Iterator to the position the character should be inserted before. * @param n Number of characters to inserts. * @param c Character to insert. * * @return Iterator to the first inserted character, or \p p if no character was inserted. * * @throws std::out_of_range if \p p is not in the range [begin(), end()]. * @throws std::length_error if `n + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ iterator insert(const_iterator p, size_type n, value_type c); /** * Inserts characters from the range `[first, last)` before the character pointed to by \p p. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param p Iterator to the position the character should be inserted before. * @param first Iterator to the first character to insert. * @param last Iterator to the first character not to be inserted. * * @return Iterator to the first inserted character, or \p p if no character was inserted. * * @throws std::out_of_range if \p p is not in the range [begin(), end()]. * @throws std::length_error if `std::distance(first, last) + size()` would be larger than * max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <class InputIterator> iterator insert(const_iterator p, InputIterator first, InputIterator last); /** * Inserts the characters in \p ilist before the character pointed to by \p p. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param p Iterator to the position the character should be inserted before. * @param ilist Initializer list of characters to insert. * * @return Iterator to the first inserted character, or \p p if no character was inserted. * * @throws std::out_of_range if \p p is not in the range [begin(), end()]. * @throws std::length_error if `ilist.size() + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ iterator insert(const_iterator p, std::initializer_list<value_type> ilist); /** * Inserts the string \p str at position \p pos. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos Position to insert characters. * @param str String to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::length_error if `str.size() + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos, const std::string& str); /** * Inserts the substring `str.substr(pos2, n)` at position \p pos1. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos1 Position to insert characters. * @param str String to insert. * @param pos2 Position in \p str to copy characters from. * @param n Number of characters to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`. * @throws std::length_error if `n + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos1, const std::string& str, size_type pos2, size_type n = npos); /** * Inserts the string_view \p sv at position \p pos. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos Position to insert characters. * @param sv String view to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::length_error if `str.size() + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos, const carb::cpp::string_view& sv); /** * Inserts the substring `sv.substr(pos2, n)` at position \p pos1. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos1 Position to insert characters. * @param sv String view to insert. * @param pos2 Position in \p str to copy characters from. * @param n Number of characters to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`. * @throws std::length_error if `n + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert(size_type pos1, const carb::cpp::string_view& sv, size_type pos2, size_type n = npos); #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and inserts that `string_view` at position \p pos. This * overload participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos Position to insert characters. * @param t Object that can be converted to `std::string_view` to initialize with. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::length_error if `str.size() + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& insert(size_type pos, const T& t); /** * Implicitly converts @p t to type `std::string_view` and inserts inserts the substring `sv.substr(pos2, n)` at * position \p pos1. This overload participates in overload resolution only if `std::is_convertible_v<const T&, * std::string_view>` is true. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param pos1 Position to insert characters. * @param t Object that can be converted to `std::string_view` to initialize with. * @param pos2 Position in \p str to copy characters from. * @param n Number of characters to insert. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`. * @throws std::length_error if `n + size()` would be larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& insert(size_type pos1, const T& t, size_type pos2, size_type n = npos); #endif /** * Inserts the \c printf style format string and arguments before the \p pos position. * * @param pos Position to insert characters. * @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this. * @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this. * @return \c *this. * * @throws std::out_of_range if \p pos is not in the range [0, size()]. * @throws std::length_error if the resulting string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert_printf(size_type pos, const char* fmt, ...) CARB_PRINTF_FUNCTION(3, 4); /** * Inserts the \c vprintf style format string and arguments before the \p pos position. * * @param pos Position to insert characters. * @param fmt \c vprintf style format string to initialize the string with. Must not overlap with \c *this. * @param ap \c va_list as initialized by \c va_start. Arguments must not overlap with \c *this. * @return \c *this. * * @throws std::out_of_range if \p pos is not in the range [0, size()]. * @throws std::length_error if the resulting string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& insert_vprintf(size_type pos, const char* fmt, va_list ap); /** * Inserts the \c printf style format string and arguments before the character pointed to by \p p. * * @param p Iterator to the position the string should be inserted before. * @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this. * @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this. * @return Iterator to the first inserted character, or \p p if nothing was inserted. * * @throws std::out_of_range if \p p is not in the range [begin(), end()]. * @throws std::length_error if the resulting string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ iterator insert_printf(const_iterator p, const char* fmt, ...) CARB_PRINTF_FUNCTION(3, 4); /** * Inserts the \c vprintf style format string and arguments before the character pointed to by \p p. * * @param p Iterator to the position the string should be inserted before. * @param fmt \c vprintf style format string to initialize the string with. Must not overlap with \c *this. * @param ap \c va_list as initialized by \c va_start. Arguments must not overlap with \c *this. * @return Iterator to the first inserted character, or \p p if nothing was inserted. * * @throws std::out_of_range if \p p is not in the range [begin(), end()]. * @throws std::length_error if the resulting string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ iterator insert_vprintf(const_iterator p, const char* fmt, va_list ap); /** * Erases \p n characters from the string starting at \p pos. If \p n is \p npos or `pos + n > size()`, * characters are erased to the end of the string. * * Pointers, references, and iterators may be invalidated. * * @param pos Position to begin erasing. * @param n Number of characters to erase. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). */ constexpr string& erase(size_type pos = 0, size_type n = npos); /** * Erases the character pointed to by \p pos. * * Pointers, references, and iterators may be invalidated. * * @param pos Position to erase character at. * * @return iterator pointing to the character immediately following the character erased, or end() if no such * character exists. */ constexpr iterator erase(const_iterator pos); /** * Erases characters in the range `[first, last)`. * * Pointers, references, and iterators may be invalidated. * * @param first Position to begin erasing at. * @param last Position to stop erasing at. * * @return iterator pointing to the character last pointed to before the erase, or end() if no such character * exists. * * @throws std::out_of_range if the range `[first, last)` is invalid (not in the range [begin(), end()], * or `first > last`. */ constexpr iterator erase(const_iterator first, const_iterator last); /** * Appends the character \p c to the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @return none. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ void push_back(value_type c); /** * Removes the last character from the string. * * Pointers, references, and iterators may be invalidated. * * @return none. * * @throws std::runtime_error if the string is empty(). */ constexpr void pop_back(); /** * Appends \p n copies of character \p c to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param n Number of characters to append. * @param c Character to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(size_type n, value_type c); /** * Appends \p str to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param str The string to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const string& str); /** * Appends the substring `str.substr(pos2, n)` to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param str The string to append. * @param pos Position of the first character to append. * @param n Number of characters to append. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than `str.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const string& str, size_type pos, size_type n = npos); /** * Appends \p n character of the string \p s to the end of the string. The range can contain nulls. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param s String to append characters from. * @param n Number of characters to append. * * @return \c *this. * * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const value_type* s, size_type n); /** * Appends the null-terminated string \p s to the end of the string. Behavior is undefined if \p s is not a valid * string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param s String to append characters from. * * @return \c *this. * * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const value_type* s); /** * Appends characters in the range `[first, last)` to the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param first First character in the range to append. * @param last End of the range to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <class InputIterator> string& append(InputIterator first, InputIterator last); /** * Appends characters in \p ilist to the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param ilist Initializer list of characters to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(std::initializer_list<value_type> ilist); /** * Appends \p str to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param str The string to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const std::string& str); /** * Appends the substring `str.substr(pos2, n)` to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param str The string to append. * @param pos Position of the first character to append. * @param n Number of characters to append. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than `str.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const std::string& str, size_type pos, size_type n = npos); /** * Appends \p sv to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param sv The string view to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const carb::cpp::string_view& sv); /** * Appends the substring `sv.substr(pos2, n)` to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param sv The string view to append. * @param pos Position of the first character to append. * @param n Number of characters to append. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than `str.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& append(const carb::cpp::string_view& sv, size_type pos, size_type n = npos); #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and appends it to the end of the string. This overload * participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param t Object that can be converted to `std::string_view` to initialize with. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& append(const T& t); /** * Implicitly converts @p t to type `std::string_view` and appends the substring `sv.substr(pos2, n)` to the end of * the string. This overload participates in overload resolution only if `std::is_convertible_v<const T&, * std::string_view>` is true. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param t Object that can be converted to `std::string_view` to initialize with. * @param pos Position of the first character to append. * @param n Number of characters to append. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than `str.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& append(const T& t, size_type pos, size_type n = npos); #endif /** * Appends the \c printf style format string and arguments to the string. * * @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this. * @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this. * @return \c *this. * * @throws std::length_error if the resulting string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& append_printf(const char* fmt, ...) CARB_PRINTF_FUNCTION(2, 3); /** * Appends the \c printf style format string and arguments to the string. * * @param fmt \c printf style format string to initialize the string with. Must not overlap with \c *this. * @param ap \c va_list as initialized by \c va_start. Arguments must not overlap with \c *this. * @return \c *this. * * @throws std::length_error if the resulting string would be larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& append_vprintf(const char* fmt, va_list ap); /** * Appends \p str to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param str The string to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator+=(const string& str); /** * Appends the character \p c to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param c Character to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator+=(value_type c); /** * Appends the null-terminated string \p s to the end of the string. Behavior is undefined if \p s is not a valid * string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param s String to append characters from. * * @return \c *this. * * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator+=(const value_type* s); /** * Appends characters in \p ilist to the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param ilist Initializer list of characters to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator+=(std::initializer_list<value_type> ilist); /** * Appends \p str to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param str The string to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator+=(const std::string& str); /** * Appends \p sv to the end of the string. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param sv The string view to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& operator+=(const carb::cpp::string_view& sv); #if CARB_HAS_CPP17 /** * Implicitly converts @c t to type `std::string_view` and appends it to the end of the string. This overload * participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param t Object that can be converted to `std::string_view` to append. * * @return \c *this. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& operator+=(const T& t); #endif /** * Compares \p str to this string. * * \code * Comparison is performed as follows: * If Traits::compare(this, str, min(size(), str.size())) < 0, a negative value is returned * If Traits::compare(this, str, min(size(), str.size())) == 0, then: * If size() < str.size(), a negative value is returned * If size() = str.size(), zero is returned * If size() > str.size(), a positive value is returned * If Traits::compare(this, str, min(size(), str.size())) > 0, a positive value is returned * \endcode * * @param str String to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. */ constexpr int compare(const string& str) const noexcept; /** * Compares \p str to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param str String to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size(). */ constexpr int compare(size_type pos1, size_type n1, const string& str) const; /** * Compares `str.substr(pos2, n2)` to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param str String to compare to. * @param pos2 Position to start other substring. * @param n2 Number of characters in other substring. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`. */ constexpr int compare(size_type pos1, size_type n1, const string& str, size_type pos2, size_type n2 = npos) const; /** * Compares the null-terminated string \p s to this string. * * @see compare() for details on how the comparison is performed. * * @param s String to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr int compare(const value_type* s) const; /** * Compares the null-terminated string \p s to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param s String to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr int compare(size_type pos1, size_type n1, const value_type* s) const; /** * Compares the first \p n2 characters of string string \p s to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param s String to compare to. * @param n2 Number of characters of \p s to compare. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr int compare(size_type pos1, size_type n1, const value_type* s, size_type n2) const; /** * Compares \p str to this string. * * @see compare() for details on how the comparison is performed. * * @param str String to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. */ CARB_CPP20_CONSTEXPR int compare(const std::string& str) const noexcept; /** * Compares \p str to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param str String to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size(). */ CARB_CPP20_CONSTEXPR int compare(size_type pos1, size_type n1, const std::string& str) const; /** * Compares `str.substr(pos2, n2)` to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param str String to compare to. * @param pos2 Position to start other substring. * @param n2 Number of characters in other substring. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`. */ CARB_CPP20_CONSTEXPR int compare( size_type pos1, size_type n1, const std::string& str, size_type pos2, size_type n2 = npos) const; /** * Compares \p sv to this string. * * @see compare() for details on how the comparison is performed. * * @param sv String view to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. */ constexpr int compare(const carb::cpp::string_view& sv) const noexcept; /** * Compares \p sv to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param sv String view to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size(). */ constexpr int compare(size_type pos1, size_type n1, const carb::cpp::string_view& sv) const; /** * Compares `sv.substr(pos2, n2)` to the substring `substr(pos1, n1)`. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param sv String view to compare to. * @param pos2 Position to start other substring. * @param n2 Number of characters in other substring. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`. */ constexpr int compare( size_type pos1, size_type n1, const carb::cpp::string_view& sv, size_type pos2, size_type n2 = npos) const; #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and compares it to the string. This overload * participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true. * * @see compare() for details on how the comparison is performed. * * @param t Object that can be converted to `std::string_view` to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr int compare(const T& t) const noexcept; /** * Implicitly converts @p t to type `std::string_view` and compares it to the substring `substr(pos1, n1)`. This * overload participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param t Object that can be converted to `std::string_view` to compare to. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size(). */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr int compare(size_type pos1, size_type n1, const T& t) const; /** * Implicitly converts @p t to type `std::string_view` and compares `sv.substr(pos2, n2)` to the substring * `substr(pos1, n1)`. This overload participates in overload resolution only if `std::is_convertible_v<const T&, * std::string_view>` is true. * * @see compare() for details on how the comparison is performed. * * @param pos1 Position to start this substring. * @param n1 Number of characters in this substring. * @param t Object that can be converted to `std::string_view` to compare to. * @param pos2 Position to start other substring. * @param n2 Number of characters in other substring. * * @return A negative value if \c *this appears before the other string in lexicographical order, * zero if \c *this and the other string compare equivalent, * or a positive value if \c *this appears after the other string in lexicographical order. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr int compare(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2 = npos) const; #endif /** * Checks if the string begins with the character \p c. * * @param c Character to check. * * @return true if the string starts with \p c, false otherwise. */ constexpr bool starts_with(value_type c) const noexcept; /** * Checks if the string begins with the string \p s. * * @param s String to check. * * @return true if the string starts with \p s, false otherwise. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr bool starts_with(const_pointer s) const; /** * Checks if the string begins with the string view \p sv. * * @param sv String view to check. * * @return true if the string starts with \p sv, false otherwise. */ constexpr bool starts_with(carb::cpp::string_view sv) const noexcept; #if CARB_HAS_CPP17 /** * Checks if the string begins with the string view \p sv. * * @param sv String view to check. * * @return true if the string starts with \p sv, false otherwise. */ constexpr bool starts_with(std::string_view sv) const noexcept; #endif /** * Checks if the string ends with the character \p c. * * @param c Character to check. * * @return true if the string ends with \p c, false otherwise. */ constexpr bool ends_with(value_type c) const noexcept; /** * Checks if the string ends with the string \p s. * * @param s String to check. * * @return true if the string ends with \p s, false otherwise. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr bool ends_with(const_pointer s) const; /** * Checks if the string ends with the string view \p sv. * * @param sv String view to check. * * @return true if the string ends with \p sv, false otherwise. */ constexpr bool ends_with(carb::cpp::string_view sv) const noexcept; #if CARB_HAS_CPP17 /** * Checks if the string ends with the string view \p sv. * * @param sv String view to check. * * @return true if the string ends with \p sv, false otherwise. */ constexpr bool ends_with(std::string_view sv) const noexcept; #endif /** * Checks if the string contains the character \p c. * * @param c Character to check. * * @return true if the string contains \p c, false otherwise. */ constexpr bool contains(value_type c) const noexcept; /** * Checks if the string contains the string \p s. * * @param s String to check. * * @return true if the string contains \p s, false otherwise. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr bool contains(const_pointer s) const; /** * Checks if the string contains the string view \p sv. * * @param sv String view to check. * * @return true if the string contains \p sv, false otherwise. */ constexpr bool contains(carb::cpp::string_view sv) const noexcept; #if CARB_HAS_CPP17 /** * Checks if the string contains the string view \p sv. * * @param sv String view to check. * * @return true if the string contains \p sv, false otherwise. */ constexpr bool contains(std::string_view sv) const noexcept; #endif /** * Replaces the portion of this string `[pos, pos + n1)` with \p str. If `n == npos`, or `pos + n` is greater than * size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param str String to replace characters with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size(). * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos1, size_type n1, const string& str); /** * Replaces the portion of this string `[pos, pos + n1)` with the substring `str.substr(pos2, n2)`. If * `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param str String to replace characters with. * @param pos2 Position of substring to replace characters with. * @param n2 Number of characters in the substring to replace with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos1, size_type n1, const string& str, size_type pos2, size_type n2 = npos); /** * Replaces the portion of this string `[i1, i2)` with `[j1, j2)`. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param j1 Start position of replacement characters. * @param j2 End position of replacement characters. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <class InputIterator> string& replace(const_iterator i1, const_iterator i2, InputIterator j1, InputIterator j2); /** * Replaces the portion of this string `[pos, pos + n1)` with \p n2 characters from string \p s. The character * sequence can contain null characters. If `n == npos`, or `pos + n` is greater than size(), the substring to * the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos Position to start replacement. * @param n1 Number of characters to replace. * @param s String to replace characters with. * @param n2 The number of replacement characters. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos, size_type n1, const value_type* s, size_type n2); /** * Replaces the portion of this string `[pos, pos + n1)` with the null-terminated string \p s. If `n == npos`, or * `pos + n` is greater than size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos Position to start replacement. * @param n1 Number of characters to replace. * @param s String to replace characters with. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos, size_type n1, const value_type* s); /** * Replaces the portion of this string `[pos, pos + n1)` with \p n2 copies of character \p c. If `n == npos`, or * `pos + n` is greater than size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos Position to start replacement. * @param n1 Number of characters to replace. * @param n2 Number of characters to replace with. * @param c Character to replace with. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos, size_type n1, size_type n2, value_type c); /** * Replaces the portion of this string `[pos, pos + n1)` with \p str. If `n == npos`, or `pos + n` is greater than * size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param str String to replace characters with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size(). * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos1, size_type n1, const std::string& str); /** * Replaces the portion of this string `[pos, pos + n1)` with the substring `str.substr(pos2, n2)`. If * `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param str String to replace characters with. * @param pos2 Position of substring to replace characters with. * @param n2 Number of characters in the substring to replace with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `str.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos1, size_type n1, const std::string& str, size_type pos2, size_type n2 = npos); /** * Replaces the portion of this string `[pos, pos + n1)` with \c sv. If `n == npos`, or `pos + n` is greater than * size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param sv String view to replace characters with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size(). * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos1, size_type n1, const carb::cpp::string_view& sv); /** * Replaces the portion of this string `[pos, pos + n1)` with the substring `sv.substr(pos2, n2)`. If * `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param sv String view to replace characters with. * @param pos2 Position of substring to replace characters with. * @param n2 Number of characters in the substring to replace with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(size_type pos1, size_type n1, const carb::cpp::string_view& sv, size_type pos2, size_type n2 = npos); #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and replaces the portion of this string `[pos, pos + n1)` * with \p sv. If `n == npos`, or `pos + n` is greater than size(), the substring to the end of the string is * replaced. This overload participates in overload resolution only if `std::is_convertible_v<const T&, * std::string_view>` is true. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param t Object that can be converted to `std::string_view` to replace characters with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size(). * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& replace(size_type pos1, size_type n1, const T& t); /** * Implicitly converts @p t to type `std::string_view` and replaces the portion of this string `[pos, pos + n1)` * with the substring `sv.substr(pos2, n2)`. If `n == npos`, or `pos + n is greater than size(), the substring to * the end of the string is replaced. This overload participates in overload resolution only if * `std::is_convertible_v<const T&, std::string_view>` is true. * * All pointers, references, and iterators may be invalidated. * * @param pos1 Position to start replacement. * @param n1 Number of characters to replace. * @param t Object that can be converted to `std::string_view` to replace characters with. * @param pos2 Position of substring to replace characters with. * @param n2 Number of characters in the substring to replace with. * * @return \c *this. * * @throws std::out_of_range if \p pos1 is greater than size() or \p pos2 is greater than `sv.size()`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& replace(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2); #endif /** * Replaces the portion of this string `[i1, i2)` with \p str. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param str String to replace characters with. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(const_iterator i1, const_iterator i2, const string& str); /** * Replaces the portion of this string `[i1, i2)` with \p n characters from string \p s. The character * sequence can contain null characters. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param s String to replace characters with. * @param n The number of replacement characters. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(const_iterator i1, const_iterator i2, const value_type* s, size_type n); /** * Replaces the portion of this string `[i1, i2)` with the null-terminated string \p s. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param s String to replace characters with. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(const_iterator i1, const_iterator i2, const value_type* s); /** * Replaces the portion of this string `[i1, i2)` with \p n copies of character \p c. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param n Number of characters to replace with. * @param c Character to replace with. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(const_iterator i1, const_iterator i2, size_type n, value_type c); /** * Replaces the portion of this string `[i1, i2)` with the characters in \p ilist. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param ilist Initializer list of character to replace with. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(const_iterator i1, const_iterator i2, std::initializer_list<value_type> ilist); /** * Replaces the portion of this string `[i1, i2)` with \p str. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param str String to replace characters with. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(const_iterator i1, const_iterator i2, const std::string& str); /** * Replaces the portion of this string `[i1, i2)` with \p sv. * * All pointers, references, and iterators may be invalidated. * @param sv String view to replace characters with. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace(const_iterator i1, const_iterator i2, const carb::cpp::string_view& sv); #if CARB_HAS_CPP17 /** * Implicitly converts @c t to type `std::string_view` and replaces the portion of this string `[i1, i2)` with * \p sv. This overload participates in overload resolution only if `std::is_convertible_v<const T&, * std::string_view>` is true. * * All pointers, references, and iterators may be invalidated. * @param t Object that can be converted to `std::string_view` to replace characters with. * * @return \c *this. * * @throws std::out_of_range if the range `[i1,i2)` is invalid (not in the range [begin(), end()], or * `i1 > i2`. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ template <typename T, typename = detail::is_sv_convertible<T>> string& replace(const_iterator i1, const_iterator i2, const T& t); #endif /** * Replaces the portion of this string `[pos, pos + n1)` with a \c printf style formatted string. If `n == npos`, or * `pos + n` is greater than size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos Position to start replacement. * @param n1 Number of characters to replace. * @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this. * @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace_format(size_type pos, size_type n1, const value_type* fmt, ...) CARB_PRINTF_FUNCTION(4, 5); /** * Replaces the portion of this string `[pos, pos + n1)` with a \c vprintf style formatted string. If `n == npos`, * or `pos + n` is greater than size(), the substring to the end of the string is replaced. * * All pointers, references, and iterators may be invalidated. * * @param pos Position to start replacement. * @param n1 Number of characters to replace. * @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this. * @param ap \c va_list as initialized with \c va_start. Arguments must not overlap with \c *this. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace_vformat(size_type pos, size_type n1, const value_type* fmt, va_list ap); /** * Replaces the portion of this string `[i1, i2)` with a \c printf style formatted string. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this. * @param ... additional arguments matching \p fmt. Arguments must not overlap with \c *this. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace_format(const_iterator i1, const_iterator i2, const value_type* fmt, ...) CARB_PRINTF_FUNCTION(4, 5); /** * Replaces the portion of this string `[i1, i2)` with a \c printf style formatted string. * * All pointers, references, and iterators may be invalidated. * * @param i1 Position to start replacement. * @param i2 Position to stop replacement. * @param fmt \c printf style format string to replace characters with. Must not overlap with \c *this. * @param ap \c va_list as initialized with \c va_start. Arguments must not overlap with \c *this. * * @return \c *this. * * @throws std::out_of_range if \p pos is greater than \c size(). * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws std::runtime_error if an overlap is detected or \c vsnprintf reports error. * @throws Allocation This function may throw any exception thrown during allocation. */ string& replace_vformat(const_iterator i1, const_iterator i2, const value_type* fmt, va_list ap); /** * Returns a substring from `[pos, pos + n)` of this string. If `n == npos`, or `pos + n` is greater than \ref * size(), the substring is to the end of the string. * * @param pos Position to start the substring. * @param n Number of characters to include in the substring. * * @return A new string containing the substring. * * @throws std::out_of_range if \p pos is greater than size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string substr(size_type pos = 0, size_type n = npos) const; /** * Copies a substring from `[pos, pos + n)` to the provided destination \p s. If `n == npos`, or `pos + n` is * greater than size(), the substring is to the end of the string. The resulting character sequence is not null * terminated. * * @param s Destination to copy characters to. * @param n Number of characters to include in the substring. * @param pos Position to start the substring. * * @return number of characters copied. * * @throws std::invalid_argument if \p s is \c nullptr. * @throws std::out_of_range if \p pos is greater than size(). */ constexpr size_type copy(value_type* s, size_type n, size_type pos = 0) const; /** * Resizes the string to contain \p n characters. If \p n is greater than size(), copies of the character \p c * are appended. If \p n is smaller than size(), the string is shrunk to size \p n. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param n New size of the string. * @param c Character to append when growing the string. * * @return none. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ void resize(size_type n, value_type c); /** * Resizes the string to contain \p n characters. If \p n is greater than size(), copies of \c NUL are * appended. If \p n is smaller than size(), the string is shrunk to size \p n. * * If reallocation occurs, all pointers, references, and iterators are invalidated. * * @param n New size of the string. * * @return none. * * @throws std::length_error if the function would result in size() being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ void resize(size_type n); /** * Swaps the contents of this string with \p str. * * All pointers, references, and iterators may be invalidated. * * @param str The string to swap with. * * @return none. */ void swap(string& str) noexcept; /** * Finds the first substring of this string that matches \p str. The search begins at \p pos. * * @param str String to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ constexpr size_type find(const string& str, size_type pos = 0) const noexcept; /** * Finds the first substring of this string that matches the first \p n characters of \p s. The string may contain * nulls.The search begins at \p pos. * * @param s String to find. * @param pos Position to begin the search. * @param n Number of characters to search for. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find(const value_type* s, size_type pos, size_type n) const; /** * Finds the first substring of this string that matches the null-terminated string \p s. The search begins at * \p pos. * * @param s String to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find(const value_type* s, size_type pos = 0) const; /** * Finds the first substring of this string that matches \p str. The search begins at \p pos. * * @param str String to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ CARB_CPP20_CONSTEXPR size_type find(const std::string& str, size_type pos = 0) const noexcept; /** * Finds the first substring of this string that matches \p sv. The search begins at \p pos. * * @param sv String view to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ constexpr size_type find(const carb::cpp::string_view& sv, size_type pos = 0) const noexcept; #if CARB_HAS_CPP17 /** * Implicitly converts @c t to type `std::string_view` and finds the first substring of this string that matches it. * The search begins at \p pos. This overload participates in overload resolution only if * `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr size_type find(const T& t, size_type pos = 0) const noexcept; #endif /** * Finds the first substring of this string that matches \p c. The search begins at \p pos. * * @param c Character to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ constexpr size_type find(value_type c, size_type pos = 0) const noexcept; /** * Finds the last substring of this string that matches \p str. The search begins at \p pos. If `pos == npos` or * `pos >= size()`, the whole string is searched. * * @param str String to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ constexpr size_type rfind(const string& str, size_type pos = npos) const noexcept; /** * Finds the last substring of this string that matches the first \p n characters of \p s. The string may contain * nulls.The search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. * * @param s String to find. * @param pos Position to begin the search. * @param n Number of characters to search for. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type rfind(const value_type* s, size_type pos, size_type n) const; /** * Finds the last substring of this string that matches the null-terminated string \p s. The search begins at * \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. * * @param s String to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type rfind(const value_type* s, size_type pos = npos) const; /** * Finds the last substring of this string that matches \p c. The search begins at \p pos. If `pos == npos` or * `pos >= size()`, the whole string is searched. * * @param c Character to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ constexpr size_type rfind(value_type c, size_type pos = npos) const noexcept; /** * Finds the last substring of this string that matches \p str. The search begins at \p pos. If `pos == npos` or * `pos >= size()`, the whole string is searched. * * @param str String to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ CARB_CPP20_CONSTEXPR size_type rfind(const std::string& str, size_type pos = npos) const noexcept; /** * Finds the last substring of this string that matches \p sv. The search begins at \p pos. If `pos == npos` or * `pos >= size()`, the whole string is searched. * * @param sv String view to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ constexpr size_type rfind(const carb::cpp::string_view& sv, size_type pos = npos) const noexcept; #if CARB_HAS_CPP17 /** * Implicitly converts @c t to type `std::string_view` and finds the last substring of this string that matches it. * The search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. This * overload participates in overload resolution only if `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` to find. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr size_type rfind(const T& t, size_type pos = npos) const noexcept; #endif /** * Finds the first character equal to one of the characters in string \p str. The search begins at \p pos. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ constexpr size_type find_first_of(const string& str, size_type pos = 0) const noexcept; /** * Finds the first character equal to one of the characters in the first \p n characters of string \p s. The search * begins at \p pos. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * @param n Number of characters in \p s to search for. * * @return Position of the first found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr */ constexpr size_type find_first_of(const value_type* s, size_type pos, size_type n) const; /** * Finds the first character equal to one of the characters in null-terminated string \p s. The search begins at * \p pos. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find_first_of(const value_type* s, size_type pos = 0) const; /** * Finds the first character equal to \p c. The search begins at \p pos. * * @param c Character to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ constexpr size_type find_first_of(value_type c, size_type pos = 0) const noexcept; /** * Finds the first character equal to one of the characters in string \p str. The search begins at \p pos. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ CARB_CPP20_CONSTEXPR size_type find_first_of(const std::string& str, size_type pos = 0) const noexcept; /** * Finds the first character equal to one of the characters in string \p sv. The search begins at \p pos. * * @param sv String view containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ constexpr size_type find_first_of(const carb::cpp::string_view& sv, size_type pos = 0) const noexcept; #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and finds the first character equal to one of the characters * in that string view. The search begins at \p pos. This overload participates in overload resolution only if * `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr size_type find_first_of(const T& t, size_type pos = 0) const noexcept; #endif /** * Finds the last character equal to one of the characters in string \p str. The search begins at \p pos. If * `pos == npos` or `pos >= size()`, the whole string is searched. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ constexpr size_type find_last_of(const string& str, size_type pos = npos) const noexcept; /** * Finds the last character equal to one of the characters in the first \p n characters of string \p s. The search * begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * @param n Number of characters in \p s to search for. * * @return Position of the last found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find_last_of(const value_type* s, size_type pos, size_type n) const; /** * Finds the last character equal to one of the characters in the null-terminated string \p s. The search * begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find_last_of(const value_type* s, size_type pos = npos) const; /** * Finds the last character equal to \p c. The search begins at \p pos. If `pos == npos` or `pos >= size()`, * the whole string is searched. * * @param c Character to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ constexpr size_type find_last_of(value_type c, size_type pos = npos) const noexcept; /** * Finds the last character equal to one of the characters in string \p str. The search begins at \p pos. If * `pos == npos` or `pos >= size()`, the whole string is searched. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ CARB_CPP20_CONSTEXPR size_type find_last_of(const std::string& str, size_type pos = npos) const noexcept; /** * Finds the last character equal to one of the characters in string view \p sv. The search begins at \p pos. If * `pos == npos` or `pos >= size()`, the whole string is searched. * * @param sv String view containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ constexpr size_type find_last_of(const carb::cpp::string_view& sv, size_type pos = npos) const noexcept; #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and finds the last character equal to one of the characters * in that string view. The search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is * searched. The search begins at \p pos. This overload participates in overload resolution only if * `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr size_type find_last_of(const T& t, size_type pos = npos) const noexcept; #endif /** * Finds the first character not equal to one of the characters in string \p str. The search begins at \p pos. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ constexpr size_type find_first_not_of(const string& str, size_type pos = 0) const noexcept; /** * Finds the first character not equal to one of the characters in the first \p n characters of string \p s. The * search begins at \p pos. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * @param n Number of characters in \p s to search for. * * @return Position of the first found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find_first_not_of(const value_type* s, size_type pos, size_type n) const; /** * Finds the first character not equal to one of the characters in null-terminated string \p s. The search begins at * \p pos. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find_first_not_of(const value_type* s, size_type pos = 0) const; /** * Finds the first character equal to \p c. The search begins at \p pos. * * @param c Character to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ constexpr size_type find_first_not_of(value_type c, size_type pos = 0) const noexcept; /** * Finds the first character not equal to one of the characters in string \p str. The search begins at \p pos. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ CARB_CPP20_CONSTEXPR size_type find_first_not_of(const std::string& str, size_type pos = 0) const noexcept; /** * Finds the first character not equal to one of the characters in string view \p sv. The search begins at \p pos. * * @param sv String view containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first found character, or \c npos if no character is found. */ constexpr size_type find_first_not_of(const carb::cpp::string_view& sv, size_type pos = 0) const noexcept; #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and finds the first character not equal to one of the * characters in that string view. The search begins at \p pos. This overload participates in overload resolution * only if `std::is_convertible_v<const T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr size_type find_first_not_of(const T& t, size_type pos = 0) const noexcept; #endif /** * Finds the last character not equal to one of the characters in string \p str. The search begins at \p pos. If * `pos == npos` or `pos >= size()`, the whole string is searched. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ constexpr size_type find_last_not_of(const string& str, size_type pos = npos) const noexcept; /** * Finds the last character not equal to one of the characters in the first \p n characters of string \p s. The * search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * @param n Number of characters in \p s to search for. * * @return Position of the last found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find_last_not_of(const value_type* s, size_type pos, size_type n) const; /** * Finds the last character not equal to one of the characters in the null-terminated string \p s. The * search begins at \p pos. If `pos == npos` or `pos >= size()`, the whole string is searched. * * @param s String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. * * @throws std::invalid_argument if \p s is \c nullptr. */ constexpr size_type find_last_not_of(const value_type* s, size_type pos = npos) const; /** * Finds the last character not equal to \p c. The search begins at \p pos. If `pos == npos` or * `pos >= size()`, the whole string is searched. * * @param c Character to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ constexpr size_type find_last_not_of(value_type c, size_type pos = npos) const noexcept; /** * Finds the last character not equal to one of the characters in string \p str. The search begins at \p pos. If * `pos == npos` or `pos >= size()`, the whole string is searched. * * @param str String containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ CARB_CPP20_CONSTEXPR size_type find_last_not_of(const std::string& str, size_type pos = npos) const noexcept; /** * Finds the last character not equal to one of the characters in string view \p sv. The search begins at \p pos. If * `pos == npos` or `pos >= size()`, the whole string is searched. * * @param sv String view containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the last found character, or \c npos if no character is found. */ constexpr size_type find_last_not_of(const carb::cpp::string_view& sv, size_type pos = npos) const noexcept; #if CARB_HAS_CPP17 /** * Implicitly converts @p t to type `std::string_view` and finds the last character not equal to one of the * characters in that string view. The search begins at \p pos. If `pos == npos` or `pos >= size()`, the * whole string is searched. This overload participates in overload resolution only if `std::is_convertible_v<const * T&, std::string_view>` is true. * * @param t Object that can be converted to `std::string_view` containing the characters to search for. * @param pos Position to begin the search. * * @return Position of the first character of the matching substring, or \c npos if no such substring exists. */ template <typename T, typename = detail::is_sv_convertible<T>> constexpr size_type find_last_not_of(const T& t, size_type pos = npos) const noexcept; #endif private: // Size of the character buffer for small string optimization constexpr static size_type kSMALL_STRING_SIZE = 32; // The last byte of the SSO buffer contains the remaining size in the buffer constexpr static size_type kSMALL_SIZE_OFFSET = kSMALL_STRING_SIZE - 1; // Sentinel value indicating that the string is using heap allocated storage constexpr static value_type kSTRING_IS_ALLOCATED = std::numeric_limits<char>::max(); // Struct that holds the data for an allocated string. This could be an anonymous struct inside the union, // however naming it outside the union allows for the static_asserts below for ABI safety. struct allocated_data { CARB_VIZ pointer m_ptr; CARB_VIZ size_type m_size; CARB_VIZ size_type m_capacity; }; union { CARB_VIZ allocated_data m_allocated_data; /** * Local buffer for small string optimization. When the string is small enough to fit in the local buffer, the * last byte is the size remaining in the buffer. This has the advantage of when the local buffer is full, the * size remaining will be 0, which acts as the NUL terminator for the local string. When the string is larger * than the buffer, the last byte will be m_sentinel_value, indicated the string is allocated. */ CARB_VIZ value_type m_local_data[kSMALL_STRING_SIZE]; }; static_assert(kSMALL_STRING_SIZE == 32, "ABI-safety: Cannot change the small string optimization size"); static_assert(size_type(kSTRING_IS_ALLOCATED) >= kSMALL_STRING_SIZE, "Invalid assumption: Sentinel Value must be greater than max small string size."); static_assert(sizeof(allocated_data) == 24, "ABI-safety: Cannot change allocated data size"); static_assert(offsetof(allocated_data, m_ptr) == 0, "ABI-safety: Member offset cannot change"); static_assert(offsetof(allocated_data, m_size) == 8, "ABI-safety: Member offset cannot change"); static_assert(offsetof(allocated_data, m_capacity) == 16, "ABI-safety: Member offset cannot change"); static_assert(sizeof(allocated_data) < kSMALL_STRING_SIZE, "Invalid assumption: sizeof(allocated_data) must be less than the small string size."); // Helper functions constexpr bool is_local() const; constexpr void set_local(size_type new_size) noexcept; constexpr void set_allocated() noexcept; constexpr reference get_reference(size_type pos) noexcept; constexpr const_reference get_reference(size_type pos) const noexcept; constexpr pointer get_pointer(size_type pos) noexcept; constexpr const_pointer get_pointer(size_type pos) const noexcept; constexpr void set_empty() noexcept; constexpr void range_check(size_type pos, size_type size, const char* function) const; // Checks that pos is within the range [begin(), end()] constexpr void range_check(const_iterator pos, const char* function) const; // Checks that first is within the range [begin(), end()], that last is within the range [begin(), end()], and that // first <= last. constexpr void range_check(const_iterator first, const_iterator last, const char* function) const; // Checks if current+n > max_size(). If it is not, returns current+n. constexpr size_type length_check(size_type current, size_type n, const char* function) const; constexpr void set_size(size_type new_size) noexcept; constexpr bool should_allocate(size_type n) const noexcept; constexpr bool overlaps_this_string(const_pointer s) const noexcept; void overlap_check(const_pointer s) const; // Calls std::vsnprintf, but throws if it fails size_type vsnprintf_check(char* buffer, size_type buffer_size, const char* format, va_list args); template <class... Args> size_type snprintf_check(char* buffer, size_type buffer_size, const char* format, Args&&... args); void allocate_if_necessary(size_type size); void initialize(const_pointer src, size_type size); template <typename InputIterator> void initialize(InputIterator begin, InputIterator end, size_type size); void dispose(); pointer allocate_buffer(size_type old_capacity, size_type& new_capacity); void grow_buffer_to(size_type new_capacity); // Grows a buffer to new_size, fills it with the data from the three provided pointers, and swaps the new buffer // for the old one. This is used in functions like insert and replace, which may need to fill the new buffer with // characters from multiple locations. void grow_buffer_and_fill( size_type new_size, const_pointer p1, size_type s1, const_pointer p2, size_type s2, const_pointer p3, size_type s3); template <class InputIterator> void grow_buffer_and_append(size_type new_size, InputIterator first, InputIterator last); // Internal implementations string& assign_internal(const_pointer src, size_type new_size); template <typename InputIterator> string& assign_internal(InputIterator begin, InputIterator end, size_type new_size); string& insert_internal(size_type pos, value_type c, size_type n); string& insert_internal(size_type pos, const_pointer src, size_type n); string& append_internal(const_pointer src, size_type n); constexpr int compare_internal(const_pointer this_str, const_pointer other_str, size_type this_size, size_type other_size) const noexcept; void replace_setup(size_type pos, size_type replaced_size, size_type replacement_size); }; static_assert(std::is_standard_layout<string>::value, "string must be standard layout"); // Not interop-safe because not // trivially copyable static_assert(sizeof(string) == 32, "ABI Safety: String must be 32 bytes"); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const string& lhs, const string& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const string& lhs, const char* rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::invalid_argument if \p rhs is \c nullptr. * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const string& lhs, char rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const string& lhs, const std::string& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::invalid_argument if \p lhs is \c nullptr. * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const char* lhs, const string& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs Character the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(char lhs, const string& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const std::string& lhs, const string& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(string&& lhs, string&& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(string&& lhs, const string& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::invalid_argument if \p rhs is \c nullptr. * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(string&& lhs, const char* rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs Character that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(string&& lhs, char rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(string&& lhs, const string& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const string& lhs, string&& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::invalid_argument if \p lhs is \c nullptr. * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const char* lhs, string&& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs Character the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(char lhs, string&& rhs); /** * Creates a new string by concatenating \p lhs and \p rhs. * * @param lhs String the comes first in the new string. * @param rhs String that comes second in the new string. * * @return A new string containing the characters from \p lhs followed by the characters from \p rhs. * * @throws std::length_error if the resulting string would be being larger than max_size(). * @throws Allocation This function may throw any exception thrown during allocation. */ string operator+(const std::string& lhs, string&& rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are equal, false otherwise. */ constexpr bool operator==(const string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are equal, false otherwise. * * @throws std::invalid_argument if \p rhs is \c nullptr. */ constexpr bool operator==(const string& lhs, const char* rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are equal, false otherwise. * * @throws std::invalid_argument if \p lhs is \c nullptr. */ constexpr bool operator==(const char* lhs, const string& rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are equal, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator==(const string& lhs, const std::string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are equal, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator==(const std::string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are not equal, false otherwise. */ constexpr bool operator!=(const string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are not equal, false otherwise. * * @throws std::invalid_argument if \p rhs is \c nullptr. */ constexpr bool operator!=(const string& lhs, const char* rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are not equal, false otherwise. * * @throws std::invalid_argument if \p lhs is \c nullptr. */ constexpr bool operator!=(const char* lhs, const string& rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are not equal, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator!=(const string& lhs, const std::string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs and \p rhs are not equal, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator!=(const std::string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than \p rhs, false otherwise. */ constexpr bool operator<(const string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than \p rhs, false otherwise. * * @throws std::invalid_argument if \p rhs is \c nullptr. */ constexpr bool operator<(const string& lhs, const char* rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than \p rhs, false otherwise. * * @throws std::invalid_argument if \p lhs is \c nullptr. */ constexpr bool operator<(const char* lhs, const string& rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator<(const string& lhs, const std::string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator<(const std::string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than or equal to \p rhs, false otherwise. */ constexpr bool operator<=(const string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than or equal to \p rhs, false otherwise. * * @throws std::invalid_argument if \p rhs is \c nullptr. */ constexpr bool operator<=(const string& lhs, const char* rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than or equal to \p rhs, false otherwise. * * @throws std::invalid_argument if \p lhs is \c nullptr. */ constexpr bool operator<=(const char* lhs, const string& rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than or equal to \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator<=(const string& lhs, const std::string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is less than or equal to \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator<=(const std::string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than \p rhs, false otherwise. */ constexpr bool operator>(const string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than \p rhs, false otherwise. * * @throws std::invalid_argument if \p rhs is \c nullptr. */ constexpr bool operator>(const string& lhs, const char* rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than \p rhs, false otherwise. * * @throws std::invalid_argument if \p lhs is \c nullptr. */ constexpr bool operator>(const char* lhs, const string& rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator>(const string& lhs, const std::string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator>(const std::string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than or equal to \p rhs, false otherwise. */ constexpr bool operator>=(const string& lhs, const string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than or equal to \p rhs, false otherwise. * * @throws std::invalid_argument if \p rhs is \c nullptr. */ constexpr bool operator>=(const string& lhs, const char* rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than or equal to \p rhs, false otherwise. * * @throws std::invalid_argument if \p lhs is \c nullptr. */ constexpr bool operator>=(const char* lhs, const string& rhs); /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than or equal to \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator>=(const string& lhs, const std::string& rhs) noexcept; /** * Compares \p lhs and \p rhs. All comparisons are done lexicographically using omni::string::compare(). * * @param lhs Left hand side of the comparison. * @param rhs Right hand side of the comparison. * * @return true if \p lhs is greater than or equal to \p rhs, false otherwise. */ CARB_CPP20_CONSTEXPR bool operator>=(const std::string& lhs, const string& rhs) noexcept; /** * Swaps \p lhs and \p rhs via `lhs.swap(rhs)`. * * @param lhs String to swap. * @param rhs String to swap. * * @return none. */ void swap(string& lhs, string& rhs) noexcept; /** * Erases all instances of \p val from \p str. * * @param str String to erase from. * @param val Character to erase. * * @return The number of characters erased. */ template <typename U> CARB_CPP20_CONSTEXPR string::size_type erase(string& str, const U& val); /** * Erases all elements of \p str the satisfy \p pred. * * @param str String to erase from. * @param pred Predicate to check characters with. * * @return The number of characters erased. */ template <typename Pred> CARB_CPP20_CONSTEXPR string::size_type erase_if(string& str, Pred pred); /** * Output stream operator overload. Outputs the contents of \p str to the stream \p os. * * @param os Stream to output the string to. * @param str The string to output. * * @return \p os. * * @throws std::ios_base::failure if an exception is thrown during output. */ std::basic_ostream<char, std::char_traits<char>>& operator<<(std::basic_ostream<char, std::char_traits<char>>& os, const string& str); /** * Input stream operator overload. Extracts a string from \p is into \p str. * * @param is Stream to get input from. * @param str The string to put input into. * * @return \p is. * * @throws std::ios_base::failure if no characters are extracted or an exception is thrown during input. */ std::basic_istream<char, std::char_traits<char>>& operator>>(std::basic_istream<char, std::char_traits<char>>& is, string& str); /** * Reads characters from the input stream \p input and places them in the string \p str. Characters are read until * end-of-file is reached on \p input, the next character in the input is \p delim, or max_size() characters have * been extracted. * * @param input Stream to get input from. * @param str The string to put input into. * @param delim Character that indicates that extraction should end. * * @return \p input. */ std::basic_istream<char, std::char_traits<char>>& getline(std::basic_istream<char, std::char_traits<char>>&& input, string& str, char delim); /** * Reads characters from the input stream \p input and places them in the string \p str. Characters are read until * end-of-file is reached on \p input, the next character in the input it \c '\\n', or max_size() characters have * been extracted. * * @param input Stream to get input from. * @param str The string to put input into. * * @return \p input. */ std::basic_istream<char, std::char_traits<char>>& getline(std::basic_istream<char, std::char_traits<char>>&& input, string& str); /** * Interprets the string \p str as a signed integer value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * @param base The number base. * * @return Integer value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtol) sets \c errno to \c ERANGE. */ int stoi(const string& str, std::size_t* pos = nullptr, int base = 10); /** * Interprets the string \p str as a signed integer value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * @param base The number base. * * @return Integer value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtol) sets \c errno to \c ERANGE. */ long stol(const string& str, std::size_t* pos = nullptr, int base = 10); /** * Interprets the string \p str as a signed integer value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * @param base The number base. * * @return Integer value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtoll) sets \c errno to \c ERANGE. */ long long stoll(const string& str, std::size_t* pos = nullptr, int base = 10); /** * Interprets the string \p str as a unsigned integer value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * @param base The number base. * * @return Unsigned Integer value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtoul) sets \c errno to \c ERANGE. */ unsigned long stoul(const string& str, std::size_t* pos = nullptr, int base = 10); /** * Interprets the string \p str as a unsigned integer value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * @param base The number base. * * @return Unsigned Integer value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtoull) sets \c errno to \c ERANGE. */ unsigned long long stoull(const string& str, std::size_t* pos = nullptr, int base = 10); /** * Interprets the string \p str as a floating point value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * * @return Floating point value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtof) sets \c errno to \c ERANGE. */ float stof(const string& str, std::size_t* pos = nullptr); /** * Interprets the string \p str as a floating point value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * * @return Floating point value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtod) sets \c errno to \c ERANGE. */ double stod(const string& str, std::size_t* pos = nullptr); /** * Interprets the string \p str as a floating point value. * * @param str The string to convert. * @param pos Address of an integer to store the number of characters processed. * * @return Floating point value corresponding to the contents of \p str. * * @throws std::invalid_argument If no conversion could be performed. * @throws std::out_of_range If the converted value would fall out of the range of the result type or if the * underlying function (\c std::strtold) sets \c errno to \c ERANGE. */ long double stold(const string& str, std::size_t* pos = nullptr); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(int value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(long value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(long long value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(unsigned value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(unsigned long value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(unsigned long long value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(float value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(double value); /** * Converts the numerical value \p value to a string. * * @param value Value to convert. * * @return A string representing the value. * * @throws Allocation This function may throw any exception thrown during allocation. */ string to_string(long double value); } // namespace omni namespace std { /** * Hash specialization for std::string */ template <> struct hash<omni::string> { /** Argument type alias. */ using argument_type = omni::string; /** Result type alias. */ using result_type = std::size_t; /** Hash operator */ size_t operator()(const argument_type& x) const noexcept { return carb::hashBuffer(x.data(), x.size()); } }; } // namespace std #include "String.inl" #pragma pop_macro("max") CARB_IGNOREWARNING_MSC_POP
omniverse-code/kit/include/omni/Span.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 Implementation of \ref omni::span #pragma once #include "../carb/cpp/Span.h" namespace omni { //! @copydoc carb::cpp::dynamic_extent constexpr auto dynamic_extent = carb::cpp::dynamic_extent; //! @copydoc carb::cpp::span template <class T, size_t Extent = dynamic_extent> using span = carb::cpp::span<T, Extent>; } // namespace omni
omniverse-code/kit/include/omni/String.inl
// Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include <algorithm> #include <cstdarg> #include <cstring> #include <locale> #include "../carb/Memory.h" #include "../carb/extras/ScopeExit.h" #include "core/Assert.h" // TODO(saxonp): Replace usage of std::memcpy with traits_type::copy and std::memmove with traits_type::move when // making the functions using those functions constexpr. std::memcpy and std::memmove are currently used in // non-constexpr functions for performance reasons because efficient constexpr copy functions are not available until // C++20. // `pyerrors.h` defines vsnprintf() to be _vsnprintf() on Windows, which is non-standard and // breaks things. In the more modern C++ that we're using, std::vsnprintf() does what we want, // so get rid of the baddness from `pyerrors.h` here. As a service to others, we'll also undefine // `snprintf` symbol that is also defined in `pyerrors.h`. #if defined(Py_ERRORS_H) && CARB_PLATFORM_WINDOWS # undef vsnprintf # undef snprintf #endif namespace omni { namespace detail { constexpr void char_traits::assign(char& dest, const char& c) noexcept { dest = c; } constexpr char* char_traits::assign(char* dest, std::size_t count, char c) noexcept { for (std::size_t i = 0; i < count; ++i) { dest[i] = c; } return dest; } constexpr void char_traits::move(char* dest, const char* source, std::size_t count) noexcept { // Fallback basic constexpr implemenation if (std::less<const char*>{}(source, dest)) { // If source is less than dest, copy from the back to the front to avoid overwriting characters in source if // source and dest overlap. for (std::size_t i = count; i > 0; --i) { dest[i - 1] = source[i - 1]; } } else if (std::greater<const char*>{}(source, dest)) { // If source is greater than dest, copy from the the front to the back for (std::size_t i = 0; i < count; ++i) { dest[i] = source[i]; } } } constexpr void char_traits::copy(char* dest, const char* source, std::size_t count) noexcept { // Fallback basic constexpr implemenation for (std::size_t i = 0; i < count; ++i) { dest[i] = source[i]; } } constexpr int char_traits::compare(const char* s1, const char* s2, std::size_t count) noexcept { #if CARB_HAS_CPP17 return std::char_traits<char>::compare(s1, s2, count); #else for (std::size_t i = 0; i < count; ++i) { if (s1[i] < s2[i]) { return -1; } else if (s1[i] > s2[i]) { return 1; } } return 0; #endif } constexpr std::size_t char_traits::length(const char* s) noexcept { #if CARB_HAS_CPP17 return std::char_traits<char>::length(s); #else std::size_t result = 0; while (s[result] != char()) { ++result; } return result; #endif } constexpr const char* char_traits::find(const char* s, std::size_t count, char ch) noexcept { #if CARB_HAS_CPP17 return std::char_traits<char>::find(s, count, ch); #else for (std::size_t i = 0; i < count; ++i) { if (s[i] == ch) { return &s[i]; } } return nullptr; #endif } #pragma push_macro("min") #undef min #pragma push_macro("max") #undef max template <typename TRet, typename Ret = TRet, typename... Base> Ret _sto_helper(TRet (*conversion_function)(const char*, char**, Base...), const char* name, const char* str, std::size_t* pos, Base... base) { Ret result; char* endptr; // Save errno and restore it after this function completes // Ideally this could use CARB_SCOPE_EXIT, however, this causes an ICE in GCC7 in some cases. // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83204 struct errno_saver { errno_saver() : m_saved(errno) { errno = 0; } ~errno_saver() { if (errno == 0) { errno = m_saved; } } const int m_saved; } saver{}; struct range_check { static bool check(TRet, std::false_type) { return false; } static bool check(TRet val, std::true_type) { return val < TRet(std::numeric_limits<int>::min()) || val > TRet(std::numeric_limits<int>::max()); } }; const TRet conv_result = conversion_function(str, &endptr, base...); #if CARB_EXCEPTIONS_ENABLED if (endptr == str) { throw std::invalid_argument(name); } else if (errno == ERANGE || range_check::check(conv_result, std::is_same<Ret, int>{})) { throw std::out_of_range(name); } else { result = conv_result; } #else CARB_FATAL_UNLESS(endptr != str, "Unable to convert string: %s", name); CARB_FATAL_UNLESS((errno != ERANGE && !range_check::check(conv_result, std::is_same<Ret, int>{})), "Converted value out of range: %s ", name); result = conv_result; #endif if (pos) { *pos = endptr - str; } return result; } #pragma pop_macro("min") #pragma pop_macro("max") constexpr void null_check(const char* ptr, const char* function) { #if CARB_EXCEPTIONS_ENABLED if (ptr == nullptr) { throw std::invalid_argument(std::string(function) + " invalid nullptr argument"); } #else CARB_FATAL_UNLESS(ptr != nullptr, "%s invalid nullptr argument", function); #endif } } // namespace detail /* ------------------------------------------------------------------------------------------------------------------ */ /* Constructors */ /* ------------------------------------------------------------------------------------------------------------------ */ inline string::string() noexcept { set_empty(); } inline string::string(size_type n, value_type c) { size_type new_size = length_check(0, n, "string::string"); set_empty(); allocate_if_necessary(new_size); traits_type::assign(get_pointer(0), new_size, c); set_size(new_size); } inline string::string(const string& str, size_type pos) { str.range_check(pos, str.size(), "string::string"); set_empty(); initialize(str.data() + pos, str.size() - pos); } inline string::string(const string& str, size_type pos, size_type n) { str.range_check(pos, str.size(), "string::string"); set_empty(); size_type size = ::carb_min(n, str.size() - pos); initialize(str.data() + pos, size); } inline string::string(const value_type* s, size_type n) { set_empty(); if (n != size_type{ 0 }) ::omni::detail::null_check(s, "string::string"); initialize(s, n); } inline string::string(const value_type* s) { set_empty(); ::omni::detail::null_check(s, "string::string"); size_type new_size = length_check(0, traits_type::length(s), "string::string"); initialize(s, new_size); } template <typename InputIterator> string::string(InputIterator begin, InputIterator end) { set_empty(); initialize(begin, end, std::distance(begin, end)); } inline string::string(const string& str) { set_empty(); initialize(str.data(), str.size()); } inline string::string(string&& str) noexcept { set_empty(); if (str.is_local()) { std::memcpy(get_pointer(0), str.data(), str.size()); set_size(str.size()); str.set_size(0); } else { m_allocated_data.m_ptr = str.m_allocated_data.m_ptr; m_allocated_data.m_capacity = str.m_allocated_data.m_capacity; m_allocated_data.m_size = str.size(); set_allocated(); str.set_empty(); } } inline string::string(std::initializer_list<value_type> ilist) { set_empty(); initialize(ilist.begin(), ilist.end(), ilist.size()); } inline string::string(const std::string& str) { set_empty(); initialize(str.data(), str.size()); } inline string::string(const std::string& str, size_type pos, size_type n) { range_check(pos, str.size(), "string::string"); set_empty(); size_type size = ::carb_min(n, str.size() - pos); initialize(str.data() + pos, size); } inline string::string(const carb::cpp::string_view& sv) { set_empty(); initialize(sv.data(), sv.size()); } inline string::string(const carb::cpp::string_view& sv, size_type pos, size_type n) { range_check(pos, sv.size(), "string::string"); set_empty(); size_type size = ::carb_min(n, sv.size() - pos); initialize(sv.data() + pos, size); } #if CARB_HAS_CPP17 template <typename T, typename> string::string(const T& t) { const std::string_view sv = t; set_empty(); initialize(sv.data(), sv.size()); } template <typename T, typename> string::string(const T& t, size_type pos, size_type n) { const std::string_view sv = t; range_check(pos, sv.size(), "string::string"); set_empty(); size_type size = ::carb_min(n, sv.size() - pos); initialize(sv.data() + pos, size); } #endif // GCC 7 and/or GLIBC 2.27 seem to have a hard time with a string constructor that takes varargs. For instance, this // test case works just fine on MSVC 19 but fails on GCC 7: // // string s(formatted, "the %s brown fox jumped over %s %s %s%c %d", "quick", "the", "lazy", "dog", '.', 123456789); // expected: // "the quick brown fox jumped over the lazy dog. 123456789" (55 chars) // actual on GCC 7 / GLIBC 2.27: // "the quick brown fox jumped over the lazy dog" (48 chars) // // I suspect that this has something to do with the number of arguments (since some will be passed on the stack) // combined with how the constructor is compiled since append_printf() et al do not appear to have this issue. // Therefore, this function is implemented with variadic templates instead of varargs. template <class... Args> string::string(formatted_t, const char* fmt, Args&&... args) { ::omni::detail::null_check(fmt, "string::string"); set_empty(); // Optimistically try to format as a small string. If the string would be >= kSMALL_STRING_SIZE, it // returns the number of charaters that would be written given unlimited buffer. size_type fmt_size = snprintf_check(m_local_data, kSMALL_STRING_SIZE, fmt, std::forward<Args>(args)...); length_check(0, fmt_size, "string::string"); if (fmt_size >= kSMALL_STRING_SIZE) { allocate_if_necessary(fmt_size); // CARB_SCOPE_EXCEPT would be applicable here, but it is slow (much slower than a `try` block) and on older // versions of glibc (especially 2.17 which is what Centos7 uses) it can lock an internal mutex that is shared // with the loader, which can cause deadlocks. // If CARB_EXCEPTIONS_ENABLED is false, `snprintf_check` will terminate on failure. #if CARB_EXCEPTIONS_ENABLED try { #endif // If vsnprintf_check throws (it shouldn't), clean up. snprintf_check(get_pointer(0), fmt_size + 1, fmt, std::forward<Args>(args)...); #if CARB_EXCEPTIONS_ENABLED } catch (...) { dispose(); /*re-*/ throw; } #endif } set_size(fmt_size); } inline string::string(vformatted_t, const char* fmt, va_list ap) { ::omni::detail::null_check(fmt, "string::string"); set_empty(); va_list ap2; va_copy(ap2, ap); CARB_SCOPE_EXIT { va_end(ap2); }; // Optimistically try to format as a small string. If the string would be bigger than kSMALL_STRING_SIZE - 1, it // returns the number of characters that would be written. size_type fmt_size = vsnprintf_check(m_local_data, kSMALL_STRING_SIZE, fmt, ap); length_check(0, fmt_size, "string::string"); if (fmt_size >= kSMALL_STRING_SIZE) { allocate_if_necessary(fmt_size); CARB_SCOPE_EXCEPT { dispose(); }; // If vsnprintf_check throws (it shouldn't), clean up. vsnprintf_check(get_pointer(0), fmt_size + 1, fmt, ap2); } set_size(fmt_size); } /* ------------------------------------------------------------------------------------------------------------------ */ /* Destructor */ /* ------------------------------------------------------------------------------------------------------------------ */ inline string::~string() noexcept { dispose(); } /* ------------------------------------------------------------------------------------------------------------------ */ /* Assignment */ /* ------------------------------------------------------------------------------------------------------------------ */ inline string& string::operator=(const string& str) { // Because all omni::strings use the same allocator, we don't have to worry about allocator propogation or // incompatible allocators, we can simply copy the string. return this->assign(str); } inline string& string::operator=(string&& str) noexcept { // Store our current pointer so we can give it to the other string. pointer cur_data = nullptr; size_type cur_capacity = 0; if (!is_local()) { cur_data = m_allocated_data.m_ptr; cur_capacity = m_allocated_data.m_capacity; } // If other string is short string optimized, just copy if (str.is_local()) { // This is now a local string set_local(0); // Copy the data if (!str.empty()) { std::memcpy(get_pointer(0), str.data(), str.size()); } set_size(str.size()); } else { // This is now an allocated string set_allocated(); // Take the other string's pointer m_allocated_data.m_ptr = str.m_allocated_data.m_ptr; m_allocated_data.m_capacity = str.m_allocated_data.m_capacity; m_allocated_data.m_size = str.m_allocated_data.m_size; str.set_empty(); } if (cur_data != nullptr) { str.m_allocated_data.m_ptr = cur_data; str.m_allocated_data.m_capacity = cur_capacity; str.set_allocated(); } str.clear(); return *this; } inline string& string::operator=(const value_type* s) { ::omni::detail::null_check(s, "string::operator="); return this->assign(s); } inline string& string::operator=(value_type c) { return this->assign(1, c); } inline string& string::operator=(std::initializer_list<value_type> ilist) { return this->assign(ilist); } inline string& string::operator=(const std::string& str) { return this->assign(str); } inline string& string::operator=(const carb::cpp::string_view& sv) { return this->assign(sv); } #if CARB_HAS_CPP17 template <typename T, typename> string& string::operator=(const T& t) { return this->assign(t); } #endif /* ------------------------------------------------------------------------------------------------------------------ */ /* assign */ /* ------------------------------------------------------------------------------------------------------------------ */ inline string& string::assign(size_type n, value_type c) { size_type new_size = length_check(0, n, "string::assign"); grow_buffer_to(new_size); set_size(new_size); if (new_size) { traits_type::assign(get_pointer(0), new_size, c); } return *this; } inline string& string::assign(const string& str) { // Assigning an object to itself has no effect if (this != &str) { return assign_internal(str.data(), str.size()); } return *this; } inline string& string::assign(const string& str, size_type pos, size_type n) { str.range_check(pos, str.size(), "string::assign"); size_type new_size = ::carb_min(n, str.size() - pos); return assign_internal(str.data() + pos, new_size); } inline string& string::assign(string&& str) { return *this = std::move(str); } inline string& string::assign(const value_type* s, size_type n) { if (n != size_type{ 0 }) ::omni::detail::null_check(s, "string::assign"); return assign_internal(s, n); } inline string& string::assign(const value_type* s) { ::omni::detail::null_check(s, "string::assign"); return assign_internal(s, traits_type::length(s)); } template <class InputIterator> string& string::assign(InputIterator first, InputIterator last) { return assign_internal(first, last, std::distance(first, last)); } inline string& string::assign(std::initializer_list<value_type> ilist) { return assign_internal(ilist.begin(), ilist.end(), ilist.size()); } inline string& string::assign(const std::string& str) { return assign_internal(str.data(), str.size()); } inline string& string::assign(const std::string& str, size_type pos, size_type n) { range_check(pos, str.size(), "string::assign"); size_type new_size = ::carb_min(n, str.size() - pos); return assign_internal(str.data() + pos, new_size); } inline string& string::assign(const carb::cpp::string_view& sv) { return assign_internal(sv.data(), sv.size()); } inline string& string::assign(const carb::cpp::string_view& sv, size_type pos, size_type n) { range_check(pos, sv.size(), "string::assign"); size_type new_size = ::carb_min(n, sv.size() - pos); return assign_internal(sv.data() + pos, new_size); } #if CARB_HAS_CPP17 template <typename T, typename> string& string::assign(const T& t) { const std::string_view sv = t; return assign_internal(sv.data(), sv.size()); } template <typename T, typename> string& string::assign(const T& t, size_type pos, size_type n) { const std::string_view sv = t; range_check(pos, sv.size(), "string::assign"); size_type new_size = ::carb_min(n, sv.size() - pos); return assign_internal(sv.data() + pos, new_size); } #endif inline string& string::assign_printf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); CARB_SCOPE_EXIT { va_end(ap); }; return assign_vprintf(fmt, ap); } inline string& string::assign_vprintf(const char* fmt, va_list ap) { ::omni::detail::null_check(fmt, "string::assign_vprintf"); overlap_check(fmt); va_list ap2; va_copy(ap2, ap); CARB_SCOPE_EXIT { va_end(ap2); }; // Measure the string first size_type fmt_size = vsnprintf_check(nullptr, 0, fmt, ap); length_check(0, fmt_size, "assign_vprintf"); allocate_if_necessary(fmt_size); int check = std::vsnprintf(get_pointer(0), fmt_size + 1, fmt, ap2); OMNI_FATAL_UNLESS(check >= 0, "Unrecoverable error: vsnprintf failed"); set_size(fmt_size); return *this; } /* ------------------------------------------------------------------------------------------------------------------ */ /* Element Access */ /* ------------------------------------------------------------------------------------------------------------------ */ constexpr string::reference string::at(size_type pos) { range_check(pos, size(), "string::at"); return get_reference(pos); } constexpr string::const_reference string::at(size_type pos) const { range_check(pos, size(), "string::at"); return get_reference(pos); } constexpr string::reference string::operator[](size_type pos) { return get_reference(pos); } constexpr string::const_reference string::operator[](size_type pos) const { return get_reference(pos); } constexpr string::reference string::front() { return operator[](0); } constexpr string::const_reference string::front() const { return operator[](0); } constexpr string::reference string::back() { return operator[](size() - 1); } constexpr string::const_reference string::back() const { return operator[](size() - 1); } constexpr const string::value_type* string::data() const noexcept { return get_pointer(0); } constexpr string::value_type* string::data() noexcept { return get_pointer(0); } constexpr const string::value_type* string::c_str() const noexcept { return get_pointer(0); } constexpr string::operator carb::cpp::string_view() const noexcept { return carb::cpp::string_view(data(), size()); } #if CARB_HAS_CPP17 constexpr string::operator std::string_view() const noexcept { return std::string_view(data(), size()); } #endif /* ------------------------------------------------------------------------------------------------------------------ */ /* Iterators */ /* ------------------------------------------------------------------------------------------------------------------ */ constexpr string::iterator string::begin() noexcept { return iterator(get_pointer(0)); } constexpr string::const_iterator string::begin() const noexcept { return const_iterator(get_pointer(0)); } constexpr string::const_iterator string::cbegin() const noexcept { return const_iterator(get_pointer(0)); } constexpr string::iterator string::end() noexcept { return iterator(get_pointer(0) + size()); } constexpr string::const_iterator string::end() const noexcept { return const_iterator(get_pointer(0) + size()); } constexpr string::const_iterator string::cend() const noexcept { return const_iterator(get_pointer(0) + size()); } inline string::reverse_iterator string::rbegin() noexcept { return reverse_iterator(end()); } inline string::const_reverse_iterator string::rbegin() const noexcept { return const_reverse_iterator(end()); } inline string::const_reverse_iterator string::crbegin() const noexcept { return const_reverse_iterator(end()); } inline string::reverse_iterator string::rend() noexcept { return reverse_iterator(begin()); } inline string::const_reverse_iterator string::rend() const noexcept { return const_reverse_iterator(begin()); } inline string::const_reverse_iterator string::crend() const noexcept { return const_reverse_iterator(begin()); } /* ------------------------------------------------------------------------------------------------------------------ */ /* Capacity */ /* ------------------------------------------------------------------------------------------------------------------ */ constexpr bool string::empty() const noexcept { return size() == 0; } constexpr string::size_type string::size() const noexcept { if (is_local()) { return kSMALL_STRING_SIZE - m_local_data[kSMALL_SIZE_OFFSET] - 1; } else { return m_allocated_data.m_size; } } constexpr string::size_type string::length() const noexcept { return size(); } constexpr string::size_type string::max_size() const noexcept { return std::numeric_limits<size_type>::max() - 1; } inline void string::reserve(size_type new_cap) { // Don't shrink below size if (new_cap < size()) { new_cap = size(); } if (new_cap != capacity()) { // If the new capacity is greater than the current capacity, or if it is smaller (so we're shrinking), but does // not fit in the local buffer, we need to allocate if (new_cap > capacity() || new_cap >= kSMALL_STRING_SIZE) { // Allocate new buffer first in case the allocation throws pointer tmp_ptr = allocate_buffer(capacity(), new_cap); size_type tmp_size = size(); // Copy to new buffer, including null terminator std::memcpy(tmp_ptr, get_pointer(0), size() + 1); dispose(); set_allocated(); m_allocated_data.m_ptr = tmp_ptr; m_allocated_data.m_capacity = new_cap; m_allocated_data.m_size = tmp_size; } else if (!is_local()) { // The case where we have allocated a buffer, but our size could now fit in the local buffer, and the new // capacity can fit in the local buffer. pointer tmp_ptr = m_allocated_data.m_ptr; size_type tmp_size = m_allocated_data.m_size; // Mark the string as local and copy the data to the local buffer set_local(tmp_size); std::memcpy(get_pointer(0), tmp_ptr, tmp_size); set_size(tmp_size); carb::deallocate(tmp_ptr); } } } inline void string::reserve() { reserve(0); } constexpr string::size_type string::capacity() const noexcept { if (is_local()) { return kSMALL_STRING_SIZE - 1; } else { return m_allocated_data.m_capacity; } } inline void string::shrink_to_fit() { if (capacity() > size()) { reserve(0); } } /* ------------------------------------------------------------------------------------------------------------------ */ /* Operations */ /* ------------------------------------------------------------------------------------------------------------------ */ constexpr void string::clear() noexcept { set_size(0); } inline string& string::insert(size_type pos, size_type n, value_type c) { return insert_internal(pos, c, n); } inline string& string::insert(size_type pos, const value_type* s) { ::omni::detail::null_check(s, "string::insert"); return insert_internal(pos, s, traits_type::length(s)); } inline string& string::insert(size_type pos, const value_type* s, size_type n) { ::omni::detail::null_check(s, "string::insert"); return insert_internal(pos, s, n); } inline string& string::insert(size_type pos, const string& str) { return insert_internal(pos, str.data(), str.size()); } inline string& string::insert(size_type pos1, const string& str, size_type pos2, size_type n) { str.range_check(pos2, str.size(), "string::insert"); size_type substr_size = ::carb_min(n, (str.size() - pos2)); return insert_internal(pos1, str.get_pointer(pos2), substr_size); } inline string::iterator string::insert(const_iterator p, value_type c) { range_check(p, "string::insert"); size_type pos = std::distance(cbegin(), p); insert_internal(pos, c, 1); return iterator(get_pointer(pos)); } inline string::iterator string::insert(const_iterator p, size_type n, value_type c) { range_check(p, "string::insert"); size_type pos = std::distance(cbegin(), p); insert_internal(pos, c, n); return iterator(get_pointer(pos)); } template <class InputIterator> string::iterator string::insert(const_iterator p, InputIterator first, InputIterator last) { range_check(p, "string::insert"); size_type pos = std::distance(cbegin(), p); size_type n = std::distance(first, last); length_check(size(), n, "string::insert"); // Reuse the logic in replace to handle potentially overlapping regions replace(p, p, first, last); return iterator(get_pointer(pos)); } inline string::iterator string::insert(const_iterator p, std::initializer_list<value_type> ilist) { return insert(p, ilist.begin(), ilist.end()); } inline string& string::insert(size_type pos, const std::string& str) { return insert_internal(pos, str.data(), str.size()); } inline string& string::insert(size_type pos1, const std::string& str, size_type pos2, size_type n) { range_check(pos2, str.size(), "string::insert"); size_type substr_size = ::carb_min(n, (str.size() - pos2)); return insert_internal(pos1, str.data() + pos2, substr_size); } inline string& string::insert(size_type pos, const carb::cpp::string_view& sv) { return insert_internal(pos, sv.data(), sv.size()); } inline string& string::insert(size_type pos1, const carb::cpp::string_view& sv, size_type pos2, size_type n) { range_check(pos2, sv.size(), "string::insert"); size_type substr_size = ::carb_min(n, (sv.size() - pos2)); return insert_internal(pos1, sv.data() + pos2, substr_size); } #if CARB_HAS_CPP17 template <typename T, typename> string& string::insert(size_type pos, const T& t) { const std::string_view sv = t; return insert_internal(pos, sv.data(), sv.size()); } template <typename T, typename> string& string::insert(size_type pos1, const T& t, size_type pos2, size_type n) { const std::string_view sv = t; range_check(pos2, sv.size(), "string::insert"); size_type substr_size = ::carb_min(n, (sv.size() - pos2)); return insert_internal(pos1, sv.data() + pos2, substr_size); } #endif inline string& string::insert_printf(size_type pos, const char* fmt, ...) { va_list ap; va_start(ap, fmt); CARB_SCOPE_EXIT { va_end(ap); }; return insert_vprintf(pos, fmt, ap); } inline string& string::insert_vprintf(size_type pos, const char* fmt, va_list ap) { ::omni::detail::null_check(fmt, "string::insert_vprintf"); overlap_check(fmt); range_check(pos, size(), "string::insert_vprintf"); va_list ap2; va_copy(ap2, ap); CARB_SCOPE_EXIT { va_end(ap2); }; // Measure first size_type fmt_size = vsnprintf_check(nullptr, 0, fmt, ap); size_type new_size = length_check(size(), fmt_size, "string::insert_vprintf"); grow_buffer_to(new_size); size_type to_copy = size() - pos; pointer copy_start = get_pointer(pos); pointer copy_dest = copy_start + fmt_size; std::memmove(copy_dest, copy_start, to_copy); value_type c = *copy_dest; // vsnprintf will overwrite the first character copied with the NUL, so save it. int check = std::vsnprintf(copy_start, fmt_size + 1, fmt, ap2); OMNI_FATAL_UNLESS(check >= 0, "Unrecoverable error: vsnprintf failed"); *copy_dest = c; set_size(new_size); return *this; } inline string::iterator string::insert_printf(const_iterator p, const char* fmt, ...) { va_list ap; va_start(ap, fmt); CARB_SCOPE_EXIT { va_end(ap); }; return insert_vprintf(p, fmt, ap); } inline string::iterator string::insert_vprintf(const_iterator p, const char* fmt, va_list ap) { ::omni::detail::null_check(fmt, "string::insert_vprintf"); overlap_check(fmt); va_list ap2; va_copy(ap2, ap); CARB_SCOPE_EXIT { va_end(ap2); }; // Measure first size_type fmt_size = vsnprintf_check(nullptr, 0, fmt, ap); size_type pos = std::distance(cbegin(), p); range_check(pos, size(), "string::insert_vprintf"); size_type new_size = length_check(size(), fmt_size, "string::insert_vprintf"); grow_buffer_to(new_size); size_type to_copy = size() - pos; pointer copy_start = get_pointer(pos); pointer copy_dest = copy_start + fmt_size; std::memmove(copy_dest, copy_start, to_copy); value_type c = *copy_dest; // vsnprintf will overwrite the first character copied with the NUL, so save it. int check = std::vsnprintf(copy_start, fmt_size + 1, fmt, ap2); OMNI_FATAL_UNLESS(check >= 0, "Unrecoverable error: vsnprintf failed"); *copy_dest = c; set_size(new_size); return iterator(copy_start); } constexpr string& string::erase(size_type pos, size_type n) { range_check(pos, size(), "string::erase"); // Erase to end of the string if (n >= (size() - pos)) { set_size(pos); } else if (n != 0) { size_type remainder = size() - pos - n; if (remainder) { traits_type::move(get_pointer(pos), get_pointer(pos + n), remainder); } set_size(size() - n); } return *this; } constexpr string::iterator string::erase(const_iterator pos) { if (pos < cbegin()) { return end(); } size_type start = pos - cbegin(); if (start >= size()) { return end(); } size_type remainder = size() - start - 1; if (remainder) { traits_type::move(get_pointer(start), get_pointer(start + 1), remainder); } set_size(size() - 1); return iterator(get_pointer(start)); } constexpr string::iterator string::erase(const_iterator first, const_iterator last) { range_check(first, last, "string::erase"); size_type pos = first - cbegin(); if (last == end()) { set_size(pos); } else { erase(pos, (last - first)); } return iterator(get_pointer(pos)); } inline void string::push_back(value_type c) { grow_buffer_to(size() + 1); traits_type::assign(get_reference(size()), c); set_size(size() + 1); } constexpr void string::pop_back() { #if CARB_EXCEPTIONS_ENABLED if (empty()) { throw std::runtime_error("string::pop_back called on empty string"); } #else CARB_FATAL_UNLESS(!empty(), "string::pop_back called on empty string"); #endif erase(size() - 1, 1); } inline string& string::append(size_type n, value_type c) { size_type new_size = length_check(size(), n, "string::append"); grow_buffer_to(new_size); traits_type::assign(get_pointer(size()), n, c); set_size(new_size); return *this; } inline string& string::append(const string& str) { return append_internal(str.data(), str.size()); } inline string& string::append(const string& str, size_type pos, size_type n) { str.range_check(pos, str.size(), "string::append"); size_type substr_size = ::carb_min(n, (str.size() - pos)); return append_internal(str.get_pointer(pos), substr_size); } inline string& string::append(const value_type* s, size_type n) { ::omni::detail::null_check(s, "string::append"); return append_internal(s, n); } inline string& string::append(const value_type* s) { ::omni::detail::null_check(s, "string::append"); return append_internal(s, traits_type::length(s)); } template <class InputIterator> string& string::append(InputIterator first, InputIterator last) { size_type new_size = length_check(size(), std::distance(first, last), "string::append"); if (new_size <= capacity()) { for (auto ptr = get_pointer(size()); first != last; ++first, ++ptr) { traits_type::assign(*ptr, *first); } set_size(new_size); } else { grow_buffer_and_append(new_size, first, last); } return *this; } inline string& string::append(std::initializer_list<value_type> ilist) { return append(ilist.begin(), ilist.end()); } inline string& string::append(const std::string& str) { return append_internal(str.data(), str.size()); } inline string& string::append(const std::string& str, size_type pos, size_type n) { range_check(pos, str.size(), "string::append"); size_type substr_size = ::carb_min(n, (str.size() - pos)); return append_internal(str.data() + pos, substr_size); } inline string& string::append(const carb::cpp::string_view& sv) { return append_internal(sv.data(), sv.size()); } inline string& string::append(const carb::cpp::string_view& sv, size_type pos, size_type n) { range_check(pos, sv.size(), "string::append"); size_type substr_size = ::carb_min(n, (sv.size() - pos)); return append_internal(sv.data() + pos, substr_size); } #if CARB_HAS_CPP17 template <typename T, typename> string& string::append(const T& t) { std::string_view sv = t; return append_internal(sv.data(), sv.size()); } template <typename T, typename> string& string::append(const T& t, size_type pos, size_type n) { std::string_view sv = t; range_check(pos, sv.size(), "string::append"); size_type substr_size = ::carb_min(n, (sv.size() - pos)); return append_internal(sv.data() + pos, substr_size); } #endif inline string& string::append_printf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); CARB_SCOPE_EXIT { va_end(ap); }; return append_vprintf(fmt, ap); } inline string& string::append_vprintf(const char* fmt, va_list ap) { ::omni::detail::null_check(fmt, "string::append_vprintf"); overlap_check(fmt); va_list ap2; va_copy(ap2, ap); CARB_SCOPE_EXIT { va_end(ap2); }; // Measure first size_type fmt_size = vsnprintf_check(nullptr, 0, fmt, ap); size_type new_size = length_check(size(), fmt_size, "string::append_vprintf"); grow_buffer_to(new_size); int check = std::vsnprintf(get_pointer(size()), fmt_size + 1, fmt, ap2); OMNI_FATAL_UNLESS(check >= 0, "Unrecoverable error: vsnprintf failed"); set_size(new_size); return *this; } inline string& string::operator+=(const string& str) { return append(str); } inline string& string::operator+=(value_type c) { return append(1, c); } inline string& string::operator+=(const value_type* s) { ::omni::detail::null_check(s, "string::operator+="); return append(s); } inline string& string::operator+=(std::initializer_list<value_type> ilist) { return append(ilist); } inline string& string::operator+=(const std::string& str) { return append(str); } inline string& string::operator+=(const carb::cpp::string_view& sv) { return append(sv); } #if CARB_HAS_CPP17 template <typename T, typename> inline string& string::operator+=(const T& t) { return append(t); } #endif constexpr int string::compare(const string& str) const noexcept { return compare_internal(get_pointer(0), str.data(), size(), str.size()); } constexpr int string::compare(size_type pos1, size_type n1, const string& str) const { range_check(pos1, size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); return compare_internal(get_pointer(pos1), str.data(), this_size, str.size()); } constexpr int string::compare(size_type pos1, size_type n1, const string& str, size_type pos2, size_type n2) const { range_check(pos1, size(), "string::compare"); str.range_check(pos2, str.size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); size_type other_size = ::carb_min(n2, str.size() - pos2); return compare_internal(get_pointer(pos1), str.get_pointer(pos2), this_size, other_size); } constexpr int string::compare(const value_type* s) const { ::omni::detail::null_check(s, "string::compare"); return compare_internal(get_pointer(0), s, size(), traits_type::length(s)); } constexpr int string::compare(size_type pos1, size_type n1, const value_type* s) const { range_check(pos1, size(), "string::compare"); ::omni::detail::null_check(s, "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); return compare_internal(get_pointer(pos1), s, this_size, traits_type::length(s)); } constexpr int string::compare(size_type pos1, size_type n1, const value_type* s, size_type n2) const { range_check(pos1, size(), "string::compare"); ::omni::detail::null_check(s, "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); return compare_internal(get_pointer(pos1), s, this_size, n2); } CARB_CPP20_CONSTEXPR inline int string::compare(const std::string& str) const noexcept { return compare_internal(get_pointer(0), str.data(), size(), str.size()); } CARB_CPP20_CONSTEXPR inline int string::compare(size_type pos1, size_type n1, const std::string& str) const { range_check(pos1, size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); return compare_internal(get_pointer(pos1), str.data(), this_size, str.size()); } CARB_CPP20_CONSTEXPR inline int string::compare( size_type pos1, size_type n1, const std::string& str, size_type pos2, size_type n2) const { range_check(pos1, size(), "string::compare"); range_check(pos2, str.size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); size_type other_size = ::carb_min(n2, str.size() - pos2); return compare_internal(get_pointer(pos1), str.data() + pos2, this_size, other_size); } constexpr int string::compare(const carb::cpp::string_view& sv) const noexcept { return compare_internal(get_pointer(0), sv.data(), size(), sv.size()); } constexpr int string::compare(size_type pos1, size_type n1, const carb::cpp::string_view& sv) const { range_check(pos1, size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); return compare_internal(get_pointer(pos1), sv.data(), this_size, sv.size()); } constexpr int string::compare(size_type pos1, size_type n1, const carb::cpp::string_view& sv, size_type pos2, size_type n2) const { range_check(pos1, size(), "string::compare"); range_check(pos2, sv.size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); size_type other_size = ::carb_min(n2, sv.size() - pos2); return compare_internal(get_pointer(pos1), sv.data() + pos2, this_size, other_size); } #if CARB_HAS_CPP17 template <typename T, typename> constexpr int string::compare(const T& t) const noexcept { std::string_view sv = t; return compare_internal(get_pointer(0), sv.data(), size(), sv.size()); } template <typename T, typename> constexpr int string::compare(size_type pos1, size_type n1, const T& t) const { std::string_view sv = t; range_check(pos1, size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); return compare_internal(get_pointer(pos1), sv.data(), this_size, sv.size()); } template <typename T, typename> constexpr int string::compare(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2) const { std::string_view sv = t; range_check(pos1, size(), "string::compare"); range_check(pos2, sv.size(), "string::compare"); size_type this_size = ::carb_min(n1, size() - pos1); size_type other_size = ::carb_min(n2, sv.size() - pos2); return compare_internal(get_pointer(pos1), sv.data() + pos2, this_size, other_size); } #endif constexpr bool string::starts_with(value_type c) const noexcept { if (!empty()) { return get_reference(0) == c; } return false; } constexpr bool string::starts_with(const_pointer s) const { ::omni::detail::null_check(s, "string::starts_with"); size_type length = traits_type::length(s); if (size() >= length) { return traits_type::compare(get_pointer(0), s, length) == 0; } return false; } constexpr bool string::starts_with(carb::cpp::string_view sv) const noexcept { if (size() >= sv.size()) { return traits_type::compare(get_pointer(0), sv.data(), sv.size()) == 0; } return false; } #if CARB_HAS_CPP17 constexpr bool string::starts_with(std::string_view sv) const noexcept { if (size() >= sv.size()) { return traits_type::compare(get_pointer(0), sv.data(), sv.size()) == 0; } return false; } #endif constexpr bool string::ends_with(value_type c) const noexcept { if (!empty()) { return get_reference(size() - 1) == c; } return false; } constexpr bool string::ends_with(const_pointer s) const { ::omni::detail::null_check(s, "string::ends_with"); size_type length = traits_type::length(s); if (size() >= length) { return traits_type::compare(get_pointer(size() - length), s, length) == 0; } return false; } constexpr bool string::ends_with(carb::cpp::string_view sv) const noexcept { if (size() >= sv.size()) { return traits_type::compare(get_pointer(size() - sv.size()), sv.data(), sv.size()) == 0; } return false; } #if CARB_HAS_CPP17 constexpr bool string::ends_with(std::string_view sv) const noexcept { if (size() >= sv.size()) { return traits_type::compare(get_pointer(size() - sv.size()), sv.data(), sv.size()) == 0; } return false; } #endif constexpr bool string::contains(value_type c) const noexcept { return find(c) != npos; } constexpr bool string::contains(const_pointer s) const { ::omni::detail::null_check(s, "string::contains"); return find(s) != npos; } constexpr bool string::contains(carb::cpp::string_view sv) const noexcept { return find(sv) != npos; } #if CARB_HAS_CPP17 template <typename T, typename> constexpr string::size_type string::find(const T& t, size_type pos) const noexcept { std::string_view sv = t; return find(sv.data(), pos, sv.size()); } constexpr bool string::contains(std::string_view sv) const noexcept { return find(sv) != npos; } #endif inline string& string::replace(size_type pos1, size_type n1, const string& str) { return replace(pos1, n1, str.data(), str.size()); } inline string& string::replace(size_type pos1, size_type n1, const string& str, size_type pos2, size_type n2) { str.range_check(pos2, str.size(), "string::replace"); size_type replacement_size = ::carb_min(n2, (str.size() - pos2)); return replace(pos1, n1, str.data() + pos2, replacement_size); } template <class InputIterator> string& string::replace(const_iterator i1, const_iterator i2, InputIterator j1, InputIterator j2) { range_check(i1, i2, "string::replace"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); #if CARB_HAS_CPP17 // If the InputIterator is a string::iterator, we can skip making the temporary string and convert the iterator to a // pointer and use that directly. if constexpr (std::is_same_v<InputIterator, iterator>) { return replace(pos, n1, j1.operator->(), std::distance(j1, j2)); } else { // Make a temporary string and use that as the replacement string string tmp(j1, j2); return replace(pos, n1, tmp.data(), tmp.size()); } #else string tmp(j1, j2); return replace(pos, n1, tmp.data(), tmp.size()); #endif } inline string& string::replace(size_type pos, size_type n1, const value_type* s, size_type n2) { ::omni::detail::null_check(s, "string::replace"); size_type replaced_size = ::carb_min(n1, (size() - pos)); size_type replacement_size = n2; size_type new_size = size() - replaced_size + replacement_size; size_type remaining_chars = size() - (pos + replaced_size); pointer replacement_start = get_pointer(pos); if (new_size <= capacity()) { // If the replacement string is part of this string, and things fit into the current capacity, we do the // replacement in place if (overlaps_this_string(s)) { if (replacement_size > 0 && replacement_size <= replaced_size) { std::memmove(replacement_start, s, replacement_size); } if (remaining_chars && replacement_size != replaced_size) { std::memmove(replacement_start + replacement_size, replacement_start + replaced_size, remaining_chars); } if (replacement_size > replaced_size) { // We may need to account for the replacement characters being shifted by the move above to shift the // remaining characters to the end to make room for the larger replacement string. There are three // possible scenarios for this: // Replacement characters not shifted at all if ((uintptr_t)(s + replacement_size) <= (uintptr_t)(replacement_start + replaced_size)) { std::memmove(replacement_start, s, replacement_size); } // Replacement characters entirely shifted else if (((uintptr_t)(s) >= (uintptr_t)(replacement_start + replaced_size))) { std::memcpy(replacement_start, s + (replacement_size - replaced_size), replacement_size); } // Replacement characters split between shifted and non shifted else { size_type non_shifted_amount = uintptr_t(replacement_start + replaced_size) - (uintptr_t)s; std::memmove(replacement_start, s, non_shifted_amount); std::memcpy(replacement_start + non_shifted_amount, replacement_start + replacement_size, replacement_size - non_shifted_amount); } } } else { // If there's no overlap between the replacement characters and this string, we can simply make room for the // replacement characters and copy them in. Move remaining characters to their new location if (remaining_chars) { std::memmove(replacement_start + replacement_size, replacement_start + replaced_size, remaining_chars); } // Move in the replacement characters std::memcpy(replacement_start, s, replacement_size); } } else { // We need to grow the buffer. This function correctly copies the characters from the existing buffer into the // new buffer before disposing the existing buffer. grow_buffer_and_fill(new_size, get_pointer(0), pos, s, replacement_size, remaining_chars ? get_pointer(pos + replaced_size) : nullptr, remaining_chars); } set_size(new_size); return *this; } inline string& string::replace(size_type pos, size_type n1, const value_type* s) { ::omni::detail::null_check(s, "string::replace"); size_type replacement_size = traits_type::length(s); return replace(pos, n1, s, replacement_size); } inline string& string::replace(size_type pos, size_type n1, size_type n2, value_type c) { replace_setup(pos, n1, n2); traits_type::assign(get_pointer(pos), n2, c); return *this; } inline string& string::replace(size_type pos1, size_type n1, const std::string& str) { return replace(pos1, n1, str.data(), str.size()); } inline string& string::replace(size_type pos1, size_type n1, const std::string& str, size_type pos2, size_type n2) { range_check(pos2, str.size(), "string::replace"); size_type replacement_size = ::carb_min(n2, (str.size() - pos2)); return replace(pos1, n1, str.data() + pos2, replacement_size); } inline string& string::replace(size_type pos1, size_type n1, const carb::cpp::string_view& sv) { return replace(pos1, n1, sv.data(), sv.size()); } inline string& string::replace(size_type pos1, size_type n1, const carb::cpp::string_view& sv, size_type pos2, size_type n2) { range_check(pos2, sv.size(), "string::replace"); size_type replacement_size = ::carb_min(n2, (sv.size() - pos2)); return replace(pos1, n1, sv.data() + pos2, replacement_size); } #if CARB_HAS_CPP17 template <typename T, typename> string& string::replace(size_type pos1, size_type n1, const T& t) { std::string_view sv = t; return replace(pos1, n1, sv.data(), sv.size()); } template <typename T, typename> string& string::replace(size_type pos1, size_type n1, const T& t, size_type pos2, size_type n2) { std::string_view sv = t; range_check(pos2, sv.size(), "string::replace"); size_type replacement_size = ::carb_min(n2, (sv.size() - pos2)); return replace(pos1, n1, sv.data() + pos2, replacement_size); } #endif inline string& string::replace(const_iterator i1, const_iterator i2, const string& str) { range_check(i1, i2, "string::replace"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); return replace(pos, n1, str.data(), str.size()); } inline string& string::replace(const_iterator i1, const_iterator i2, const value_type* s, size_type n) { range_check(i1, i2, "string::replace"); ::omni::detail::null_check(s, "string::replace"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); return replace(pos, n1, s, n); } inline string& string::replace(const_iterator i1, const_iterator i2, const value_type* s) { range_check(i1, i2, "string::replace"); ::omni::detail::null_check(s, "string::replace"); size_type replacement_size = traits_type::length(s); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); return replace(pos, n1, s, replacement_size); } inline string& string::replace(const_iterator i1, const_iterator i2, size_type n, value_type c) { range_check(i1, i2, "string::replace"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); replace_setup(pos, n1, n); traits_type::assign(get_pointer(pos), n, c); return *this; } inline string& string::replace(const_iterator i1, const_iterator i2, std::initializer_list<value_type> ilist) { return replace(i1, i2, ilist.begin(), ilist.end()); } inline string& string::replace(const_iterator i1, const_iterator i2, const std::string& str) { range_check(i1, i2, "string::replace"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); return replace(pos, n1, str.data(), str.size()); } inline string& string::replace(const_iterator i1, const_iterator i2, const carb::cpp::string_view& sv) { range_check(i1, i2, "string::replace"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); return replace(pos, n1, sv.data(), sv.size()); } #if CARB_HAS_CPP17 template <typename T, typename> string& string::replace(const_iterator i1, const_iterator i2, const T& t) { std::string_view sv = t; range_check(i1, i2, "string::replace"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); return replace(pos, n1, sv.data(), sv.size()); } #endif inline string& string::replace_format(size_type pos, size_type n1, const value_type* fmt, ...) { va_list ap; va_start(ap, fmt); CARB_SCOPE_EXIT { va_end(ap); }; return replace_vformat(pos, n1, fmt, ap); } inline string& string::replace_vformat(size_type pos, size_type n1, const value_type* fmt, va_list ap) { ::omni::detail::null_check(fmt, "string::replace_vformat"); overlap_check(fmt); va_list ap2; va_copy(ap2, ap); CARB_SCOPE_EXIT { va_end(ap2); }; // Measure first size_type fmt_size = vsnprintf_check(nullptr, 0, fmt, ap); replace_setup(pos, n1, fmt_size); // vsnprintf will overwrite the last character with a NUL, so save it value_type c = *get_pointer(pos + fmt_size); int check = std::vsnprintf(get_pointer(pos), fmt_size + 1, fmt, ap2); OMNI_FATAL_UNLESS(check >= 0, "Unrecoverable error: vsnprintf failed"); *get_pointer(pos + fmt_size) = c; return *this; } inline string& string::replace_format(const_iterator i1, const_iterator i2, const value_type* fmt, ...) { va_list ap; va_start(ap, fmt); CARB_SCOPE_EXIT { va_end(ap); }; return replace_vformat(i1, i2, fmt, ap); } inline string& string::replace_vformat(const_iterator i1, const_iterator i2, const value_type* fmt, va_list ap) { ::omni::detail::null_check(fmt, "string::replace_vformat"); range_check(i1, i2, "string::replace_format"); size_type pos = std::distance(cbegin(), i1); size_type n1 = std::distance(i1, i2); return replace_vformat(pos, n1, fmt, ap); } inline string string::substr(size_type pos, size_type n) const { range_check(pos, size(), "string::substr"); size_type substr_size = ::carb_min(n, (size() - pos)); return string(get_pointer(pos), substr_size); } constexpr string::size_type string::copy(value_type* s, size_type n, size_type pos) const { ::omni::detail::null_check(s, "string::copy"); range_check(pos, size(), "string::copy"); size_type to_copy = ::carb_min(n, (size() - pos)); traits_type::copy(s, get_pointer(pos), to_copy); return to_copy; } inline void string::resize(size_type n, value_type c) { if (n < size()) { set_size(n); } else if (n > size()) { append((n - size()), c); } } inline void string::resize(size_type n) { resize(n, value_type()); } inline void string::swap(string& str) noexcept { string tmp(std::move(*this)); *this = std::move(str); str = std::move(tmp); } /* ------------------------------------------------------------------------------------------------------------------ */ /* Search */ /* ------------------------------------------------------------------------------------------------------------------ */ constexpr string::size_type string::find(const string& str, size_type pos) const noexcept { return find(str.data(), pos, str.size()); } constexpr string::size_type string::find(const value_type* s, size_type pos, size_type n) const { ::omni::detail::null_check(s, "string::find"); if (n == 0) { return pos <= size() ? pos : npos; } if (pos >= size()) { return npos; } const value_type first_element = s[0]; const_pointer search_start = get_pointer(pos); const_pointer const last_char = get_pointer(size()); size_type remaining_length = size() - pos; while (remaining_length >= n) { // Look for the first character search_start = traits_type::find(search_start, remaining_length - n + 1, first_element); // Not found if (search_start == nullptr) { return npos; } // Now compare the full string if (traits_type::compare(search_start, s, n) == 0) { // Return position of first character return search_start - get_pointer(0); } // Match was not found, update remaining length and try again ++search_start; remaining_length = last_char - search_start; } // Search string wasn't found return npos; } constexpr string::size_type string::find(const value_type* s, size_type pos) const { ::omni::detail::null_check(s, "string::find"); return find(s, pos, traits_type::length(s)); } constexpr string::size_type string::find(value_type c, size_type pos) const noexcept { if (pos >= size()) { return npos; } const value_type* location = traits_type::find(get_pointer(pos), size() - pos, c); if (location != nullptr) { return location - get_pointer(0); } return npos; } CARB_CPP20_CONSTEXPR inline string::size_type string::find(const std::string& str, size_type pos) const noexcept { return find(str.data(), pos, str.size()); } constexpr string::size_type string::find(const carb::cpp::string_view& sv, size_type pos) const noexcept { return find(sv.data(), pos, sv.size()); } constexpr string::size_type string::rfind(const string& str, size_type pos) const noexcept { return rfind(str.data(), pos, str.size()); } constexpr string::size_type string::rfind(const value_type* s, size_type pos, size_type n) const { ::omni::detail::null_check(s, "string::rfind"); if (n == 0) { if (pos > size()) { return size(); } else { return pos; } } if (n > size()) { return npos; } size_type search_position = ::carb_min((size() - n), pos); do { if (traits_type::compare(get_pointer(search_position), s, n) == 0) { return search_position; } } while (search_position-- > 0); return npos; } constexpr string::size_type string::rfind(const value_type* s, size_type pos) const { ::omni::detail::null_check(s, "string::rfind"); return rfind(s, pos, traits_type::length(s)); } constexpr string::size_type string::rfind(value_type c, size_type pos) const noexcept { if (empty()) { return npos; } size_type search_position = ::carb_min(pos, size() - 1); do { if (get_reference(search_position) == c) { return search_position; } } while (search_position-- > 0); return npos; } CARB_CPP20_CONSTEXPR inline string::size_type string::rfind(const std::string& str, size_type pos) const noexcept { return rfind(str.data(), pos, str.size()); } constexpr string::size_type string::rfind(const carb::cpp::string_view& sv, size_type pos) const noexcept { return rfind(sv.data(), pos, sv.size()); } #if CARB_HAS_CPP17 template <typename T, typename> constexpr string::size_type string::rfind(const T& t, size_type pos) const noexcept { std::string_view sv = t; return rfind(sv.data(), pos, sv.size()); } #endif constexpr string::size_type string::find_first_of(const string& str, size_type pos) const noexcept { return find_first_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_first_of(const value_type* s, size_type pos, size_type n) const { ::omni::detail::null_check(s, "string::find_first_of"); if (n == 0) { return npos; } for (; pos < size(); ++pos) { // Search the provided string for the character at pos if (traits_type::find(s, n, get_reference(pos)) != nullptr) { return pos; } } return npos; } constexpr string::size_type string::find_first_of(const value_type* s, size_type pos) const { ::omni::detail::null_check(s, "string::find_first_of"); return find_first_of(s, pos, traits_type::length(s)); } constexpr string::size_type string::find_first_of(value_type c, size_type pos) const noexcept { return find(c, pos); } CARB_CPP20_CONSTEXPR inline string::size_type string::find_first_of(const std::string& str, size_type pos) const noexcept { return find_first_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_first_of(const carb::cpp::string_view& sv, size_type pos) const noexcept { return find_first_of(sv.data(), pos, sv.size()); } #if CARB_HAS_CPP17 template <typename T, typename> constexpr string::size_type string::find_first_of(const T& t, size_type pos) const noexcept { std::string_view sv = t; return find_first_of(sv.data(), pos, sv.size()); } #endif constexpr string::size_type string::find_last_of(const string& str, size_type pos) const noexcept { return find_last_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_last_of(const value_type* s, size_type pos, size_type n) const { ::omni::detail::null_check(s, "string::find_last_of"); if (empty() || n == 0) { return npos; } size_type search_position = ::carb_min(pos, size() - 1); do { // Search the provided string for the character at pos if (traits_type::find(s, n, get_reference(search_position)) != nullptr) { return search_position; } } while (search_position-- != 0); return npos; } constexpr string::size_type string::find_last_of(const value_type* s, size_type pos) const { ::omni::detail::null_check(s, "string::find_last_of"); return find_last_of(s, pos, traits_type::length(s)); } constexpr string::size_type string::find_last_of(value_type c, size_type pos) const noexcept { return rfind(c, pos); } CARB_CPP20_CONSTEXPR inline string::size_type string::find_last_of(const std::string& str, size_type pos) const noexcept { return find_last_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_last_of(const carb::cpp::string_view& sv, size_type pos) const noexcept { return find_last_of(sv.data(), pos, sv.size()); } #if CARB_HAS_CPP17 template <typename T, typename> constexpr string::size_type string::find_last_of(const T& t, size_type pos) const noexcept { std::string_view sv = t; return find_last_of(sv.data(), pos, sv.size()); } #endif constexpr string::size_type string::find_first_not_of(const string& str, size_type pos) const noexcept { return find_first_not_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_first_not_of(const value_type* s, size_type pos, size_type n) const { ::omni::detail::null_check(s, "string::find_first_not_of"); for (; pos < size(); ++pos) { // If this char isn't in the search string, return if (traits_type::find(s, n, get_reference(pos)) == nullptr) { return pos; } } return npos; } constexpr string::size_type string::find_first_not_of(const value_type* s, size_type pos) const { ::omni::detail::null_check(s, "string::find_first_not_of"); return find_first_not_of(s, pos, traits_type::length(s)); } constexpr string::size_type string::find_first_not_of(value_type c, size_type pos) const noexcept { for (; pos < size(); ++pos) { if (c != get_reference(pos)) { return pos; } } return npos; } CARB_CPP20_CONSTEXPR inline string::size_type string::find_first_not_of(const std::string& str, size_type pos) const noexcept { return find_first_not_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_first_not_of(const carb::cpp::string_view& sv, size_type pos) const noexcept { return find_first_not_of(sv.data(), pos, sv.size()); } #if CARB_HAS_CPP17 template <typename T, typename> constexpr string::size_type string::find_first_not_of(const T& t, size_type pos) const noexcept { std::string_view sv = t; return find_first_not_of(sv.data(), pos, sv.size()); } #endif constexpr string::size_type string::find_last_not_of(const string& str, size_type pos) const noexcept { return find_last_not_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_last_not_of(const value_type* s, size_type pos, size_type n) const { ::omni::detail::null_check(s, "string::find_last_not_of"); if (empty()) { return npos; } size_type search_position = ::carb_min(pos, size() - 1); do { // If the current character isn't in the search string, return if (traits_type::find(s, n, get_reference(search_position)) == nullptr) { return search_position; } } while (search_position-- > 0); return npos; } constexpr string::size_type string::find_last_not_of(const value_type* s, size_type pos) const { ::omni::detail::null_check(s, "string::find_last_not_of"); return find_last_not_of(s, pos, traits_type::length(s)); } constexpr string::size_type string::find_last_not_of(value_type c, size_type pos) const noexcept { if (empty()) { return npos; } size_type search_position = ::carb_min(pos, size() - 1); do { if (c != get_reference(search_position)) { return search_position; } } while (search_position-- > 0); return npos; } CARB_CPP20_CONSTEXPR inline string::size_type string::find_last_not_of(const std::string& str, size_type pos) const noexcept { return find_last_not_of(str.data(), pos, str.size()); } constexpr string::size_type string::find_last_not_of(const carb::cpp::string_view& sv, size_type pos) const noexcept { return find_last_not_of(sv.data(), pos, sv.size()); } #if CARB_HAS_CPP17 template <typename T, typename> constexpr string::size_type string::find_last_not_of(const T& t, size_type pos) const noexcept { std::string_view sv = t; return find_last_not_of(sv.data(), pos, sv.size()); } #endif /* ------------------------------------------------------------------------------------------------------------------*/ /* Private Functions */ /* ------------------------------------------------------------------------------------------------------------------*/ constexpr bool string::is_local() const { return m_local_data[kSMALL_SIZE_OFFSET] != kSTRING_IS_ALLOCATED; } constexpr void string::set_local(size_type new_size) noexcept { CARB_ASSERT(new_size < kSMALL_STRING_SIZE, "Local size must be less than kSMALL_STRING_SIZE"); m_local_data[kSMALL_SIZE_OFFSET] = kSMALL_STRING_SIZE - static_cast<char>(new_size) - 1; } constexpr void string::set_allocated() noexcept { m_local_data[kSMALL_SIZE_OFFSET] = kSTRING_IS_ALLOCATED; } constexpr string::reference string::get_reference(size_type pos) noexcept { if (is_local()) { return m_local_data[pos]; } else { return m_allocated_data.m_ptr[pos]; } } constexpr string::const_reference string::get_reference(size_type pos) const noexcept { if (is_local()) { return m_local_data[pos]; } else { return m_allocated_data.m_ptr[pos]; } } constexpr string::pointer string::get_pointer(size_type pos) noexcept { if (is_local()) { return m_local_data + pos; } else { return m_allocated_data.m_ptr + pos; } } constexpr string::const_pointer string::get_pointer(size_type pos) const noexcept { if (is_local()) { return m_local_data + pos; } else { return m_allocated_data.m_ptr + pos; } } constexpr void string::set_empty() noexcept { m_local_data[kSMALL_SIZE_OFFSET] = kSMALL_STRING_SIZE - 1; m_local_data[0] = value_type(); } constexpr void string::range_check(size_type pos, size_type size, const char* function) const { #if CARB_EXCEPTIONS_ENABLED if (CARB_UNLIKELY(pos > size)) { throw std::out_of_range(std::string(function) + ": Provided pos " + std::to_string(pos) + " greater than string size " + std::to_string(size)); } #else CARB_FATAL_UNLESS(pos <= size, "%s: Provided pos %zu greater than string size %zu", function, pos, size); #endif } constexpr void string::range_check(const_iterator pos, const char* function) const { #if CARB_EXCEPTIONS_ENABLED if (CARB_UNLIKELY(pos < cbegin())) { throw std::out_of_range(std::string(function) + ": Provided iterator comes before the start of the string"); } else if (CARB_UNLIKELY(pos > cend())) { throw std::out_of_range(std::string(function) + ": Provided iterator comes after the end of the string"); } #else CARB_FATAL_UNLESS(pos >= cbegin(), "%s: Provided iterator comes before the start of the string", function); CARB_FATAL_UNLESS(pos <= cend(), "%s: Provided iterator comes after the end of the string", function); #endif } constexpr void string::range_check(const_iterator first, const_iterator last, const char* function) const { range_check(first, function); range_check(last, function); #if CARB_EXCEPTIONS_ENABLED if (CARB_UNLIKELY(first > last)) { throw std::out_of_range(std::string(function) + ": Iterator range is not valid"); } #else CARB_FATAL_UNLESS(first <= last, "%s: Iterator range is not valid. first is after last", function); #endif } constexpr string::size_type string::length_check(size_type current, size_type n, const char* function) const { #if CARB_EXCEPTIONS_ENABLED if (CARB_UNLIKELY(n > (max_size() - current))) { throw std::length_error(std::string(function) + ": Adding " + std::to_string(n) + " additional bytes to current size of " + std::to_string(current) + " would be greater than maximum size " + std::to_string(max_size())); } #else CARB_FATAL_UNLESS(n <= (max_size() - current), "%s: Adding %zu additional bytes to current size of %zu would be greater than maximum size %zu", function, n, current, max_size()); #endif return current + n; } constexpr void string::set_size(size_type new_size) noexcept { if (is_local()) { CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Warray-bounds") // error: array subscript is above array bounds CARB_ASSERT(new_size < kSMALL_STRING_SIZE, "Local size must be less than kSMALL_STRING_SIZE"); m_local_data[new_size] = value_type(); m_local_data[kSMALL_SIZE_OFFSET] = kSMALL_STRING_SIZE - static_cast<char>(new_size) - 1; CARB_IGNOREWARNING_GNUC_POP } else { m_allocated_data.m_ptr[new_size] = value_type(); m_allocated_data.m_size = new_size; } } constexpr bool string::should_allocate(size_type n) const noexcept { return n >= kSMALL_STRING_SIZE; } constexpr bool string::overlaps_this_string(const_pointer s) const noexcept { const_pointer data = get_pointer(0); return std::greater_equal<const_pointer>{}(s, data) && std::less_equal<const_pointer>{}(s, data + size()); } inline void string::overlap_check(const_pointer s) const { if (CARB_LIKELY(!overlaps_this_string(s))) return; #if CARB_EXCEPTIONS_ENABLED throw std::runtime_error("string may not overlap"); #else OMNI_FATAL_UNLESS(0, "string may not overlap"); #endif } inline string::size_type string::vsnprintf_check(char* buffer, size_type buffer_size, const char* format, va_list args) { int fmt_size = std::vsnprintf(buffer, buffer_size, format, args); if (fmt_size < 0) { #if CARB_EXCEPTIONS_ENABLED throw std::runtime_error("vsnprintf failed"); #else OMNI_FATAL_UNLESS(0, "vsnprintf failed"); #endif } return size_type(fmt_size); } template <class... Args> string::size_type string::snprintf_check(char* buffer, size_type buffer_size, const char* format, Args&&... args) { int fmt_size = std::snprintf(buffer, buffer_size, format, std::forward<Args>(args)...); if (fmt_size < 0) { #if CARB_EXCEPTIONS_ENABLED throw std::runtime_error("snprintf failed"); #else OMNI_FATAL_UNLESS(0, "snprintf failed"); #endif } return size_type(fmt_size); } inline void string::allocate_if_necessary(size_type size) { if (should_allocate(size)) { m_allocated_data.m_ptr = static_cast<char*>(carb::allocate(size + 1)); m_allocated_data.m_capacity = size; set_allocated(); } } inline void string::initialize(const_pointer src, size_type size) { allocate_if_necessary(size); std::memcpy(get_pointer(0), src, size); set_size(size); } template <typename InputIterator> void string::initialize(InputIterator begin, InputIterator end, size_type size) { allocate_if_necessary(size); for (auto ptr = get_pointer(0); begin != end; ++begin, ++ptr) { traits_type::assign(*ptr, *begin); } set_size(size); } inline void string::dispose() { if (!is_local()) { carb::deallocate(m_allocated_data.m_ptr); set_empty(); } } inline string::pointer string::allocate_buffer(size_type old_capacity, size_type& new_capacity) { length_check(0, new_capacity, "string::allocate_buffer"); // Always grow buffer by at least 2x if ((new_capacity > old_capacity) && (new_capacity < old_capacity * 2)) { new_capacity = old_capacity * 2; if (new_capacity > max_size()) { new_capacity = max_size(); } } return static_cast<pointer>(carb::allocate(new_capacity + 1)); } inline void string::grow_buffer_to(size_type new_capacity) { if (new_capacity > capacity()) { // Allocate new buffer first. If this throws then *this is still valid pointer new_buffer = allocate_buffer(capacity(), new_capacity); size_type cur_size = size(); if (cur_size > 0) { std::memcpy(new_buffer, get_pointer(0), cur_size); } new_buffer[cur_size] = value_type(); // Destroy the old buffer dispose(); set_allocated(); m_allocated_data.m_ptr = new_buffer; m_allocated_data.m_capacity = new_capacity; m_allocated_data.m_size = cur_size; } } inline void string::grow_buffer_and_fill( size_type new_size, const_pointer p1, size_type s1, const_pointer p2, size_type s2, const_pointer p3, size_type s3) { size_type new_capacity = new_size; pointer new_buffer = allocate_buffer(capacity(), new_capacity); size_type copy_dest = 0; if (p1) { std::memcpy(new_buffer, p1, s1); copy_dest += s1; } if (p2) { std::memcpy(new_buffer + copy_dest, p2, s2); copy_dest += s2; } if (p3) { std::memcpy(new_buffer + copy_dest, p3, s3); } new_buffer[new_size] = value_type(); // Destroy the old buffer dispose(); set_allocated(); m_allocated_data.m_ptr = new_buffer; m_allocated_data.m_capacity = new_capacity; m_allocated_data.m_size = new_size; } template <class InputIterator> void string::grow_buffer_and_append(size_type new_size, InputIterator first, InputIterator last) { size_type new_capacity = new_size; pointer new_buffer = allocate_buffer(capacity(), new_capacity); std::memcpy(new_buffer, get_pointer(0), size()); for (auto ptr = new_buffer + size(); first != last; ++first, ++ptr) { traits_type::assign(*ptr, *first); } new_buffer[new_size] = value_type(); // Destroy the old buffer dispose(); set_allocated(); m_allocated_data.m_ptr = new_buffer; m_allocated_data.m_capacity = new_capacity; m_allocated_data.m_size = new_size; } inline string& string::assign_internal(const_pointer src, size_type new_size) { new_size = length_check(0, new_size, "string::assign"); // Attempt to allocate a new buffer first before modifying the string. If allocation throws, this string will be // unmodified. grow_buffer_to(new_size); if (new_size) { std::memmove(get_pointer(0), src, new_size); } set_size(new_size); return *this; } template <typename InputIterator> string& string::assign_internal(InputIterator begin, InputIterator end, size_type new_size) { new_size = length_check(0, new_size, "string::assign"); // Attempt to allocate a new buffer first before modifying the string. If allocation throws, this string will be // unmodified. grow_buffer_to(new_size); if (new_size) { for (auto ptr = get_pointer(0); begin != end; ++begin, ++ptr) { traits_type::assign(*ptr, *begin); } } set_size(new_size); return *this; } inline string& string::insert_internal(size_type pos, value_type c, size_type n) { range_check(pos, size(), "string::insert"); size_type new_size = length_check(size(), n, "string::insert"); grow_buffer_to(new_size); size_type to_copy = size() - pos; pointer copy_start = get_pointer(pos); pointer copy_dest = copy_start + n; std::memmove(copy_dest, copy_start, to_copy); traits_type::assign(copy_start, n, c); set_size(new_size); return *this; } inline string& string::insert_internal(size_type pos, const_pointer src, size_type n) { range_check(pos, size(), "string::insert"); length_check(size(), n, "string::insert"); // Reuse the logic in replace to handle potentially overlapping regions return replace(pos, 0, src, n); } inline string& string::append_internal(const_pointer src, size_type n) { size_type new_size = length_check(size(), n, "string::append"); if (new_size <= capacity()) { std::memcpy(get_pointer(size()), src, n); set_size(new_size); } else { grow_buffer_and_fill(new_size, get_pointer(0), size(), src, n, nullptr, 0); } return *this; } constexpr int string::compare_internal(const_pointer this_str, const_pointer other_str, size_type this_size, size_type other_size) const noexcept { size_type compare_size = ::carb_min(this_size, other_size); int result = traits_type::compare(this_str, other_str, compare_size); // If the characters are equal, then compare the sizes if (result == 0) { if (this_size < other_size) { return -1; } else if (this_size > other_size) { return 1; } else { return 0; } } return result; } inline void string::replace_setup(size_type pos, size_type replaced_size, size_type replacement_size) { range_check(pos, size(), "string::replace"); replaced_size = ::carb_min(replaced_size, (size() - pos)); size_type new_size = size() - replaced_size + replacement_size; grow_buffer_to(new_size); size_type remaining_chars = size() - (pos + replaced_size); if (remaining_chars) { std::memmove(get_pointer(pos + replacement_size), get_pointer(pos + replaced_size), remaining_chars); } set_size(new_size); } /* ------------------------------------------------------------------------------------------------------------------ */ /* Non-member functions */ /* ------------------------------------------------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------------------------------------------------ */ /* operator+ */ /* ------------------------------------------------------------------------------------------------------------------ */ inline string operator+(const string& lhs, const string& rhs) { string result; result.reserve(lhs.length() + rhs.length()); result.assign(lhs); result.append(rhs); return result; } inline string operator+(const string& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator+"); string::size_type rhs_len = string::traits_type::length(rhs); string result; result.reserve(lhs.length() + rhs_len); result.assign(lhs); result.append(rhs, rhs_len); return result; } inline string operator+(const string& lhs, char rhs) { string result; result.reserve(lhs.length() + 1); result.assign(lhs); result.append(1, rhs); return result; } inline string operator+(const string& lhs, const std::string& rhs) { string result; result.reserve(lhs.length() + rhs.length()); result.assign(lhs); result.append(rhs); return result; } inline string operator+(const char* lhs, const string& rhs) { ::omni::detail::null_check(lhs, "operator+"); string::size_type lhs_len = string::traits_type::length(lhs); string result; result.reserve(lhs_len + rhs.size()); result.assign(lhs, lhs_len); result.append(rhs); return result; } inline string operator+(char lhs, const string& rhs) { string result; result.reserve(rhs.size() + 1); result.assign(1, lhs); result.append(rhs); return result; } inline string operator+(const std::string& lhs, const string& rhs) { string result; result.reserve(lhs.length() + rhs.length()); result.assign(lhs); result.append(rhs); return result; } inline string operator+(string&& lhs, string&& rhs) { auto total_size = lhs.size() + rhs.size(); if (total_size > lhs.capacity() && total_size <= rhs.capacity()) { return std::move(rhs.insert(0, lhs)); } else { return std::move(lhs.append(rhs)); } } inline string operator+(string&& lhs, const string& rhs) { return std::move(lhs.append(rhs)); } inline string operator+(string&& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator+"); return std::move(lhs.append(rhs)); } inline string operator+(string&& lhs, char rhs) { return std::move(lhs.append(1, rhs)); } inline string operator+(string&& lhs, const std::string& rhs) { return std::move(lhs.append(rhs)); } inline string operator+(const string& lhs, string&& rhs) { return std::move(rhs.insert(0, lhs)); } inline string operator+(const char* lhs, string&& rhs) { ::omni::detail::null_check(lhs, "operator+"); return std::move(rhs.insert(0, lhs)); } inline string operator+(char lhs, string&& rhs) { return std::move(rhs.insert(static_cast<string::size_type>(0), static_cast<string::size_type>(1), lhs)); } inline string operator+(const std::string& lhs, string&& rhs) { return std::move(rhs.insert(0, lhs)); } /* ------------------------------------------------------------------------------------------------------------------ */ /* operator==,!=,<,<=,>,>= */ /* ------------------------------------------------------------------------------------------------------------------ */ constexpr bool operator==(const string& lhs, const string& rhs) noexcept { return lhs.compare(rhs) == 0; } constexpr bool operator!=(const string& lhs, const string& rhs) noexcept { return !(lhs == rhs); } constexpr bool operator<(const string& lhs, const string& rhs) noexcept { return lhs.compare(rhs) < 0; } constexpr bool operator<=(const string& lhs, const string& rhs) noexcept { return lhs.compare(rhs) <= 0; } constexpr bool operator>(const string& lhs, const string& rhs) noexcept { return lhs.compare(rhs) > 0; } constexpr bool operator>=(const string& lhs, const string& rhs) noexcept { return lhs.compare(rhs) >= 0; } constexpr bool operator==(const string& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator=="); return lhs.compare(rhs) == 0; } constexpr bool operator==(const char* lhs, const string& rhs) { ::omni::detail::null_check(lhs, "operator=="); return rhs.compare(lhs) == 0; } constexpr bool operator!=(const string& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator!="); return !(lhs == rhs); } constexpr bool operator!=(const char* lhs, const string& rhs) { ::omni::detail::null_check(lhs, "operator!="); return !(lhs == rhs); } constexpr bool operator<(const string& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator<="); return lhs.compare(rhs) < 0; } constexpr bool operator<(const char* lhs, const string& rhs) { ::omni::detail::null_check(lhs, "operator<="); return rhs.compare(lhs) > 0; } constexpr bool operator<=(const string& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator<="); return lhs.compare(rhs) <= 0; } constexpr bool operator<=(const char* lhs, const string& rhs) { ::omni::detail::null_check(lhs, "operator<="); return rhs.compare(lhs) >= 0; } constexpr bool operator>(const string& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator>"); return lhs.compare(rhs) > 0; } constexpr bool operator>(const char* lhs, const string& rhs) { ::omni::detail::null_check(lhs, "operator>"); return rhs.compare(lhs) < 0; } constexpr bool operator>=(const string& lhs, const char* rhs) { ::omni::detail::null_check(rhs, "operator>="); return lhs.compare(rhs) >= 0; } constexpr bool operator>=(const char* lhs, const string& rhs) { ::omni::detail::null_check(lhs, "operator>="); return rhs.compare(lhs) <= 0; } CARB_CPP20_CONSTEXPR inline bool operator==(const string& lhs, const std::string& rhs) noexcept { return lhs.compare(rhs) == 0; } CARB_CPP20_CONSTEXPR inline bool operator==(const std::string& lhs, const string& rhs) noexcept { return rhs.compare(lhs) == 0; } CARB_CPP20_CONSTEXPR inline bool operator!=(const string& lhs, const std::string& rhs) noexcept { return !(lhs == rhs); } CARB_CPP20_CONSTEXPR inline bool operator!=(const std::string& lhs, const string& rhs) noexcept { return !(lhs == rhs); } CARB_CPP20_CONSTEXPR inline bool operator<(const string& lhs, const std::string& rhs) noexcept { return lhs.compare(rhs) < 0; } CARB_CPP20_CONSTEXPR inline bool operator<(const std::string& lhs, const string& rhs) noexcept { return rhs.compare(lhs) > 0; } CARB_CPP20_CONSTEXPR inline bool operator<=(const string& lhs, const std::string& rhs) noexcept { return lhs.compare(rhs) <= 0; } CARB_CPP20_CONSTEXPR inline bool operator<=(const std::string& lhs, const string& rhs) noexcept { return rhs.compare(lhs) >= 0; } CARB_CPP20_CONSTEXPR inline bool operator>(const string& lhs, const std::string& rhs) noexcept { return lhs.compare(rhs) > 0; } CARB_CPP20_CONSTEXPR inline bool operator>(const std::string& lhs, const string& rhs) noexcept { return rhs.compare(lhs) < 0; } CARB_CPP20_CONSTEXPR inline bool operator>=(const string& lhs, const std::string& rhs) noexcept { return lhs.compare(rhs) >= 0; } CARB_CPP20_CONSTEXPR inline bool operator>=(const std::string& lhs, const string& rhs) noexcept { return rhs.compare(lhs) <= 0; } inline void swap(string& lhs, string& rhs) noexcept { lhs.swap(rhs); } template <typename U> CARB_CPP20_CONSTEXPR string::size_type erase(string& str, const U& val) { auto it = std::remove(str.begin(), str.end(), val); auto removed = std::distance(it, str.end()); str.erase(it, str.end()); return removed; } template <class Pred> CARB_CPP20_CONSTEXPR string::size_type erase_if(string& str, Pred pred) { auto it = std::remove_if(str.begin(), str.end(), pred); auto removed = std::distance(it, str.end()); str.erase(it, str.end()); return removed; } inline std::basic_ostream<char, std::char_traits<char>>& operator<<(std::basic_ostream<char, std::char_traits<char>>& os, const string& str) { using _ostream = std::basic_ostream<char, std::char_traits<char>>; using traits_type = std::char_traits<char>; using size_type = string::size_type; std::basic_ostream<char, std::char_traits<char>>::iostate err = std::basic_ostream<char, std::char_traits<char>>::goodbit; // Get and check the sentry first _ostream::sentry sentry(os); if (sentry) { size_type pad; if (os.width() <= 0 || static_cast<size_type>(os.width()) < str.size()) { pad = 0; } else { pad = static_cast<size_type>(os.width()) - str.size(); } using int_type = traits_type::int_type; int_type eof = traits_type::eof(); // Pad on the left if ((os.flags() & _ostream::adjustfield) != _ostream::left) { for (; pad > 0; --pad) { int_type result = os.rdbuf()->sputc(os.fill()); if (traits_type::eq_int_type(result, eof)) { err |= _ostream::badbit; break; } } } if (err == _ostream::goodbit) { std::streamsize result = os.rdbuf()->sputn(str.data(), static_cast<std::streamsize>(str.size())); if (result != static_cast<std::streamsize>(str.size())) { err |= _ostream::badbit; } else { // Pad on the right; for (; pad > 0; --pad) { int_type res = os.rdbuf()->sputc(os.fill()); if (traits_type::eq_int_type(res, eof)) { err |= _ostream::badbit; break; } } } } } os.width(0); if (err) { os.setstate(err); } return os; } inline std::basic_istream<char, std::char_traits<char>>& operator>>(std::basic_istream<char, std::char_traits<char>>& is, string& str) { string::size_type char_count = 0; using _istream = std::basic_istream<char, std::char_traits<char>>; using traits_type = std::char_traits<char>; _istream::iostate err = _istream::goodbit; // Get and check the sentry first _istream::sentry sentry(is, false); if (sentry) { str.erase(); using size_type = string::size_type; size_type n = str.max_size(); if (is.width() > 0) { n = static_cast<size_type>(is.width()); } using int_type = traits_type::int_type; int_type eof = traits_type::eof(); int_type c = is.rdbuf()->sgetc(); while (!traits_type::eq_int_type(c, eof) && !std::isspace(traits_type::to_char_type(c), is.getloc()) && char_count < n) { str.append(1UL, traits_type::to_char_type(c)); ++char_count; c = is.rdbuf()->snextc(); } if (traits_type::eq_int_type(c, eof)) { err |= _istream::eofbit; } is.width(0); } // Extracting no characters is always a failure if (char_count == 0) { err |= _istream::failbit; } if (err) { is.setstate(err); } return is; } inline std::basic_istream<char, std::char_traits<char>>& getline(std::basic_istream<char, std::char_traits<char>>&& input, string& str, char delim) { string::size_type char_count = 0; using _istream = std::basic_istream<char, std::char_traits<char>>; using traits_type = std::char_traits<char>; _istream::iostate err = _istream::goodbit; // Get and check the sentry first _istream::sentry sentry(input, true); if (sentry) { str.erase(); using int_type = traits_type::int_type; int_type eof = traits_type::eof(); int_type delim_int = traits_type::to_int_type(delim); int_type c = input.rdbuf()->sgetc(); auto max_size = str.max_size(); // Loop over the input stream until we get eof, the delimiter, or reach the max size of the string while (!traits_type::eq_int_type(c, eof) && !traits_type::eq_int_type(c, delim_int) && char_count < max_size) { str.append(1, traits_type::to_char_type(c)); ++char_count; c = input.rdbuf()->snextc(); } // Update any necessary failure bits if (traits_type::eq_int_type(c, eof)) { err |= _istream::eofbit; } else if (traits_type::eq_int_type(c, delim_int)) { ++char_count; // Pop off the delimiter input.rdbuf()->sbumpc(); } else { err |= _istream::failbit; } } // Extracting no characters is always a failure if (char_count == 0) { err |= _istream::failbit; } if (err) { input.setstate(err); } return input; } inline std::basic_istream<char, std::char_traits<char>>& getline(std::basic_istream<char, std::char_traits<char>>&& input, string& str) { return getline(std::move(input), str, input.widen('\n')); } inline int stoi(const string& str, std::size_t* pos, int base) { return ::omni::detail::_sto_helper<long, int>(&std::strtol, "stoi", str.c_str(), pos, base); } inline long stol(const string& str, std::size_t* pos, int base) { return ::omni::detail::_sto_helper(&std::strtol, "stol", str.c_str(), pos, base); } inline long long stoll(const string& str, std::size_t* pos, int base) { return ::omni::detail::_sto_helper(&std::strtoll, "stoll", str.c_str(), pos, base); } inline unsigned long stoul(const string& str, std::size_t* pos, int base) { return ::omni::detail::_sto_helper(&std::strtoul, "stoul", str.c_str(), pos, base); } inline unsigned long long stoull(const string& str, std::size_t* pos, int base) { return ::omni::detail::_sto_helper(&std::strtoull, "stoull", str.c_str(), pos, base); } inline float stof(const string& str, std::size_t* pos) { return ::omni::detail::_sto_helper(&std::strtof, "stof", str.c_str(), pos); } inline double stod(const string& str, std::size_t* pos) { return ::omni::detail::_sto_helper(&std::strtod, "stod", str.c_str(), pos); } inline long double stold(const string& str, std::size_t* pos) { return ::omni::detail::_sto_helper(&std::strtold, "stold", str.c_str(), pos); } inline string to_string(int value) { return string(formatted, "%d", value); } inline string to_string(long value) { return string(formatted, "%ld", value); } inline string to_string(long long value) { return string(formatted, "%lld", value); } inline string to_string(unsigned value) { return string(formatted, "%u", value); } inline string to_string(unsigned long value) { return string(formatted, "%lu", value); } inline string to_string(unsigned long long value) { return string(formatted, "%llu", value); } inline string to_string(float value) { return string(formatted, "%f", value); } inline string to_string(double value) { return string(formatted, "%f", value); } inline string to_string(long double value) { return string(formatted, "%Lf", value); } } // namespace omni
omniverse-code/kit/include/omni/hydra/ISceneDelegate.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 <cstddef> namespace omni { namespace usd { namespace hydra // carbonite style interface to allow other plugins to access scene delegates { // defined in rtx/hydra/IHydraEngine.h struct IHydraSceneDelegate; struct ISceneDelegateFactory { CARB_PLUGIN_INTERFACE("omni::hydra::ISceneDelegateFactory", 0, 1) void(CARB_ABI* getInterface)(IHydraSceneDelegate& delegateInterface); }; } // namespace hydra } // namespace usd } // namespace omni
omniverse-code/kit/include/omni/hydra/IOmniHydra.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 "OmniHydraTypes.h" // Avoid including USD Headers as they come from UsdPCH.h included in .cpp files PXR_NAMESPACE_OPEN_SCOPE class SdfPath; class GfMatrix4d; class GfMatrix4f; class GfVec3f; template<typename> class VtArray; typedef VtArray<GfVec3f> VtVec3fArray; PXR_NAMESPACE_CLOSE_SCOPE namespace omni { namespace usd { namespace hydra { struct IOmniHydra { CARB_PLUGIN_INTERFACE("omni::hydra::IOmniHydra", 2, 0) /* * Transform Get/Set */ // get world space transform in s,q,t format bool(CARB_ABI* GetWorldTransform)(pxr::SdfPath const& id, Transform& transform); // Set standard s,q,t transform to hydra. bool(CARB_ABI* SetWorldTransform)(pxr::SdfPath const& id, Transform const& transform); // get local space transform in 4x4 matrix bool(CARB_ABI* GetLocalMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d& matrix); // set local space transform in 4x4 matrix bool(CARB_ABI* SetLocalMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d const& matrix); // get world space transform in 4x4 matrix bool(CARB_ABI* GetWorldMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d& matrix); // set world space transform in 4x4 matrix bool(CARB_ABI* SetWorldMatrix)(pxr::SdfPath const& id, pxr::GfMatrix4d const& matrix); /* * Per vertex primvar buffers (points, normals, etc.) */ // set points directly without triggering usd notice using generic buffer descriptor bool(CARB_ABI* SetPointsBuffer)(pxr::SdfPath const& id, BufferDesc const& bufferDesc); // set points directly without triggering usd notice using usd point array bool(CARB_ABI* SetPointsArray)(pxr::SdfPath const& id, pxr::VtVec3fArray const& pointsArray); /* * Instancer */ // set transform of once instance by instance path + instance index bool(CARB_ABI* SetInstanceTransform)(const pxr::SdfPath& instancerPath, uint32_t instanceIndex, const Transform& transform); // Scatter the position data to corresponding instance position slots routed by the indexMap bool(CARB_ABI* SetInstancePosition)(const pxr::SdfPath& instancerPath, const carb::Double3* position, const uint32_t* indexMap, const uint32_t& instanceCount); // Legacy float support bool(CARB_ABI* SetInstancePositionF)(const pxr::SdfPath& instancerPath, const carb::Float3* position, const uint32_t* indexMap, const uint32_t& instanceCount); /* * Cached Paths */ // get size of prim range at specified prim. size_t(CARB_ABI* GetPrimRangePathCount)(const pxr::SdfPath& primPath); // This includes paths for prim + all its descendents. void(CARB_ABI* GetPrimRangePaths)(const pxr::SdfPath& primPath, pxr::SdfPath* primRangePaths, size_t pathRangeSize); void(CARB_ABI* BlockUSDUpdate)(bool val); /* * Bypass RTX render's skel deformation (in favor of external deformer processing) */ bool(CARB_ABI* GetBypassRenderSkelMeshProcessing)(pxr::SdfPath const& primPath, bool& bypass); bool(CARB_ABI* SetBypassRenderSkelMeshProcessing)(pxr::SdfPath const& primPath, bool const& bypass); bool(CARB_ABI* SetSkelMeshGraphCallbacks)(SkelMeshGraphCallback setupFunc); }; } // namespace hydra } // namespace usd } // namespace omni
omniverse-code/kit/include/omni/hydra/IDebug.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/InterfaceUtils.h> #include <omni/hydra/OmniHydraTypes.h> namespace omni { namespace usd { namespace hydra { struct IDebug { CARB_PLUGIN_INTERFACE("omni::hydra::IDebug", 0, 1) size_t(CARB_ABI* getTimestampedTransformCount)(); void(CARB_ABI* getTimestampedTransforms)(TimestampedTransform* out, size_t outCount); }; } } }
omniverse-code/kit/include/omni/hydra/OmniHydraTypes.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/Defines.h> #include <carb/Types.h> // Avoid including USD Headers as they come from UsdPCH.h included in .cpp files PXR_NAMESPACE_OPEN_SCOPE class UsdPrim; PXR_NAMESPACE_CLOSE_SCOPE namespace omni { namespace usd { namespace hydra { struct Transform { carb::Double3 position; carb::Float4 orientation; carb::Float3 scale; }; struct TimestampedTransform { int64_t wakeupTimeNumerator; uint64_t wakeupTimeDenominator; int64_t sampleTimeNumerator; uint64_t sampleTimeDenominator; bool transformPresent; omni::usd::hydra::Transform transform; }; struct BufferDesc { BufferDesc() = default; BufferDesc(const void* _data, uint32_t _elementStride, uint32_t _elementSize) : data(_data), elementStride(_elementStride), elementSize(_elementSize) { } const void* data = nullptr; // float elements, vec2, vec3 or vec4 uint32_t elementStride = 0; // in bytes uint32_t elementSize = 0; // in bytes size_t count = 0; // vertex count, ... bool isGPUBuffer = false; // TODO - add GPU interop later bool isSafeToRender = false; // true if the data is safe to use from the render thread bool isDataRpResource = false; }; using SkelMeshGraphCallback = void(*)(const pxr::UsdPrim&); } // namespace hydra } // namespace usd } // namespace omni
omniverse-code/kit/include/omni/extras/DictHelpers.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. // //! @file //! @brief Helpers for \ref carb::dictionary::Item and \ref carb::dictionary::IDictionary #pragma once #include "../../carb/dictionary/DictionaryUtils.h" #include <string> #include <vector> namespace carb { namespace dictionary { /** * Gets a child value from a given Item if present, otherwise returns the given default value. * @tparam T the type of the return value and default value * @param baseItem The \ref carb::dictionary::Item to use as a base (required) * @param path The path of children from \p baseItem using `/` as a separator * @param defaultValue The default value to return if no item is present at the given location * @returns The \ref carb::dictionary::Item converted to `T` with \ref carb::dictionary::IDictionary::get(), or * \p defaultValue if the given \p baseItem and \p path did not resolve to an Item */ template <typename T> T getValueOrDefault(const Item* baseItem, const char* path, T defaultValue) { IDictionary* d = getCachedDictionaryInterface(); auto item = d->getItem(baseItem, path); if (!item) return defaultValue; return d->get<T>(item); } /** * Set a string array at the given path with the given array (creating it if it doesn't yet exist). * @param baseItem The \ref carb::dictionary::Item to use as a base (required) * @param path The path of children from \p baseItem using `/` as a separator * @param arr The array of string data to set at the given path * @returns The \ref carb::dictionary::Item that was either created or found at the given \p path */ inline Item* makeStringArrayAtPath(Item* baseItem, const char* path, const std::vector<std::string>& arr) { IDictionary* dict = getCachedDictionaryInterface(); ScopedWrite g(*dict, baseItem); Item* item = dict->getItemMutable(baseItem, path); if (!item) { item = dict->createItem(baseItem, path, ItemType::eDictionary); } for (size_t i = 0, count = arr.size(); i < count; ++i) { dict->setStringAt(item, i, arr[i].c_str()); } return item; } } // namespace dictionary } // namespace carb
omniverse-code/kit/include/omni/extras/FileSystemHelpers.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 \ref carb::filesystem::IFileSystem #pragma once #include "../../carb/InterfaceUtils.h" #include "../../carb/extras/Path.h" #include "../../carb/filesystem/IFileSystem.h" #include "../../carb/tokens/TokensUtils.h" #include <string> #include <vector> namespace omni { namespace extras { /** * Helper function for acquiring and caching the filesystem. * @returns \ref carb::filesystem::IFileSystem acquired as by \ref carb::getCachedInterface() */ inline carb::filesystem::IFileSystem* getFileSystem() { return carb::getCachedInterface<carb::filesystem::IFileSystem>(); } /** * Returns a list of all files and sub-folders in the given folder. * @param folder The folder path to list * @returns a `std::vector` of all files and sub-folders in \p folder (non-recursive), or an empty `std::vector` if the * path could not be accessed or was otherwise empty. Each item in the vector will be prefixed with \p folder. * @see carb::filesystem::IFileSystem::forEachDirectoryItem(), getDirectoryItemsOfType(), getSubfolders() */ inline std::vector<std::string> getDirectoryItems(const std::string& folder) { std::vector<std::string> items; getFileSystem()->forEachDirectoryItem(folder.c_str(), [](const carb::filesystem::DirectoryItemInfo* const info, void* userData) { decltype(items)* _items = static_cast<decltype(items)*>(userData); _items->push_back(info->path); return carb::filesystem::WalkAction::eContinue; }, &items); return items; } /** * Returns a list of either files or sub-folders in the given folder. * @param folder The folder path to list * @param type The \ref carb::filesystem::DirectoryItemType to find * @returns a `std::vector` of items of \p type in \p folder (non-recursive), or an empty `std::vector` if the path * could not be accessed or was otherwise empty. Each item in the vector will be prefixed with \p folder. * @see carb::filesystem::IFileSystem::forEachDirectoryItem(), getDirectoryItems(), getSubfolders() */ inline std::vector<std::string> getDirectoryItemsOfType(const std::string& folder, carb::filesystem::DirectoryItemType type) { struct UserData { carb::filesystem::DirectoryItemType type; std::vector<std::string> items; }; UserData data{ type, {} }; getFileSystem()->forEachDirectoryItem(folder.c_str(), [](const carb::filesystem::DirectoryItemInfo* const info, void* userData) { decltype(data)* _data = static_cast<decltype(data)*>(userData); if (info->type == _data->type) _data->items.push_back(info->path); return carb::filesystem::WalkAction::eContinue; }, &data); return data.items; } /** * Helper function to gather all sub-folders within a given folder. * * Effectively the same as `getDirectoryItemsOfType(folder, carb::filesystem::DirectoryItemType::eDirectory)` * @param folder The folder path to list * @returns a `std::vector` of sub-folders in \p folder (non-recursive), or an empty `std::vector` if the path could not * be accessed or was otherwise empty. Each item in the vector will be prefixed with \p folder. * @see carb::filesystem::IFileSystem::forEachDirectoryItem(), getDirectoryItems(), getDirectoryItemsOfType() */ inline std::vector<std::string> getSubfolders(const std::string& folder) { return getDirectoryItemsOfType(folder, carb::filesystem::DirectoryItemType::eDirectory); } /** * Helper function to gather all sub-folders within an array of sub-folders. * * @note This is not recursive; it only goes one level deeper beyond the given collection of \p folders. * @param folders a `std::vector` of folders. This vector is walked and \ref getSubfolders() is called on each entry. * Each entry in the vector will be prefixed with the entry from \p folders that contained it. * @returns a `std::vector` of sub-folders comprised of all of the sub-folders of the folders given in \p folders */ inline std::vector<std::string> getSubfolders(const std::vector<std::string>& folders) { std::vector<std::string> allSubFolders; for (const std::string& folder : folders) { const std::vector<std::string> subFolders = getSubfolders(folder); allSubFolders.insert(allSubFolders.end(), subFolders.begin(), subFolders.end()); } return allSubFolders; } /** * Resolves a given path by resolving all Tokens and optionally prepending the given root path. * @param path A path that may contain tokens (see \ref carb::tokens::ITokens) * @param root If \p path (after token resolution) is a relative path and this is provided, the returned path is * prepended with this value. * @returns \p path with tokens resolved, prepended by \p root (if \p root is provided and the token-resolved path is * relative) */ inline std::string resolvePath(const std::string& path, const std::string& root = {}) { auto tokens = carb::getCachedInterface<carb::tokens::ITokens>(); carb::extras::Path resultPath = carb::tokens::resolveString(tokens, path.c_str()); // If relative - relative to the root if (!root.empty() && resultPath.isRelative()) { resultPath = carb::extras::Path(root).join(resultPath); } return resultPath; } /** * Reads file content into a string. * @warning This function reads data in a binary fashion and stores it in a `std::string`. As such, the string may * contain non-printable characters or even `NUL` characters. No conversion of Windows line endings is performed. * @param path The path to read * @returns a `std::pair`, where the `first` member indicates success if `true` and the `second` member is the contents; * if `first` is `false` then `second` will always be empty. If the file is valid but empty, `first` will be `true` * but `second` will be empty. */ inline std::pair<bool, std::string> readFile(const char* path) { auto fs = getFileSystem(); if (fs->exists(path)) { carb::filesystem::File* file = fs->openFileToRead(path); if (file) { size_t size = fs->getFileSize(file); if (size) { std::string buffer(size, ' '); fs->readFileChunk(file, &buffer[0], size); fs->closeFile(file); return std::make_pair(true, buffer); } else { fs->closeFile(file); return std::make_pair(true, std::string{}); } } } return std::make_pair(false, std::string{}); } } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/StringHelpers.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. // //! @file //! @brief String manipulation helper utilities #pragma once #include "../../carb/Types.h" #include <algorithm> #include <sstream> #include <string> #include <vector> #include <cctype> namespace omni { namespace extras { #pragma push_macro("max") #undef max /** * Splits a string based on a delimiter. * @param s The string to split * @param d The delimiter character * @param count The maximum number of sections to split \p s into * @returns a `std::vector` of strings that have been split from \p s at delimiter \p d. The delimiter is not included * in the strings. Adjacent delimiters do not produce empty strings in the returned vector. Up to \p count entries * will be in the returned vector. e.g. `"a.b..c.dee."` would produce `{ "a", "b", "c", "dee" }` assuming that \p d is * `.` and \p count is >= 4. */ inline std::vector<std::string> split(const std::string& s, char d, size_t count = std::numeric_limits<size_t>::max()) { std::vector<std::string> res; std::stringstream ss(s); size_t i = 0; while (ss.good() && i < count) { std::string tmp; if (i == count - 1) { std::getline(ss, tmp, (char)0); } else { std::getline(ss, tmp, d); } if (!tmp.empty()) { res.push_back(tmp); } i++; } return res; } #pragma pop_macro("max") /** * Checks a string to see if it ends with a given suffix. * @param str The string to check * @param ending The possible ending to check for * @returns `true` if \p str ends with \p ending; `false` otherwise */ inline bool endsWith(const std::string& str, const std::string& ending) { if (ending.size() > str.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), str.rbegin()); } /** * Checks a string to see if it begins with a given prefix. * @param str The string to check * @param prefix The possible prefix to check for * @returns `true` if \p str starts with \p prefix; `false` otherwise */ inline bool startsWith(const std::string& str, const std::string& prefix) { return (str.length() >= prefix.length() && str.compare(0, prefix.size(), prefix) == 0); } /** * Transforms a string to lowercase in-place. * @warning This performs an ASCII lowercase only; current locale and UTF-8 encoding is ignored. * @param str The string to transform in-place. When the function returns the string has been changed to ASCII * lowercase. */ inline void toLower(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); }); } /** * Converts a given string to a 32-bit signed integer value. * @warning This function will truncate values and may lose information even though `true` is returned. It's use is not * recommended. * @param str The string to convert. May be a decimal, hexadecimal (`0x` prefix) or octal (`0` prefix) number. A * floating point value may also be given including with exponential notation, though floating point values will be * casted to an integer and may lose precision. * @param[out] outResult The reference that receives the integer result * @returns `true` if `strtoll` or `strtod` parse \p str in its entirety; `false` otherwise. **NOTE** a return value of * `true` does not mean that information or precision is not lost! */ inline bool stringToInteger(const std::string& str, int32_t& outResult) { char* numericEnd; uint32_t val = (int32_t)strtoll(str.c_str(), &numericEnd, 0); if (*numericEnd == '\0') { outResult = val; return true; } double fVal = strtod(str.c_str(), &numericEnd); if (*numericEnd == '\0') { outResult = static_cast<int32_t>(fVal); return true; } return false; } //! Default delimiters for \ref stringToInt2. constexpr char kInt2Delimiters[] = ",x"; /** * Converts a string value to an Int2 representation, that is, a two-component vector. * \details This function attempts to convert values such as `0,-1` or `99x84` into a \ref carb::Int2. The delimiters * given by \p delims are tried in order, passed along with \p str to \ref split(). If two components are found, * both components must successfully parse with \ref stringToInteger() in order to consider the result valid. * @warning See the warnings at \ref stringToInteger() about potential data loss. * @param str The string to convert * @param[out] outResult Reference that receives the \ref carb::Int2 result from parsing. Only valid if `true` is * returned. * @param delims Delimiters to separate the vector components * @returns `true` if parsing was successful; `false` otherwise */ inline bool stringToInt2(const std::string& str, carb::Int2& outResult, const char* delims = kInt2Delimiters) { // try splitting by different delimiters for (int delimIndex = 0; delims[delimIndex] != 0; delimIndex++) { auto delim = delims[delimIndex]; auto pathAndOther = split(str, delim); if (pathAndOther.size() == 2) { int32_t x, y; if (extras::stringToInteger(pathAndOther[0], x) && extras::stringToInteger(pathAndOther[1], y)) { outResult = { x, y }; return true; } } } return false; } //! \defgroup stringtrim String Trimming Utilities //! @{ //! Default whitespace characters for string trimming functions constexpr char kTrimCharsDefault[] = " \t\n\r\f\v"; /** * Performs an in-place right-trim on a given string. * \details This will trim the characters in \p t from the right side of \p s. e.g. given \p s = `" asdf "` with the * default \p t value, \p s would be modified to contain `" asdf"`. This is effectively * `s.erase(s.find_last_not_of(t) + 1)`. * @param s The string to trim in-place * @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault) * @returns \p s for convenience * @see ltrim(), trim(), trimCopy() */ inline std::string& rtrim(std::string& s, const char* t = kTrimCharsDefault) { s.erase(s.find_last_not_of(t) + 1); return s; } /** * Performs an in-place left-trim on a given string. * \details This will trim the characters in \p t from the left side of \p s. e.g. given \p s = `" asdf "` with the * default \p t value, \p s would be modified to contain `"asdf "`. This is effectively * `s.erase(0, s.find_first_not_of(t))`. * @param s The string to trim in-place * @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault) * @returns \p s for convenience * @see rtrim(), trim(), trimCopy() */ inline std::string& ltrim(std::string& s, const char* t = kTrimCharsDefault) { s.erase(0, s.find_first_not_of(t)); return s; } /** * Performs an in-place trim (from both sides) on a given string. * \details This will trim the characters in \p t from both sides of \p s. e.g. given \p s = `" asdf "` with the * default \p t value, \p s would be modified to contain `"asdf"`. This is effectively * `ltrim(rtrim(s, t), t)`. * @param s The string to trim in-place * @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault) * @returns \p s for convenience * @see ltrim(), rtrim(), trimCopy() */ inline std::string& trim(std::string& s, const char* t = kTrimCharsDefault) { return ltrim(rtrim(s, t), t); } /** * Performs a trim (from both sides) on a given string, returning a copy. * \details This will trim the characters in \p t from both sides of \p s. e.g. given \p s = `" asdf "` with the * default \p t value, `"asdf"` would be returned. This is effectively `std::string copy(s); return trim(copy);`. * @param s The string to trim * @param t A string containing the list of characters to trim (such as \ref kTrimCharsDefault) * @returns The trimmed string * @see ltrim(), rtrim(), trim() */ inline std::string trimCopy(std::string s, const char* t = kTrimCharsDefault) { trim(s, t); return s; } //! @} /** * Replaces all instances of a substring within a given string with a replacement value. * \details This function calls `std::string::replace()` in a loop so that all instances are replaced. * \note The replacement is not recursive, so \p replaceWith may contain the substring \p subStr without causing endless * recursion. Whenever a replacement occurs, the search for \p subStr resumes after the inserted \p replaceWith. * @param str The string to modify in-place * @param subStr The substring to find within \p str * @param replaceWith The substring that all instances of \p subStr are replaced with */ inline void replaceAll(std::string& str, const std::string& subStr, const std::string& replaceWith) { size_t pos = str.find(subStr); while (pos != std::string::npos) { str.replace(pos, subStr.size(), replaceWith); pos = str.find(subStr, pos + replaceWith.size()); } } /** * Checks two strings for equality in an ASCII case-insensitive manner. * \warning This function checks for ASCII case-insensitivity only. UTF-8 encoding and locale are ignored. * @param str1 The first string to compare * @param str2 The second string to compare * @returns `true` if the strings are equal when ASCII case is ignored; `false` otherwise */ inline bool stringCompareCaseInsensitive(const std::string& str1, const std::string& str2) { return ((str1.size() == str2.size()) && std::equal(str1.begin(), str1.end(), str2.begin(), [](char a, char b) { return std::tolower(a) == std::tolower(b); })); } /** * Checks if two given file paths are equal with case sensitivity based on the platform. * \warning For Windows, this function checks for ASCII case-insensitivity only. UTF-8 encoding and locale are ignored. * Therefore, this function does not work properly with Windows paths that may contain non-ASCII characters and its * use should be avoided. * \note This is intended for file paths only. URLs are case sensitive. * @param strLeft The first path to compare * @param strRight The second path to compare * @returns `true` if \p strLeft and \p strRight are equal paths with the caveats presented above; `false` otherwise */ inline bool isPathEqual(const std::string& strLeft, const std::string& strRight) { #if CARB_PLATFORM_WINDOWS if (strLeft.size() != strRight.size()) { return false; } return stringCompareCaseInsensitive(strLeft, strRight); #else return (strLeft == strRight); #endif } } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/PathMap.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /** @file * @brief A set of helper templates to provide platform specific behavior around path handling. */ #pragma once #include "../core/Platform.h" #include "../../carb/extras/Utf8Parser.h" #include "../../carb/CarbWindows.h" #include <map> #include <unordered_map> #if !OMNI_PLATFORM_WINDOWS # include <algorithm> #endif namespace omni { /** common namespace for extra helper functions and classes. */ namespace extras { #if OMNI_PLATFORM_WINDOWS /** Custom hash functor for a case sensitive or insensitive hash based on the OS. On Windows * this allows the keys with any casing to hash to the same bucket for lookup. This reimplements * the std::hash<std::string> FNV1 functor except that it first lower-cases each character. This * intentionally avoids allocating a new string that is lower-cased for performance reasons. * On Linux, this just uses std::hash<> directly which implements a case sensitive hash. * * On Windows, note that this uses the Win32 function LCMapStringW() to do the lower case * conversion. This is done because functions such as towlower() do not properly lower case * codepoints outside of the ASCII range unless the current codepage for the calling thread * is set to one that specifically uses those extended characters. Since changing the codepage * for the thread is potentially destructive, we need to use another way to lower case * the string's codepoints for hashing. */ struct PathHash { /** Accumulates a buffer of bytes into an FNV1 hash. * * @param[in] value The initial hash value to accumulate onto. For the first call * in a sequence, this should be std::_FNV_offset_basis. * @param[in] data The buffer of data to accumulate into the hash. This may not * be `nullptr`. * @param[in] bytes The total number of bytes to accumulate into the hash. * @returns The accumulated hash value. This value is suitable to pass back into this * function in the @p value parameter for the next buffer being accumulated. */ size_t accumulateHash(size_t value, const void* data, size_t bytes) const noexcept { const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); for (size_t i = 0; i < bytes; i++) { value ^= ptr[i]; value *= std::_FNV_prime; } return value; } /** Case insensitive string hashing operator. * * @param[in] key The key string to be hashed. This may be any length and contain any * UTF-8 codepoints. This may be empty. * @returns The calculated FNV1 hash of the given string as though it had been converted to * all lower case first. This will ensure that hashes match for the same string * content excluding case. */ size_t operator()(const std::string& key) const noexcept { carb::extras::Utf8Iterator it(key.c_str()); carb::extras::Utf8Iterator::CodePoint cp; size_t hash = std::_FNV_offset_basis; size_t count; int result; while (it) { cp = *it; it++; count = carb::extras::Utf8Parser::encodeUtf16CodePoint(cp, &cp); result = LCMapStringW(CARBWIN_LOCALE_INVARIANT, CARBWIN_LCMAP_LOWERCASE, reinterpret_cast<WCHAR*>(&cp), (int)count, reinterpret_cast<WCHAR*>(&cp), 2); if (result != 0) hash = accumulateHash(hash, &cp, count * sizeof(WCHAR)); } return hash; } }; /** Custom comparison functor for a case insensitive comparison. This does a simple case * insensitive string comparison on the contents of each string's buffer. The return * value indicates the ordering of the two string inputs. * * Note that this uses the Win32 function LCMapStringW() to do the lower case conversion. * This is done because functions such as towlower() do not properly lower case codepoints * outside of the ASCII range unless the current codepage for the calling thread is set * to one that specifically uses those extended characters. Since changing the codepage * for the thread is potentially destructive, we need to use another way to lower case * the strings' codepoints for comparison. */ struct PathCompare { /** Case insensitive string comparison operator. * * @param[in] left The first string to compare. This may be of any length and contain * any UTF-8 codepoint. * @param[in] right The second string to compare. This may be of any length and contain * any UTF-8 codepoint. * @returns `0` if the two strings are equal disregarding case. * @returns A negative value if the first string should be lexicographical ordered before * the second string disregarding case. * @returns A positive value if the first string should be lexicographical ordered after * the second string disregarding case. */ int32_t operator()(const std::string& left, const std::string& right) const noexcept { carb::extras::Utf8Iterator itLeft(left.c_str()); carb::extras::Utf8Iterator itRight(right.c_str()); carb::extras::Utf8Iterator::CodePoint l; carb::extras::Utf8Iterator::CodePoint r; size_t countLeft; size_t countRight; int resultLeft; int resultRight; // walk the strings and compare the lower case versions of each codepoint. while (itLeft && itRight) { l = *itLeft; r = *itRight; itLeft++; itRight++; countLeft = carb::extras::Utf8Parser::encodeUtf16CodePoint(l, &l); countRight = carb::extras::Utf8Parser::encodeUtf16CodePoint(r, &r); resultLeft = LCMapStringW(CARBWIN_LOCALE_INVARIANT, CARBWIN_LCMAP_LOWERCASE, reinterpret_cast<WCHAR*>(&l), (int)countLeft, reinterpret_cast<WCHAR*>(&l), 2); resultRight = LCMapStringW(CARBWIN_LOCALE_INVARIANT, CARBWIN_LCMAP_LOWERCASE, reinterpret_cast<WCHAR*>(&r), (int)countRight, reinterpret_cast<WCHAR*>(&r), 2); if (l != r) return l - r; } // the strings only match if both ended at the same point and all codepoints matched. if (!itLeft && !itRight) return 0; if (!itLeft) return -1; return 1; } }; /** Custom greater-than functor for a case insensitive map lookup. This does a simple case * insensitive string comparison on the contents of each string's buffer. */ struct PathGreater { bool operator()(const std::string& left, const std::string& right) const noexcept { PathCompare compare; return compare(left, right) > 0; } }; /** Custom less-than functor for a case insensitive map lookup. This does a simple case * insensitive string comparison on the contents of each string's buffer. */ struct PathLess { bool operator()(const std::string& left, const std::string& right) const noexcept { PathCompare compare; return compare(left, right) < 0; } }; /** Custom equality functor for a case insensitive map lookup. This does a simple case * insensitive string comparison on the contents of each string's buffer. */ struct PathEqual { bool operator()(const std::string& left, const std::string& right) const noexcept { // the two strings are different lengths -> they cannot possibly match => fail. if (left.length() != right.length()) return false; PathCompare compare; return compare(left, right) == 0; } }; #else /** Custom hash functor for a case sensitive or insensitive hash based on the OS. On Windows * this allows the keys with any casing to hash to the same bucket for lookup. This reimplements * the std::hash<std::string> FNV1 functor except that it first lower-cases each character. This * intentionally avoids allocating a new string that is lower-cased for performance reasons. * On Linux, this just uses std::hash<> directly which implements a case sensitive hash. * * On Windows, note that this uses the Win32 function LCMapStringW() to do the lower case * conversion. This is done because functions such as towlower() do not properly lower case * codepoints outside of the ASCII range unless the current codepage for the calling thread * is set to one that specifically uses those extended characters. Since changing the codepage * for the thread is potentially destructive, we need to use another way to lower case * the string's codepoints for hashing. */ using PathHash = std::hash<std::string>; /** Custom greater-than functor for a case sensitive or insensitive map lookup. On Windows, * this does a simple case insensitive string comparison on the contents of each string's buffer. * On Linux, this performs a case sensitive string comparison. */ using PathGreater = std::greater<std::string>; /** Custom less-than functor for a case sensitive or insensitive map lookup. On Windows, this does * a simple case insensitive string comparison on the contents of each string's buffer. On * Linux, this performs a case sensitive string comparison. */ using PathLess = std::less<std::string>; /** Custom equality functor for a case sensitive or insensitive map lookup. On Windows, this does * a simple case insensitive string comparison on the contents of each string's buffer. On * Linux, this performs a case sensitive string comparison. */ using PathEqual = std::equal_to<std::string>; #endif /** @brief A map to store file paths and associated data according to local OS rules. * * Templated type to use to create a map from a file name or file path to another object. * The map implementation is based on the std::map<> implementation. This will treat the * key as though it is a file path on the local system - on Windows the comparisons will * be case insensitive while on Linux they will be case sensitive. This is also suitable * for storing environment variables since they are also treated in a case insensitive manner * on Windows and case insensitive on Linux. * * @tparam T The type for the map to contain as the value for each path name key. * @tparam Compare The string comparison functor to use when matching path name keys. * * @note A std::map<> object is usually implemented as a red-black tree and will take on * that algorithm's performance and storage characteristics. Please consider this * when choosing a container type. */ template <typename T, class Compare = PathLess> using PathMap = std::map<std::string, T, Compare>; /** @brief An unordered map to store file paths and associated data according to local OS rules. * * Templated type to use to create an unordered map from a file name or file path to another * object. The map implementation is based on the std::unordered_map<> implementation. This * will treat the key as though it is a file path on the local system - on Windows the * comparisons will be case insensitive while on Linux they will be case sensitive. This * is also suitable for storing environment variables since they are also treated in a case * insensitive manner on Windows and case insensitive on Linux. * * @tparam T The type for the map to contain as the value for each path name key. * @tparam Hash The string hashing functor to use to generate hash values for each path * name key. * @tparam KeyEqual The string comparison functor to use to test if two path name keys are * equal * * @note A std::unordered_map<> object is usually implemented as a hash table of lists or trees * and will take on that algorithm's performance and storage characteristics. Please * consider this when choosing a container type. */ template <typename T, class Hash = PathHash, class KeyEqual = PathEqual> using UnorderedPathMap = std::unordered_map<std::string, T, Hash, KeyEqual>; } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/RtxSettings.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 RTX Settings utilities //! \todo This should probably not be in Carbonite. #pragma once #include "../../carb/dictionary/IDictionary.h" #include "../../carb/logging/Log.h" #include "../../carb/settings/ISettings.h" #include "../../carb/settings/SettingsUtils.h" #include "../../carb/tasking/TaskingUtils.h" #include "StringHelpers.h" #include <algorithm> #include <sstream> #include <string> #include <unordered_map> #include "md5.h" namespace rtx { /* Usage: // init globalOverrides = Settings::createContext(); vp0Context = Settings::createContext(); // update loop { // Frame begin // clone global settings Settings::cloneToContext(vp0Context, nullptr); Settings::getIDictionary()->makeIntAtPath(vp0Context, "path/to/int", 10); // ... Settings::applyOverridesToContext(vp0Context, globalOverrides); // ... // will have all the overrides Settings::getIDictionary()->getAsInt(vp0Context, "path/to/int"); } */ //! Settings path for RTX default settings. constexpr char kDefaultSettingsPath[] = "/rtx-defaults"; //! Settings path for RTX settings. constexpr char kSettingsPath[] = "/rtx"; //! Settings path for persistent default settings. constexpr char kDefaultPersistentSettingsPath[] = "/persistent-defaults"; //! Settings path for persistent settings. constexpr char kPersistentSettingsPath[] = "/persistent"; //! Settings path for transient RTX settings. constexpr char kTransientSettingsPath[] = "/rtx-transient"; //! Settings path for RTX flag settings. constexpr char kFlagsSettingsPath[] = "/rtx-flags"; // A note on internal setting handling. // Settings in /rtx-transient/internal and /rtx/internal are automatically mapped to entries in /rtx-transient/hashed // and /rtx/hashed, respectively. We use the MD5 hash of the full internal setting string as the key inside the "hashed" // scope. See the comments in InternalSettings.h for more details. //! Internal setting key. constexpr char kInternalSettingKey[] = "internal"; //! Hashed setting key constexpr char kHashedSettingKey[] = "hashed"; //! Settings root keys constexpr const char* kInternalSettingRoots[] = { kSettingsPath, kTransientSettingsPath, }; //! \defgroup rtxsettingflags RTX Settings Flags //! @{ //! Setting Flags type definition typedef uint32_t SettingFlags; //! Value indicating no settings flags. constexpr SettingFlags kSettingFlagNone = 0; //! Indicates that a setting flag is transient. //! \details Do not read or store in USD. Transient settings automatically disables reset feature. Note that settings //! under /rtx-transient are transient irrespective of this setting. constexpr SettingFlags kSettingFlagTransient = 1 << 0; //! Flag to indicate that resetting of the setting under /rtx-defaults is not allowed. constexpr SettingFlags kSettingFlagResetDisabled = 1 << 1; //! Default Setting Flag constexpr SettingFlags kSettingFlagDefault = kSettingFlagNone; //! @} //! Worst case hashed setting root path length. constexpr size_t kHashedSettingPrefixMaxSize = carb_max(carb::countOf(kSettingsPath), carb::countOf(kTransientSettingsPath)) + 1 + carb::countOf(kHashedSettingKey); //! Worst case hashed setting string length. constexpr size_t kHashedSettingCStringMaxLength = kHashedSettingPrefixMaxSize + MD5::kDigestStringSize + 1; /** * A class encapsulating render settings. */ class RenderSettings { public: /** * Statically-sized container for hashed setting strings. * \details We use MD5 hashes which have constant size, so we can compute the worst case hashed setting string size * and pass them around on the stack instead of on the heap. In the future this may also help with hashing at build * time. */ struct HashedSettingCString { //! String data char data[kHashedSettingCStringMaxLength]; }; /** * Checks a path to see if it matches the RTX setting root. * @param path The path to check * @returns `true` if \p path compares equal (case sensitive) to \ref kSettingsPath; `false` otherwise */ static bool isPathRenderSettingsRoot(const char* path) { size_t rtxSettingsPathLen = CARB_COUNTOF(kSettingsPath) - 1; size_t pathLen = strlen(path); if (pathLen == rtxSettingsPathLen && strcmp(path, kSettingsPath) == 0) { return true; } return false; } /** * Translates the given path to the defaults path. * \details For instance if \p cPath is `"/rtx/foo"`, `"/rtx-defaults/foo"` would be returned. * @param cPath The path to translate * @returns The path key in the defaults tree. See details above. */ static std::string getAssociatedDefaultsPath(const char* cPath) { std::string path(cPath); size_t pos = path.find_first_of("/", 1); std::string parentPath; std::string childPath; if (pos == std::string::npos) { parentPath = path; } else { parentPath = path.substr(0, pos); childPath = path.substr(pos); } return parentPath + "-defaults" + childPath; } /** * Translates a string into a key-value mapping. * \details Only two types of `<KeyType, ValueType>` are allowed: `<uint32_t, std::vector<uint32_t>>`, or * `<std::string, uint32_t>`. A colon (`:`) is the key/value separator and a semicolon (`;`) is the map separator. * This function first splits \p keyToValueDictStr by (`;`) and then each substring is split by (`:`). If exactly * two values are found by this second split, the value is added to \p outputDict. When `ValueType` is a * `std::vector`, the values are found by splitting the value substring by a comma (`,`). * @tparam KeyType The type of the key. See above for details. * @tparam ValueType The type of the value. See above for details. * @param keyToValueDictStr A string that is processed according to the details above * @param[out] outputDict The `std::unordered_map` that receives processed key/value pairs. This map is not cleared; * any values that exist in it before this function is called remain, but existing keys that are encountered in * \p keyToValueDictStr will overwrite existing values (however, if `ValueType` is `std::vector` the values are * appended to existing values). * @param debugStr (required) a string that will be used in logging if parse errors occur */ template <typename KeyType, typename ValueType> static void stringToKeyTypeToValueTypeDictionary(const std::string& keyToValueDictStr, std::unordered_map<KeyType, ValueType>& outputDict, const char* debugStr) { // Convert from string to a dictionary mapping KeyType values to ValueType values // // Example syntax: 0:0; 1:1,2; 2:3,4; 3:5; 4:6; 5:6; 6:6; 7;6" // Example syntax: "AsphaltStandard:0; AsphaltWeathered:1; ConcreteRough:2" // I.e.: use semicolon (';') to separate dictionary entries from each other, // use colon (':') to separate key from value and // use comma (',') to separate entries in a list of values std::stringstream ss(keyToValueDictStr); static constexpr char kMappingSep = ';'; static constexpr char kKeyValueSep = ':'; // Split by ';' into key:value mappings std::vector<std::string> keyToValueStrVec = omni::extras::split(keyToValueDictStr, kMappingSep); for (auto& keyToValue : keyToValueStrVec) { // Split a mapping into its key and value std::vector<std::string> keyToValueStrVec = omni::extras::split(keyToValue, kKeyValueSep); if (keyToValueStrVec.size() == 2) // this is a key,value pair { // find an appropriate overloaded function to add a key:value pair to the dictionary addValueAtKey(keyToValueStrVec[0], keyToValueStrVec[1], outputDict, debugStr); } } } /** * A helper function to determine if a setting flag path exists. * @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface() * @param settingPath The path to check for. \ref kFlagsSettingsPath will be prepended to this value * @returns `true` if the settings flag exists; `false` otherwise */ static inline bool hasSettingFlags(carb::settings::ISettings& settings, const char* settingPath) { std::string settingPathStr(kFlagsSettingsPath); settingPathStr += settingPath; return settings.getItemType(settingPathStr.c_str()) != carb::dictionary::ItemType::eCount; } /** * A helper function for reading settings flags. * @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface() * @param settingPath The path to read. \ref kFlagsSettingsPath will be prepended to this value * @returns the \ref rtxsettingflags read as an integer from the given \p settingsPath */ static inline SettingFlags getSettingFlags(carb::settings::ISettings& settings, const char* settingPath) { std::string settingPathStr(kFlagsSettingsPath); settingPathStr += settingPath; return SettingFlags(settings.getAsInt(settingPathStr.c_str())); } /** * A helper function for writing settings flags. * @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface() * @param settingPath The path to write. \ref kFlagsSettingsPath will be prepended to this value * @param flags The flags to write. These values will overwrite any existing flags */ static inline void setSettingFlags(carb::settings::ISettings& settings, const char* settingPath, SettingFlags flags) { std::string settingPathStr(kFlagsSettingsPath); settingPathStr += settingPath; settings.setInt64(settingPathStr.c_str(), flags); } /** * A helper function for deleting a settings flags key. * \post The settings path at \ref kFlagsSettingsPath + \p settingPath is destroyed. * @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface() * @param settingPath The path to delete. \ref kFlagsSettingsPath will be prepended to this value */ static inline void removeSettingFlags(carb::settings::ISettings& settings, const char* settingPath) { std::string settingPathStr(kFlagsSettingsPath); settingPathStr += settingPath; settings.destroyItem(settingPathStr.c_str()); } /** * Sets the default value for a RTX setting value and backs up the value. * \details The \ref carb::settings::ISettings API is used to set the default value at \p settingPath if the setting * key does not exist. If \p flags has neither \ref kSettingFlagTransient and \ref kSettingFlagResetDisabled set, * then the default path is constructed by \ref getAssociatedDefaultsPath(). If the default path is under the * `/persistent` root, the default path setting is updated with \p value, otherwise the default path setting is * updated with the current value read from \p settingPath. Finally, \ref setSettingFlags() is called with * \p settingPath and \p flags. * @param settingPath the setting path to set default for and to back up * @param value the default value to set at \p settingPath * @param flags \ref rtxsettingflags to apply to \p settingPath */ template <typename SettingType> static void setAndBackupDefaultSetting(const char* settingPath, SettingType value, SettingFlags flags = kSettingFlagDefault) { carb::settings::ISettings* settings = getISettings(); settings->setDefault<SettingType>(settingPath, value); bool allowReset = (flags & (kSettingFlagTransient | kSettingFlagResetDisabled)) == 0; if (allowReset) { std::string defaultSettingPath = getAssociatedDefaultsPath(settingPath); if (!defaultSettingPath.empty()) { std::string path(defaultSettingPath); if (path.substr(0, std::strlen(kPersistentSettingsPath)) == kPersistentSettingsPath) { settings->set<SettingType>(defaultSettingPath.c_str(), value); } else { settings->setDefault<SettingType>( defaultSettingPath.c_str(), settings->get<SettingType>(settingPath)); } } } // Set per setting flag (persistent, etc.) setSettingFlags(*settings, settingPath, flags); } /** * Returns a hashed setting string based on the given setting path. * @param s The setting path * @returns A hashed setting string based on \p s */ static inline std::string getInternalSettingString(const char* s) { return std::string(getHashedSettingString(s).data); } // TODO: Make private? It looks like this function is just subscribed for change events in // setAndBackupPersistentDefaultSetting. //! @private static void updateSetting(const carb::dictionary::Item* changedItem, carb::dictionary::ChangeEventType eventType, void* userData) { CARB_UNUSED(eventType); if (!changedItem) { CARB_LOG_ERROR("Unexpected setting deletion"); } const char* path = reinterpret_cast<const char*>(userData); carb::dictionary::IDictionary* dictionary = getIDictionary(); carb::settings::ISettings* settings = getISettings(); carb::dictionary::ItemType itemType = dictionary->getItemType(changedItem); if (itemType == carb::dictionary::ItemType::eString) { settings->setString(path, dictionary->getStringBuffer(changedItem)); } else if (itemType == carb::dictionary::ItemType::eFloat) { settings->setFloat(path, dictionary->getAsFloat(changedItem)); } else if (itemType == carb::dictionary::ItemType::eInt) { settings->setInt(path, dictionary->getAsInt(changedItem)); } else if (itemType == carb::dictionary::ItemType::eBool) { settings->setBool(path, dictionary->getAsBool(changedItem)); } } /** * Sets a setting value to a given default value and back up the previous value. * \warning The \p settingPath pointer value is captured by this function. Its lifetime must be for the rest of the * application, or undefined behavior will occur. * @tparam SettingType the type of the value * @param settingPath the setting path to set default for and to back up. **NOTE** see warning above * @param value The default value to assign */ template <typename SettingType> static void setAndBackupPersistentDefaultSetting(const char* settingPath, SettingType value) { carb::settings::ISettings* settings = getISettings(); std::string persistentPath = std::string("/persistent") + settingPath; settings->setDefault<SettingType>(persistentPath.c_str(), value); std::string defaultSettingPath = getAssociatedDefaultsPath(persistentPath.c_str()); if (!defaultSettingPath.empty()) { std::string path(defaultSettingPath); if (path.substr(0, std::strlen(kPersistentSettingsPath)) == kPersistentSettingsPath) { settings->set<SettingType>(defaultSettingPath.c_str(), value); } else { settings->set<SettingType>( defaultSettingPath.c_str(), settings->get<SettingType>(persistentPath.c_str())); } } settings->subscribeToNodeChangeEvents( persistentPath.c_str(), RenderSettings::updateSetting, (void*)(settingPath)); settings->set<SettingType>(settingPath, settings->get<SettingType>(persistentPath.c_str())); } /** * Sets a setting value to a given array value and backs up the previous value. * @tparam SettingArrayType the type of the elements of the array * @param settingPath the setting path to set default for and to back up * @param array The array of values to assign as the default for \p settingPath * @param arrayLength The number of items in \p array * @param flags \ref rtxsettingflags to apply to \p settingPath */ template <typename SettingArrayType> static void setAndBackupDefaultSettingArray(const char* settingPath, const SettingArrayType* array, size_t arrayLength, SettingFlags flags = kSettingFlagDefault) { carb::settings::ISettings* settings = getISettings(); settings->setDefaultArray<SettingArrayType>(settingPath, array, arrayLength); bool allowReset = (flags & (kSettingFlagTransient | kSettingFlagResetDisabled)) == 0; if (allowReset) { std::string defaultSettingPath = getAssociatedDefaultsPath(settingPath); if (!defaultSettingPath.empty()) { settings->destroyItem(defaultSettingPath.c_str()); size_t arrayLength = settings->getArrayLength(settingPath); for (size_t idx = 0; idx < arrayLength; ++idx) { std::string elementPath = std::string(settingPath) + "/" + std::to_string(idx); std::string defaultElementPath = std::string(defaultSettingPath) + "/" + std::to_string(idx); settings->setDefault<SettingArrayType>( defaultElementPath.c_str(), settings->get<SettingArrayType>(elementPath.c_str())); } } } // Set per setting flag (persistent, etc.) setSettingFlags(*settings, settingPath, flags); } /** * Reads the default value for the given path and restores it. * @param path The setting path to restore */ static void resetSettingToDefault(const char* path) { carb::dictionary::IDictionary* dictionary = getIDictionary(); carb::settings::ISettings* settings = getISettings(); std::string defaultsPathStorage; defaultsPathStorage = getAssociatedDefaultsPath(path); const carb::dictionary::Item* srcItem = settings->getSettingsDictionary(defaultsPathStorage.c_str()); carb::dictionary::ItemType srcItemType = dictionary->getItemType(srcItem); size_t srcItemArrayLength = dictionary->getArrayLength(srcItem); if ((srcItemType == carb::dictionary::ItemType::eDictionary) && (srcItemArrayLength == 0)) { resetSectionToDefault(path); return; } switch (srcItemType) { case carb::dictionary::ItemType::eBool: { settings->set<bool>(path, dictionary->getAsBool(srcItem)); break; } case carb::dictionary::ItemType::eInt: { settings->set<int32_t>(path, dictionary->getAsInt(srcItem)); break; } case carb::dictionary::ItemType::eFloat: { settings->set<float>(path, dictionary->getAsFloat(srcItem)); break; } case carb::dictionary::ItemType::eString: { settings->set<const char*>(path, dictionary->getStringBuffer(srcItem)); break; } case carb::dictionary::ItemType::eDictionary: { if (srcItemArrayLength > 0) { settings->update(path, srcItem, nullptr, carb::dictionary::kUpdateItemOverwriteOriginal, nullptr); } break; } default: break; } } /** * Restores the subtree at the given path from the backed up values. * @param path The subtree setting path */ static void resetSectionToDefault(const char* path) { carb::settings::ISettings* settings = getISettings(); std::string defaultsPathStorage; const char* defaultsPath = nullptr; defaultsPathStorage = getAssociatedDefaultsPath(path); if (!defaultsPathStorage.empty()) { defaultsPath = defaultsPathStorage.c_str(); } if (defaultsPath) { // Do not delete existing original settings. // If the source item exists (rtx-default value), overwrite the destination (original rtx value). // Otherwise, leave them as-is. We want to keep original values until we find some default values in the // future. Plugins may load at a later time and we should not remove original values until we have some // default values. settings->update(path, settings->getSettingsDictionary(defaultsPath), nullptr, carb::dictionary::kUpdateItemOverwriteOriginal, nullptr); } else { CARB_LOG_ERROR("%s: failed to resolve default paths", __func__); } } /** * Creates a root level dictionary item. * \details This item is created as via \ref carb::dictionary::IDictionary::createItem() with `<rtx context>` as the * name. * @returns a \ref carb::dictionary::Item that is of type \ref carb::dictionary::ItemType::eDictionary */ static carb::dictionary::Item* createContext() { return getIDictionary()->createItem(nullptr, "<rtx context>", carb::dictionary::ItemType::eDictionary); } /** * Helper function to destroy a dictionary item. * \details This function is a helper function to call \ref carb::dictionary::IDictionary::destroyItem(). * @param ctx the \ref carb::dictionary::Item to destroy */ static void destroyContext(carb::dictionary::Item* ctx) { getIDictionary()->destroyItem(ctx); } /** * Copies a source context to a destination context. * \warning This function appears to have a bug where \p dstContext is used after destroyed if \p srcContext is not * `nullptr`. * @param dstContext The destination context to overwrite * @param srcContext The source context to copy to \p dstContext. Maybe `nullptr` to re-initialize \p dstContext. */ static void cloneToContext(carb::dictionary::Item* dstContext, carb::dictionary::Item* srcContext) { carb::dictionary::IDictionary* dict = getIDictionary(); carb::settings::ISettings* settings = getISettings(); dict->destroyItem(dstContext); if (srcContext) { // TODO: It is undefined behavior to use dstContext after destroyItem above dict->update(dstContext, "", srcContext, "", carb::dictionary::kUpdateItemOverwriteOriginal, nullptr); } else { dstContext = settings->createDictionaryFromSettings(kSettingsPath); } } /** * Copies a subtree over the destination subtree. * @param dstContext The destination to overwrite * @param overridesContext The subtree to write over \p dstContext */ static void applyOverridesToContext(carb::dictionary::Item* dstContext, carb::dictionary::Item* overridesContext) { if (!overridesContext) { CARB_LOG_ERROR("%s needs context to override from", __FUNCTION__); } carb::dictionary::IDictionary* dict = getIDictionary(); dict->update(dstContext, "", overridesContext, "", carb::dictionary::kUpdateItemOverwriteOriginal, nullptr); } /** * Dictionary access helper function. * @returns \ref carb::dictionary::IDictionary as by \ref carb::getCachedInterface() */ static carb::dictionary::IDictionary* getIDictionary() { return carb::getCachedInterface<carb::dictionary::IDictionary>(); } /** * Settings access helper function. * @returns \ref carb::settings::ISettings as by \ref carb::getCachedInterface() */ static carb::settings::ISettings* getISettings() { return carb::getCachedInterface<carb::settings::ISettings>(); } /** * Translates plaintext internal settings to hashed settings and removes the plaintext settings. * \details This is to ensure that the plaintext internal settings are not inadvertently saved to USD. */ static void hashInternalRenderSettings() { auto settings = getISettings(); auto hashRtxSetting = [&settings](const char* itemPath, uint32_t, void*) -> uint32_t { const carb::dictionary::ItemType itemType = settings->getItemType(itemPath); if (itemType == carb::dictionary::ItemType::eDictionary) { return 0; } const auto newHashedPath = getHashedSettingString(itemPath); switch (settings->getItemType(itemPath)) { case carb::dictionary::ItemType::eBool: settings->setBool(newHashedPath.data, settings->getAsBool(itemPath)); break; case carb::dictionary::ItemType::eFloat: settings->setFloat(newHashedPath.data, settings->getAsFloat(itemPath)); break; case carb::dictionary::ItemType::eInt: settings->setInt(newHashedPath.data, settings->getAsInt(itemPath)); break; case carb::dictionary::ItemType::eString: settings->setString(newHashedPath.data, settings->getStringBuffer(itemPath)); break; case carb::dictionary::ItemType::eDictionary: CARB_FALLTHROUGH; default: CARB_ASSERT(0); } if (hasSettingFlags(*settings, itemPath)) { setSettingFlags(*settings, newHashedPath.data, getSettingFlags(*settings, itemPath)); removeSettingFlags(*settings, itemPath); } return 0; }; carb::dictionary::IDictionary* dictionary = getIDictionary(); for (const char* root : kInternalSettingRoots) { std::stringstream ss; ss << root << '/' << kInternalSettingKey; const std::string internalRoot = ss.str(); carb::settings::walkSettings(dictionary, settings, carb::dictionary::WalkerMode::eSkipRoot, internalRoot.c_str(), 0, hashRtxSetting, nullptr); settings->destroyItem(internalRoot.c_str()); } } private: // Key : Value = uint32_t : std::vector<uint32_t> static void addValueAtKey(std::string key, std::string value, std::unordered_map<uint32_t, std::vector<uint32_t>>& outputDict, const char* debugStr) { static const char kListElemSep = ','; int intKey = 0; if (!omni::extras::stringToInteger(key, intKey)) { CARB_LOG_WARN("Non-integer value %s set in \"%s\"", key.c_str(), debugStr); } // Split the value into a list of values std::vector<std::string> intVecStrVec = omni::extras::split(value, kListElemSep); int32_t intVecValueEntry = 0; outputDict[intKey].clear(); for (auto& intVecValueEntryStr : intVecStrVec) { if (omni::extras::stringToInteger(intVecValueEntryStr, intVecValueEntry)) { outputDict[intKey].push_back(intVecValueEntry); } else { CARB_LOG_WARN("Non-integer value %s set in \"%s\"", intVecValueEntryStr.c_str(), debugStr); } } } // Key : Value = std::string : uint32_t static void addValueAtKey(std::string key, std::string value, std::unordered_map<std::string, uint32_t>& outputDict, const char* debugStr) { int32_t outInt = 0; if (omni::extras::stringToInteger(value, outInt)) { outputDict[key] = outInt; } else { CARB_LOG_WARN("Non-integer value %s set in \"%s\"", key.c_str(), debugStr); } } static HashedSettingCString getHashedSettingString(const char* settingStr) { constexpr size_t sizeOfRtxSettingsRoot = carb::countOf(kSettingsPath) - 1; const bool isRtxSettingsPath = strncmp(settingStr, kSettingsPath, sizeOfRtxSettingsRoot) == 0 && settingStr[sizeOfRtxSettingsRoot] == '/'; // Default to kTransientSettingsPath for anything outside /rtx/. // We don't promise that anything works for paths not rooted in /rtx[-transient]/internal, but implement // reasonable behavior rather than crash or map all invalid settings to a null string. Improperly rooted strings // will work fine except that hashInternalRenderSettings() won't know to translate them. const char* hashedRoot = isRtxSettingsPath ? kSettingsPath : kTransientSettingsPath; return getHashedSettingString( MD5::getDigestString(MD5::run((const uint8_t*)settingStr, strlen(settingStr))), hashedRoot); } static HashedSettingCString getHashedSettingString(const MD5::DigestString& digestStr, const char* root) { HashedSettingCString result = {}; char* s = std::copy_n(root, strlen(root), result.data); *s++ = '/'; s = std::copy_n(kHashedSettingKey, carb::countOf(kHashedSettingKey) - 1, s); *s++ = '/'; s = std::copy_n(digestStr.s, MD5::kDigestStringSize, s); *s = '\0'; return result; } }; /** * Dummy function. * \todo remove this? * @returns `false` */ inline bool enableAperture() { // Enabling Aperture mode adds 2 ray types. return false; } /** * Caches and returns the value of "/rtx/mdltranslator/distillMaterial". * \details The value is read from \ref carb::settings::ISettings once and cached; future calls to this function are * very fast. * @thread_safety This function is thread safe. * @returns The value read from `/rtx/mdltranslator/distillMaterial` */ inline bool enableMDLDistilledMtls() { auto&& init = [] { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); return settings->getAsBool("/rtx/mdltranslator/distillMaterial"); }; static bool result = init(); return result; } /** * Caches and returns whether the value of "/rtx/rendermode" is "abisko". * \details The value is read from \ref carb::settings::ISettings once and cached; future calls to this function are * very fast. * @thread_safety This function is thread safe. * @returns `true` if the value read from `/rtx/rendermode` is equal to `abisko` */ inline bool enableAbiskoMode() { auto&& init = [] { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); const char* renderMode = settings->getStringBuffer("/rtx/rendermode"); return strcmp(renderMode, "abisko") == 0; }; static bool result = init(); return result; } // Returns how many ray types we are going to use during the whole Kit rendering. This CAN'T be changed once the // renderer is initialized /** * Returns how many ray types the renderer will use based on settings. * \details This value cannot be changed once the renderer is initialized. This value is read from * \ref carb::settings::ISettings the first time this function is called and cached so that future calls are very * fast. * @thread_safety This function is thread safe. * @returns The number of ray types the renderer will use */ inline uint32_t getRayTypeCount() { auto&& init = [] { uint32_t rayCount = 2; // MATERIAL_RAY and VISIBILITY_RAY for RTX are always available if (!rtx::enableAbiskoMode()) // Abisko only has two ray types { if (rtx::enableAperture()) { rayCount += 2; // APERTURE_MATERIAL_RAY and APERTURE_VISIBILTY_RAY } if (rtx::enableMDLDistilledMtls()) { rayCount += 1; // DISTILLED_MATERIAL_RAY } } return rayCount; }; static uint32_t result = init(); return result; } /** * A helper function that atomically sets the setting value at path if and only if it doesn't exist. * @param settings \ref carb::settings::ISettings as if by \ref carb::getCachedInterface() * @param path The settings path to check * @param value The value to write to \p path if it doesn't exist * @retval true The value did not exist and was atomically set to \p value * @retval false The value already existed and was not set */ inline bool setDefaultBoolEx(carb::settings::ISettings* settings, const char* path, bool value) { // Unfortunately need a write lock since we might be writing carb::dictionary::ScopedWrite writeLock(*carb::getCachedInterface<carb::dictionary::IDictionary>(), const_cast<carb::dictionary::Item*>(settings->getSettingsDictionary(path))); if (settings->getItemType(path) != carb::dictionary::ItemType::eCount) return false; settings->setBool(path, value); return true; } } // namespace rtx
omniverse-code/kit/include/omni/extras/DataStreamer.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. // #pragma once #include "../log/ILog.h" #include "../../carb/events/IEvents.h" #include "../../carb/events/EventsUtils.h" #include "../../carb/tasking/ITasking.h" #include "../../carb/tasking/TaskingUtils.h" #include "../../carb/RString.h" namespace omni { namespace extras { /** An ID that identifies a data type. */ using DataStreamType = int64_t; /** The event type when an event contains data. * If you need to send other events through the stream, you can use another ID. */ constexpr carb::events::EventType kEventTypeData = 0; /** Generate a unique ID for a specific data type. * @tparam T The type to generate an ID for. * @returns A unique ID for T. */ template <typename T> DataStreamType getDataStreamType() noexcept { #if CARB_COMPILER_MSC return carb::fnv1aHash(__FUNCSIG__); #elif CARB_COMPILER_GNUC return carb::fnv1aHash(__PRETTY_FUNCTION__); #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** This allows a series of ordered packets of raw binary data to be sent * through @ref carb::events::IEvents. * * To use this class, the data producer will call pushData() whenever it has * a packet of data, then it will either call pump() or pumpAsync() to send * the data to the listeners. * * It's also possible to grab the underlying event stream and send other events * through for the listener to consume. * * Each listener should call getEventStream() and use it to construct a * @ref DataListener implementation. */ class DataStreamer { public: DataStreamer() noexcept { m_events = carb::getFramework()->tryAcquireInterface<carb::events::IEvents>(); if (m_events == nullptr) { OMNI_LOG_ERROR("unable to acquire IEvents"); return; } m_tasking = carb::getFramework()->tryAcquireInterface<carb::tasking::ITasking>(); if (m_tasking == nullptr) { OMNI_LOG_ERROR("unable to acquire ITasking"); return; } m_eventStream = m_events->createEventStream(); if (!m_eventStream) { OMNI_LOG_ERROR("unable to create an event stream"); return; } m_initialized = true; } ~DataStreamer() noexcept { flush(); } /** Synchronously submit a packet of data to all listeners. * * @remarks This will call the onDataReceived() function for all listeners * on the current thread. * The onDataReceived() calls are serialized, so this can be * called concurrently with pumpAsync() or other calls to pump(). */ void pump() noexcept { if (!m_initialized) { return; } m_throttler.acquire(); m_eventStream->pump(); m_throttler.release(); } /** Asynchronously submit a packet of data to all listeners. * * @remarks This will spawn a task which calls the onDataReceived() * function for all listeners. * * @note To verify that all tasks have finished, you must call flush(). * This is automatically done when deleting the class instance. */ void pumpAsync(carb::tasking::Priority priority = carb::tasking::Priority::eLow) noexcept { if (!m_initialized) { return; } m_tasking->addThrottledTask(m_throttler, priority, m_tasks, [this] { m_eventStream->pump(); }); } /** Push a new packet of data into the stream. * * @tparam T The type pointed to by @p data. * This type will be copied around, so it must be trivially copyable. * @param[in] data The data packet to submit to the stream. * The data in this pointer is copied, so the pointer is * is safe to be invalidated after this call returns. * @param[in] size The length of @p data in elements. * * @remarks After a packet of data is placed in the stream, it will just be * queued up. * For each call to pushData(), there should be a corresponding * call to pump() or pumpAsync() to dequeue that packet and send * it to the listeners. */ template <typename T> void pushData(const T* data, size_t size) noexcept { static_assert(std::is_trivially_copyable<T>::value, "non-trivially-copyable types will not work here"); if (!m_initialized) { return; } m_eventStream->push( kEventTypeData, std::make_pair("data", carb::cpp::string_view(reinterpret_cast<const char*>(data), size * sizeof(T))), std::make_pair("type", getDataStreamType<T>())); } /** Retrieve the event stream used by the data streamer. * @returns The event stream used by the data streamer. * * @remarks This event stream can be subscribed to, but you can also send * further events on this stream as long as their type is not * @ref kEventTypeData. */ carb::events::IEventStreamPtr getEventStream() noexcept { return m_eventStream; } /** Check if the class actually initialized successfully. * @returns whether the class actually initialized successfully. */ bool isWorking() noexcept { return m_initialized; } /** Wait for all asynchronous tasks created by pumpAsync() to finish. */ void flush() noexcept { CARB_LOG_INFO("waiting for all tasks to finish"); m_tasks.wait(); CARB_LOG_INFO("all tasks have finished"); } private: /** The events interface. */ carb::events::IEvents* m_events; /** The tasking interface, which we need for pumpAsync(). */ carb::tasking::ITasking* m_tasking; /** The event stream we're using to queue and send data. */ carb::events::IEventStreamPtr m_eventStream; /** A group to hold all of our tasks so we can shut down safely. */ carb::tasking::TaskGroup m_tasks; /** This is used to serialize calls to @ref m_eventStream->pump(). */ carb::tasking::SemaphoreWrapper m_throttler{ 1 }; /** Flag to specify whether the class initialized properly. */ bool m_initialized = false; }; /** This is an abstract class that allows data from a @ref DataStreamer to be * received in an easy way. * * The listener implementation just needs to add an onDataReceived() call to * receive the raw binary data and an onEventReceived() call to handle any * other events that may be sent on the stream. */ class DataListener { public: /** Constructor. * @param[in] stream The event stream from a @ref DataStreamer to listen to. */ DataListener(carb::events::IEventStreamPtr stream) noexcept { m_dict = carb::getFramework()->tryAcquireInterface<carb::dictionary::IDictionary>(); if (m_dict == nullptr) { OMNI_LOG_ERROR("failed to acquire IDictionary"); return; } m_sub = carb::events::createSubscriptionToPop(stream.get(), [this](const carb::events::IEvent* e) { if (e->type != kEventTypeData) { onEventReceived(e); return; } const carb::dictionary::Item* child; child = m_dict->getItem(e->payload, "type"); if (child == nullptr) { OMNI_LOG_ERROR("the event had no /type field?"); return; } DataStreamType type = m_dict->getAsInt64(child); child = m_dict->getItem(e->payload, "data"); if (child == nullptr) { OMNI_LOG_ERROR("the event had no /data field?"); return; } size_t len; const char* bytes = m_dict->getStringBuffer(child, &len); onDataReceived(bytes, len, type); }, 0, "DataListener"); } virtual ~DataListener() noexcept { // in case disconnect() has additional functionality in the future disconnect(); } protected: /** The function that will receive data packets. * @param[in] payload The packet of data that was received. * This pointer will be invalid after this call returns, * so it must not be held. * Due to the nature of @ref carb::events::IEvents, there * is no guarantee that the alignment of this data will * be correct, so you should memcpy it into a separate * buffer first to be safe. * @param[in] bytes The length of @p payload in bytes. * @param[in] type The data type ID of the data contained in @p payload. */ virtual void onDataReceived(const void* payload, size_t bytes, DataStreamType type) noexcept = 0; /** The function that will receive non-data events from the stream. * @param[in] e The event that was received. */ virtual void onEventReceived(const carb::events::IEvent* e) noexcept = 0; /** Disconnect this listener from the event stream. * @remarks This might be useful if your information wants to do something * during shutdown that would crash if an event was received * concurrently. */ void disconnect() noexcept { m_sub = nullptr; } /** The dictionary interface used to read the event payloads. */ carb::dictionary::IDictionary* m_dict = nullptr; private: /** The event subscription used for this stream. */ carb::events::ISubscriptionPtr m_sub; }; } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/SettingsHelpers.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. // //! @file //! @brief Helpers for carb.settings #pragma once #include "../../carb/settings/SettingsUtils.h" #include <string> #include <vector> namespace carb { namespace settings { /** * Access a setting key if present, otherwise returning a default value. * \details This function does not use the \ref carb::settings::ISettings API to set the value as a default if \p path * does not exist. In order to do that, use \ref setDefaultAndGetSetting(). * @tparam T the type of the return value and default value * @param path The setting key path to check * @param defaultValue The default value to return if the setting key does not exist * @returns The value read from \p path, or \p defaultValue if the setting key does not exist */ template <typename T> T getSettingOrDefault(const char* path, T defaultValue = {}) { ISettings* s = getCachedInterface<ISettings>(); if (s->getItemType(path) == dictionary::ItemType::eCount) return defaultValue; return s->get<T>(path); } /** * Sets a default value for a setting key and returns the current value. * \details Setting a default value will only have an effect if the setting key is not already present. The distinction * between this function and \ref getSettingOrDefault() is that this function will set the default value with the * \ref carb::settings::ISettings API. Any attempts to query the key directly will return the default value if it has * not been modified. * @tparam T the type of the return value and default value * @param path The setting key path * @param defaultValue The default value to set for the setting key if it does not exist * @return The current value read from \p path, which will be \p defaultValue if the setting key did not exist before * this function was called. */ template <typename T> T setDefaultAndGetSetting(const char* path, T defaultValue = {}) { ISettings* s = getCachedInterface<ISettings>(); s->setDefault<T>(path, defaultValue); return s->get<T>(path); } /** * Appends a set of string values to the end of a setting key. * @see carb::settings::ISettings * @param path The setting key path containing a string array. If the key does not exist it will be created. If the key * is already present as a different type it will be changed to a string array. * @param values A `std::vector` of string values to add to the end of the string array at the setting key */ inline void appendToStringArray(const char* path, const std::vector<std::string>& values) { if (values.empty()) return; ISettings* s = getCachedInterface<ISettings>(); // Hold a write lock while the modification takes place carb::dictionary::ScopedWrite writeLock( *getCachedInterface<dictionary::IDictionary>(), const_cast<dictionary::Item*>(s->getSettingsDictionary("/"))); // TODO: This could be implemented a lot more efficiently than fully copying everything twice std::vector<std::string> v = settings::getStringArray(s, path); v.insert(v.end(), values.begin(), values.end()); settings::setStringArray(s, path, v); } } // namespace settings } // namespace carb
omniverse-code/kit/include/omni/extras/UniqueApp.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 Helper class to manage a unique process. */ #pragma once #include "../core/Omni.h" #include <string> #if OMNI_PLATFORM_WINDOWS # include "../../carb/CarbWindows.h" # include "../../carb/extras/WindowsPath.h" #else # include <unistd.h> # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> #endif namespace omni { /** common namespace for extra helper functions and classes. */ namespace extras { /** Helper class to manage a unique app. A unique app is one that is intended to only * run a single instance of it at any given time. This contains helper functions to handle * common tasks that are intended to be used on both the unique app's side and on the host * app side. This contains two major sets of helper functions. * * One set is to manage the uniqueness of the app itself. These can either be called * entirely from within the unique app process after launch to determine if another * instance of the app is already running and that the new one should exit immediately. * Alternatively, the launching host app could also first check if the unique app process * is already running before deciding to launch it in the first place. * * The other set is to manage notifying the unique app process when it should exit * naturally. These functions setup a signal that a host app is still running that * the unique app can then poll on. The host app is responsible for setting its * 'running' signal early on its launch. The unique app process will then periodically * poll to see if any host apps are still running. * * Note that a 'connection' to the unique app is not actually a connection in a communication * sense. This is more akin to a reference count on an object that the operating system will * manage regardless of how the host app exits or stops running. The 'connection' can exist * for the host app before the unique app is even launched (in fact, this behavior is preferred * since it simplifies polling and avoids the possibility of an unintentional early exit). * The host app's 'connection' to the unique app does not require any actual communication, just * that the connection object remain open until it is either explicitly closed or the host app * process exits. */ class UniqueApp { public: /** Constructor: creates a new unique app object with default settings. * * This creates a new object with all default settings. Note that this will use the default * guard name. If the caller doesn't set a different guard name with @ref setGuardName(), * the uniqueness of the app represented by this object may conflict with other apps that * also use that name. */ UniqueApp() = default; /** Constructor: creates a new unique app object with explicit settings. * * @param[in] guardPath The directory to store the various guard files in. This may not * be `nullptr`. This may be a relative or absolute path. If this * is an empty string, the current directory will be used instead. * @param[in] guardName The prefix to use for the guard objects. This may not be * `nullptr`. If this is an empty string, the default prefix will * be used. This should be a name that is unique to the app being * launched. However, all instances trying to launch that single * unique app must use the same guard name. * * This creates a new object with explicit settings for the guard path and guard names. * This is a convenience shortcut for creating an object with default settings, then * changing the guard path and guard name manually using @ref setGuardPath() and * @ref setGuardName(). */ UniqueApp(const char* guardPath, const char* guardName) { setGuardPath(guardPath); setGuardName(guardName); } ~UniqueApp() { // Note: We are *intentionally* leaking any created guard objects here. If either of // them were to be closed on destruction of the object, undesirable effects would // result: // * If the launch guard was created, closing it would allow other instances // of the unique app to successfully launch. // * If this process 'connected' to the unique app process, closing the exit // guard object would remove its reference and could allow the unique app to // exit prematurely thinking all of its 'clients' had exited already. // // An alternative to this would require forcing all callers to store the created // object at a global level where it would live for the duration of the process. // While this is certainly possible, enforcing that would be difficult at best. } /** Sets the path to put the guard file(s) in. * * @param[in] path The directory to store the various guard files in. This may not * be `nullptr`. This may be a relative or absolute path. If this is * an empty string, the current directory will be used instead. * @returns no return value. * * @note If the given path or any components on it do not exist at the time a guard * file is being created, any missing directories will be created. This only * occurs when a guard file is being used however, not directly during this call. * * @thread_safety This call is not thread safe. It is the caller's responsibility to * ensure this call is protected. */ void setGuardPath(const char* path) { if (path[0] == 0 || path == nullptr) path = "."; m_guardPath = path; } /** Sets the name for the guard file(s). * * @param[in] name The prefix to use for the guard objects. This may not be `nullptr`. * If this is an empty string, the default prefix will be used. This * should be a name that is unique to the app being launched. However, * all instances trying to launch that single unique app must use the * same guard name. * @returns no return value. * * @thread_safety This call is not thread safe. It is the caller's responsibility to * ensure this call is protected. */ void setGuardName(const char* name) { if (name[0] == 0 || name == nullptr) name = kDefaultNamePrefix; m_guardName = name; } /** Creates the run guard object for the unique app. * * @returns `true` if the unique app launch guard was newly created successfully. Returns * `false` if the launch guard could not be created or it was already created by * another process. * * This creates the run guard object that is used to determine if the unique app is * already running. This is intended to be called exactly once from the unique app's * process early during its startup. The guard object that is created will exist for the * remaining lifetime of the unique app's process. Once the process that calls this exits, * the object will be cleaned up by the operating system. * * The @ref checkLaunchGuard() function is intended to be used to determine if this * object still exists. It may be called either from within the unique app itself * to determine if new launches of it should just exit, or it may called from a host app * to determine whether to launch the unique app in the first place. This function * however is intended to be called from the unique app itself and acts as both the * guard object creation and a check for its existence. * * @thread_safety This call is not thread safe. It is the caller's responsibility to * ensure calls to it are protected. However, since this is intended * to work between multiple processes, thread safety is not necessarily the * main concern and a race condition may still be possible. This is intended * to only be called once from the creating process. */ bool createLaunchGuard() { FileHandle handle; // this process has already created the launch guard object -> nothing to do => succeed. if (m_launchGuard != kBadFileHandle) return true; #if OMNI_PLATFORM_WINDOWS std::string name = m_guardName + kLaunchLockExtension; handle = CreateEventA(nullptr, false, false, name.c_str()); if (handle == nullptr) return false; if (GetLastError() == CARBWIN_ERROR_ALREADY_EXISTS) { CloseHandle(handle); return false; } #else std::string path = _getGuardName(kLaunchLockExtension).c_str(); handle = _openFile(path.c_str()); if (handle == kBadFileHandle) return false; if (!_lockFile(handle, LockType::eExclusive)) { close(handle); return false; } #endif // save the exit guard event so we can destroy it later. m_launchGuard = handle; // intentionally 'leak' the guard handle here. This will keep the handle open for the // entire remaining duration of the process. This is important because the existence // of the guard object is what is used by other host apps to determine if the unique // app is already running. Once the unique app process exits (or it makes a call to // @ref destroyLaunchGuard()), the OS will automatically close the guard object. return true; } /** Destroys the locally created launch guard object. * * @returns No return value. * * This destroys the launch guard object that was most recently created with * @ref createLaunchGuard(). The launch guard object can be recreated with another * call to @ref createLaunchGuard() later. * * @thread_safety This call is not thread safe. It is the caller's responsibility to * ensure any calls are protected. However, note that since this is a * global object potentially used for interprocess operations, there may * still be a possible race condition with its use. */ void destroyLaunchGuard() { FileHandle fp = m_launchGuard; m_launchGuard = kBadFileHandle; _closeFile(fp); } /** Tests whether the unique app is already running. * * @returns `true` if the unique app is currently running. Returns `false` if the * unique app is not running or if the guard object could not be accessed. * * This tests whether the unique app is currently running. This is done by trying * to detect whether the guard object exists in the system. When the unique app process * exits (naturally or otherwise), the operating system will remove the guard object * automatically. * * This call differs from @ref createLaunchGuard() in that this will not create the guard * object if it does not already exist. This is intended to be used from host apps before * launching the unique app instead of checking for uniqueness from the unique app itself. * * @thread_safety This call is technically thread safe on Windows. On Linux it is thread * safe as long as @ref setGuardPath() is not called concurrently. However, * since it is meant to test for an object that is potentially owned by * another process there may still be race conditions that could arise. */ bool checkLaunchGuard() { #if OMNI_PLATFORM_WINDOWS HANDLE event; DWORD error; std::string name = m_guardName + kLaunchLockExtension; event = CreateEventA(nullptr, false, false, name.c_str()); // failed to create the event handle (?!?) => fail. if (event == nullptr) return false; error = GetLastError(); CloseHandle(event); return error == CARBWIN_ERROR_ALREADY_EXISTS; #else FileHandle fp; bool success; fp = _openFile(_getGuardName(kLaunchLockExtension).c_str()); if (fp == kBadFileHandle) return false; success = _lockFile(fp, LockType::eExclusive, LockAction::eTest); _closeFile(fp); return !success; #endif } /** Notifies the unique app that a host app is running. * * @returns `true` if the unique app was successfully notified of the new running * host app. Returns `false` if the notification either couldn't be sent or * could not be completed. * * This lets the unique app know that the calling host app is still running. This * is done by adding a shared lock reference to a marker file that the unique app * can poll on periodically. The operating system will automatically remove the lock * reference(s) for this call once the calling process exits (naturally or otherwise). * * This is intended to be called only once by any given host app. However, it may be * called multiple times without much issue. The only downside to calling it multiple * times would be that extra handles (Windows) or file descriptors (Linux) will be * consumed for each call. * * @thread_safety This call is not thread safe. It is the caller's responsibility to * ensure calls to it are protected. However, since it is meant to * operate between processes, there may still be unavoidable race conditions * that could arise. */ bool connectClientProcess() { bool success; FileHandle fp; // this object has already 'connected' to the unique app -> nothing to do => succeed. if (m_exitGuard != kBadFileHandle) return true; fp = _openFile(_getGuardName(kExitLockExtension).c_str()); // failed to open the guard file (?!?) => fail. if (fp == kBadFileHandle) return false; // grab a shared lock to the file. This will allow all clients to still also grab a // shared lock but will prevent the unique app from grabbing its exclusive lock // that it uses to determine whether any client apps are still 'connected'. success = _lockFile(fp, LockType::eShared); if (!success) _closeFile(fp); // save the exit guard handle in case we need to explicitly disconnect this app later. else m_exitGuard = fp; // intentionally 'leak' the file handle here. Since the file lock is associated with // the file handle, we can't close it until the process exits otherwise the unique app // will think this client has 'disconnected'. If we leak the handle, the OS will take // care of closing the handle when the process exits and that will automatically remove // this process's file lock. return success; } /** 'Disconnect' the calling process from the exit guard. * * @returns No return value. * * This closes the calling process's reference to the exit guard file. This will allow * the exit guard for a host app process to be explicitly cleaned up before exit if * needed. * * @thread_safety This call is not thread safe. It is the caller's responsibility to * ensure calls to it are protected. */ void disconnectClientProcess() { FileHandle fp = m_exitGuard; m_exitGuard = kBadFileHandle; _closeFile(fp); } /** Tests whether all 'connected' host apps have exited. * * @returns `true` if all connected host apps have exited (naturally or otherwise). Returns * `false` if at least one host app is still running. * * This tests whether all 'connected' host apps have exited. A host app is considered to * be 'connected' if it had called @ref connectClientProcess() that had succeeded. * Once a host app exits, all of its 'connections' to the unique app are automatically * cleaned up by the operating system. * * This is intended to be called from the unique app periodically to determine if it * should exit itself. The expectation is that this would be called once per minute or * so to check whether it should be shut down. When this does succeed, the unique app * should perform any final cleanup tasks then exit itself. * * @thread_safety This call is not thread safe. It is the caller's responsibility to ensure * calls to it are protected. However, since it is meant to operate between * processes, there may still be unavoidable race conditions that could arise. */ bool haveAllClientsExited() { bool success; FileHandle fp; std::string path; path = _getGuardName(kExitLockExtension); fp = _openFile(path.c_str()); // failed to open the guard file (?!?) => fail. if (fp == kBadFileHandle) return false; success = _lockFile(fp, LockType::eExclusive, LockAction::eTest); _closeFile(fp); // the file lock was successfully acquired -> no more clients are 'connected' => delete // the lock file as a final cleanup step. if (success) _deleteFile(path.c_str()); // all the clients have 'disconnected' when we're able to successfully grab an exclusive // lock on the file. This means that all of the clients have exited and the OS has // released their shared locks on the file thus allowing us to grab an exclusive lock. return success; } private: /** Extension of the name for the launch guard locks. */ static constexpr const char* kLaunchLockExtension = ".lock"; /** Extension of the name for the exit guard locks. */ static constexpr const char* kExitLockExtension = ".exit"; /** Default prefix for the lock guards. */ static constexpr const char* kDefaultNamePrefix = "nvidia-unique-app"; #if OMNI_PLATFORM_WINDOWS using FileHandle = HANDLE; static constexpr FileHandle kBadFileHandle = CARBWIN_INVALID_HANDLE_VALUE; #else /** Platform specific type for a file handle. */ using FileHandle = int; /** Platform specific value for a failed file open operation. */ static constexpr FileHandle kBadFileHandle = -1; #endif /** Names for the type of lock to apply or test. */ enum class LockType { /** A shared (read) lock. Multiple shared locks may succeed simultaneously on the same * file. If at least one shared lock exists on a file, it will prevent anything else * from acquiring an exclusive lock on the same file. */ eShared, /** An exclusive (write) lock. Only a single exclusive lock may exist on a file at any * given time. The file must be completely unlocked in order for an exclusive lock to * succeed (unless a process's existing shared lock is being upgraded to an exclusive * lock). If the file has any shared locks on it from another process, an exclusive * lock cannot be acquired. */ eExclusive, }; /** Names for the action to take when locking a file. */ enum class LockAction { eSet, ///< attempt to acquire a lock on the file. eTest, ///< test whether a lock is immediately possible on a file. }; /** Creates the full name of the guard object for a given extension. * * @param[in] extension The extension to use on the guard name. This should either be * @a kLaunchLockExtension or @a kExitLockExtension. * @returns A string representing the full name and path of the guard object to create or * test. */ std::string _getGuardName(const char* extension) const { return m_guardPath + "/" + m_guardName + extension; } /** Opens a guard file for read and write. * * @param[in] filename The name and path of the file to open. This may not be `nullptr` * or an empty string. The file may already exist. If the file * does not exist, it will be created. * @returns A handle to the opened file. This may be passed to _closeFile() or _lockFile() * as needed. When the handle is no longer necessary, it should be closed using * _closeFile(). Returns @a kBadFileHandle if the file could not be opened. */ static FileHandle _openFile(const char* filename) { // make sure the path up to the file exists. Note that this will likely just fail to // open the file below if creating the directories fail. _makeDirectories(filename); #if OMNI_PLATFORM_WINDOWS std::wstring pathW = carb::extras::convertCarboniteToWindowsPath(filename); return CreateFileW(pathW.c_str(), CARBWIN_GENERIC_READ | CARBWIN_GENERIC_WRITE, CARBWIN_FILE_SHARE_READ | CARBWIN_FILE_SHARE_WRITE, nullptr, CARBWIN_OPEN_ALWAYS, 0, nullptr); #else return open(filename, O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP); #endif } /** Closes a guard file opened with _openFile(). * * @param[in] fp The file handle to close. This may be kBadFileHandle. * @returns No return value. */ static void _closeFile(FileHandle fp) { #if OMNI_PLATFORM_WINDOWS CloseHandle(fp); #else close(fp); #endif } /** Deletes a file on the file system. * * @param[in] filename The name and path of the file to delete. This may not be * `nullptr` or an empty string. The file will only be deleted * if all open handles to it have been closed. Depending on the * platform, the file may still exist and be able to be opened * again if an open file handle to it still exists. * @returns No return value. */ static void _deleteFile(const char* filename) { #if OMNI_PLATFORM_WINDOWS std::wstring pathW = carb::extras::convertCarboniteToWindowsPath(filename); DeleteFileW(pathW.c_str()); #else unlink(filename); #endif } /** Attempts to lock a file. * * @param[in] fp The handle to the file to attempt to lock. This must be a valid * file handle returned by a call to _openFile(). This may not be * @a kBadFileHandle. * @param[in] type The type of lock to grab. * @param[in] action Whether to set the lock or test it. Setting the lock will grab * a new lock reference to the file. Testing it will just check if * the requested type of lock can be immediately grabbed without * changing the file's lock state. * @returns `true` if the lock is successfully acquired in 'set' mode or if the lock is * immediately available to be acquired in 'test' mode. Returns `false` if the * lock could not be acquired in 'set' mode or if the lock was not immediately * available to be acquired in 'test' mode. Also returns `false` if an error * occurred. */ static bool _lockFile(FileHandle fp, LockType type, LockAction action = LockAction::eSet) { #if OMNI_PLATFORM_WINDOWS BOOL success; CARBWIN_OVERLAPPED ov = {}; DWORD flags = CARBWIN_LOCKFILE_FAIL_IMMEDIATELY; if (type == LockType::eExclusive) flags |= CARBWIN_LOCKFILE_EXCLUSIVE_LOCK; success = LockFileEx(fp, flags, 0, 1, 0, reinterpret_cast<LPOVERLAPPED>(&ov)); if (action == LockAction::eTest) UnlockFileEx(fp, 0, 1, 0, reinterpret_cast<LPOVERLAPPED>(&ov)); return success; #else int result; struct flock fl; fl.l_type = (type == LockType::eExclusive ? F_WRLCK : F_RDLCK); fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 1; fl.l_pid = 0; result = fcntl(fp, (action == LockAction::eTest ? F_GETLK : F_SETLK), &fl); if (result != 0) return false; if (action == LockAction::eTest) return fl.l_type == F_UNLCK; return true; #endif } /** Creates all the directories leading up to a path. * * @param[in] path The full path to create all the directories for. This may be an absolute * or relative path. If the path ends in a path separator all paths up to * and including the last component will be created. Otherwise the last * component will be assumed to be a filename and be ignored. This may not * be `nullptr`. * @returns `true` if all the directories on the given path either already existed or were * successfully created. Returns `false` otherwise. */ static bool _makeDirectories(const std::string& path) { size_t start = 0; #if CARB_PLATFORM_WINDOWS constexpr const char* separators = "\\/"; if (path.size() > 3 && (path[1] == ':' || path[0] == '/' || path[0] == '\\')) start = 3; #elif CARB_POSIX constexpr const char* separators = "/"; if (path.size() > 1 && path[0] == '/') start = 1; #else CARB_UNSUPPORTED_PLATFORM(); #endif for (;;) { size_t pos = path.find_first_of(separators, start); std::string next; if (pos == std::string::npos) break; next = path.substr(0, pos); start = pos + 1; #if CARB_PLATFORM_WINDOWS std::wstring pathW = carb::extras::convertCarboniteToWindowsPath(next); DWORD attr = GetFileAttributesW(pathW.c_str()); if (attr != CARBWIN_INVALID_FILE_ATTRIBUTES) { // already a directory -> nothing to do => skip it. if ((attr & CARBWIN_FILE_ATTRIBUTE_DIRECTORY) != 0) continue; // exists but not a directory -> cannot continue => fail. else return false; } // failed to create the directory -> cannot continue => fail. if (!CreateDirectoryW(pathW.c_str(), nullptr)) return false; #elif CARB_POSIX struct stat st; if (stat(next.c_str(), &st) == 0) { // already a directory -> nothing to do => skip it. if (S_ISDIR(st.st_mode)) continue; // exists but not a directory -> cannot continue => fail. else return false; } // failed to create the directory -> cannot continue => fail. if (mkdir(next.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0) return false; #else CARB_UNSUPPORTED_PLATFORM(); #endif } return true; } /** The path to use to store the guard files. This may either be a relative or absolute * path and will most often be specified by the caller. This defaults to the current * directory. */ std::string m_guardPath = "."; /** The name to use for the guard files. This should be unique to the app being launched. * There is no formatting or syntax requirement for this aside from being valid on the * file system for the calling platform. This defaults to @a kDefaultNamePrefix. */ std::string m_guardName = kDefaultNamePrefix; /** The last created launch guard object. This is used to prevent multiple launch guard * objects from being created from this object for a single unique app process. */ FileHandle m_launchGuard = kBadFileHandle; /** The last created exit guard object. This is used to prevent multiple 'connections' * to the unique app from being created from this object for a single host app process. */ FileHandle m_exitGuard = kBadFileHandle; }; } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/Version.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 Version utilities #pragma once #include "StringHelpers.h" #include "../../carb/RString.h" #include <string> namespace omni { namespace extras { /** * Version struct, follows Semantic Versioning 2.0. https://semver.org/ * @warning This struct is not @rstref{ABI safe <abi-compatibility>} and must not be passed through ABI boundaries. For * an ABI-safe version, see \ref omni::ext::Version. */ struct SemanticVersion { //! The major version, as defined by <a href="https://semver.org">Semantic Versioning</a>. May be negative to match //! any major version. int32_t major{ -1 }; //! The minor version, as defined by <a href="https://semver.org">Semantic Versioning</a>. May be negative to match //! any minor version. int32_t minor{ -1 }; //! The patch version, as defined by <a href="https://semver.org">Semantic Versioning</a>. May be negative to match //! any patch version. int32_t patch{ -1 }; std::string prerelease; //!< A string indicating a pre-release value. May be empty std::string build; //!< A string indicating a build value. May be empty //! Constructor. //! \details Initializes a SemanticVersion with `-1` for all version values and empty pre-release and build values. SemanticVersion() = default; /** * Converts this version to a string. * \details If \ref major, \ref minor and \ref patch are negative, an empty string is returned. Otherwise the string * returned is `<major>.<minor>.<patch>[-<prerelease>][+<build>]`. The `+<build>` section is only included if * \p includeBuildMetadata is `true`. The `-<prerelease>` and `+<build>` sections are only included if the * \ref prerelease and \ref build members (respectively) are not empty. * @param includeBuildMetadata If `true`, the `+<build>` section is included in the returned string * @returns the version string. See above for detailed explanation */ std::string toString(bool includeBuildMetadata = true) const { if (this->major < 0 && this->minor < 0 && this->patch < 0) return ""; else { std::ostringstream ss; if (this->major >= 0 || this->minor >= 0 || this->patch >= 0) ss << this->major << "." << this->minor << "." << this->patch; if (!std::string(this->prerelease).empty()) ss << "-" << this->prerelease; if (includeBuildMetadata && !std::string(this->build).empty()) ss << "+" << this->build; return ss.str(); } } //! Replaces major, minor or patch values with zeros if they are negative. void replaceNegativesWithZeros() noexcept { if (this->major < 0) this->major = 0; if (this->minor < 0) this->minor = 0; if (this->patch < 0) this->patch = 0; } //! Checks if the major, minor and patch values are all zeros. //! @returns `true` if the \ref major, \ref minor and \ref patch values are all zero; `false` otherwise bool isAllZeroes() const noexcept { return this->major == 0 && this->minor == 0 && this->patch == 0; } //! Returns a default-constructed SemanticVersion. //! @returns a default-constructed SemanticVersion static SemanticVersion getDefault() noexcept { return {}; } }; /** * Checks if the given SemanticVersion has negative major, minor and patch values. * @param v A \ref SemanticVersion to test * @returns `true` if @p v has negative major, minor and patch values; `false` otherwise */ inline bool isAnyVersion(const SemanticVersion& v) { return v.major < 0 && v.minor < 0 && v.patch < 0; } /** * Semantic Version pre-release less-than comparator. * @param x A pre-release value from a \ref SemanticVersion * @param y A pre-release value from a \ref SemanticVersion * @returns `true` if \p x should be ordered-before \p y according to rules at https://semver.org/#spec-item-11 */ inline bool prereleaseCmpLess(const char* x, const char* y) { // SemVer prerelease part comparison according to: https://semver.org/#spec-item-11 const size_t xLen = strlen(x); const size_t yLen = strlen(y); // ("" < "") => false if (xLen == 0 && yLen == 0) return false; // ("abc" < "") => true if (yLen == 0) return true; // ("" < "abc") => false if (xLen == 0) return false; const char* xPartFrom = x; const char* yPartFrom = y; while (1) { // Find next '.'. Chunks are: [xPartFrom, xPartTo] and [yPartFrom, yPartTo] const char* xPartTo = strchr(xPartFrom, '.'); xPartTo = xPartTo ? xPartTo : x + xLen; const char* yPartTo = strchr(yPartFrom, '.'); yPartTo = yPartTo ? yPartTo : y + yLen; const size_t xPartLen = xPartTo - xPartFrom; const size_t yPartLen = yPartTo - yPartFrom; // Try to convert to integer until next '.'. char* end; const long xNum = strtol(xPartFrom, &end, 10); const bool xIsNum = (end == xPartTo); const long yNum = strtol(yPartFrom, &end, 10); const bool yIsNum = (end == yPartTo); // "123" < "abc" if (xIsNum && !yIsNum) return true; if (!xIsNum && yIsNum) return false; if (xIsNum && yIsNum) { // numerical comparison if (xNum != yNum) return xNum < yNum; } else { // string comparison until next nearest '.' const int res = strncmp(xPartFrom, yPartFrom, carb_min(xPartLen, yPartLen)); // if different "zzz" < "abc", return: if (res != 0) return res < 0; // they are the same, but one longer? "abc" < "abcdef" if (xPartLen != yPartLen) return xPartLen < yPartLen; } // Go to the next `.` part xPartFrom = xPartTo + 1; yPartFrom = yPartTo + 1; // Reached the end of both? => they are equal if (xPartFrom == x + xLen + 1 && yPartFrom == y + yLen + 1) break; // x ended first? "abc.def" < "abc.def.xyz" if (xPartFrom == x + xLen + 1) return true; // y ended first? if (yPartFrom == y + yLen + 1) return false; } return false; } //! @copydoc prereleaseCmpLess(const char*,const char*) inline bool prereleaseCmpLess(const std::string& x, const std::string& y) { return prereleaseCmpLess(x.c_str(), y.c_str()); } /** * Less-than comparator for two versions. * @tparam VersionT The type of the version struct, typically \ref omni::ext::Version or \ref SemanticVersion. * @param lhs The first version to compare * @param rhs The second version to compare * @returns `true` if \p lhs should be ordered-before \p rhs; `false` otherwise * @see prereleaseCmpLess(const char*,const char*) */ template <class VersionT> inline bool versionsCmpLess(const VersionT& lhs, const VersionT& rhs) { if (lhs.major != rhs.major) return lhs.major < rhs.major; if (lhs.minor != rhs.minor) return lhs.minor < rhs.minor; if (lhs.patch != rhs.patch) return lhs.patch < rhs.patch; return prereleaseCmpLess(lhs.prerelease, rhs.prerelease); } /** * Less-than operator for two semantic versions. * @param lhs The first \ref SemanticVersion to compare * @param rhs The second \ref SemanticVersion to compare * @returns `true` if \p lhs should be ordered-before \p rhs; `false` otherwise * @see prereleaseCmpLess(const char*,const char*), versionsCmpLess() */ inline bool operator<(const SemanticVersion& lhs, const SemanticVersion& rhs) { return versionsCmpLess(lhs, rhs); } /** * Equality operator for two semantic versions. * @param lhs The first \ref SemanticVersion to compare * @param rhs The second \ref SemanticVersion to compare * @returns `true` if \p lhs and \p rhs are equal; `false` otherwise */ inline bool operator==(const SemanticVersion& lhs, const SemanticVersion& rhs) { // Notice that "build metadata" is ignored in version comparison return lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch && lhs.prerelease == rhs.prerelease; } /** * Parses a given string into a semantic version. * @param str The string to parse into a semantic version, as described by \ref SemanticVersion::toString() * @param outVersion A reference that will receive the semantic version. If `false` is returned, this reference will be * in an indeterminate state. * @returns `true` if parsing succeeded and \p outVersion has received the parsed semantic version; `false` if parsing * failed and \p outVersion is in an indeterminate state and should not be used */ inline bool stringToVersion(const std::string& str, SemanticVersion& outVersion) { outVersion = SemanticVersion::getDefault(); // [major].[minor].[patch]-[prerelease]+[build] auto versionAndBuild = extras::split(str, '+'); // Only one `+` allowed in semver if (versionAndBuild.size() > 2) return false; auto versionParts = extras::split(versionAndBuild[0], '-', 2); // parse first part: [major].[minor].[patch] { auto parts = extras::split(versionParts[0], '.'); if (parts.empty()) return false; // 1.2.3.4 is not semver if (parts.size() > 3) return false; if (!extras::stringToInteger(parts[0], outVersion.major)) return false; if (parts.size() > 1) { if (!extras::stringToInteger(parts[1], outVersion.minor)) return false; } if (parts.size() > 2) { if (!extras::stringToInteger(parts[2], outVersion.patch)) return false; } } // parse second part: [prerelease]+[build] if (versionParts.size() > 1) outVersion.prerelease = versionParts[1]; if (versionAndBuild.size() > 1) outVersion.build = versionAndBuild[1]; return true; } /** * Parses a string to a semantic version, or a default value if parsing fails. * @param str The string to parse * @returns a \ref SemanticVersion parsed from \p str, or \ref SemanticVersion::getDefault() if parsing fails */ inline SemanticVersion stringToVersionOrDefault(const std::string& str) { SemanticVersion v; if (!stringToVersion(str, v)) v = SemanticVersion::getDefault(); return v; } /** * Attempts to parse the Git hash from an Omniverse-specific semantic version. * \details An Omniverse Flow version format is `<version>+<gitbranch>.<number>.<githash>.<build_location>`. This * function parses out the `<githash>` from this format. * @param version The \ref SemanticVersion to process * @param outHash A reference that receives the Git hash if `true` is returned; if `false` is returned this will be * `00000000`. * @returns `true` if parsing succeeded; `false` otherwise */ inline bool gitHashFromOmniverseVersion(const extras::SemanticVersion& version, std::string& outHash) { // Omniverse Flow format: "{version}+{gitbranch}.{number}.{githash}.{build_location}" auto parts = extras::split(version.build, '.'); outHash = "00000000"; if (parts.size() > 2) { outHash = parts[2]; return true; } return false; } } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/md5.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 MD5 hash utils #pragma once // This file seems like it was copied from somewhere without attribution. // TODO: It should be refactored or reimplemented with our coding guidelines #ifndef DOXYGEN_BUILD # include "../../carb/Defines.h" // Can't undo this at the end of this file when doing static compilation, the compiler complains CARB_IGNOREWARNING_MSC(4307) // 'operator' : integral constant overflow namespace MD5 { //! Integer portions of sines of integers, in radians. constexpr uint32_t K[64] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; //! Per-round bit shift amounts. constexpr uint32_t S[64] = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 }; //! Struct representing an MD5 digest. struct digest { //! MD5 digest bytes uint8_t u8[16]; }; //! String size of an MD5 digest (not including NUL terminator). constexpr size_t kDigestStringSize = sizeof(digest) * 2; struct DigestString { //! String of length \ref kDigestStringSize //! @warning this is **not** NUL terminated! char s[kDigestStringSize]; }; struct Data { uint32_t A0 = 0x67452301; uint32_t B0 = 0xefcdab89; uint32_t C0 = 0x98badcfe; uint32_t D0 = 0x10325476; static constexpr uint32_t kBlocksize = 64; uint8_t buffer[kBlocksize] = {}; }; constexpr uint32_t rotate_left(uint32_t x, int n) { return (x << n) | (x >> (32 - n)); } constexpr uint32_t packUint32(const uint8_t block[Data::kBlocksize], uint32_t index) { uint32_t u32 = 0; for (uint32_t i = 0; i < 4; i++) { u32 |= uint32_t(block[index + i]) << (8 * i); } return u32; } constexpr void processBlock(Data& data, const uint8_t block[Data::kBlocksize]) { uint32_t A = data.A0; uint32_t B = data.B0; uint32_t C = data.C0; uint32_t D = data.D0; for (uint32_t i = 0; i < 64; i++) { uint32_t F = 0; uint32_t g = 0; switch (i / 16) { case 0: F = (B & C) | ((~B) & D); g = i; break; case 1: F = (D & B) | ((~D) & C); g = (5 * i + 1) % 16; break; case 2: F = B ^ C ^ D; g = (3 * i + 5) % 16; break; case 3: F = C ^ (B | (~D)); g = (7 * i) % 16; break; } // constexpr won't allow us to do pointer cast uint32_t Mg = packUint32(block, g * 4); F = F + A + K[i] + Mg; A = D; D = C; C = B; B = B + rotate_left(F, S[i]); } data.A0 += A; data.B0 += B; data.C0 += C; data.D0 += D; } constexpr void memcopyConst(uint8_t dst[], const uint8_t src[], size_t count) { for (size_t i = 0; i < count; i++) dst[i] = src[i]; } template <typename T> constexpr void unpackUint(uint8_t dst[], T u) { for (uint32_t i = 0; i < sizeof(T); i++) dst[i] = 0xff & (u >> (i * 8)); } constexpr void processLastBlock(Data& data, const uint8_t str[], size_t strLen, size_t blockIndex) { auto lastChunkSize = strLen % Data::kBlocksize; lastChunkSize = (!lastChunkSize && strLen) ? Data::kBlocksize : lastChunkSize; // We need at least 9 available bytes - 1 for 0x80 and 8 bytes for the length bool needExtraBlock = (Data::kBlocksize - lastChunkSize) < (sizeof(size_t) + 1); bool lastBitInExtraBlock = (lastChunkSize == Data::kBlocksize); { uint8_t msg[Data::kBlocksize]{}; memcopyConst(msg, &str[blockIndex * Data::kBlocksize], lastChunkSize); if (!lastBitInExtraBlock) msg[lastChunkSize] = 0x80; if (!needExtraBlock) unpackUint(&msg[Data::kBlocksize - 8], strLen * 8); processBlock(data, msg); } if (needExtraBlock) { uint8_t msg[Data::kBlocksize]{}; if (lastBitInExtraBlock) msg[0] = 0x80; unpackUint(&msg[Data::kBlocksize - 8], strLen * 8); processBlock(data, msg); } } constexpr digest createDigest(Data& data) { digest u128 = {}; unpackUint(&u128.u8[0], data.A0); unpackUint(&u128.u8[4], data.B0); unpackUint(&u128.u8[8], data.C0); unpackUint(&u128.u8[12], data.D0); return u128; } constexpr digest run(const uint8_t src[], size_t count) { Data data; // Compute the number of blocks we need to process. We may need to add a block for padding size_t blockCount = 1; if (count) { blockCount = (count + Data::kBlocksize - 1) / Data::kBlocksize; for (size_t i = 0; i < blockCount - 1; i++) processBlock(data, &src[i * Data::kBlocksize]); } processLastBlock(data, src, count, blockCount - 1); return createDigest(data); } template <size_t lengthWithNull> constexpr static inline digest run(const char (&str)[lengthWithNull]) { // Can't do pointer cast at compile time, need to create a copy uint8_t unsignedStr[lengthWithNull] = {}; for (size_t i = 0; i < lengthWithNull; i++) unsignedStr[i] = (uint8_t)str[i]; constexpr size_t length = lengthWithNull - 1; return run(unsignedStr, length); } // TODO: Move the rest of the MD5 implementation details into the detail namespace in a non-functional change. namespace detail { constexpr static inline char nibbleToHex(uint8_t n) { n &= 0xf; const char base = n < 10 ? '0' : ('a' - 10); return base + n; } } // namespace detail constexpr static inline DigestString getDigestString(const MD5::digest& d) { DigestString s = {}; for (uint32_t i = 0; i < carb::countOf(d.u8); i++) { const uint32_t offset = i * 2; s.s[offset + 0] = detail::nibbleToHex(d.u8[i] >> 4); s.s[offset + 1] = detail::nibbleToHex(d.u8[i]); } return s; } } // namespace MD5 #endif
omniverse-code/kit/include/omni/extras/OutArrayUtils.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 templated helper functions to fill an arbitrary array of values. //! #pragma once #include "../core/IObject.h" // for omni::core::Result #include <type_traits> #include <vector> namespace omni { //! common namespace for extra helper functions and classes. namespace extras { //! Fills the array given by outArray by calling fillFn. //! //! fillFn's signature is void(T* outArray, uint32_t outArrayCount). //! //! If outArrayCount is `nullptr`, kResultInvalidArgument is returned. //! //! If outArray is `nullptr`, *outArrayCount is populated with requiredAccount. //! //! If *outArrayCount is less than requiredCount, kResultInsufficientBuffer is returned. //! //! If the checks above pass, outArray is filled by the given function. *outArrayCount is updated to requiredCount. template <typename T, typename Callable, typename SizeType> omni::core::Result fillOutArray(T* outArray, SizeType* outArrayCount, SizeType requiredCount, Callable&& fillFn) { static_assert(std::is_unsigned<SizeType>::value, "SizeType must be an unsigned integer type!"); if (!outArrayCount) { return omni::core::kResultInvalidArgument; } if (!outArray) { *outArrayCount = requiredCount; return omni::core::kResultSuccess; } if (*outArrayCount < requiredCount) { *outArrayCount = requiredCount; return omni::core::kResultInsufficientBuffer; } *outArrayCount = requiredCount; fillFn(outArray, requiredCount); return omni::core::kResultSuccess; } //! Retrieves an array of unknown size using @p getFn and passes it to @p fillFn. //! //! This utility is useful for transferring a raw array from the ABI to a modern C++ container. //! //! In order to avoid heap access, @p stackCount can be used to try to transfer the array from @p getFn to @p fillFn //! using temporary stack storage. @p stackCount is the number of T's that should be temporarily allocated on the //! stack. If //! @p stackCount is inadequate, this function falls back to using the heap. Care should be taken to not set @p //! stackCount to a value that would cause a stack overflow. //! //! The source array may be dynamically growing in another thread, in which case this method will try @p maxRetryCount //! times to allocate an array of the proper size and retrieve the values. If this method exceeds the retry count, //! @ref omni::core::kResultTryAgain is returned. //! //! @retval omni::core::kResultSuccess on success, an appropriate error code otherwise. template <typename T, typename GetCallable, typename FillCallable> omni::core::Result getOutArray(GetCallable&& getFn, FillCallable&& fillFn, uint32_t stackCount = (4096 / sizeof(T)), uint32_t maxRetryCount = (UINT32_MAX - 1)) { // constructors won't run when we call alloca, make sure the type doesn't need a constructor to run. static_assert(std::is_trivially_default_constructible<T>::value, "T must be trivially default constructible"); T* stack = CARB_STACK_ALLOC(T, stackCount); std::vector<T> heap; T* buffer = stack; uint32_t count = stackCount; omni::core::Result result = getFn(buffer, &count); uint32_t retryCount = maxRetryCount + 1; while (--retryCount) { switch (result) { case omni::core::kResultSuccess: if (buffer) { fillFn(buffer, count); return omni::core::kResultSuccess; } CARB_FALLTHROUGH; // (alloca returned nullptr, count is now correct and we should alloc on heap) case omni::core::kResultInsufficientBuffer: heap.resize(count); buffer = heap.data(); result = getFn(buffer, &count); break; default: return result; } } return omni::core::kResultTryAgain; } } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/ForceLink.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 Provides functionality to force a symbol to be linked to a module * instead of the optimizer potentially removing it out. */ #pragma once #include "../core/Platform.h" #if OMNI_PLATFORM_WINDOWS // see below for why we unfortunately either need this or to forward declare SetLastError() // directly here instead of using something like strerror_s() on Windows. # include "../../carb/CarbWindows.h" #endif namespace omni { /** common namespace for extra helper functions and classes. */ namespace extras { /** Helper class to force the linking of a C++ symbol. This is done by having the symbol's * address be passed to a function in another module. Since, at link time, the linker * doesn't know what the other module's function will do with the symbol, it can't discard * the symbol. This is useful for ensuring that debug-only or initializer-only symbols * do not get unintentionally eliminated from the module they are present in. * * Note that since this does not have any data members, it shouldn't occupy any space in the * module's data section. It will however generate a C++ static initializer and shutdown * destructor. * * This class should not be used directly, but instead through the @ref OMNI_FORCE_SYMBOL_LINK * macro. */ class ForceSymbolLink { public: /** Constructor: passes an argument's value to a system library. * * @param[in] ptr The address to pass on to a system library call. This prevents the * linker from being able to discard the symbol as unused or unreferenced. * This value is not accessed as a pointer in any way so any value is * acceptable. * @returns No return value. */ ForceSymbolLink(void* ptr) { #if OMNI_PLATFORM_WINDOWS // On Windows, we unfortunately can't call into something like strerror_s() to // accomplish this task because the CRT is statically linked to the module that // will be using this. That would make the function we're passing the symbol // to local and therefore the symbol will still be discardable. Instead, we'll // pass the address to SetLastError() which will always be available from 'kernel32'. SetLastError(static_cast<DWORD>(reinterpret_cast<uintptr_t>(ptr))); #else char* str; CARB_UNUSED(str); str = strerror(static_cast<int>(reinterpret_cast<uintptr_t>(ptr))); #endif } }; } // namespace extras } // namespace omni /** Helper to force a symbol to be linked. * * @param[in] symbol_ The symbol that must be linked to the calling module. This must be a * valid symbol name including any required namespaces given the calling * location. * @param[in] tag_ A single token name to give to the symbol that forces the linking. * This is used purely for debugging purposes to give an identifiable name * to the symbol that is used to force linking of @p symbol_. This must * be a valid C++ single token name (ie: only contains [A-Za-z0-9_] and * must not start with a number). * @returns No return value. * * @remarks This is used to ensure an unused symbol is linked into a module. This is done * by tricking the linker into thinking the symbol is not discardable because its * address is being passed to a function in another module. This is useful for * example to ensure symbols that are meant purely for debugger use are not discarded * from the module. Similarly, it can be used on symbols that are only meant to * anchor C++ object initializers but are unreferenced otherwise. */ #define OMNI_FORCE_SYMBOL_LINK(symbol_, tag_) \ static omni::extras::ForceSymbolLink CARB_JOIN( \ g_forceLink##tag_##_, CARB_JOIN(CARB_JOIN(__COUNTER__, _), __LINE__))(&(symbol_))
omniverse-code/kit/include/omni/extras/PrivacySettings.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 Helper class to retrieve the current privacy settings state. */ #pragma once #include "../../carb/InterfaceUtils.h" #include "../../carb/settings/ISettings.h" #include "../../carb/extras/StringSafe.h" namespace omni { /** common namespace for extra helper functions and classes. */ namespace extras { /** Consent level names. These consent levels control which types of structured log events * produced by an app will be sent to telemetry servers for analysis. Each consent * level will default to `false` before the privacy settings have been loaded. */ enum class ConsentLevel { /** Privacy consent level that corresponds to the @ref PrivacySettings::kPerformanceKey * setting name. This consent level controls whether events such as hardware information, * app performance statistics, resource usage levels, or crash reports will be sent to * telemetry servers for analysis. */ ePerformance, /** Privacy consent level that corresponds to the @ref PrivacySettings::kPersonalizationKey * setting name. This consent level controls whether events such as user app settings, * window layouts, search keywords, etc will be sent to telemetry servers for analysis. */ ePersonalization, /** Privacy consent level that corresponds to the @ref PrivacySettings::kUsageKey setting * name. This consent level controls whether events such as user activity, app feature * usage, extension usage, etc will be sent to the telemetry servers for analysis. */ eUsage, /** The total number of available consent levels. This is not a valid consent level to * query and will always return `false`. */ eCount, }; /** Static helper class to provide standardized access to the telemetry privacy setting values. * These settings provide information such as the active user ID and the consent permissions * for the various event types. These settings are expected to already have been loaded into * the settings registry (accessible through ISettings). This just provides simple access * to the settings values but does not provide functionality for loading the settings in the * first place or providing a wrapper for change subscriptions on those settings. * * Loading the settings is left up to the `omni.structuredlog.plugin` module. This module will * manage loading the settings when it initializes. It will also refresh the settings any * time the original settings file for them changes. This file is located at * `$HOME_PATH/.nvidia-omniverse/config/privacy.toml` (where `$HOME_PATH` is the user's home * directory on the local system). * * This helper class does not directly handle change subscriptions to the various privacy * settings. This is done to avoid complication and potential issues during shutdown * of global objects. It does however expose the paths of the various privacy settings * so that external callers can subscribe for and manage their own change notifications. * * @note The methods in this helper class are just as thread safe as the ISettings interface * itself is when retrieving a value. All methods are static so there is no state * data that could be clobbered by multiple threads in this object itself. * * @note The Carbonite framework must be initialized before using this helper class. A * crash will occur if the framework is not initialized first. */ class PrivacySettings { public: /** @addtogroup keySettings Privacy Settings Keys * * Paths for the various expected privacy settings. These can be used to manually * access the settings values or to subscribe for change notifications on either * each individual setting or the entire privacy settings tree. * @{ */ /** The settings key path for the version of the privacy settings file. */ static constexpr const char* kVersionKey = "/privacy/version"; /** The settings key path for the 'performance' consent level. */ static constexpr const char* kPerformanceKey = "/privacy/performance"; /** The settings key path for the 'personalization' consent level. */ static constexpr const char* kPersonalizationKey = "/privacy/personalization"; /** The settings key path for the 'usage' consent level. */ static constexpr const char* kUsageKey = "/privacy/usage"; /** The settings key path for the current user ID name. */ static constexpr const char* kUserIdKey = "/privacy/userId"; /** The settings key path for the current user's email address. This is not * expected to be present for all users. */ static constexpr const char* kEmailKey = "/privacy/email"; /** The settings key path for the 'external build' flag. */ static constexpr const char* kExternalBuildKey = "/privacy/externalBuild"; /** The settings key path for the 'send extra diagnostic data' flag. */ static constexpr const char* kExtraDiagnosticDataOptInKey = "/privacy/extraDiagnosticDataOptIn"; /** The settings key path for the identity provider's name. */ static constexpr const char* kIdpNameKey = "/privacy/idpName"; /** The settings key path for the identity provider's identifier. */ static constexpr const char* kIdpIdKey = "/privacy/idpId"; /** The settings key path for all of the privacy settings tree. */ static constexpr const char* kSettingTree = "/privacy"; /** @} */ /** Retrieves the version setting found in the privacy config. * * @returns A string containing the version information value for the privacy settings * file. This version gives an indication of what other values might be * expected in the file. * * @thread_safety This call is thread safe. */ static const char* getVersion() { return _getSettingStringValue(kVersionKey, "1.0"); } /** Retrieves the user ID found in the privacy config. * * @returns A string containing the user ID that is currently logged into omniverse. * This is the user ID that should be used when writing out any structured * log events or sending crash reports. This does not necessarily reflect the * user ID that will be used to login to a Nucleus server instance however. * @returns An empty string if no user ID setting is currently present. * * @thread_safety This call is thread safe. */ static const char* getUserId() { return _getSettingStringValue(kUserIdKey, ""); } /** Retrieves the user email address if specified in the privacy config. * * @returns A string containing the currently logged in user's email address. This * is only expected to be present for some users. This email address will * not be emitted with any structured log events. * @returns An empty string if no user email address is currently present. * * @thread_safety This call is thread safe. */ static const char* getEmail() { return _getSettingStringValue(kEmailKey, ""); } /** Retrieves the identity provider's name if specified in the privacy config. * * @retval A string containing the name of the identity provider that was used to * authenticate the current user. This name is optional. * @retval An empty string if no identity provider name is currently present. * * @thread_safety This call is thread safe. */ static const char* getIdpName() { return _getSettingStringValue(kIdpNameKey, ""); } /** Retrieves the identity provider's identifier if specified in the privacy config. * * @retval A string containing the identifier of the identity provider that was used to * authenticate the current user. This identifier is optional. * @retval An empty string if no identity provider identifier is currently present. * * @thread_safety This call is thread safe. */ static const char* getIdpId() { return _getSettingStringValue(kIdpIdKey, ""); } /** Retrieves the consent state for a requested consent level. * * @param[in] level The consent level to query. * @returns The current state of the requested consent level if present. * @returns `false` if the state of the requested consent level could not be successfully * queried. * * @thread_safety This call is thread safe. */ static bool getConsentLevel(ConsentLevel level) { static const char* map[] = { kPerformanceKey, kPersonalizationKey, kUsageKey }; if (((size_t)level) >= ((size_t)ConsentLevel::eCount)) return false; return _getSettingBoolValue(map[(size_t)level], false); } /** Checks whether the user has opted into sending diagnostic data. * * @returns `true` if the user has opted into sending diagnostic data. * @returns `false` if the user has opted out of sending diagnostic data. */ static bool canSendExtraDiagnosticData() { const char* optIn = _getSettingStringValue(kExtraDiagnosticDataOptInKey, ""); return carb::extras::compareStringsNoCase(optIn, "externalBuilds") == 0; } private: /** Attempts to retrieve the ISettings interface. * * @returns The ISettings interface object if loaded and successfully acquired. * @returns `nullptr` if the ISettings interface object could not be acquired or has not * already been loaded. * * @note This does not attempt to load the ISettings plugin itself. It is assumed that * an external caller will have already loaded the appropriate module before calling * into here. However, if acquiring the interface object does fail, all calls that * use it will still gracefully fail. * * @thread_safety This call is thread safe. */ static carb::settings::ISettings* _getSettingsInterface() { return carb::getCachedInterface<carb::settings::ISettings>(); } /** Attempts to retrieve a setting as a string value. * * @param[in] name The name of the setting to retrieve the value for. This may * not be `nullptr`. * @param[in] defaultValue The default value to return in case the setting cannot be * returned for any reason. This value is not interpreted or * accessed in any way except to return it to the caller in * failure cases. * @returns The value of the requested setting if it is present and accessible as a string. * @returns The @p defaultValue parameter if the ISettings interface object could not be * acquired or is not loaded. * @returns The @p defaultValue parameter if the requested setting is not accessible as a * string value. * * @thread_safety This call is thread safe. */ static const char* _getSettingStringValue(const char* name, const char* defaultValue) { carb::settings::ISettings* settings = _getSettingsInterface(); const char* value; if (settings == nullptr || name == nullptr) return defaultValue; value = settings->getStringBuffer(name); if (value == nullptr) return defaultValue; return value; } /** Attempts to retrieve a setting as a boolean value. * * @param[in] name The name of the setting to retrieve the value for. This may * not be `nullptr`. * @param[in] defaultValue The default value to return in case the setting cannot be * returned for any reason. This value is not interpreted or * accessed in any way except to return it to the caller in * failure cases. * @returns The value of the requested setting if it is present and accessible as a boolean. * @returns The @p defaultValue parameter if the ISettings interface object could not be * acquired or is not loaded. * @returns The @p defaultValue parameter if the requested setting is not accessible as a * string value. * * @thread_safety This call is thread safe. */ static bool _getSettingBoolValue(const char* name, bool defaultValue) { carb::settings::ISettings* settings = _getSettingsInterface(); if (settings == nullptr || !settings->isAccessibleAs(carb::dictionary::ItemType::eBool, name)) return defaultValue; return settings->getAsBool(name); } }; } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/OmniConfig.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 "../../carb/Defines.h" #include "../../carb/filesystem/IFileSystem.h" #include "../../carb/dictionary/IDictionary.h" #include "../../carb/dictionary/ISerializer.h" #include "../../carb/extras/Utf8Parser.h" #include "../../carb/extras/Path.h" #include "../../carb/extras/EnvironmentVariable.h" #include "ScratchBuffer.h" #if CARB_POSIX # include <unistd.h> # include <pwd.h> #elif CARB_PLATFORM_WINDOWS # include "../../carb/CarbWindows.h" #else CARB_UNSUPPORTED_PLATFORM(); #endif namespace omni { namespace extras { /** Retrieve the path to the home directory. * @retval The path to the home directory. * @retval Empty path on failure. * @remarks This retrieves the path to `$HOME` on POSIX platforms and `%USEPROFILE%` on Windows. * If those are unset, this uses system calls as a fallback. */ inline carb::extras::Path getHomePath() { #if CARB_POSIX constexpr const char* homeVar = "HOME"; #elif CARB_PLATFORM_WINDOWS constexpr const char* homeVar = "USERPROFILE"; #else CARB_UNSUPPORTED_PLATFORM(); #endif // POSIX and Windows both have an envvar for this std::string home; if (carb::extras::EnvironmentVariable::getValue(homeVar, home) && !home.empty()) { return home; } #if CARB_POSIX // omni-config-cpp had code to handle cases where $HOME was unset, so that remains here. struct passwd info; struct passwd* out = nullptr; omni::extras::ScratchBuffer<char, 4096> buffer; const long len = sysconf(_SC_GETPW_R_SIZE_MAX); if (len == -1) { return {}; // sysconf() failed } if (!buffer.resize(len)) { return {}; } const int result = CARB_RETRY_EINTR(getpwuid_r(getuid(), &info, buffer.data(), len, &out)); if (result != 0 || out != &info) { return {}; } return info.pw_dir; #elif CARB_PLATFORM_WINDOWS omni::extras::ScratchBuffer<wchar_t, 2048> buffer; void* token = nullptr; unsigned long len = 0; if (!OpenProcessToken(GetCurrentProcess(), CARBWIN_TOKEN_QUERY, &token)) { return {}; } CARB_SCOPE_EXIT { CloseHandle(token); }; GetUserProfileDirectoryW(token, nullptr, &len); if (len == 0) { return {}; } if (!buffer.resize(len)) { return {}; } if (!GetUserProfileDirectoryW(token, buffer.data(), &len)) { return {}; } const size_t offset = (wcsncmp(buffer.data(), L"\\\\?\\", 4) == 0) ? 4 : 0; return carb::extras::convertWideStringToUtf8(buffer.data() + offset); #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** This collects information about standard paths for Omniverse applications, such as the config * directory, the logs directory, etc. * This is designed to be a replacement of the omniverse::GlobalConfig class from omni-config-cpp. * This class is designed for serialized access. * This does not require the carb framework to be initialized, but omniverse.toml will not be * loaded without the carb framework. */ class OmniConfig { public: OmniConfig(const char* configFileName = "omniverse.toml") { carb::extras::Path base; m_configFileName = configFileName; m_homePath = omni::extras::getHomePath(); if (!m_homePath.empty()) { base = m_homePath.join(".nvidia-omniverse"); } // config directory std::string omniConfigPath; if (carb::extras::EnvironmentVariable::getValue("OMNI_CONFIG_PATH", omniConfigPath) && !omniConfigPath.empty()) { m_baseConfigPath = omniConfigPath; } else if (!base.empty()) { m_baseConfigPath = base.join("config"); } // log directory if (!base.empty()) { m_baseLogsPath = base.join("logs"); } // data, library and cache directories // OVCC-1272: This is not a POSIX operation but omni-config-cpp just assumed all non-windows // was Linux, leading to this split. #if CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS const carb::extras::Path xdgData = _getXdgDataDir(m_homePath); if (!xdgData.empty()) { m_baseDataPath = xdgData.join("ov").join("data"); m_baseLibraryPath = xdgData.join("ov").join("pkg"); } const carb::extras::Path xdgCache = _getXdgCacheDir(m_homePath); if (!xdgCache.empty()) { m_baseCachePath = xdgCache.join("ov"); } #elif CARB_PLATFORM_WINDOWS // OVCC-1271: More robust to use SHGetKnownFolder here (FOLDERID_LocalAppData) std::string localAppDataStr; if (carb::extras::EnvironmentVariable::getValue("LOCALAPPDATA", localAppDataStr) && !localAppDataStr.empty()) { const auto localAppDataOv = carb::extras::Path(localAppDataStr).join("ov"); m_baseDataPath = localAppDataOv.join("data"); m_baseLibraryPath = localAppDataOv.join("pkg"); m_baseCachePath = localAppDataOv.join("cache"); } #else CARB_UNSUPPORTED_PLATFORM(); #endif // Load setting overrides from the config file specified. // This function uses Carbonite to load these. _loadSettingOverrides(); } ~OmniConfig() { if (m_omniverseToml != nullptr) { m_dictionary->destroyItem(m_omniverseToml); } } /** Retrieves the directory to the path to the $HOME directory (%USERPROFILE% on Windows). * @retval The $HOME directory. * @retval Empty path on failure. */ inline carb::extras::Path getHomePath() { return m_homePath; } /** Retrieves the directory to the path where Omniverse config files are stored. * @retval The config directory. * @retval Empty path on failure. * @note This can be overridden with the `$OMNI_CONFIG_PATH` environment variable. */ inline carb::extras::Path getBaseConfigPath() { return m_baseConfigPath; } /** Retrieves the directory to the path where Omniverse log files are stored. * @retval The logs directory. * @retval Empty path on failure. */ inline carb::extras::Path getBaseLogsPath() { return m_baseLogsPath; } /** Retrieves the directory to the path where Omniverse data files are stored. * @retval The data directory. * @retval Empty path on failure. * @note This returns a non-standard path on Mac OS. * This is a bug that was inherited from omni-config-cpp. * This will be fixed in a later version, so this should be considered unstable on Mac OS. */ inline carb::extras::Path getBaseDataPath() { return m_baseDataPath; } /** Retrieves the directory to the path where Omniverse library files are stored. * @retval The library directory. * @retval Empty path on failure. * @note This returns a non-standard path on Mac OS. * This is a bug that was inherited from omni-config-cpp. * This will be fixed in a later version, so this should be considered unstable on Mac OS. */ inline carb::extras::Path getBaseLibraryPath() { return m_baseLibraryPath; } /** Retrieves the directory to the path where Omniverse cache files are stored. * @retval The data directory. * @retval Empty path on failure. * @note This returns a non-standard path on Mac OS. * This is a bug that was inherited from omni-config-cpp. * This will be fixed in a later version, so this should be considered unstable on Mac OS. */ inline carb::extras::Path getBaseCachePath() { return m_baseCachePath; } /** Retrieves the omniverse.toml dictionary. * @retval The omniverse.toml dictionary contents. * This is valid until the class instance is destroyed. * @retval nullptr if omniverse.toml couldn't be loaded (e.g. the file doesn't exist, the carb * framework isn't loaded). * @remarks This is the dictionary that provides overrides for default paths. * You may want to retrieve this for additional information from omniverse.toml (e.g. * kit-kernel retrieves paths.documents_root). * @note omniverse.toml is loaded when the class is constructed. */ inline carb::dictionary::Item* getOmniverseToml() { return m_omniverseToml; } /** Helper to retrieve config strings from omniverse.toml. * @param path The path to the element in the config. * Path separators are `/`, so if you wanted `{ paths: { documents_root: "..." } }`, * you would pass `"paths/documents_root"`. * @retval The string from @p path in omniverse.toml, if it exists and was a string. * @retval Empty string if the requested item was not as string, the requested path did not * exist, omniverse.toml did not exist or the carb framework was not loaded. */ std::string getConfigEntry(const char* path) { if (m_omniverseToml == nullptr) { return {}; } const carb::dictionary::Item* item = m_dictionary->getItem(m_omniverseToml, path); if (item == nullptr) { return {}; } return m_dictionary->getStringBuffer(item); } private: #if CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS /** Retrieve the XDG standard data directory. * @param[in] home The user's home directory. * @retval The XDG standard data directory. * @retval Empty string if nothing could be retrieved. */ inline carb::extras::Path _getXdgDataDir(const carb::extras::Path& home) { const char* xdg = getenv("XDG_DATA_HOME"); if (xdg != nullptr && xdg[0] != '\0') { return xdg; } if (home.empty()) { return {}; } return home.join(".local").join("share"); } /** Retrieve the XDG standard cache directory. * @param[in] home The user's home directory. * @retval The XDG standard cache directory. * @retval Empty string if nothing could be retrieved. */ inline carb::extras::Path _getXdgCacheDir(const carb::extras::Path& home) { const char* xdg = getenv("XDG_CACHE_HOME"); if (xdg != nullptr && xdg[0] != '\0') { return xdg; } if (home.empty()) { return {}; } return home.join(".cache"); } #endif /** Load omniverse.toml into m_omniverseToml. */ inline void _loadOmniverseToml() { carb::Framework* framework = carb::getFramework(); if (framework == nullptr) { return; } m_dictionary = framework->tryAcquireInterface<carb::dictionary::IDictionary>(); carb::filesystem::IFileSystem* fs = framework->tryAcquireInterface<carb::filesystem::IFileSystem>(); carb::dictionary::ISerializer* serializer = framework->tryAcquireInterface<carb::dictionary::ISerializer>("carb.dictionary.serializer-toml.plugin"); if (fs == nullptr || m_dictionary == nullptr || serializer == nullptr) { return; } // Load the file contents carb::filesystem::File* f = fs->openFileToRead(m_baseConfigPath.join(m_configFileName).getStringBuffer()); if (f == nullptr) { return; } CARB_SCOPE_EXIT { fs->closeFile(f); }; omni::extras::ScratchBuffer<char, 4096> buffer; size_t size = fs->getFileSize(f); if (!buffer.resize(size + 1)) { return; } size_t read = fs->readFileChunk(f, buffer.data(), size); if (read != size) { return; } buffer.data()[size] = '\0'; // Parse the toml m_omniverseToml = serializer->createDictionaryFromStringBuffer(buffer.data()); } /** Load the setting overrides from the base config path using the Carbonite framework. */ void _loadSettingOverrides() { _loadOmniverseToml(); // this loads m_omniverseToml if (m_omniverseToml == nullptr) { return; } // Load the individual settings const carb::dictionary::Item* libraryRoot = m_dictionary->getItem(m_omniverseToml, "paths/library_root"); if (libraryRoot != nullptr) { m_baseLibraryPath = m_dictionary->getStringBuffer(libraryRoot); } const carb::dictionary::Item* dataRoot = m_dictionary->getItem(m_omniverseToml, "paths/data_root"); if (dataRoot != nullptr) { m_baseDataPath = m_dictionary->getStringBuffer(dataRoot); } const carb::dictionary::Item* cacheRoot = m_dictionary->getItem(m_omniverseToml, "paths/cache_root"); if (cacheRoot != nullptr) { m_baseCachePath = m_dictionary->getStringBuffer(cacheRoot); } const carb::dictionary::Item* logsRoot = m_dictionary->getItem(m_omniverseToml, "paths/logs_root"); if (logsRoot != nullptr) { m_baseLogsPath = m_dictionary->getStringBuffer(logsRoot); } } std::string m_configFileName; carb::extras::Path m_homePath; carb::extras::Path m_baseConfigPath; carb::extras::Path m_baseLogsPath; carb::extras::Path m_baseDataPath; carb::extras::Path m_baseLibraryPath; carb::extras::Path m_baseCachePath; /** The contents of omniverse.toml. * This gets set if _loadOmniverseToml() succeeds. */ carb::dictionary::Item* m_omniverseToml = nullptr; /** A cached dictionary interface. * This gets set if _loadOmniverseToml() succeeds. */ carb::dictionary::IDictionary* m_dictionary = nullptr; }; } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/ScratchBuffer.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 A helper class to provide a resizable scratch buffer. #pragma once #include "../../carb/Defines.h" #include <algorithm> #include <iterator> namespace omni { /** common namespace for extra helper functions and classes. */ namespace extras { /** A templated helper class to provide a simple resizable scratch buffer. The buffer will only * perform a dynamic allocation if the requested size requires it. If only a small size is * needed, a stack buffer will be used instead. The intended usage pattern is to create the * object, set its required size, then write to each item in the array as needed. The buffer * will not be initialized unless the contained type is a class that constructs itself. It * is left up to the caller to initialize the buffer's contents in all other cases. * * The buffer will always occupy enough stack space to hold the larger of 512 bytes worth of * the contained type, or 16 items of the contained type. If the size is set beyond that * limit, a new buffer will be allocated from the heap. There is no tracking of how many * items have been written to the buffer - that is left as an exercise for the caller. * * @thread_safety There are no thread safety protections on this class. This is intended * to be used as a local scratch buffer. If potential concurrent access is * required, it is the caller's responsibility to protect access to this * object. * * @tparam T The data type that will be contained in the scratch buffer. This * can be any primitive, struct, or class type. * @tparam BaseSize_ The number of items of type @p T that can be held in the scratch * buffer's stack array without needing to allocate from the heap. * By default, this is guaranteed to be at least 16 items. * @tparam ShrinkThreshold_ The threshold expressed as a percentage of the buffer's * previous size below which the buffer itself will be shrunken * on a resize operation that makes it smaller. If the new * size of the buffer expressed as a percentage of the old size * is larger than this number, the previous buffer will be * kept instead of allocating and copying a new one. This is * done as a performance optimization for callers that need * to grow and shrink their buffer frequently, but don't * necessarily want to incur the overhead of an allocation * and copy each time. For example, if the threshold is 25% * and the buffer is resized from 20 items to 6, a reallocation * will not occur since the new size is 30% of the previous. * By contrast, if it is resized to 4 items from 20, a reallocation * will occur since the new size is 20% of the previous. By default * the buffer will only grow and never shrink regardless of the * size and number of resize requests. */ #ifdef DOXYGEN_BUILD // Sphinx does not like the computation and reports errors, so special case for documentation. template <typename T, size_t BaseSize_ = 16, size_t ShrinkThreshold_ = 100> #else template <typename T, size_t BaseSize_ = CARB_MAX(512ull / sizeof(T), 16ull), size_t ShrinkThreshold_ = 100> #endif class ScratchBuffer { public: /** The data type contained in this scratch buffer. This can be any primitive, struct, * or class type. This is present here so that external callers can inspect the contained * type if needed. */ using DataType = T; /** The guaranteed base size of this scratch buffer in items. This is present here so that * external callers can inspect the guaranteed size of the buffer object. */ static constexpr size_t BaseSize = BaseSize_; /** Constructor: initializes a new empty scratch buffer. * * @returns no return value. */ ScratchBuffer() { m_dynamicArray = m_localArray; m_size = BaseSize; m_capacity = BaseSize; } /** Copy constructor: copies a scratch buffer from another one. * * @param[in] right The other scratch buffer to copy. The contents of the buffer will * be copied into this object and this object will be resized to match * the size of @p right. The other object will not be modified. * @returns no return value. */ ScratchBuffer(const ScratchBuffer& right) { *this = right; } /** Move constructor: moves another scratch buffer into this one * * @param[in] right The other scratch buffer to move from. The contents of the buffer * will be copied into this object and this object will be resized to match * the size of @p right. The other object will be reset back to an empty * state after the data is moved. * @returns no return value. */ ScratchBuffer(ScratchBuffer&& right) { *this = std::move(right); } ~ScratchBuffer() { if (m_dynamicArray != nullptr && m_dynamicArray != m_localArray) delete[] m_dynamicArray; } /** Assignment operator (copy). * * @param[in] right The other scratch buffer to copy from. * @returns A reference to this object. All items in the @p right buffer will be copied * into this object by the most efficient means possible. */ ScratchBuffer& operator=(const ScratchBuffer& right) { if (&right == this) return *this; if (!resize(right.m_size)) return *this; std::copy_n(right.m_dynamicArray, m_size, m_dynamicArray); return *this; } /** Assignment operator (move). * * @param[in] right The other scratch buffer to move from. * @returns A reference to this object. All items in the @p right buffer will be moved * into this object by the most efficient means possible. The @p right buffer * will be cleared out upon return (this only really has a meaning if the * contained type is a movable class). */ ScratchBuffer& operator=(ScratchBuffer&& right) { if (&right == this) return *this; if (!resize(right.m_size)) return *this; std::copy_n(std::make_move_iterator(right.m_dynamicArray), m_size, m_dynamicArray); return *this; } /** Array access operator. * * @param[in] index The index to access the array at. It is the caller's responsibility * to ensure this index is within the bounds of the array. * @returns A reference to the requested entry in the array as an lvalue. */ T& operator[](size_t index) { return m_dynamicArray[index]; } /** Array accessor. * * @returns The base address of the buffer. This address will be valid until the next * call to resize(). It is the caller's responsibility to protect access to * this buffer as needed. */ T* data() { return m_dynamicArray; } /** @copydoc data() */ const T* data() const { return m_dynamicArray; } /** Retrieves the current size of the buffer in items. * * @returns The current size of this buffer in items. This value is valid until the next * call to resize(). The size in bytes can be calculated by multiplying this * value by `sizeof(DataType)`. */ size_t size() const { return m_size; } /** Attempts to resize this buffer. * * @param[in] count The new requested size of the buffer in items. This may not be zero. * @returns `true` if the buffer was successfully resized. If the requested count is * smaller than or equal to the @p BaseSize value for this object, resizing will * always succeed. * @returns `false` if the buffer could not be resized. On failure, the previous contents * and size of the array will be left unchanged. */ bool resize(size_t count) { T* tmp = m_localArray; size_t copyCount; if (count == 0) return true; // the buffer is already the requested size -> nothing to do => succeed. if (count == m_size) return true; // the buffer is already large enough => don't resize unless the change is drastic. if (count <= m_capacity) { if ((count * 100) >= ShrinkThreshold_ * m_size) { m_size = count; return true; } } if (count > BaseSize) { tmp = new (std::nothrow) T[count]; if (tmp == nullptr) return false; } // the buffer didn't change -> nothing to copy => update parameters and succeed. if (tmp == m_dynamicArray) { m_size = count; m_capacity = BaseSize; return true; } copyCount = m_size; if (m_size > count) copyCount = count; std::copy_n(std::make_move_iterator(m_dynamicArray), copyCount, tmp); if (m_dynamicArray != nullptr && m_dynamicArray != m_localArray) delete[] m_dynamicArray; m_dynamicArray = tmp; m_size = count; m_capacity = count; return true; } private: /** The stack allocated space for the buffer. This is always sized to be the larger of * 512 bytes or enough space to hold 16 items. This array should never be accessed * directly. If this buffer is in use, the @p m_dynamicArray member will point to * this buffer. */ T m_localArray[BaseSize]; /** The dynamically allocated buffer if the current size is larger than the base size * of this buffer, or a pointer to @p m_localArray if smaller or equal. This will * never be `nullptr`. */ T* m_dynamicArray; /** The current size of the buffer in items. */ size_t m_size = BaseSize; /** The current maximum size of the buffer in items. */ size_t m_capacity = BaseSize; }; } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/extras/ContainerHelper.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 Helper functions for dealing with docker containers. These functions will * fail gracefully on Windows or Mac. */ #pragma once #include "../../carb/Defines.h" #if CARB_PLATFORM_LINUX # include <fcntl.h> # include <unistd.h> #endif namespace omni { namespace extras { #if CARB_PLATFORM_LINUX || defined(DOXYGEN_BUILD) # ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { inline int readIntFromFile(const char* file) noexcept { auto fd = ::open(file, O_RDONLY, 0); if (fd == -1) { return -1; } char buffer[64]; auto size = CARB_RETRY_EINTR(::read(fd, buffer, sizeof(buffer) - 1)); ::close(fd); if (size <= 0) { return -1; } buffer[size] = '\0'; return std::atoi(buffer); } inline bool isRunningInContainer() noexcept { FILE* fp; // first (and easiest) check is to check whether the `/.dockerenv` file exists. This file // is not necessarily always present though. if (access("/.dockerenv", F_OK) == 0) { return true; } // a more reliable but more expensive check is to verify the control group of `init`. If // running under docker, all of the entries will have a path that starts with `/docker` or // `/lxc` instead of just `/`. fp = fopen("/proc/1/cgroup", "r"); if (fp != nullptr) { char line[256]; while (fgets(line, CARB_COUNTOF(line), fp) != nullptr) { if (feof(fp) || ferror(fp)) break; if (strstr(line, ":/docker") != nullptr || strstr(line, ":/lxc") != nullptr) { return true; } } fclose(fp); } return false; } } // namespace detail # endif /** Attempts to read the current effective CPU usage quota for processes in a container. * * @returns The effective number of logical cores that processes in the container will have * access to if a limit has been imposed. If no limit has been imposed when running * the container, -1 will be returned. * * @remarks This reads and calculates the effective CPU usage quota for processes in a container. * If a limit has been imposed, the result is the number of logical cores that can be * used. Note that this does not actually guarantee that the processes will not be * able to run on some cores, but rather that the CPU scheduler will only give a * certain percentage of its time to processes in the container thereby effectively * making their performance similar to running on a system with the returned number * of cores. * * @note This will still return a valid result outside of a container if a CPU usage limit has * been imposed on the system. By default, Linux systems allow unlimited CPU usage. */ inline int getDockerCpuLimit() noexcept { // See: // https://docs.docker.com/config/containers/resource_constraints/#cpu // https://engineering.squarespace.com/blog/2017/understanding-linux-container-scheduling const auto cfsQuota = detail::readIntFromFile("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"); const auto cfsPeriod = detail::readIntFromFile("/sys/fs/cgroup/cpu/cpu.cfs_period_us"); if (cfsQuota > 0 && cfsPeriod > 0) { // Since we can have fractional CPUs, round up half a CPU to a whole CPU, but make sure we have an even number. return ::carb_max(1, (cfsQuota + (cfsPeriod / 2)) / cfsPeriod); } return -1; } /** Attempts to detect whether this process is running inside a container. * * @returns `true` if this process is running inside a container. Returns `false` otherwise. * * @remarks This detects if the calling process is running inside a container. This is done * by checking for certain files or their contents that are known (and documented) * to be modified by Docker. Note that this currently only supports detecting Docker * and LXC containers. */ inline bool isRunningInContainer() { static bool s_inContainer = detail::isRunningInContainer(); return s_inContainer; } #else inline int getDockerCpuLimit() noexcept { return -1; } inline bool isRunningInContainer() noexcept { return false; } #endif } // namespace extras } // namespace omni
omniverse-code/kit/include/omni/math/linalg/vec.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 <usdrt/gf/vec.h>
omniverse-code/kit/include/omni/math/linalg/half.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 <usdrt/gf/half.h>
omniverse-code/kit/include/omni/math/linalg/quat.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 <usdrt/gf/matrix.h>
omniverse-code/kit/include/omni/math/linalg/debug.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 "half.h" #include "matrix.h" #include "quat.h" #include "vec.h" #include <iomanip> #include <iostream> namespace omni { namespace math { namespace linalg { // ================================================================================= // Debug output operators for linalg types std::ostream& operator<<(std::ostream& out, half const& v) { return out << (float)v; } template <typename T, size_t precision = 4> struct NumericFormatter { explicit NumericFormatter(T d) { m_val = d; } static constexpr size_t s_precision = precision; static constexpr size_t s_width = 14; T m_val; }; template <typename T> std::ostream& operator<<(std::ostream& out, NumericFormatter<T> const& f) { return out << std::setprecision(NumericFormatter<T>::s_precision) << std::fixed << std::left << std::setw(NumericFormatter<T>::s_width) << std::setfill(' ') << f.m_val; } template <typename T, size_t N> std::ostream& operator<<(std::ostream& out, base_matrix<T, N> const& m) { using Fmt = NumericFormatter<T>; for (size_t i = 0; i < (N - 1); ++i) { out << '|'; for (size_t j = 0; j < (N - 1); ++j) out << Fmt(m[i][j]); out << Fmt(m[i][N - 1]) << '|'; if (i < (N - 1)) out << '\n'; } return out; } template<typename T, size_t N> std::ostream& operator<<(std::ostream& out, base_vec<T, N> const& v) { using Fmt = NumericFormatter<T>; out << '('; for (size_t i = 0; i < (N - 1); ++i) out << Fmt(v[0]); return out << Fmt(v[N - 1]) << ')'; } template <typename T> std::ostream& operator<<(std::ostream& out, quat<T> const& q) { auto i = q.GetImaginary(); auto real = q.GetReal(); return out << vec4<T>{ real, i[0], i[1], i[2] }; } } // linalg } // math } // omni
omniverse-code/kit/include/omni/math/linalg/SafeCast.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 <pxr/pxr.h> #include <type_traits> #include <stdint.h> // Forward declarations, to avoid needing to include the world. PXR_NAMESPACE_OPEN_SCOPE namespace pxr_half { class half; } using GfHalf = pxr_half::half; class GfVec2h; class GfVec2f; class GfVec2d; class GfVec2i; class GfVec3h; class GfVec3f; class GfVec3d; class GfVec3i; class GfVec4h; class GfVec4f; class GfVec4d; class GfVec4i; class GfQuath; class GfQuatf; class GfQuatd; class GfMatrix2f; class GfMatrix2d; class GfMatrix3f; class GfMatrix3d; class GfMatrix4f; class GfMatrix4d; PXR_NAMESPACE_CLOSE_SCOPE namespace omni { namespace math { namespace linalg { class half; template <typename T, std::size_t N> class base_vec; template <typename T> class vec2; template <typename T> class vec3; template <typename T> class vec4; template <typename T> class quat; template <typename T, std::size_t N> class base_matrix; template <typename T> class matrix2; template <typename T> class matrix3; template <typename T> class matrix4; using vec2h = vec2<half>; using vec2f = vec2<float>; using vec2d = vec2<double>; using vec2i = vec2<int>; using vec3h = vec3<half>; using vec3f = vec3<float>; using vec3d = vec3<double>; using vec3i = vec3<int>; using vec4h = vec4<half>; using vec4f = vec4<float>; using vec4d = vec4<double>; using vec4i = vec4<int>; using quath = quat<half>; using quatf = quat<float>; using quatd = quat<double>; using matrix2f = matrix2<float>; using matrix2d = matrix2<double>; using matrix3f = matrix3<float>; using matrix3d = matrix3<double>; using matrix4f = matrix4<float>; using matrix4d = matrix4<double>; template<typename T> struct TypeStruct { using type = T; }; template<typename USD_TYPE> struct OmniType : TypeStruct<void> {}; template<typename OMNI_TYPE> struct USDType : TypeStruct<void> {}; template <> struct OmniType<pxr::GfHalf> : TypeStruct<half> {}; template <> struct OmniType<float> : TypeStruct<float> {}; template <> struct OmniType<double> : TypeStruct<double> {}; template <> struct OmniType<int> : TypeStruct<int> {}; template <> struct OmniType<unsigned char> : TypeStruct<unsigned char> {}; template <> struct OmniType<unsigned int> : TypeStruct<unsigned int> {}; template <> struct OmniType<int64_t> : TypeStruct<int64_t> {}; template <> struct OmniType<uint64_t> : TypeStruct<uint64_t> {}; template <> struct OmniType<bool> : TypeStruct<bool> {}; template <> struct OmniType<pxr::GfVec2h> : TypeStruct<vec2h> {}; template <> struct OmniType<pxr::GfVec2f> : TypeStruct<vec2f> {}; template <> struct OmniType<pxr::GfVec2d> : TypeStruct<vec2d> {}; template <> struct OmniType<pxr::GfVec2i> : TypeStruct<vec2i> {}; template <> struct OmniType<pxr::GfVec3h> : TypeStruct<vec3h> {}; template <> struct OmniType<pxr::GfVec3f> : TypeStruct<vec3f> {}; template <> struct OmniType<pxr::GfVec3d> : TypeStruct<vec3d> {}; template <> struct OmniType<pxr::GfVec3i> : TypeStruct<vec3i> {}; template <> struct OmniType<pxr::GfVec4h> : TypeStruct<vec4h> {}; template <> struct OmniType<pxr::GfVec4f> : TypeStruct<vec4f> {}; template <> struct OmniType<pxr::GfVec4d> : TypeStruct<vec4d> {}; template <> struct OmniType<pxr::GfVec4i> : TypeStruct<vec4i> {}; template <> struct OmniType<pxr::GfQuath> : TypeStruct<quath> {}; template <> struct OmniType<pxr::GfQuatf> : TypeStruct<quatf> {}; template <> struct OmniType<pxr::GfQuatd> : TypeStruct<quatd> {}; template <> struct OmniType<pxr::GfMatrix2f> : TypeStruct<matrix2f> {}; template <> struct OmniType<pxr::GfMatrix2d> : TypeStruct<matrix2d> {}; template <> struct OmniType<pxr::GfMatrix3f> : TypeStruct<matrix3f> {}; template <> struct OmniType<pxr::GfMatrix3d> : TypeStruct<matrix3d> {}; template <> struct OmniType<pxr::GfMatrix4f> : TypeStruct<matrix4f> {}; template <> struct OmniType<pxr::GfMatrix4d> : TypeStruct<matrix4d> {}; template <> struct USDType<half> : TypeStruct<pxr::GfHalf> {}; template <> struct USDType<float> : TypeStruct<float> {}; template <> struct USDType<double> : TypeStruct<double> {}; template <> struct USDType<int> : TypeStruct<int> {}; template <> struct USDType<unsigned char> : TypeStruct<unsigned char> {}; template <> struct USDType<unsigned int> : TypeStruct<unsigned int> {}; template <> struct USDType<int64_t> : TypeStruct<int64_t> {}; template <> struct USDType<uint64_t> : TypeStruct<uint64_t> {}; template <> struct USDType<bool> : TypeStruct<bool> {}; template <> struct USDType<vec2h> : TypeStruct<pxr::GfVec2h> {}; template <> struct USDType<vec2f> : TypeStruct<pxr::GfVec2f> {}; template <> struct USDType<vec2d> : TypeStruct<pxr::GfVec2d> {}; template <> struct USDType<vec2i> : TypeStruct<pxr::GfVec2i> {}; template <> struct USDType<vec3h> : TypeStruct<pxr::GfVec3h> {}; template <> struct USDType<vec3f> : TypeStruct<pxr::GfVec3f> {}; template <> struct USDType<vec3d> : TypeStruct<pxr::GfVec3d> {}; template <> struct USDType<vec3i> : TypeStruct<pxr::GfVec3i> {}; template <> struct USDType<vec4h> : TypeStruct<pxr::GfVec4h> {}; template <> struct USDType<vec4f> : TypeStruct<pxr::GfVec4f> {}; template <> struct USDType<vec4d> : TypeStruct<pxr::GfVec4d> {}; template <> struct USDType<vec4i> : TypeStruct<pxr::GfVec4i> {}; template <> struct USDType<quath> : TypeStruct<pxr::GfQuath> {}; template <> struct USDType<quatf> : TypeStruct<pxr::GfQuatf> {}; template <> struct USDType<quatd> : TypeStruct<pxr::GfQuatd> {}; template <> struct USDType<matrix2f> : TypeStruct<pxr::GfMatrix2f> {}; template <> struct USDType<matrix2d> : TypeStruct<pxr::GfMatrix2d> {}; template <> struct USDType<matrix3f> : TypeStruct<pxr::GfMatrix3f> {}; template <> struct USDType<matrix3d> : TypeStruct<pxr::GfMatrix3d> {}; template <> struct USDType<matrix4f> : TypeStruct<pxr::GfMatrix4f> {}; template <> struct USDType<matrix4d> : TypeStruct<pxr::GfMatrix4d> {}; template <typename USD_TYPE> const typename OmniType<USD_TYPE>::type* safeCastToOmni(const USD_TYPE* p) { return reinterpret_cast<const typename OmniType<USD_TYPE>::type*>(p); } template <typename USD_TYPE> typename OmniType<USD_TYPE>::type* safeCastToOmni(USD_TYPE* p) { return reinterpret_cast<typename OmniType<USD_TYPE>::type*>(p); } template <typename USD_TYPE> const typename OmniType<USD_TYPE>::type& safeCastToOmni(const USD_TYPE& p) { return reinterpret_cast<const typename OmniType<USD_TYPE>::type&>(p); } template <typename USD_TYPE> typename OmniType<USD_TYPE>::type& safeCastToOmni(USD_TYPE& p) { return reinterpret_cast<typename OmniType<USD_TYPE>::type&>(p); } template <typename OMNI_TYPE> const typename USDType<OMNI_TYPE>::type* safeCastToUSD(const OMNI_TYPE* p) { return reinterpret_cast<const typename USDType<OMNI_TYPE>::type*>(p); } template <typename OMNI_TYPE> typename USDType<OMNI_TYPE>::type* safeCastToUSD(OMNI_TYPE* p) { return reinterpret_cast<typename USDType<OMNI_TYPE>::type*>(p); } template <typename OMNI_TYPE> const typename USDType<OMNI_TYPE>::type& safeCastToUSD(const OMNI_TYPE& p) { return reinterpret_cast<const typename USDType<OMNI_TYPE>::type&>(p); } template <typename OMNI_TYPE> typename USDType<OMNI_TYPE>::type& safeCastToUSD(OMNI_TYPE& p) { return reinterpret_cast<typename USDType<OMNI_TYPE>::type&>(p); } } } }
omniverse-code/kit/include/omni/math/linalg/math.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 <usdrt/gf/math.h>
omniverse-code/kit/include/omni/math/linalg/matrix.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 <usdrt/gf/matrix.h>
omniverse-code/kit/include/omni/math/linalg/README.md
Moved to include/usdrt/gf ========================= The implementation of the omni\:\:math\:\:linalg classes has been moved to `include/usdrt/gf`. The existing headers are left in place as stubs that include the relocated files so that existing code will work as-is.
omniverse-code/kit/include/omni/population/Population.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/Types.h> namespace carb { namespace ujitso { struct Agent; } }; namespace omni { namespace fabric { struct FabricId; struct UsdStageId; } }; namespace omni { namespace population { // Temporary struct until cache merging and querying are implemented in FabricAgent struct FabricCache { const omni::fabric::FabricId& fabricId; const omni::fabric::UsdStageId& usdStageId; }; struct IPopulation { CARB_PLUGIN_INTERFACE("omni::population::IPopulation", 0, 1); // fabricCache is optional, nullptr will create a new cache. Will be removed later. // if fabricCache contains data, that stage and cache will be populated. // We pass both the Fabric stage and the cache because in IStageReaderWriter they are tied. void(CARB_ABI* populateFabric)(carb::ujitso::Agent& agent, const char* usdStagePath, const FabricCache* fabricCache); }; // TODO: this is only for tests right now, the entire code should be in tests. // The reason it is here is because test.unit has no dependency on USD now. // We can either add USD dependency to test.unit or move omni.population tests to e.g. test.unit.fabric struct IValidate { CARB_PLUGIN_INTERFACE("omni::population::IValidate", 0, 1); bool (CARB_ABI* validateFabric)(const char* stagePath, const omni::fabric::FabricId& fabricId); }; } // namespace population } // namespace omni
omniverse-code/kit/include/omni/detail/ExpectedImpl.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 "../../carb/cpp/Functional.h" #include "../../carb/cpp/Memory.h" #include "../../carb/cpp/TypeTraits.h" #include "../../carb/cpp/Utility.h" #include "../../carb/cpp/Memory.h" #include "../../carb/cpp/TypeTraits.h" #include "../core/IObject.h" #include "ConvertsFromAnyCvRef.h" #include "ParamPack.h" #include <cstddef> #include <initializer_list> //! \cond DEV //! //! \file //! Implementation details for \c omni::expected and related classes. //! //! \warning //! Take \e extreme care when altering anything that can affect ABI. This is not just the obvious things like object //! structure. ABI altering changes also include changing the trivial-ness of a destructor or copy operation based on a //! member type. namespace omni { template <typename TValue, typename TError> class expected; template <typename TError> class unexpected; struct unexpect_t { explicit unexpect_t() = default; }; constexpr unexpect_t unexpect{}; template <typename TError> class bad_expected_access; //! \warning //! This is not ABI safe, since it derives from \c std::exception. template <> class bad_expected_access<void> : public std::exception { public: bad_expected_access() = default; char const* what() const noexcept override { return "Invalid access of `omni::expected`"; } }; //! \warning //! This is not ABI safe, since it derives from \c std::exception through \c bad_expected_access<void>. template <typename TError> class bad_expected_access : public bad_expected_access<void> { public: explicit bad_expected_access(TError e) : m_error(std::move(e)) { } TError const& error() const& noexcept { return m_error; } TError& error() & noexcept { return m_error; } TError const&& error() const&& noexcept { return std::move(m_error); } TError&& error() && noexcept { return std::move(m_error); } private: TError m_error; }; namespace detail { using carb::cpp::bool_constant; using carb::cpp::conjunction; using carb::cpp::disjunction; using carb::cpp::in_place; using carb::cpp::in_place_t; using carb::cpp::is_void; using carb::cpp::negation; using carb::cpp::remove_cvref_t; using carb::cpp::type_identity; using carb::cpp::void_t; using omni::core::Result; using std::conditional_t; using std::enable_if_t; using std::false_type; using std::integral_constant; using std::is_constructible; using std::is_copy_constructible; using std::is_move_constructible; using std::is_nothrow_constructible; using std::is_nothrow_copy_assignable; using std::is_nothrow_copy_constructible; using std::is_nothrow_destructible; using std::is_nothrow_move_assignable; using std::is_nothrow_move_constructible; using std::is_trivially_copy_assignable; using std::is_trivially_copy_constructible; using std::is_trivially_destructible; using std::is_trivially_move_assignable; using std::is_trivially_move_constructible; using std::true_type; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Helpers // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename T> struct IsExpected : false_type { }; template <typename TValue, typename TError> struct IsExpected<omni::expected<TValue, TError>> : true_type { }; template <typename T> struct IsUnexpected : false_type { }; template <typename TError> struct IsUnexpected<omni::unexpected<TError>> : true_type { }; //! This empty structure is used when an \c expected is going to store a \c void element. This is needed because \c void //! is not a valid \c union member. struct ExpectedStorageVoid { }; //! Test if \c T is a valid \c value_type for \c omni::expected or \c omni::unexpected. template <typename T> struct IsValidExpectedValue : conjunction<disjunction<std::is_object<T>, is_void<T>>, negation<std::is_array<T>>> { }; //! Test if \c T is a valid \c error_type for \c omni::expected. This is similar to \c IsValidExpectedValue with the //! additional restrictions that it can not be CV qualified. template <typename T> struct IsValidExpectedError : conjunction<disjunction<std::is_object<T>, is_void<T>>, negation<std::is_array<T>>, negation<IsUnexpected<T>>, negation<std::is_const<T>>, negation<std::is_volatile<T>>> { }; //! Apply \c TTTransform to \c T if it is possibly cv \c void or be \c TFallback if it is \c void. template <template <typename...> class TTTransform, typename T, typename TFallback = void, typename = void_t<>> struct ExpectedTransformIfNonVoid { using type = TFallback; }; template <template <typename...> class TTTransform, typename T, typename TFallback> struct ExpectedTransformIfNonVoid<TTTransform, T, TFallback, std::enable_if_t<!std::is_void<T>::value>> { using type = typename TTTransform<T>::type; }; template <typename TFromValue, typename TFromError, typename TFromValueExpr, typename TFromErrorExpr, typename TToValue, typename TToError, typename = void_t<>> struct IsExpectedConvertibleImpl : std::false_type { }; template <typename TFromValue, typename TFromError, typename TFromValueExpr, typename TFromErrorExpr, typename TToValue, typename TToError> struct IsExpectedConvertibleImpl< TFromValue, TFromError, TFromValueExpr, TFromErrorExpr, TToValue, TToError, std::enable_if_t<conjunction< // (18.1): is_constructible_v<T, UF> is true; and disjunction<conjunction<std::is_void<TToValue>, std::is_void<TFromValue>>, std::is_constructible<TToValue, TFromValue>>, // (18.2): is_constructible_v<E, GF> is true; and disjunction<conjunction<std::is_void<TToError>, std::is_void<TFromError>>, std::is_constructible<TToError, TFromError>>, // (18.3): if T is not cv bool, converts-from-any-cvref<T, expected<U, G>> is false; and disjunction<std::is_same<bool, std::remove_cv_t<TToValue>>, negation<ConvertsFromAnyCvRef<TToValue, omni::expected<TFromValue, TFromError>>>>, // (18.4): is_constructible_v<unexpected<E>, expected<U, G>&> is false; and negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError>&>>, // (18.5): is_constructible_v<unexpected<E>, expected<U, G>> is false; and negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError>>>, // (18.6): is_constructible_v<unexpected<E>, const expected<U, G>&> is false; and negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError> const&>>, // (18.7): is_constructible_v<unexpected<E>, const expected<U, G>> is false. negation<std::is_constructible<omni::unexpected<TToError>, omni::expected<TFromValue, TFromError> const>>>::value>> : std::true_type { static constexpr bool is_explicit = disjunction<negation<std::is_convertible<TFromValueExpr, TToValue>>, negation<std::is_convertible<TFromErrorExpr, TToError>>>::value; }; //! Type test to determine if \c omni::expected \c TFrom is convertible to \c TTo by a converting constructor. The //! elements are transformed by \c TTTypeTransformer for expressiion value category changes (copy vs move). //! //! The final structure will have either 1 or 2 member values: //! //! * `static constexpr bool value`: This is \c true if \c TFrom is convertible to \c TTo or \c false if it is not. //! * `static constexpr bool is_explicit`: This is \c true if the conversion between types should be \c explicit or //! \c false if it is an implicit conversion. This member is only present if \c value is \c true and is safe for use //! in SFINAE contexts. //! //! This type is responsible for filtering out cases where \c TFrom is exactly equal to \c TTo. If this is the case, it //! is not convertable, but either copyable or moveable (depending on the member types). //! //! \see IsExpectedCopyConstructibleFrom //! \see IsExpectedMoveConstructibleFrom template <typename TFrom, typename TTo, template <typename...> class TTTypeTransformer, typename = void_t<>> struct IsExpectedConvertible : std::false_type { }; template <typename TFromValue, typename TFromError, typename TToValue, typename TToError, template <typename...> class TTTypeTransformer> struct IsExpectedConvertible< omni::expected<TFromValue, TFromError>, omni::expected<TToValue, TToError>, TTTypeTransformer, std::enable_if_t<!conjunction<std::is_same<TFromValue, TToValue>, std::is_same<TFromError, TToError>>::value>> : IsExpectedConvertibleImpl<TFromValue, TFromError, typename ExpectedTransformIfNonVoid<TTTypeTransformer, TFromValue>::type, typename ExpectedTransformIfNonVoid<TTTypeTransformer, TFromError>::type, TToValue, TToError> { }; template <typename T> struct AddConstLvalueRef { using type = std::add_lvalue_reference_t<std::add_const_t<T>>; }; template <typename TFrom, typename TTo> using IsExpectedCopyConstructibleFrom = IsExpectedConvertible<TFrom, TTo, AddConstLvalueRef>; template <typename TFrom, typename TTo> using IsExpectedMoveConstructibleFrom = IsExpectedConvertible<TFrom, TTo, type_identity>; template <typename TFrom, typename TTo, typename = void_t<>> struct IsExpectedDirectConstructibleFromImpl : std::false_type { }; template <typename UValue, typename TValue, typename TError> struct IsExpectedDirectConstructibleFromImpl< UValue, omni::expected<TValue, TError>, std::enable_if_t< conjunction<negation<is_void<TValue>>, negation<std::is_same<in_place_t, remove_cvref_t<UValue>>>, negation<std::is_same<omni::expected<TValue, TError>, remove_cvref_t<UValue>>>, is_constructible<TValue, UValue>, negation<IsUnexpected<remove_cvref_t<UValue>>>, disjunction<negation<std::is_same<bool, remove_cvref_t<TValue>>>, negation<IsExpected<UValue>>>>::value>> : std::false_type { static constexpr bool is_explicit = !std::is_convertible<UValue, TValue>::value; }; template <typename TFrom, typename TTo> struct IsExpectedDirectConstructibleFrom : IsExpectedDirectConstructibleFromImpl<TFrom, TTo> { }; //! This is used by expected base classes in order to create versions of special constructors (copy and move) without //! defining them in a way that would interfere with their trivial definition from `= default`. struct ExpectedCtorBypass { }; #if CARB_EXCEPTIONS_ENABLED //! Implementation of \c expected_reinit which optimizes the algorithm based on if the operations are potentially //! throwing. The generic case assumes that all operations can throw. template <typename TOld, typename TNew, typename TParamPack, typename = void_t<>> struct ExpectedReinitImpl { template <typename... TArgs> static void reinit(TOld* pold, TNew* pnew, TArgs&&... args) { TOld temp{ std::move(*pold) }; carb::cpp::destroy_at(pold); try { carb::cpp::construct_at(pnew, std::forward<TArgs>(args)...); } catch (...) { carb::cpp::construct_at(pold, std::move(temp)); throw; } } }; //! If `TNew(TArgs...)` construction is non-throwing, then we don't need to back up anything. template <typename TOld, typename TNew, typename... TArgs> struct ExpectedReinitImpl<TOld, TNew, ParamPack<TArgs...>, std::enable_if_t<std::is_nothrow_constructible<TNew, TArgs...>::value>> { static void reinit(TOld* pold, TNew* pnew, TArgs&&... args) { carb::cpp::destroy_at(pold); carb::cpp::construct_at(pnew, std::forward<TArgs>(args)...); } }; //! If \c TNew is non-throwing move, but `TNew(TArgs...)` could throw, then create it on the stack first, then move it. template <typename TOld, typename TNew, typename... TArgs> struct ExpectedReinitImpl<TOld, TNew, ParamPack<TArgs...>, std::enable_if_t<conjunction<std::is_nothrow_move_constructible<TNew>, negation<std::is_nothrow_constructible<TNew, TArgs...>>>::value>> { static void reinit(TOld* pold, TNew* pnew, TArgs&&... args) { TNew temp{ std::forward<TArgs>(args)... }; carb::cpp::destroy_at(pold); carb::cpp::construct_at(pnew, std::move(temp)); } }; #else // !CARB_EXCEPTIONS_ENABLED //! Without exceptions enabled, there is no mechanism for failure, so the algorithm is simple. template <typename TOld, typename TNew, typename TParamPack> struct ExpectedReinitImpl { template <typename... TArgs> static void reinit(TOld* pold, TNew* pnew, TArgs&&... args) noexcept { carb::cpp::destroy_at(pold); carb::cpp::construct_at(pnew, std::forward<TArgs>(args)...); } }; #endif // CARB_EXCEPTIONS_ENABLED //! Used in type-changing assignment -- reinitializes the contents of an \c ExpectedStorage union from \c TOld to //! \c TNew without allowing an uninitialized state to leak (a \c std::bad_variant_access equivalent is not allowed for //! \c std::expected implementations). //! //! \exception //! An exception raised will leave the \a pold in a non-destructed, but possibly moved-from state. template <typename TOld, typename TNew, typename... TArgs> constexpr void expected_reinit(TOld* pold, TNew* pnew, TArgs&&... args) { ExpectedReinitImpl<TOld, TNew, ParamPack<TArgs...>>::reinit(pold, pnew, std::forward<TArgs>(args)...); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Unexpected // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename TError> class UnexpectedImpl { static_assert(IsValidExpectedError<TError>::value, "Type is not valid for an expected error type"); template <typename UError> friend class UnexpectedImpl; public: constexpr UnexpectedImpl(UnexpectedImpl const&) = default; constexpr UnexpectedImpl(UnexpectedImpl&&) = default; template <typename UError = TError, typename = std::enable_if_t<conjunction<negation<IsUnexpected<remove_cvref_t<UError>>>, negation<std::is_same<remove_cvref_t<UError>, in_place_t>>, is_constructible<TError, UError>>::value>> constexpr explicit UnexpectedImpl(UError&& src) : m_error{ std::forward<UError>(src) } { } template <typename... TArgs, typename = std::enable_if_t<is_constructible<TError, TArgs...>::value>> constexpr explicit UnexpectedImpl(in_place_t, TArgs&&... args) : m_error{ std::forward<TArgs>(args)... } { } template <typename U, typename... TArgs, typename = std::enable_if_t<is_constructible<TError, std::initializer_list<U>&, TArgs...>::value>> constexpr explicit UnexpectedImpl(in_place_t, std::initializer_list<U> init_list, TArgs&&... args) : m_error{ init_list, std::forward<TArgs>(args)... } { } constexpr TError& error() & noexcept { return m_error; } constexpr TError const& error() const& noexcept { return m_error; } constexpr TError&& error() && noexcept { return std::move(m_error); } constexpr TError const&& error() const&& noexcept { return std::move(m_error); } constexpr void swap(UnexpectedImpl<TError>& other) { using std::swap; swap(m_error, other.m_error); } template <typename UError> constexpr bool operator==(UnexpectedImpl<UError> const& other) const { return m_error == other.m_error; } protected: TError m_error; }; template <> class UnexpectedImpl<void> { public: constexpr UnexpectedImpl() noexcept { } constexpr explicit UnexpectedImpl(in_place_t) noexcept { } constexpr void error() const noexcept { } constexpr void swap(UnexpectedImpl<void>) noexcept { } constexpr bool operator==(UnexpectedImpl<void>) const noexcept { return true; } }; //! Called from `expected::error()` overloads when the instance `has_value()`. [[noreturn]] inline void invalid_expected_access_error() noexcept { CARB_FATAL_UNLESS(false, "Call to `omni::expected::error()` on successful instance"); } #if CARB_EXCEPTIONS_ENABLED template <typename T> [[noreturn]] inline enable_if_t<conjunction<negation<std::is_same<std::decay_t<T>, ExpectedStorageVoid>>, std::is_constructible<std::decay_t<T>, T>>::value> invalid_expected_access(T&& x) { throw ::omni::bad_expected_access<std::decay_t<T>>(std::forward<T>(x)); } template <typename T> [[noreturn]] inline enable_if_t<conjunction<negation<std::is_same<std::decay_t<T>, ExpectedStorageVoid>>, negation<std::is_constructible<std::decay_t<T>, T>>>::value> invalid_expected_access(T&&) { throw ::omni::bad_expected_access<void>(); } [[noreturn]] inline void invalid_expected_access(ExpectedStorageVoid) { throw ::omni::bad_expected_access<void>(); } #else // !CARB_EXCEPTIONS_ENABLED template <typename T> [[noreturn]] inline enable_if_t<std::is_same<std::decay_t<T>, ExpectedStorageVoid>::value> invalid_expected_access(T&&) { CARB_FATAL_UNLESS(false, "Invalid access of `omni::expected::value()`"); } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Storage // // This section governs the byte layout of an `omni::excepted` and the trivialness of its special member functions // // (namely: copy, move, and destructor -- initialization is never trivial). All information relevant to the ABI of // // `expected` should be defined in this section. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enum class ExpectedState : std::uint8_t { //! The instance holds the success value. eSUCCESS = 0, //! The instance holds an error. eUNEXPECTED = 1, }; //! The \c ExpectedStorage type stores the value or error contents of an \c expected instance. //! //! This is stored as a union to make \c e.value and \c e.error show up properly in debugging. //! //! The member \c uninit is used for the copy and move constructors, but only exists in this state inside of an //! \c ExpectedImplBase constructor for types with non-trivial versions of these operations. While the copy or move //! constructor needs to initialize either \c value or \c error, there is no syntax in C++ to conditionally do this //! based on a value. //! //! \tparam TrivialDtor If both the \c TValue and \c TError types are either \c void or have trivial destructors, then //! the union itself does not need a destructor. // clang-format off template <typename TValue, typename TError, bool TrivialDtor = conjunction<disjunction<is_void<TValue>, is_trivially_destructible<TValue>>, disjunction<is_void<TError>, is_trivially_destructible<TError>> >::value > union ExpectedStorage; // clang-format on template <typename TValue, typename TError> union ExpectedStorage<TValue, TError, /*TrivialDtor=*/true> { conditional_t<is_void<TValue>::value, ExpectedStorageVoid, TValue> value; conditional_t<is_void<TError>::value, ExpectedStorageVoid, TError> error; ExpectedStorageVoid uninit; template <typename... TArgs> constexpr explicit ExpectedStorage(in_place_t, TArgs&&... args) : value{ std::forward<TArgs>(args)... } { } template <typename... TArgs> constexpr explicit ExpectedStorage(unexpect_t, TArgs&&... args) : error{ std::forward<TArgs>(args)... } { } constexpr explicit ExpectedStorage(ExpectedCtorBypass) : uninit{} { } }; template <typename TValue, typename TError> union ExpectedStorage<TValue, TError, /*TrivialDtor=*/false> { conditional_t<is_void<TValue>::value, ExpectedStorageVoid, TValue> value; conditional_t<is_void<TError>::value, ExpectedStorageVoid, TError> error; ExpectedStorageVoid uninit; template <typename... TArgs> constexpr explicit ExpectedStorage(in_place_t, TArgs&&... args) : value{ std::forward<TArgs>(args)... } { } template <typename... TArgs> constexpr explicit ExpectedStorage(unexpect_t, TArgs&&... args) : error{ std::forward<TArgs>(args)... } { } constexpr explicit ExpectedStorage(ExpectedCtorBypass) : uninit{} { } ~ExpectedStorage() noexcept { // Intentionally empty -- it is the responsibility of the owner to call value or error destructor, since only it // knows which alternative is active. } }; template <typename TValue, typename TError> class ExpectedImplBase { using StoredValueType = conditional_t<is_void<TValue>::value, ExpectedStorageVoid, TValue>; using StoredErrorType = conditional_t<is_void<TError>::value, ExpectedStorageVoid, TError>; template <typename UValue, typename UError> friend class ExpectedImplBase; protected: template <typename... TArgs, typename = enable_if_t<is_constructible<StoredValueType, TArgs...>::value>> explicit ExpectedImplBase(in_place_t, TArgs&&... args) noexcept(is_nothrow_constructible<StoredValueType, TArgs...>::value) : m_state{ ExpectedState::eSUCCESS }, m_storage{ in_place, std::forward<TArgs>(args)... } { } template <typename... TArgs, typename = enable_if_t<is_constructible<StoredErrorType, TArgs...>::value>> explicit ExpectedImplBase(unexpect_t, TArgs&&... args) noexcept(is_nothrow_constructible<StoredErrorType, TArgs...>::value) : m_state{ ExpectedState::eUNEXPECTED }, m_storage{ unexpect, std::forward<TArgs>(args)... } { } template <typename UValue, typename UError> constexpr explicit ExpectedImplBase(ExpectedCtorBypass bypass, ExpectedImplBase<UValue, UError> const& src) : m_state{ src.m_state }, m_storage{ bypass } { if (src.m_state == ExpectedState::eSUCCESS) carb::cpp::construct_at(carb::cpp::addressof(m_storage.value), src.m_storage.value); else carb::cpp::construct_at(carb::cpp::addressof(m_storage.error), src.m_storage.error); m_state = src.m_state; } template <typename UValue, typename UError> constexpr explicit ExpectedImplBase(ExpectedCtorBypass bypass, ExpectedImplBase<UValue, UError>&& src) : m_state{ src.m_state }, m_storage{ bypass } { if (src.m_state == ExpectedState::eSUCCESS) carb::cpp::construct_at(carb::cpp::addressof(m_storage.value), std::move(src.m_storage.value)); else carb::cpp::construct_at(carb::cpp::addressof(m_storage.error), std::move(src.m_storage.error)); m_state = src.m_state; } //! Destroy the contents of this instance. This is called from the destructor of types with non-trivial destructors. //! It \e must only be called once. See \c ExpectedPayload with \c ExpectedPayloadTag::eCALL_DTOR for usage. //! //! \pre This is either a success or unexpected //! \post The active alternative has been destroyed -- this implementation is in an uninitialized state void unsafe_destroy() { if (m_state == ExpectedState::eSUCCESS) carb::cpp::destroy_at(carb::cpp::addressof(m_storage.value)); else carb::cpp::destroy_at(carb::cpp::addressof(m_storage.error)); } void copy_from(ExpectedImplBase const& src) { if (m_state == src.m_state) { if (m_state == ExpectedState::eSUCCESS) m_storage.value = src.m_storage.value; else m_storage.error = src.m_storage.error; } else if (m_state == ExpectedState::eSUCCESS) // && src.m_state == ExpectedState::eUNEXPECTED { expected_reinit( carb::cpp::addressof(m_storage.value), carb::cpp::addressof(m_storage.error), src.m_storage.error); } else // m_state == ExpectedState::eUNEXPECTED && src.m_state == ExpectedState::eSUCCESS { expected_reinit( carb::cpp::addressof(m_storage.error), carb::cpp::addressof(m_storage.value), src.m_storage.value); } m_state = src.m_state; } void move_from(ExpectedImplBase&& src) { if (m_state == src.m_state) { if (m_state == ExpectedState::eSUCCESS) m_storage.value = std::move(src.m_storage.value); else m_storage.error = std::move(src.m_storage.error); } else if (m_state == ExpectedState::eSUCCESS) // && src.m_state == ExpectedState::eUNEXPECTED { expected_reinit(carb::cpp::addressof(m_storage.value), carb::cpp::addressof(m_storage.error), std::move(src.m_storage.error)); } else // m_state == ExpectedState::eUNEXPECTED && src.m_state == ExpectedState::eSUCCESS { expected_reinit(carb::cpp::addressof(m_storage.error), carb::cpp::addressof(m_storage.value), std::move(src.m_storage.value)); } m_state = src.m_state; } protected: ExpectedState m_state; ExpectedStorage<TValue, TError> m_storage; }; //! Special case of base class where both alternatives are \c void and we only want to store a byte. template <> class ExpectedImplBase<void, void> { protected: explicit ExpectedImplBase(in_place_t) noexcept : m_state{ ExpectedState::eSUCCESS } { } explicit ExpectedImplBase(unexpect_t) noexcept : m_state{ ExpectedState::eUNEXPECTED } { } //! This covers both copy and move constructor use cases, since there isn't data to move anyway. explicit ExpectedImplBase(ExpectedCtorBypass, ExpectedImplBase const& src) noexcept : m_state{ src.m_state } { } //! Fills the same role as the non-specialized version, but does nothing. constexpr void unsafe_destroy() { } protected: ExpectedState m_state; }; //! Used by \c ExpectedPayload in order to determine which special member functions need definitions vs which of them //! can be defaulted. //! //! - \c eTRIVIAL -- copy, move, and destructor are all trivial, so nothing must be done for any operation //! - \c eCALL_COPY -- copy is non-trivial, but move and destructor are trivial //! - \c eCALL_MOVE -- move is non-trivial, but copy and destructor are trivial //! - \c eCALL_BOTH -- both copy and move are non-trivial, but the destructor is //! - \c eCALL_DTOR -- the destructor must be called, which makes both copy- and move-assignment non-trivial, as //! assignment from the opposite alternative can cause the destructor to be called. //! //! \see ExpectedPayloadTagFor enum class ExpectedPayloadTag : std::uint8_t { eTRIVIAL, eCALL_COPY, eCALL_MOVE, eCALL_BOTH, eCALL_DTOR, }; // clang-format off template <typename TValue, typename TError, bool TrivialCopy = conjunction<disjunction<is_void<TValue>, conjunction<is_trivially_copy_assignable<TValue>, is_trivially_copy_constructible<TValue>>>, disjunction<is_void<TError>, conjunction<is_trivially_copy_assignable<TError>, is_trivially_copy_constructible<TError>>> >::value, bool TrivialMove = conjunction<disjunction<is_void<TValue>, conjunction<is_trivially_move_assignable<TValue>, is_trivially_move_constructible<TValue>>>, disjunction<is_void<TError>, conjunction<is_trivially_move_assignable<TError>, is_trivially_move_constructible<TError>>> >::value, bool TrivialDtor = conjunction<disjunction<is_void<TValue>, is_trivially_destructible<TValue>>, disjunction<is_void<TError>, is_trivially_destructible<TError>> >::value > struct ExpectedPayloadTagFor; // clang-format on template <typename TValue, typename TError> struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/true, /*TrivialMove=*/true, /*TrivialDtor=*/true> : integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eTRIVIAL> { }; template <typename TValue, typename TError> struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/false, /*TrivialMove=*/true, /*TrivialDtor=*/true> : integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_COPY> { }; template <typename TValue, typename TError> struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/true, /*TrivialMove=*/false, /*TrivialDtor=*/true> : integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_MOVE> { }; template <typename TValue, typename TError> struct ExpectedPayloadTagFor<TValue, TError, /*TrivialCopy=*/false, /*TrivialMove=*/false, /*TrivialDtor=*/true> : integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_BOTH> { }; template <typename TValue, typename TError, bool TrivialCopy, bool TrivialMove> struct ExpectedPayloadTagFor<TValue, TError, TrivialCopy, TrivialMove, /*TrivialDtor=*/false> : integral_constant<ExpectedPayloadTag, ExpectedPayloadTag::eCALL_DTOR> { }; //! The payload is responsible for managing the special member functions of copy and move construction and assignment, //! as well as the destructor. template <typename TValue, typename TError, ExpectedPayloadTag Optimization = ExpectedPayloadTagFor<TValue, TError>::value> class ExpectedPayload; template <typename TValue, typename TError> class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eTRIVIAL> : public ExpectedImplBase<TValue, TError> { public: using ExpectedImplBase<TValue, TError>::ExpectedImplBase; ExpectedPayload(ExpectedPayload const&) = default; ExpectedPayload(ExpectedPayload&&) = default; ExpectedPayload& operator=(ExpectedPayload const&) = default; ExpectedPayload& operator=(ExpectedPayload&&) = default; ~ExpectedPayload() = default; }; template <typename TValue, typename TError> class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_COPY> : public ExpectedImplBase<TValue, TError> { public: using ExpectedImplBase<TValue, TError>::ExpectedImplBase; ExpectedPayload(ExpectedPayload const&) = default; ExpectedPayload(ExpectedPayload&&) = default; // clang-format off ExpectedPayload& operator=(ExpectedPayload const& src) noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_copy_constructible<TValue>, is_nothrow_copy_assignable<TValue>>>, disjunction<is_void<TError>, conjunction<is_nothrow_copy_constructible<TError>, is_nothrow_copy_assignable<TError>>> >::value ) { this->copy_from(src); return *this; } // clang-format on ExpectedPayload& operator=(ExpectedPayload&&) = default; ~ExpectedPayload() = default; }; template <typename TValue, typename TError> class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_MOVE> : public ExpectedImplBase<TValue, TError> { public: using ExpectedImplBase<TValue, TError>::ExpectedImplBase; ExpectedPayload(ExpectedPayload const&) = default; ExpectedPayload(ExpectedPayload&&) = default; ExpectedPayload& operator=(ExpectedPayload const&) = default; // clang-format off ExpectedPayload& operator=(ExpectedPayload&& src) noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_move_constructible<TValue>, is_nothrow_move_assignable<TValue>>>, disjunction<is_void<TError>, conjunction<is_nothrow_move_constructible<TError>, is_nothrow_move_assignable<TError>>> >::value ) { this->move_from(std::move(src)); return *this; } // clang-format on ~ExpectedPayload() = default; }; template <typename TValue, typename TError> class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_BOTH> : public ExpectedImplBase<TValue, TError> { public: using ExpectedImplBase<TValue, TError>::ExpectedImplBase; ExpectedPayload(ExpectedPayload const&) = default; ExpectedPayload(ExpectedPayload&&) = default; // clang-format off ExpectedPayload& operator=(ExpectedPayload const& src) noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_copy_constructible<TValue>, is_nothrow_copy_assignable<TValue>>>, disjunction<is_void<TError>, conjunction<is_nothrow_copy_constructible<TError>, is_nothrow_copy_assignable<TError>>> >::value ) { this->copy_from(src); return *this; } ExpectedPayload& operator=(ExpectedPayload&& src) noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_move_constructible<TValue>, is_nothrow_move_assignable<TValue>>>, disjunction<is_void<TError>, conjunction<is_nothrow_move_constructible<TError>, is_nothrow_move_assignable<TError>>> >::value ) { this->move_from(std::move(src)); return *this; } // clang-format on ~ExpectedPayload() = default; }; template <typename TValue, typename TError> class ExpectedPayload<TValue, TError, ExpectedPayloadTag::eCALL_DTOR> : public ExpectedImplBase<TValue, TError> { public: using ExpectedImplBase<TValue, TError>::ExpectedImplBase; ExpectedPayload(ExpectedPayload const&) = default; ExpectedPayload(ExpectedPayload&&) = default; // clang-format off ExpectedPayload& operator=(ExpectedPayload const& src) noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_copy_constructible<TValue>, is_nothrow_copy_assignable<TValue>>>, disjunction<is_void<TError>, conjunction<is_nothrow_copy_constructible<TError>, is_nothrow_copy_assignable<TError>>> >::value ) { this->copy_from(src); return *this; } ExpectedPayload& operator=(ExpectedPayload&& src) noexcept(conjunction<disjunction<is_void<TValue>, conjunction<is_nothrow_move_constructible<TValue>, is_nothrow_move_assignable<TValue>>>, disjunction<is_void<TError>, conjunction<is_nothrow_move_constructible<TError>, is_nothrow_move_assignable<TError>>> >::value ) { this->move_from(std::move(src)); return *this; } ~ExpectedPayload() noexcept(conjunction<disjunction<is_void<TValue>, is_nothrow_destructible<TValue>>, disjunction<is_void<TError>, is_nothrow_destructible<TError>> >::value ) { this->unsafe_destroy(); } // clang-format on }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // API // // These classes layer the API based on the type of TValue and TError (specifically: Are they void or an object?). // // Definitions in this section shall not affect the ABI of an `omni::expected` type; special members are all defined // // by `= default` or by `using BaseType::BaseType`. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // clang-format off //! This class controls the presence and trivialness of copy and move constructors. //! //! A copy or move constructor can be defaulted, defined, or deleted. The operation is defaulted when both \c TValue and //! \c TError are either \c void or have that operation as trivial as well (this comes from the definition of when this //! is allowed on \c union types). If either \c TValue or \c TError has the operation deleted, it is deleted on the //! \c expected type as well. For the cases where the operation is non-trivial, it is defined explicitly using the //! \c ExpectedCtorBypass trick. Since these 3 options can happen for both copy and move operations, this results in 9 //! partial specializations. //! //! The `= delete` overloads are not needed, as `= default`ing these will still end up with a deleted definition since //! the \c ExpectedStorage union is deleted by default. However, this leads to awful error messages that lead people to //! think the implementation is broken. By spelling them out, the `= delete` looks more intentional. template <typename TValue, typename TError, bool CopyCtor = conjunction<disjunction<is_void<TValue>, is_copy_constructible<TValue>>, disjunction<is_void<TError>, is_copy_constructible<TError>> >::value, bool DefaultCopyCtor = conjunction<bool_constant<CopyCtor>, disjunction<is_void<TValue>, is_trivially_copy_constructible<TValue>>, disjunction<is_void<TError>, is_trivially_copy_constructible<TError>> >::value, bool MoveCtor = conjunction<disjunction<is_void<TValue>, is_move_constructible<TValue>>, disjunction<is_void<TError>, is_move_constructible<TError>> >::value, bool DefaultMoveCtor = conjunction<bool_constant<MoveCtor>, disjunction<is_void<TValue>, is_trivially_move_constructible<TValue>>, disjunction<is_void<TError>, is_trivially_move_constructible<TError>> >::value > class ExpectedApiCtors; // clang-format on template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/true, /*MoveCtor=*/true, /*DefaultMoveCtor=*/true> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; ExpectedApiCtors(ExpectedApiCtors const&) = default; ExpectedApiCtors(ExpectedApiCtors&&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/true, /*MoveCtor=*/false, /*DefaultMoveCtor=*/false> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; ExpectedApiCtors(ExpectedApiCtors const&) = default; ExpectedApiCtors(ExpectedApiCtors&&) = delete; ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/true, /*MoveCtor=*/true, /*DefaultMoveCtor=*/false> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; ExpectedApiCtors(ExpectedApiCtors const&) = default; constexpr ExpectedApiCtors(ExpectedApiCtors&& src) noexcept( conjunction<disjunction<is_void<TValue>, is_nothrow_move_constructible<TValue>>, disjunction<is_void<TError>, is_nothrow_move_constructible<TError>>>::value) : ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, std::move(src) } { } ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/false, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/true> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; ExpectedApiCtors(ExpectedApiCtors const&) = delete; ExpectedApiCtors(ExpectedApiCtors&&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/false, /*DefaultCopyCtor=*/false, /*MoveCtor=*/false, /*DefaultMoveCtor=*/false> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; ExpectedApiCtors(ExpectedApiCtors const&) = delete; ExpectedApiCtors(ExpectedApiCtors&&) = delete; ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/false, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/false> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; ExpectedApiCtors(ExpectedApiCtors const&) = delete; constexpr ExpectedApiCtors(ExpectedApiCtors&& src) noexcept( conjunction<disjunction<is_void<TValue>, is_nothrow_move_constructible<TValue>>, disjunction<is_void<TError>, is_nothrow_move_constructible<TError>>>::value) : ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, std::move(src) } { } ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/true> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; constexpr ExpectedApiCtors(ExpectedApiCtors const& src) noexcept( conjunction<disjunction<is_void<TValue>, is_nothrow_copy_constructible<TValue>>, disjunction<is_void<TError>, is_nothrow_copy_constructible<TError>>>::value) : ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, src } { } ExpectedApiCtors(ExpectedApiCtors&&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/false, /*MoveCtor=*/false, /*DefaultMoveCtor=*/false> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; constexpr ExpectedApiCtors(ExpectedApiCtors const& src) noexcept( conjunction<disjunction<is_void<TValue>, is_nothrow_copy_constructible<TValue>>, disjunction<is_void<TError>, is_nothrow_copy_constructible<TError>>>::value) : ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, src } { } ExpectedApiCtors(ExpectedApiCtors&&) = delete; ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; template <typename TValue, typename TError> class ExpectedApiCtors<TValue, TError, /*CopyCtor=*/true, /*DefaultCopyCtor=*/false, /*MoveCtor=*/true, /*DefaultMoveCtor=*/false> : public ExpectedPayload<TValue, TError> { public: using ExpectedPayload<TValue, TError>::ExpectedPayload; constexpr ExpectedApiCtors(ExpectedApiCtors const& src) noexcept( conjunction<disjunction<is_void<TValue>, is_nothrow_copy_constructible<TValue>>, disjunction<is_void<TError>, is_nothrow_copy_constructible<TError>>>::value) : ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, src } { } constexpr ExpectedApiCtors(ExpectedApiCtors&& src) noexcept( conjunction<disjunction<is_void<TValue>, is_nothrow_move_constructible<TValue>>, disjunction<is_void<TError>, is_nothrow_move_constructible<TError>>>::value) : ExpectedPayload<TValue, TError>{ ExpectedCtorBypass{}, std::move(src) } { } ExpectedApiCtors& operator=(ExpectedApiCtors const&) = default; ExpectedApiCtors& operator=(ExpectedApiCtors&&) = default; ~ExpectedApiCtors() = default; }; //! \tparam IsObject Is the error an object type? This is false in the case where \c TError is a possibly cv-qualified //! \c void. The allowance of cv-qualified types is why the partial specialization operates on this extra //! parameter instead of simply covering the case of `class ExpectedApiError<TValue, void>`. template <typename TValue, typename TError, bool IsObject = !is_void<TError>::value> class ExpectedApiError : public ExpectedApiCtors<TValue, TError> { using BaseType = ExpectedApiCtors<TValue, TError>; public: using BaseType::BaseType; template <typename... TArgs, typename = enable_if_t<is_constructible<TError, TArgs...>::value>> explicit ExpectedApiError(unexpect_t, TArgs&&... args) noexcept(is_nothrow_constructible<TError, TArgs...>::value) : BaseType{ unexpect, std::forward<TArgs>(args)... } { } constexpr TError const& error() const& noexcept { if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED)) invalid_expected_access_error(); return this->m_storage.error; } constexpr TError& error() & noexcept { if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED)) invalid_expected_access_error(); return this->m_storage.error; } constexpr TError const&& error() const&& noexcept { if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED)) invalid_expected_access_error(); return std::move(this->m_storage.error); } constexpr TError&& error() && noexcept { if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED)) invalid_expected_access_error(); return std::move(this->m_storage.error); } protected: //! \{ //! Called from \c ExpectedApiValue when a caller attempts to access a \c value requiring function, but the monad is //! in the error state. These functions throw their errors in the exception, but when \c TError is \c void, the //! \c m_storage.error is invalid (if both \c TValue and \c TError are \c void, \c m_storage does not exist at all). //! Handling this at the \c ExpectedApiError layer seems the most elegant approach. //! //! \pre `this->m_state == ExpectedState::eUNEXPECTED` [[noreturn]] void invalid_value_access() const& { CARB_FATAL_UNLESS( this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED"); invalid_expected_access(this->m_storage.error); } [[noreturn]] void invalid_value_access() & { CARB_FATAL_UNLESS( this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED"); invalid_expected_access(this->m_storage.error); } [[noreturn]] void invalid_value_access() && { CARB_FATAL_UNLESS( this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED"); invalid_expected_access(std::move(this->m_storage.error)); } [[noreturn]] void invalid_value_access() const&& { CARB_FATAL_UNLESS( this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED"); invalid_expected_access(std::move(this->m_storage.error)); } //! \} }; template <typename TValue, typename TError> class ExpectedApiError<TValue, TError, /*IsObject=*/false> : public ExpectedApiCtors<TValue, TError> { using BaseType = ExpectedApiCtors<TValue, TError>; using BaseType::BaseType; public: constexpr ExpectedApiError(unexpect_t) noexcept : BaseType{ unexpect } { } // NOTE: This from-unexpected constructor does not have a mirror in the `ExpectedApiError<..., IsObject=True>` // implementation, as that conversion constructor comes from the `expected` class. constexpr ExpectedApiError(unexpected<void> const&) noexcept : BaseType{ unexpect } { } constexpr void error() const& noexcept { if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED)) invalid_expected_access_error(); } constexpr void error() && noexcept { if (CARB_UNLIKELY(this->m_state != ExpectedState::eUNEXPECTED)) invalid_expected_access_error(); } protected: [[noreturn]] void invalid_value_access() const { CARB_FATAL_UNLESS( this->m_state == ExpectedState::eUNEXPECTED, "internal error: omni::expected::m_state must be eUNEXPECTED"); invalid_expected_access(ExpectedStorageVoid{}); } }; //! \tparam IsObject Is the value an object type? This is false in the case where \c TValue is a possibly cv-qualified //! \c void. The allowance of cv-qualified types is why the partial specialization operates on this extra //! parameter instead of simply covering the case of `class ExpectedApiValue<void, TError>`. template <typename TValue, typename TError, bool IsObject = !is_void<TValue>::value> class ExpectedApiValue : public ExpectedApiError<TValue, TError> { using BaseType = ExpectedApiError<TValue, TError>; using BaseType::BaseType; public: template <typename = std::enable_if_t<std::is_default_constructible<TValue>::value>> constexpr ExpectedApiValue() noexcept(std::is_nothrow_default_constructible<TValue>::value) : BaseType{ in_place } { } template <typename... TArgs, typename = enable_if_t<is_constructible<TValue, TArgs...>::value>> explicit ExpectedApiValue(in_place_t, TArgs&&... args) noexcept(is_nothrow_constructible<TValue, TArgs...>::value) : BaseType{ in_place, std::forward<TArgs>(args)... } { } constexpr TValue& value() & { if (this->m_state != ExpectedState::eSUCCESS) this->invalid_value_access(); else return this->m_storage.value; } constexpr TValue const& value() const& { if (this->m_state != ExpectedState::eSUCCESS) this->invalid_value_access(); else return this->m_storage.value; } constexpr TValue&& value() && { if (this->m_state != ExpectedState::eSUCCESS) std::move(*this).invalid_value_access(); else return std::move(this->m_storage.value); } constexpr TValue const&& value() const&& { if (this->m_state != ExpectedState::eSUCCESS) std::move(*this).invalid_value_access(); else return std::move(this->m_storage.value); } template <typename UValue> constexpr TValue value_or(UValue&& default_value) const& { if (this->m_state == ExpectedState::eSUCCESS) return this->m_storage.value; else return static_cast<TValue>(std::forward<UValue>(default_value)); } template <typename UValue> constexpr TValue value_or(UValue&& default_value) && { if (this->m_state == ExpectedState::eSUCCESS) return std::move(this->m_storage.value); else return static_cast<TValue>(std::forward<UValue>(default_value)); } constexpr TValue const& operator*() const& noexcept { return this->value(); } constexpr TValue& operator*() & noexcept { return this->value(); } constexpr TValue const&& operator*() const&& noexcept { return std::move(*this).value(); } constexpr TValue&& operator*() && noexcept { return std::move(*this).value(); } constexpr TValue const* operator->() const noexcept { return &this->value(); } constexpr TValue* operator->() noexcept { return &this->value(); } template <typename... TArgs> constexpr std::enable_if_t<std::is_nothrow_constructible<TValue, TArgs...>::value, TValue&> emplace(TArgs&&... args) noexcept { return this->emplace_impl(std::forward<TArgs>(args)...); } template <typename U, typename... TArgs> constexpr std::enable_if_t<std::is_nothrow_constructible<TValue, std::initializer_list<U>&, TArgs...>::value, TValue&> emplace( std::initializer_list<U>& arg0, TArgs&&... args) noexcept { return this->emplace_impl(arg0, std::forward<TArgs>(args)...); } private: template <typename... TArgs> constexpr TValue& emplace_impl(TArgs&&... args) { if (this->m_state == ExpectedState::eSUCCESS) expected_reinit(carb::cpp::addressof(this->m_storage.value), carb::cpp::addressof(this->m_storage.value), std::forward<TArgs>(args)...); else expected_reinit(carb::cpp::addressof(this->m_storage.error), carb::cpp::addressof(this->m_storage.value), std::forward<TArgs>(args)...); this->m_state = ExpectedState::eSUCCESS; return this->m_storage.value; } }; template <typename TValue, typename TError> class ExpectedApiValue<TValue, TError, /*IsObject=*/false> : public ExpectedApiError<TValue, TError> { using BaseType = ExpectedApiError<TValue, TError>; public: using BaseType::BaseType; constexpr explicit ExpectedApiValue() noexcept : BaseType{ in_place } { } constexpr explicit ExpectedApiValue(in_place_t) noexcept : BaseType{ in_place } { } ExpectedApiValue(ExpectedApiValue const&) = default; ExpectedApiValue(ExpectedApiValue&&) = default; ExpectedApiValue& operator=(ExpectedApiValue const&) = default; ExpectedApiValue& operator=(ExpectedApiValue&&) = default; ~ExpectedApiValue() = default; constexpr void value() & { if (this->m_state != ExpectedState::eSUCCESS) this->invalid_value_access(); } constexpr void value() const& { if (this->m_state != ExpectedState::eSUCCESS) this->invalid_value_access(); } constexpr void value() && { if (this->m_state != ExpectedState::eSUCCESS) std::move(*this).invalid_value_access(); } constexpr void value() const&& { if (this->m_state != ExpectedState::eSUCCESS) std::move(*this).invalid_value_access(); } constexpr void operator*() const noexcept { value(); } constexpr void emplace() noexcept { if (this->m_state != ExpectedState::eSUCCESS) { // Destroy the error state if one exists (note that if TError is also void, there is no m_storage) this->unsafe_destroy(); this->m_state = ExpectedState::eSUCCESS; } } }; template <typename TValue, typename TError> class ExpectedImpl : public ExpectedApiValue<TValue, TError> { using BaseType = ExpectedApiValue<TValue, TError>; static_assert(!std::is_same<in_place_t, std::remove_cv_t<TValue>>::value, "expected value can not be in_place_t"); static_assert(!std::is_same<in_place_t, std::remove_cv_t<TError>>::value, "expected error can not be in_place_t"); static_assert(!std::is_same<unexpect_t, std::remove_cv_t<TValue>>::value, "expected value can not be unexpect_t"); static_assert(!std::is_same<unexpect_t, std::remove_cv_t<TError>>::value, "expected error can not be unexpect_t"); public: using BaseType::BaseType; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Monadic Operations // // Functions like `expected::transform` are complicated by `void`, which is syntactically separate from a value type. // // The implementation is split into separate parts: `ExpectedMonadOpImpl`, which contains the implementation of all // // valid monadic operations and is specialized per type transform; `ExpectedOp___` per function, which chooses the // // proper type transformation. The grouping of functions this way seems slightly easier to read, but it still hairy. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MSC thinks some of the code branches in these implementations are unreachable. Specifically, it dislikes the use of a // return statement after a call to `carb::cpp::invoke(f)` (with no second parameter). The invoke implementation is // not marked `[[noreturn]]` or anything like that and the unit tests exercise that code path, so it is unclear why MSC // thinks that. This can be removed when MS fixes the bug. CARB_IGNOREWARNING_MSC_WITH_PUSH(4702) // unreachable code //! Each \c ExpectedMonadOpImpl contains the four monadic operations for \c expected (22.8.6.7). The template parameters //! represent the non-ref-qualified \c value_type and \c error_type parameters of the \c expected instance and result //! type; \c TValue and \c TError for the instance, \c RValue and \c RError for the result. The function implementation //! takes care of the ref-qualification of the expression category (e.g. the \c expected::transform ref-qualified as //! `&&` passes \c TExpected as `std::move(*this)` so the values are moved). //! //! Partial specializations of this place \c void for the type parameters, since the syntax for invoking and returning //! \c void is different than a non \c void value. There are 16 specializations of this template, but not all //! specializations contain implementations for all functions, as some of them are invalid. For example, it is not legal //! to change the type of \c error_type via the \c transform operation, so the \c ExpectedMonadOpImpl where //! `(TError == void) != (RError == void)` do not exist. template <typename TValue, typename TError, typename RValue, typename RError> struct ExpectedMonadOpImpl { template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, TError> transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, TError>( in_place, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value())); else return omni::expected<RValue, TError>(unexpect, std::forward<TExpected>(ex).error()); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, RError> and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()); else return omni::expected<RValue, RError>(unexpect, std::forward<TExpected>(ex).error()); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, RError> transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value()); else return omni::expected<RValue, RError>( unexpect, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error())); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, RError> or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value()); else return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()); } }; template <typename TError, typename RError> struct ExpectedMonadOpImpl<void, TError, void, RError> { template <typename FTransform, typename TExpected> static constexpr omni::expected<void, TError> transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { carb::cpp::invoke(std::forward<FTransform>(f)); return omni::expected<void, TError>(in_place); } else { return omni::expected<void, TError>(unexpect, std::forward<TExpected>(ex).error()); } } template <typename FTransform, typename TExpected> static constexpr omni::expected<void, RError> and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f)); else return omni::expected<void, RError>(unexpect, std::forward<TExpected>(ex).error()); } template <typename FTransform, typename TExpected> static constexpr omni::expected<void, RError> transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<void, RError>(in_place); else return omni::expected<void, RError>( unexpect, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error())); } template <typename FTransform, typename TExpected> static constexpr omni::expected<void, RError> or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<void, RError>(in_place); else return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()); } }; template <typename TValue, typename RValue> struct ExpectedMonadOpImpl<TValue, void, RValue, void> { template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, void>( in_place, carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value())); else return omni::expected<RValue, void>(unexpect); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()); else return omni::expected<RValue, void>(unexpect); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value()); } else { carb::cpp::invoke(std::forward<FTransform>(f)); return omni::expected<RValue, void>(unexpect); } } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value()); else return carb::cpp::invoke(std::forward<FTransform>(f)); } }; template <typename TValue, typename TError, typename RError> struct ExpectedMonadOpImpl<TValue, TError, void, RError> { template <typename FTransform, typename TExpected> static constexpr omni::expected<void, TError> transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()); return omni::expected<void, TError>(in_place); } else { return omni::expected<void, TError>(unexpect, std::forward<TExpected>(ex).error()); } } template <typename FTransform, typename TExpected> static constexpr omni::expected<void, RError> and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()); else return omni::expected<void, RError>(unexpect, std::forward<TExpected>(ex).error()); } }; template <typename TError, typename RValue, typename RError> struct ExpectedMonadOpImpl<void, TError, RValue, RError> { template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, TError> transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, TError>(in_place, carb::cpp::invoke(std::forward<FTransform>(f))); else return omni::expected<RValue, TError>(unexpect, std::forward<TExpected>(ex).error()); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, RError> and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f)); else return omni::expected<RValue, RError>(unexpect, std::forward<TExpected>(ex).error()); } }; template <typename TValue> struct ExpectedMonadOpImpl<TValue, void, void, void> { template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()); return TReturn(in_place); } else { return TReturn(unexpect); } } template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).value()); else return TReturn(unexpect); } }; template <typename RValue> struct ExpectedMonadOpImpl<void, void, RValue, void> { template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, void>(in_place, carb::cpp::invoke(std::forward<FTransform>(f))); else return omni::expected<RValue, void>(unexpect); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f)); else return omni::expected<RValue, void>(unexpect); } }; template <typename TValue, typename TError, typename RValue> struct ExpectedMonadOpImpl<TValue, TError, RValue, void> { template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value()); } else { carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()); return omni::expected<RValue, void>(unexpect); } } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, void> or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, void>(in_place, std::forward<TExpected>(ex).value()); else return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()); } }; template <typename TError> struct ExpectedMonadOpImpl<void, TError, void, void> { template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { return TReturn(in_place); } else { carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()); return TReturn(unexpect); } } template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return TReturn(in_place); else return carb::cpp::invoke(std::forward<FTransform>(f), std::forward<TExpected>(ex).error()); } }; template <typename TValue, typename RValue, typename RError> struct ExpectedMonadOpImpl<TValue, void, RValue, RError> { template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, RError> transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value()); else return omni::expected<RValue, RError>(unexpect, carb::cpp::invoke(std::forward<FTransform>(f))); } template <typename FTransform, typename TExpected> static constexpr omni::expected<RValue, RError> or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<RValue, RError>(in_place, std::forward<TExpected>(ex).value()); else return carb::cpp::invoke(std::forward<FTransform>(f)); } }; template <typename RError> struct ExpectedMonadOpImpl<void, void, void, RError> { template <typename FTransform, typename TExpected> static constexpr omni::expected<void, RError> transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<void, RError>(in_place); else return omni::expected<void, RError>(unexpect, carb::cpp::invoke(std::forward<FTransform>(f))); } template <typename FTransform, typename TExpected> static constexpr omni::expected<void, RError> or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return omni::expected<void, RError>(in_place); else return carb::cpp::invoke(std::forward<FTransform>(f)); } }; template <> struct ExpectedMonadOpImpl<void, void, void, void> { template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn transform(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { carb::cpp::invoke(std::forward<FTransform>(f)); return TReturn(in_place); } else { return TReturn(unexpect); } } template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn and_then(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return carb::cpp::invoke(std::forward<FTransform>(f)); else return TReturn(unexpect); } template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn transform_error(FTransform&& f, TExpected&& ex) { if (ex.has_value()) { return TReturn(in_place); } else { carb::cpp::invoke(std::forward<FTransform>(f)); return TReturn(unexpect); } } template <typename FTransform, typename TExpected, typename TReturn = omni::expected<void, void>> static constexpr TReturn or_else(FTransform&& f, TExpected&& ex) { if (ex.has_value()) return TReturn(in_place); else return carb::cpp::invoke(std::forward<FTransform>(f)); } }; template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>> struct ExpectedOpTransform { }; template <typename FTransform, typename TValue, typename TError, typename RefExpected> struct ExpectedOpTransform<FTransform, omni::expected<TValue, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>>> : ExpectedMonadOpImpl<TValue, TError, carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>, TError> { }; template <typename FTransform, typename TError, typename RefExpected> struct ExpectedOpTransform<FTransform, omni::expected<void, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>> : ExpectedMonadOpImpl<void, TError, carb::cpp::invoke_result_t<FTransform>, TError> { }; template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>> struct ExpectedOpAndThen { template <typename UExpected> static constexpr void and_then(FTransform&&, UExpected&&) { // HELLO! If you're seeing one of these failures, that means you called `.and_then` with a callable that can't // be called with the `value_type` of the expected. This base template is only used through misuse of that // member function, so one of these `static_assert`s will always hit and give a slightly better diagnostic. static_assert(is_void<typename TExpected::value_type>::value, "function provided to `and_then` must accept the `expected::value_type`"); static_assert(!is_void<typename TExpected::value_type>::value, "function provided to `and_then` must accept no parameters"); } }; template <typename TExpected, typename UExpected> struct ExpectedOpAndThenImpl { template <typename FTransform, typename VExpected> static constexpr void and_then(FTransform&&, VExpected&&) { // HELLO! If you're seeing this failure, it means the function provided to `.and_then` did not return an // `expected` when called with the `value_type`. static_assert(is_void<FTransform>::value, "function provided to `and_then` must return an `expected<T, E>`"); } }; template <typename TValue, typename TError, typename UValue, typename UError> struct ExpectedOpAndThenImpl<omni::expected<TValue, TError>, omni::expected<UValue, UError>> : ExpectedMonadOpImpl<TValue, TError, UValue, UError> { }; template <typename FTransform, typename TValue, typename TError, typename RefExpected> struct ExpectedOpAndThen<FTransform, omni::expected<TValue, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>>> : ExpectedOpAndThenImpl<omni::expected<TValue, TError>, carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().value())>> { }; template <typename FTransform, typename TError, typename RefExpected> struct ExpectedOpAndThen<FTransform, omni::expected<void, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>> : ExpectedOpAndThenImpl<omni::expected<void, TError>, carb::cpp::invoke_result_t<FTransform>> { }; template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>> struct ExpectedOpTransformError { }; template <typename FTransform, typename TValue, typename TError, typename RefExpected> struct ExpectedOpTransformError<FTransform, omni::expected<TValue, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>>> : ExpectedMonadOpImpl<TValue, TError, TValue, carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>> { }; template <typename FTransform, typename TValue, typename RefExpected> struct ExpectedOpTransformError<FTransform, omni::expected<TValue, void>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>> : ExpectedMonadOpImpl<TValue, void, TValue, carb::cpp::invoke_result_t<FTransform>> { }; template <typename FTransform, typename TExpected, typename RefExpected, typename = void_t<>> struct ExpectedOpOrElse { template <typename UExpected> static constexpr void or_else(FTransform&&, UExpected&&) { // HELLO! If you're seeing one of these failures, that means you called `.or_else` with a callable that can't // be called with the `value_type` of the expected. This base template is only used through misuse of that // member function, so one of these `static_assert`s will always hit and give a slightly better diagnostic. static_assert(is_void<typename TExpected::error_type>::value, "function provided to `or_else` must accept the `expected::value_type`"); static_assert(!is_void<typename TExpected::error_type>::value, "function provided to `or_else` must accept no parameters"); } }; template <typename TExpected, typename UExpected> struct ExpectedOpOrElseImpl { template <typename FTransform, typename VExpected> static constexpr void or_else(FTransform&&, VExpected&&) { // HELLO! If you're seeing this failure, it means the function provided to `.or_else` did not return an // `expected` when called with the `value_type`. static_assert(is_void<FTransform>::value, "function provided to `or_else` must return an `expected<T, E>`"); } }; template <typename TValue, typename TError, typename UValue, typename UError> struct ExpectedOpOrElseImpl<omni::expected<TValue, TError>, omni::expected<UValue, UError>> : ExpectedMonadOpImpl<TValue, TError, UValue, UError> { }; template <typename FTransform, typename TValue, typename TError, typename RefExpected> struct ExpectedOpOrElse<FTransform, omni::expected<TValue, TError>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>>> : ExpectedOpOrElseImpl<omni::expected<TValue, TError>, carb::cpp::invoke_result_t<FTransform, decltype(std::declval<RefExpected>().error())>> { }; template <typename FTransform, typename TValue, typename RefExpected> struct ExpectedOpOrElse<FTransform, omni::expected<TValue, void>, RefExpected, void_t<carb::cpp::invoke_result_t<FTransform>>> : ExpectedOpOrElseImpl<omni::expected<TValue, void>, carb::cpp::invoke_result_t<FTransform>> { }; CARB_IGNOREWARNING_MSC_POP //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Comparison Functions // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename TExpected1, typename TExpected2, typename = void_t<>> struct ExpectedComparer { }; template <typename TValue1, typename TError1, typename TValue2, typename TError2> struct ExpectedComparer< expected<TValue1, TError1>, expected<TValue2, TError2>, std::enable_if_t<negation<disjunction<is_void<TValue1>, is_void<TError1>, is_void<TValue2>, is_void<TError2>>>::value>> { template <typename TExpectedLhs, typename TExpectedRhs> static constexpr bool eq(TExpectedLhs const& lhs, TExpectedRhs const& rhs) { if (lhs.has_value() && rhs.has_value()) return lhs.value() == rhs.value(); else if (!lhs.has_value() && !rhs.has_value()) return lhs.error() == rhs.error(); else return false; } }; template <typename TValue1, typename TValue2> struct ExpectedComparer<expected<TValue1, void>, expected<TValue2, void>, enable_if_t<negation<disjunction<is_void<TValue1>, is_void<TValue2>>>::value>> { template <typename TExpectedLhs, typename TExpectedRhs> static constexpr bool eq(TExpectedLhs const& lhs, TExpectedRhs const& rhs) { if (lhs.has_value() && rhs.has_value()) return lhs.value() == rhs.value(); else if (!lhs.has_value() && !rhs.has_value()) return true; else return false; } }; template <typename TError1, typename TError2> struct ExpectedComparer<expected<void, TError1>, expected<void, TError2>, enable_if_t<negation<disjunction<is_void<TError1>, is_void<TError2>>>::value>> { template <typename TExpectedLhs, typename TExpectedRhs> static constexpr bool eq(TExpectedLhs const& lhs, TExpectedRhs const& rhs) { if (lhs.has_value() && rhs.has_value()) return true; else if (!lhs.has_value() && !rhs.has_value()) return lhs.error() == rhs.error(); else return false; } }; template <> struct ExpectedComparer<expected<void, void>, expected<void, void>, void> { template <typename TExpected> static constexpr bool eq(TExpected const& lhs, TExpected const& rhs) { return lhs.has_value() == rhs.has_value(); } }; template <typename TErrorLhs, typename TErrorRhs> struct ExpectedUnexpectedComparer { template <typename TExpected, typename TUnexpected> static constexpr bool eq(TExpected const& lhs, TUnexpected const& rhs) { return !lhs.has_value() && static_cast<bool>(lhs.error() == rhs.error()); } }; template <> struct ExpectedUnexpectedComparer<void, void> { template <typename TExpected> static constexpr bool eq(TExpected const& lhs, unexpected<void> const&) { return !lhs.has_value(); } }; } // namespace detail } // namespace omni //! \endcond
omniverse-code/kit/include/omni/detail/ParamPack.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 //! \cond DEV //! \file //! \brief Contains the \c ParamPack helper type. namespace omni { namespace detail { //! Wrapper type containing a pack of template parameters. This is only useful in metaprogramming. template <typename... Args> struct ParamPack { }; } // namespace detail } // namespace omni //! \endcond
omniverse-code/kit/include/omni/detail/ConvertsFromAnyCvRef.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 "../../carb/cpp/TypeTraits.h" #include <type_traits> //! \cond DEV namespace omni { namespace detail { //! This is defined by the exposition-only concept "converts-from-any-cvref" in 22.5.3.2/1 [optional.ctor]. Generally //! tests if a given \c T can be constructed from a \c W by value, const value, reference, or const reference. This is //! used for wrapper monads like \c optional and \c expected to disquality overloads in cases of ambiguity with copy or //! move constructors. For example, constructing `optional<optional<string>> x{optional<string>{"hi"}}` should use the //! value-constructing overload (22.5.3.2/23) instead of the converting constructor (22.5.3.2/33). Note that the end //! result is the same. template <typename T, typename W> using ConvertsFromAnyCvRef = carb::cpp::disjunction<std::is_constructible<T, W&>, std::is_convertible<W&, T>, std::is_constructible<T, W>, std::is_convertible<W, T>, std::is_constructible<T, W const&>, std::is_convertible<W const&, T>, std::is_constructible<T, W const>, std::is_convertible<W const, T>>; } // namespace detail } // namespace omni //! \endcond
omniverse-code/kit/include/omni/detail/FunctionImpl.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. // #pragma once #include "../../carb/Defines.h" #include "../../carb/Memory.h" #include "../../carb/cpp/Functional.h" #include "../../carb/cpp/TypeTraits.h" #include "../../carb/detail/NoexceptType.h" #include "../core/Assert.h" #include "../core/IObject.h" #include "../core/ResultError.h" #include <array> #include <cstddef> #include <cstdint> #include <cstring> #include <functional> #include <memory> #include <new> #include <utility> namespace omni { template <typename Signature> class function; //! \cond DEV namespace detail { CARB_DETAIL_PUSH_IGNORE_NOEXCEPT_TYPE() // NOTE: GCC added a warning about the use of memcpy and memset on class types with non-trivial copy-assignment. In most // cases, this is a valid warning that should be paid attention to. #if CARB_COMPILER_GNUC && __GNUC__ >= 8 # define OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS() CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wclass-memaccess") # define OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS() CARB_IGNOREWARNING_GNUC_POP #else # define OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS() # define OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS() #endif using carb::cpp::bool_constant; using carb::cpp::conjunction; using carb::cpp::disjunction; using carb::cpp::is_invocable_r; using carb::cpp::negation; using carb::cpp::void_t; using omni::core::Result; //! Called when attempting to invoke a function that is unbound. It will throw \c std::bad_function_call if exceptions //! are enabled or terminate immediately. [[noreturn]] inline void null_function_call() { #if CARB_EXCEPTIONS_ENABLED throw std::bad_function_call(); #else OMNI_FATAL_UNLESS(false, "Attempt to call null function"); std::terminate(); // Enforce [[noreturn]] #endif } //! Called when an internal function operation returns a non-success error case. This function will throw a //! \c ResultError if exceptions are enabled or terminate immediately. [[noreturn]] inline void function_operation_failure(Result rc, char const* msg) { #if CARB_EXCEPTIONS_ENABLED throw core::ResultError(rc, msg); #else OMNI_FATAL_UNLESS(false, "%s: %s", msg, core::resultToString(rc)); std::terminate(); // Enforce [[noreturn]] #endif } //! Metafunction to check if \c T is a \c omni::function or not. template <typename T> struct IsFunction : std::false_type { }; template <typename Signature> struct IsFunction<omni::function<Signature>> : std::true_type { }; constexpr std::size_t kFUNCTION_BUFFER_SIZE = 16U; constexpr std::size_t kFUNCTION_BUFFER_ALIGN = alignof(std::max_align_t); constexpr std::size_t kFUNCTION_SIZE = 32U; //! \see FunctionBuffer struct FunctionUnusedBase { }; //! \see FunctionBuffer struct FunctionUnused : virtual FunctionUnusedBase { }; //! This data type stores the content of the functor or a pointer to it. Only the \c raw member is used by the //! implementation, but the other union members are here to make sure size and alignment stay as expected even when //! strange types are used. union alignas(kFUNCTION_BUFFER_ALIGN) FunctionBuffer { std::array<char, kFUNCTION_BUFFER_SIZE> raw; void* pointer; void (*pfunc)(); void (FunctionUnused::*pmemfunc)(); std::max_align_t FunctionUnused::*pmemsel; }; static_assert(sizeof(FunctionBuffer) == kFUNCTION_BUFFER_SIZE, "Actual size of FunctionBuffer does not match goal"); static_assert(alignof(FunctionBuffer) == kFUNCTION_BUFFER_ALIGN, "Actual align of FunctionBuffer does not match goal"); struct FunctionCharacteristics { //! The size of this instance. This is useful for ABI compatibility if needs expand. size_t _size; //! Called on function destructor. If the target functor is trivially-destructible, then this should be \c nullptr //! to make nothing happen on destruction. void (*destroy)(FunctionBuffer* self); //! Called when a function is copied. If the target functor is trivially-relocatable, then this should be \c nullptr //! so the buffer is copied by \c memcpy. Result (*clone)(FunctionBuffer* target, FunctionBuffer const* source); constexpr FunctionCharacteristics(void (*destroy_)(FunctionBuffer*), Result (*clone_)(FunctionBuffer*, FunctionBuffer const*)) noexcept : _size{ sizeof(FunctionCharacteristics) }, destroy{ destroy_ }, clone{ clone_ } { } }; //! This holds the core data of the \c omni::function type. struct FunctionData { FunctionBuffer m_buffer; //! The entry point into the function. The real type is `TReturn(*)(FunctionBuffer const*, TArgs...)`. void* m_trampoline; //! The management of the erased target of this function. This will be null in cases where the copy constructor and //! destructor are trivial, meaning \c memcpy and \c memset are acceptable substitutes. FunctionCharacteristics const* m_characteristics; explicit FunctionData(std::nullptr_t) noexcept { clear_unsafe(); } FunctionData(FunctionData const& src) { // NOTE: Another approach could be to copy m_trampoline and m_characteristics, then conditionally memcpy the // m_buffer. However, the current approach of unconditional memcpy makes the operation twice as fast. copy_from_unsafe(src); if (m_characteristics && m_characteristics->clone) { if (auto rc = m_characteristics->clone(&m_buffer, &src.m_buffer)) { clear_unsafe(); function_operation_failure(rc, "failed to clone function"); } } } FunctionData(FunctionData&& src) noexcept { copy_from_unsafe(src); src.clear_unsafe(); } //! Initialize through binding with the given \a assigner and functor \a f. //! //! \tparam Assigner The assigner type for this function, picked through `FunctionAssigner<F>`. template <typename Assigner, typename F> FunctionData(Assigner assigner, F&& f) { if (auto rc = bind_unsafe(assigner, std::forward<F>(f))) { function_operation_failure(rc, "failed to bind to functor"); } } FunctionData& operator=(FunctionData const& src) { if (this == &src) return *this; // The copy constructor can throw, but the move-assignment can not, so we get the proper commit or rollback // semantics return operator=(FunctionData{ src }); } FunctionData& operator=(FunctionData&& src) noexcept { if (this == &src) return *this; reset(); copy_from_unsafe(src); src.clear_unsafe(); return *this; } ~FunctionData() noexcept { reset(); } //! Clear the contents of this instance without checking. //! //! \pre No cleanup is performed, so the responsibility for doing this must have been taken care of (`reset`) or //! deferred (move-assigned from). void clear_unsafe() noexcept { OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS() std::memset(this, 0, sizeof(*this)); OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS() } //! Copy the contents of \a src to this instance without clearing. //! //! \pre `this != &src` //! \pre No cleanup is performed, so the responsibility for doing so must have been taken care of (`reset`) or //! deferred (copied to another instance). //! \post The copied-from \a src cannot be destructed in the normal manner. void copy_from_unsafe(FunctionData const& src) noexcept { OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS() std::memcpy(this, &src, sizeof(*this)); OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS() } //! Assign the function or functor \a f with the \c Assigner. //! //! \tparam Assigner The appropriate \c FunctionAssigner type for the \c FunctionTraits and \c F we are trying to //! bind. //! \pre This function must be either uninitialized or otherwise clear. This function will overwrite any state //! without checking if it is engaged ahead of time. As such, it should only be called from a constructor or //! after a \c reset. template <typename Assigner, typename F> CARB_NODISCARD Result bind_unsafe(Assigner, F&& f) { if (!Assigner::is_active(f)) { clear_unsafe(); return core::kResultSuccess; } if (Result rc = Assigner::initialize(m_buffer, std::forward<F>(f))) return rc; m_trampoline = reinterpret_cast<void*>(&Assigner::trampoline); m_characteristics = Assigner::characteristics(); return core::kResultSuccess; } void reset() noexcept { if (m_characteristics && m_characteristics->destroy) m_characteristics->destroy(&m_buffer); clear_unsafe(); } void swap(FunctionData& other) noexcept { if (this == &other) return; std::array<char, sizeof(*this)> temp; std::memcpy(temp.data(), this, sizeof(temp)); std::memcpy(this, &other, sizeof(*this)); OMNI_FUNCTION_PUSH_IGNORE_CLASS_MEMACCESS() std::memcpy(&other, temp.data(), sizeof(other)); OMNI_FUNCTION_POP_IGNORE_CLASS_MEMACCESS() } }; static_assert(sizeof(FunctionData) == kFUNCTION_SIZE, "FunctionData incorrect size"); static_assert(alignof(FunctionData) == kFUNCTION_BUFFER_ALIGN, "FunctionData incorrect alignment"); struct TrivialFunctorCharacteristics { static FunctionCharacteristics const* characteristics() noexcept { return nullptr; } }; template <typename Signature> struct FunctionTraits; template <typename TReturn, typename... TArgs> struct FunctionTraits<TReturn(TArgs...)> { using result_type = TReturn; }; //! The "assigner" for a function is used in bind operations. It is responsible for managing copy and delete operations, //! detecting if a binding target is non-null, and creating a trampoline function to bridge the gap between the function //! signature `TReturn(TArgs...)` and the target function signature. //! //! When the bind \c Target is not bindable-to, this base case is matched, which has no member typedef \c type. This is //! used in \c omni::function to disqualify types which cannot be bound to. When the \c Target is bindable (see the //! partial specializations below), the member \c type is a structure with the following static functions: //! //! * `TReturn trampoline(FunctionBuffer const*, TArgs...)` -- The trampoline function performs an arbitrary action to //! convert `TArgs...` and `TReturn` of the actual call. //! * `FunctionCharacteristics const* characteristics() noexcept` -- Give the singleton which describes the managment //! operations for this target. //! * `bool is_active(Target const&) noexcept` -- Detects if the \c Target is null or not. //! * `Result initialize(FunctionBuffer&, Target&&)` -- Initializes the buffer from the provided target. //! //! See \c FunctionAssigner template <typename TTraits, typename Target, typename = void> struct FunctionAssignerImpl { }; //! Binding for any pointer-like type. template <typename TReturn, typename... TArgs, typename TPointer> struct FunctionAssignerImpl<FunctionTraits<TReturn(TArgs...)>, TPointer, std::enable_if_t<conjunction<is_invocable_r<TReturn, TPointer, TArgs...>, disjunction<std::is_pointer<TPointer>, std::is_member_function_pointer<TPointer>, std::is_member_object_pointer<TPointer>>>::value>> { struct type : TrivialFunctorCharacteristics { static TReturn trampoline(FunctionBuffer const* buf, TArgs... args) { auto realfn = const_cast<TPointer*>(reinterpret_cast<TPointer const*>(buf->raw.data())); // NOTE: The use of invoke_r here is for cases where TReturn is void, but `(*realfn)(args...)` is not. It is // fully qualified to prevent ADL ambiguity with std::invoke_r when any of TArgs reside in the std // namespace. return ::carb::cpp::invoke_r<TReturn>(*realfn, std::forward<TArgs>(args)...); } CARB_NODISCARD static Result initialize(FunctionBuffer& buffer, TPointer fn) noexcept { static_assert(sizeof(fn) <= sizeof(buffer.raw), "Function too large to fit in buffer"); std::memcpy(buffer.raw.data(), &fn, sizeof(fn)); return 0; } static bool is_active(TPointer func) noexcept { return bool(func); } }; }; //! Binding to a class or union type with `operator()`. template <typename TReturn, typename... TArgs, typename Functor> struct FunctionAssignerImpl<FunctionTraits<TReturn(TArgs...)>, Functor, std::enable_if_t<conjunction< // do not match exactly this function negation<std::is_same<Functor, omni::function<TReturn(TArgs...)>>>, // must be a class or union type (not a pointer or reference to a function) disjunction<std::is_class<Functor>, std::is_union<Functor>>, // must be callable is_invocable_r<TReturn, Functor&, TArgs...>>::value>> { struct InBuffer : TrivialFunctorCharacteristics { static TReturn trampoline(FunctionBuffer const* buf, TArgs... args) { auto real = const_cast<Functor*>(reinterpret_cast<Functor const*>(buf->raw.data())); // NOTE: invoke_r is fully qualified to prevent ADL ambiguity with std::invoke_r when any of TArgs reside in // the std namespace. return ::carb::cpp::invoke_r<TReturn>(*real, std::forward<TArgs>(args)...); } template <typename F> CARB_NODISCARD static Result initialize(FunctionBuffer& buffer, F&& func) { static_assert(sizeof(func) <= sizeof(buffer), "Provided functor is too large to fit in buffer"); // GCC 7.1-7.3 has a compiler bug where a diagnostic for uninitialized `func` is emitted in cases where it refers to a // lambda expression which has been `forward`ed multiple times. This is erroneous in GCC 7.1-7.3, but other compilers // complaining about uninitialized access might have a valid point. #if CARB_COMPILER_GNUC && !CARB_TOOLCHAIN_CLANG && __GNUC__ == 7 && __GNUC_MINOR__ <= 3 CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wmaybe-uninitialized") #endif std::memcpy(buffer.raw.data(), &func, sizeof(func)); #if CARB_COMPILER_GNUC && !CARB_TOOLCHAIN_CLANG && __GNUC__ == 7 && __GNUC_MINOR__ <= 3 CARB_IGNOREWARNING_GNUC_POP #endif return 0; } static constexpr bool is_active(Functor const&) noexcept { return true; } }; struct InBufferWithDestructor : InBuffer { static FunctionCharacteristics const* characteristics() noexcept { static FunctionCharacteristics const instance{ [](FunctionBuffer* self) { reinterpret_cast<Functor*>(self->raw.data())->~Functor(); }, nullptr, }; return &instance; } }; struct HeapAllocated { template <typename... AllocArgs> static Functor* make(AllocArgs&&... args) { std::unique_ptr<void, void (*)(void*)> tmp{ carb::allocate(sizeof(Functor), alignof(Functor)), &carb::deallocate }; if (!tmp) return nullptr; new (tmp.get()) Functor{ std::forward<AllocArgs>(args)... }; return static_cast<Functor*>(tmp.release()); } CARB_NODISCARD static Result clone(FunctionBuffer* target, FunctionBuffer const* source) { if (auto created = make(*static_cast<Functor const*>(source->pointer))) { target->pointer = static_cast<void*>(created); return core::kResultSuccess; } else { return core::kResultFail; } } static void destroy(FunctionBuffer* buffer) noexcept { auto real = static_cast<Functor*>(buffer->pointer); real->~Functor(); carb::deallocate(real); } static TReturn trampoline(FunctionBuffer const* buf, TArgs... args) { auto real = static_cast<Functor*>(buf->pointer); return ::carb::cpp::invoke_r<TReturn>(*real, std::forward<TArgs>(args)...); } template <typename Signature> static bool is_active(omni::function<Signature> const& f) noexcept { // omni::function derives from FunctionData, so this is a correct cast, even though it is not defined yet. // The use of reinterpret_cast is required here because omni::function derives privately. auto underlying = reinterpret_cast<FunctionData const*>(&f); return underlying->m_trampoline; } template <typename Signature> static bool is_active(std::function<Signature> const& f) noexcept { return bool(f); } template <typename UFunctor> static bool is_active(UFunctor const&) noexcept { return true; } template <typename UFunctor> CARB_NODISCARD static Result initialize(FunctionBuffer& buffer, UFunctor&& func) { if (auto created = make(std::forward<UFunctor>(func))) { buffer.pointer = static_cast<void*>(created); return core::kResultSuccess; } else { // we can't guarantee that anything in make sets the error code, so use the generic "fail" return core::kResultFail; } } static FunctionCharacteristics const* characteristics() noexcept { static FunctionCharacteristics const instance{ &destroy, &clone, }; return &instance; } }; // clang-format off using type = std::conditional_t< conjunction<bool_constant<(sizeof(Functor) <= kFUNCTION_BUFFER_SIZE && kFUNCTION_BUFFER_ALIGN % alignof(Functor) == 0)>, // we're really looking for relocatability, but trivial copy will do for now std::is_trivially_copyable<Functor> >::value, std::conditional_t<std::is_trivially_destructible<Functor>::value, InBuffer, InBufferWithDestructor>, HeapAllocated>; // clang-format on }; //! Choose the proper function assigner from its properties. This will fail in a SFINAE-safe manner if the \c Target is //! not bindable to a function with the given \c TTraits. template <typename TTraits, typename Target> using FunctionAssigner = typename FunctionAssignerImpl<TTraits, std::decay_t<Target>>::type; CARB_DETAIL_POP_IGNORE_NOEXCEPT_TYPE() } // namespace detail //! \endcond } // namespace omni
omniverse-code/kit/include/omni/detail/PointerIterator.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 Provides @c omni::detail::PointerIterator class for constructing pointer-based iterators. #pragma once #include "../../carb/Defines.h" #include <iterator> #include <type_traits> #if CARB_HAS_CPP20 # include <concepts> #endif namespace omni { //! Internal implementation details namespace. namespace detail { //! @class PointerIterator //! //! This iterator adapter wraps a pointer type into a class. It does not change the semantics of any operations from the //! fundamental logic of pointers. There are no bounds checks, there is no additional safety. //! //! @tparam TPointer The pointer to base this wrapper on. The underlying value type of the pointer can be //! const-qualified. //! @tparam TContainer The container type this iterator iterates over. This is useful to make types distinct, even in //! cases where @c TPointer would be identical; for example, a @c string vs a @c vector<char>. This //! is allowed to be @c void for cases where there is no underlying container. //! //! @code //! // This is meant to be used on contiguous containers where returning a pointer from @c begin and @c end would be //! // inappropriate. //! template <typename T> //! class MyContainer //! { //! public: //! using iterator = detail::PointerIterator<T*, MyContainer>; //! using const_iterator = detail::PointerIterator<T const*, MyContainer>; //! //! // ... //! //! iterator begin() { return iterator{data()}; } //! }; //! @endcode template <typename TPointer, typename TContainer> class PointerIterator { static_assert(std::is_pointer<TPointer>::value, "TPointer must be a pointer type"); private: using underlying_traits_type = std::iterator_traits<TPointer>; public: //! The underlying value that dereferencing this iterator returns. Note that this is not const-qualified; the //! @c const_iterator for a container will still return @c T. using value_type = typename underlying_traits_type::value_type; //! The reference type dereferencing this iterator returns. This is const-qualified, so @c iterator for a container //! will return @c T& and @c const_iterator will return `const T&`. using reference = typename underlying_traits_type::reference; //! The underlying pointer type @c operator->() returns. This is const-qualified, so @c iterator for a container //! will return @c T* and @c const_iterator will return `const T*`. using pointer = typename underlying_traits_type::pointer; //! The type used to represent the distance between two iterators. This will always be @c std::ptrdiff_t. using difference_type = typename underlying_traits_type::difference_type; //! The category of this iterator. This will always be @c std::random_access_iterator_tag. using iterator_category = typename underlying_traits_type::iterator_category; #if CARB_HAS_CPP20 //! The concept this iterator models. This will always be @c std::contiguous_iterator_tag. using iterator_concept = typename underlying_traits_type::iterator_concept; #endif public: //! Default construction of a pointer-iterator results in an iterator pointing to @c nullptr. constexpr PointerIterator() noexcept : m_ptr{ nullptr } { } //! Create an iterator from @a src pointer. explicit constexpr PointerIterator(pointer src) noexcept : m_ptr{ src } { } //! Instances are trivially copy-constructible. PointerIterator(const PointerIterator&) = default; //! Instances are trivially move-constructible. PointerIterator(PointerIterator&&) = default; //! Instances are trivially copyable. PointerIterator& operator=(const PointerIterator&) = default; //! Instances are trivially movable. PointerIterator& operator=(PointerIterator&&) = default; //! Instances are trivially destructible. ~PointerIterator() = default; // clang-format off //! Converting constructor to allow conversion from a non-const iterator type to a const iterator type. Generally, //! this allows a @c TContainer::iterator to become a @c TContainer::const_iterator. //! //! This constructor is only enabled if: //! //! 1. The @c TContainer for the two types is the same. //! 2. The @c TPointer is different from @c UPointer (there is a conversion which needs to occur). //! 3. A pointer to an array of the @a src const-qualified @c value_type (aka `remove_reference_t<reference>`) is //! convertible to an array of this const-qualified @c value_type. This restricts conversion of iterators from a //! derived to a base class pointer type. template <typename UPointer, typename = std::enable_if_t < !std::is_same<TPointer, UPointer>::value && std::is_convertible < std::remove_reference_t<typename PointerIterator<UPointer, TContainer>::reference>(*)[], std::remove_reference_t<reference>(*)[] >::value > > constexpr PointerIterator(const PointerIterator<UPointer, TContainer>& src) noexcept : m_ptr{src.operator->()} { } // clang-format on //! Dereference this iterator to get its value. constexpr reference operator*() const noexcept { return *m_ptr; } //! Get the value at offset @a idx from this iterator. Negative values are supported to reference behind this //! instance. constexpr reference operator[](difference_type idx) const noexcept { return m_ptr[idx]; } //! Get a pointer to the value. constexpr pointer operator->() const noexcept { return m_ptr; } //! Move the iterator forward by one. constexpr PointerIterator& operator++() noexcept { ++m_ptr; return *this; } //! Move the iterator forward by one, but return the previous position. constexpr PointerIterator operator++(int) noexcept { PointerIterator save{ *this }; ++m_ptr; return save; } //! Move the iterator backwards by one. constexpr PointerIterator& operator--() noexcept { --m_ptr; return *this; } //! Move the iterator backwards by one, but return the previous position. constexpr PointerIterator operator--(int) noexcept { PointerIterator save{ *this }; --m_ptr; return save; } //! Move the iterator forward by @a dist. constexpr PointerIterator& operator+=(difference_type dist) noexcept { m_ptr += dist; return *this; } //! Get a new iterator pointing @a dist elements forward from this one. constexpr PointerIterator operator+(difference_type dist) const noexcept { return PointerIterator{ m_ptr + dist }; } //! Move the iterator backwards by @a dist. constexpr PointerIterator& operator-=(difference_type dist) noexcept { m_ptr -= dist; return *this; } //! Get a new iterator pointing @a dist elements backwards from this one. constexpr PointerIterator operator-(difference_type dist) const noexcept { return PointerIterator{ m_ptr - dist }; } private: pointer m_ptr; }; //! Get an iterator @a dist elements forward from @a iter. template <typename TPointer, typename TContainer> inline constexpr PointerIterator<TPointer, TContainer> operator+( typename PointerIterator<TPointer, TContainer>::difference_type dist, const PointerIterator<TPointer, TContainer>& iter) noexcept { return iter + dist; } //! Get the distance between iterators @a lhs and @a rhs. If `lhs < rhs`, this value will be negative. template <typename TPointer, typename UPointer, typename TContainer> inline constexpr auto operator-(const PointerIterator<TPointer, TContainer>& lhs, const PointerIterator<UPointer, TContainer>& rhs) noexcept -> decltype(lhs.operator->() - rhs.operator->()) { return lhs.operator->() - rhs.operator->(); } //! Test for equality between @a lhs and @a rhs. template <typename TPointer, typename UPointer, typename TContainer> inline constexpr bool operator==(const PointerIterator<TPointer, TContainer>& lhs, const PointerIterator<UPointer, TContainer>& rhs) noexcept { return lhs.operator->() == rhs.operator->(); } //! Test for inequality between @a lhs and @a rhs. template <typename TPointer, typename UPointer, typename TContainer> inline constexpr bool operator!=(const PointerIterator<TPointer, TContainer>& lhs, const PointerIterator<UPointer, TContainer>& rhs) noexcept { return lhs.operator->() != rhs.operator->(); } //! Test that @a lhs points to something less than @a rhs. template <typename TPointer, typename UPointer, typename TContainer> inline constexpr bool operator<(const PointerIterator<TPointer, TContainer>& lhs, const PointerIterator<UPointer, TContainer>& rhs) noexcept { return lhs.operator->() < rhs.operator->(); } //! Test that @a lhs points to something less than or equal to @a rhs. template <typename TPointer, typename UPointer, typename TContainer> inline constexpr bool operator<=(const PointerIterator<TPointer, TContainer>& lhs, const PointerIterator<UPointer, TContainer>& rhs) noexcept { return lhs.operator->() <= rhs.operator->(); } //! Test that @a lhs points to something greater than @a rhs. template <typename TPointer, typename UPointer, typename TContainer> inline constexpr bool operator>(const PointerIterator<TPointer, TContainer>& lhs, const PointerIterator<UPointer, TContainer>& rhs) noexcept { return lhs.operator->() > rhs.operator->(); } //! Test that @a lhs points to something greater than or equal to @a rhs. template <typename TPointer, typename UPointer, typename TContainer> inline constexpr bool operator>=(const PointerIterator<TPointer, TContainer>& lhs, const PointerIterator<UPointer, TContainer>& rhs) noexcept { return lhs.operator->() >= rhs.operator->(); } } // namespace detail } // namespace omni
omniverse-code/kit/include/omni/renderer/IDebugDraw.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/Defines.h> #include <carb/Types.h> #include <carb/scenerenderer/SceneRendererTypes.h> namespace omni { namespace renderer { typedef uint32_t SimplexBuffer; typedef uint32_t RenderInstanceBuffer; struct SimplexPoint { carb::Float3 position; uint32_t color; float width; }; /// Invalid billboardId const uint32_t kInvalidBillboardId = 0xFFFFffff; struct IDebugDraw { CARB_PLUGIN_INTERFACE("omni::renderer::IDebugDraw", 1, 2) /// Invalid buffer return value enum InvalidBuffer { eInvalidBuffer = 0 }; /// Draw a line - actual implementation /// \note Life time of a line is one frame /// /// \param startPos Line start position /// \param startColor Line start color in argb format /// \param startWidth Line start width /// \param endPos Line end position /// \param endColor Line end color in argb format /// \param endWidth Line end width void(CARB_ABI* internalDrawLine)(const carb::Float3& startPos, uint32_t startColor, float startWidth, const carb::Float3& endPos, uint32_t endColor, float endWidth); /// Draw a line without width /// \note Life time of a line is one frame /// /// \param startPos Line start position /// \param startColor Line start color in argb format /// \param endPos Line end position /// \param endColor Line end color in argb format void drawLine(const carb::Float3& startPos, uint32_t startColor, const carb::Float3& endPos, uint32_t endColor) { internalDrawLine(startPos, startColor, 1.0f, endPos, endColor, 1.0f); } /// Draw a line /// \note Life time of a line is one frame /// /// \param startPos Line start position /// \param startColor Line start color in argb format /// \param startWidth Line start width /// \param endPos Line end position /// \param endColor Line end color in argb format /// \param endWidth Line end width void drawLine(const carb::Float3& startPos, uint32_t startColor, float startWidth, const carb::Float3& endPos, uint32_t endColor, float endWidth) { internalDrawLine(startPos, startColor, startWidth, endPos, endColor, endWidth); } /// Draw lines buffer /// \note Life time of a line is one frame /// /// \param pointsBuffer Buffer of points (expected size is 2xnumLines) /// \param numLines Number of lines in the buffer void(CARB_ABI* drawLines)(const SimplexPoint* pointsBuffer, uint32_t numLines); /// Draw a point /// \note Life time of a point is one frame /// /// \param pointPos Point position /// \param pointColor Point color in argb format /// \param pointWidth Point width (diameter) void(CARB_ABI* internalDrawPoint)(const carb::Float3& pointPos, uint32_t pointColor, float pointWidth); /// Draw a point /// \note Life time of a point is one frame /// /// \param pointPos Point position /// \param pointColor Point color in argb format /// \param pointWidth Point width (diameter) void drawPoint(const carb::Float3& pointPos, uint32_t pointColor, float pointWidth = 1.0f) { internalDrawPoint(pointPos, pointColor, pointWidth); } /// Draw points buffer /// \note Life time of a point is one frame /// /// \param pointsBuffer Buffer of points (expected size is numPoints) /// \param numPoints Number of points in the buffer void(CARB_ABI* drawPoints)(const SimplexPoint* pointsBuffer, uint32_t numPoints); /// Draw a sphere - internal implementation /// \note Life time of a sphere is one frame /// /// \param spherePos Sphere positions /// \param sphereRadius Sphere radius /// \param sphereColor Sphere color in argb format /// \param lineWidth Line width /// \param tesselation Sphere tesselation void(CARB_ABI* internalDrawSphere)(const carb::Float3& spherePos, float sphereRadius, uint32_t sphereColor, float lineWidth, uint32_t tesselation); /// Draw a sphere /// \note Life time of a sphere is one frame /// /// \param spherePos Sphere positions /// \param sphereRadius Sphere radius /// \param sphereColor Sphere color in argb format /// \param lineWidth Line width /// \param tesselation Sphere tesselation void drawSphere(const carb::Float3& spherePos, float sphereRadius, uint32_t sphereColor, float lineWidth = 1.0f, uint32_t tesselation = 32) { internalDrawSphere(spherePos, sphereRadius, sphereColor, lineWidth, tesselation); } /// Draw a box - internal implementation /// \note Life time of a box is one frame /// /// \param boxPos Box position /// \param boxRotation Box rotation (quaternion) /// \param boxSize Box size - extent /// \param boxColor Box color in argb format /// \param lineWidth Line width void(CARB_ABI* internalDrawBox)( const carb::Float3& boxPos, const carb::Float4& boxRotation, const carb::Float3& boxSize, uint32_t boxColor, float lineWidth); /// Draw a box /// \note Life time of a box is one frame /// /// \param boxPos Box position /// \param boxRotation Box rotation (quaternion) /// \param boxSize Box size - extent /// \param boxColor Box color in argb format /// \param lineWidth Line width void drawBox(const carb::Float3& boxPos, const carb::Float4& boxRotation, const carb::Float3& boxSize, uint32_t boxColor, float lineWidth = 1.0f) { internalDrawBox(boxPos, boxRotation, boxSize, boxColor, lineWidth); } /// Allocate line buffer /// /// \param preallocatedBufferSize preallocated buffer size (number of lines expected) /// \returns Line buffer handle SimplexBuffer(CARB_ABI* allocateLineBuffer)(size_t preallocatedBufferSize); /// Deallocate line buffer /// /// \param bufferHandle Line buffer to deallocate void(CARB_ABI* deallocateLineBuffer)(SimplexBuffer bufferHandle); /// Set line to a buffer /// /// \param buffer Line buffer /// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase) /// \param startPos Line start position /// \param startColor Line start color in argb format /// \param startWidth Line start width /// \param endPos Line end position /// \param endColor Line end color in argb format /// \param endWidth Line end width void(CARB_ABI* internalSetLine)(SimplexBuffer buffer, size_t index, const carb::Float3& startPos, uint32_t startColor, float startWidth, const carb::Float3& endPos, uint32_t endColor, float endWidth); /// Set line to a buffer without width /// /// \param buffer Line buffer /// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase) /// \param startPos Line start position /// \param startColor Line start color in argb format /// \param endPos Line end position /// \param endColor Line end color in argb format void setLine(SimplexBuffer buffer, size_t index, const carb::Float3& startPos, uint32_t startColor, const carb::Float3& endPos, uint32_t endColor) { internalSetLine(buffer, index, startPos, startColor, 1.0f, endPos, endColor, 1.0f); } /// Set line to a buffer /// /// \param buffer Line buffer /// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase) /// \param startPos Line start position /// \param startColor Line start color in argb format /// \param startWidth Line start width /// \param endPos Line end position /// \param endColor Line end color in argb format /// \param endWidth Line end width void setLine(SimplexBuffer buffer, size_t index, const carb::Float3& startPos, uint32_t startColor, float startWidth, const carb::Float3& endPos, uint32_t endColor, float endWidth) { internalSetLine(buffer, index, startPos, startColor, startWidth, endPos, endColor, endWidth); } /// Set point within a point buffer /// /// \param buffer Point buffer /// \param index Index in buffer (if index is larger than current buffer size, size will increase) /// \param position Point position /// \param color Point color /// \param width Point size void(CARB_ABI* setPoint)(SimplexBuffer handle, size_t index, const carb::Float3& position, uint32_t color, float width); /// Allocate render instance buffer /// /// \param handle Line buffer to instance /// \param preallocatedBufferSize preallocated buffer size /// \returns Render instance buffer handle RenderInstanceBuffer(CARB_ABI* allocateRenderInstanceBuffer)(SimplexBuffer handle, size_t preallocatedSize); /// Update render instance buffer /// /// \param buffer Render instance buffer /// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase) /// \param matrix Instance transformation matrix - 4x4 matrix - 16 floats /// \param color Instance color, final color is interpolated with PrimitiveVertex.color based on alpha (in /// argb format) /// \param uid unique identifier to map PrimitiveListInstance back to prim for picking. void(CARB_ABI* internalSetRenderInstance)(RenderInstanceBuffer buffer, size_t index, const float* matrix, uint32_t color, uint32_t uid); /// Update render instance buffer without uid /// /// \param buffer Render instance buffer /// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase) /// \param matrix Instance transformation matrix - 4x4 matrix - 16 floats /// \param color Instance color, final color is interpolated with PrimitiveVertex.color based on alpha (in /// argb format) void setRenderInstance( RenderInstanceBuffer buffer, size_t index, const float* matrix, uint32_t color) { internalSetRenderInstance(buffer, index, matrix, color, 0); } /// Update render instance buffer /// /// \param buffer Render instance buffer /// \param index Index in buffer (if index is larger then preallocatedBufferSize, size will increase) /// \param matrix Instance transformation matrix - 4x4 matrix - 16 floats /// \param color Instance color, final color is interpolated with PrimitiveVertex.color based on alpha (in /// argb format) /// \param uid unique identifier to map PrimitiveListInstance back to prim for picking. void setRenderInstance( RenderInstanceBuffer buffer, size_t index, const float* matrix, uint32_t color, uint32_t uid) { internalSetRenderInstance(buffer, index, matrix, color, uid); } /// Deallocate render instance buffer /// /// \param handle Render instance buffer to deallocate void(CARB_ABI* deallocateRenderInstanceBuffer)(RenderInstanceBuffer buffer); /// Allocate point buffer /// /// \param preallocateBufferSize Preallocated buffer size (number of points expected) /// \returns Point buffer handle SimplexBuffer(CARB_ABI* allocatePointBuffer)(size_t preallocatedBufferSize); /// Deallocate point buffer /// /// \param bufferHandle Point buffer to deallocate void(CARB_ABI* deallocatePointBuffer)(SimplexBuffer bufferHandle); /// Allocate line buffer /// /// \param preallocatedBufferSize preallocated buffer size (number of lines expected) /// \param flags flags to be used when create primitive list /// \returns Line buffer handle SimplexBuffer(CARB_ABI* allocateLineBufferEx)(size_t preallocatedBufferSize, carb::scenerenderer::PrimitiveListFlags flags); /// Allocate point buffer /// /// \param preallocateBufferSize Preallocated buffer size (number of points expected) /// \param flags flags to be used when create primitive list /// \returns Point buffer handle SimplexBuffer(CARB_ABI* allocatePointBufferEx)(size_t preallocatedBufferSize, carb::scenerenderer::PrimitiveListFlags flags); /// Add billboard asset /// \note The asset is valid for the whole duration /// /// \param textureAssetName Full path to the texture asset /// \return Return assetid uint32_t (CARB_ABI* addBillboardAsset)(const char* textureAssetName); /// Update billboard asset /// /// \param assetId AssetId for billboard identification /// \param scale New scale /// \isConstantScale Constant scale hint void (CARB_ABI* updateBillboardAsset)(uint32_t assetId, double scale, bool isConstantScale); /// Add billboard instance /// /// \param assetId AssetId for billboard identification /// \param billboardUid BillboardUid - see context get Uid for selection /// \param tr Transformation matrix for the billboard instance, 4x4 float matrix /// \return Return id for the current billboard instance uint32_t (CARB_ABI* addBillboard)(uint32_t assetId, uint32_t billboardUid, const float* tr); /// Update billboard instance /// /// \param assetId AssetId for billboard identification /// \param billboardId Billboard id of the instance /// \param tr Transformation matrix for the billboard instancem 4x4 float matrix void (CARB_ABI* updateBillboard)(uint32_t assetId, uint32_t billboardId, const float* tr); /// Remove billboard instance /// /// \param assetId AssetId for billboard identification /// \param billboardId Billboard id of the instance /// \return Returns the swapped position, last item of the array is swapped with this Id, /// use the returned Id to update the instances in your database uint32_t (CARB_ABI* removeBillboard)(uint32_t assetId, uint32_t billboardId); /// Clear billboard instances for given asset /// /// \param assetId AssetId for billboard identification void (CARB_ABI* clearBillboardInstances)(uint32_t assetId); /// Remove render instance on given index /// /// \param handle Render instance buffer handle /// \param index Index in the buffer bool (CARB_ABI* removeRenderInstance)(omni::renderer::RenderInstanceBuffer handle, size_t index); /// Remove debug lines on given range of indices from the vertex array /// /// \param handle Render instance buffer handle /// \param startIndex Starting line index in the vertex buffer /// \param endIndex Ending line index in the vertex buffer bool (CARB_ABI* removeLines)(omni::renderer::SimplexBuffer handle, size_t startIndex, size_t endIndex); }; } // namespace renderer } // namespace omni
omniverse-code/kit/include/omni/renderer/utils/AssetsManagement.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/assets/IAssets.h> #include <carb/datasource/DataSourceUtils.h> #include <carb/datasource/IDataSource.h> #include <carb/filesystem/IFileSystem.h> #include <carb/logging/Log.h> #include <omni/usd/PathUtils.h> #include <unordered_map> #include <vector> namespace omni { namespace renderer { namespace utils { inline carb::datasource::IDataSource* getDataSourceFile() { return carb::getFramework()->tryAcquireInterface<carb::datasource::IDataSource>("carb.datasource-file.plugin"); } static bool isPathPrefixed(const std::string& path, const char* prefix, size_t prefixLen) { return path.length() > prefixLen && strncasecmp(path.c_str(), prefix, prefixLen) == 0; } inline std::vector<std::tuple<char, carb::datasource::IDataSource*, carb::datasource::Connection*>> getFilesystemConnections() { carb::filesystem::IFileSystem* fs = carb::getFramework()->acquireInterface<carb::filesystem::IFileSystem>(); carb::datasource::IDataSource* dataSource = carb::getFramework()->tryAcquireInterface<carb::datasource::IDataSource>("carb.datasource-omniclient.plugin"); if (!dataSource) { dataSource = getDataSourceFile(); } std::vector<std::tuple<char, carb::datasource::IDataSource*, 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_tuple(drive, dataSource, 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_tuple('/', dataSource, connection)); #endif return vec; } class AssetsManager { public: struct DataSourceMapping { carb::datasource::IDataSource* dataSource; carb::datasource::Connection* connection; }; AssetsManager(); ~AssetsManager(); void notifyShutdown(); bool getAssetAndDataSource(const char* assetUri, std::string& assetStr, DataSourceMapping& mapping); bool addDataSource(carb::datasource::IDataSource* dataSource, carb::datasource::Connection* connection, const char* prefix); bool removeDataSource(const char* prefix); protected: DataSourceMapping m_omniDataSourceMapping = { nullptr, nullptr }; std::unordered_map<std::string /* prefix */, DataSourceMapping> m_mapDataSources; std::vector<std::pair<carb::datasource::IDataSource*, carb::datasource::Connection*>> m_connections; }; inline AssetsManager::AssetsManager() { auto localConnections = getFilesystemConnections(); for (auto& connection : localConnections) { addDataSource(std::get<1>(connection), std::get<2>(connection), std::string(1, std::get<0>(connection)).c_str()); #if CARB_PLATFORM_WINDOWS addDataSource(std::get<1>(connection), std::get<2>(connection), std::string(1, std::tolower(std::get<0>(connection))).c_str()); #endif m_connections.push_back(std::make_pair(std::get<1>(connection), std::get<2>(connection))); } } inline AssetsManager::~AssetsManager() { if (m_omniDataSourceMapping.dataSource && m_omniDataSourceMapping.connection) { m_omniDataSourceMapping.dataSource->disconnect(m_omniDataSourceMapping.connection); } for (auto& connection : m_connections) { connection.first->disconnect(connection.second); } m_connections.clear(); } inline void AssetsManager::notifyShutdown() { m_omniDataSourceMapping = {}; m_connections.clear(); m_mapDataSources.clear(); } inline bool AssetsManager::addDataSource(carb::datasource::IDataSource* dataSource, carb::datasource::Connection* connection, const char* prefix) { CARB_ASSERT(dataSource && connection); auto it = m_mapDataSources.find(prefix); if (it != m_mapDataSources.end()) { if ((it->second.dataSource != dataSource) || (it->second.connection != connection)) { CARB_LOG_ERROR("A different DataSource is already registered for prefix '%s'", prefix); return false; } return true; } DataSourceMapping& mapping = m_mapDataSources[prefix]; mapping.dataSource = dataSource; mapping.connection = connection; CARB_LOG_INFO("Added dataSource connection for prefix '%s'", prefix); return true; } inline bool AssetsManager::removeDataSource(const char* prefix) { return m_mapDataSources.erase(prefix) != 0; } inline bool AssetsManager::getAssetAndDataSource(const char* assetUri, std::string& assetStr, DataSourceMapping& mapping) { if (assetUri == nullptr) { CARB_LOG_ERROR("assetUri is null"); CARB_ASSERT(assetUri); return false; } // Extract prefix from string /* The URI should be parsed in the more accurate way according to the URI Generic Syntax. URI = scheme:[//authority]path[?query][#fragment] */ const char* colonPos = std::strchr(assetUri, ':'); std::string prefix; #if CARB_PLATFORM_WINDOWS if (colonPos == nullptr) { CARB_LOG_ERROR("assetUri not a valid Uri: '%s'", assetUri); CARB_ASSERT(false); return false; } // Sanity check to ensure Uri contains a valid path after prefix:// if (std::strlen(colonPos) <= 3) { CARB_LOG_ERROR("Invalid asset Uri: '%s'", assetUri); CARB_ASSERT(false); return false; } prefix = std::string(assetUri, colonPos); #else // ":" on Linux implies an omniverse connection // clang-format off /* This comment is not exactly correct, see e.g.: ls /sys/bus/usb/devices/ 1-0:1.0 1-13:1.0 1-5:1.0 1-5:1.2 1-6:1.0 1-6:1.2 1-8:1.0 2-6 3-0:1.0 5-0:1.0 7-0:1.0 usb1 usb3 usb5 usb7 1-13 1-5 1-5:1.1 1-6 1-6:1.1 1-8 2-0:1.0 2-6:1.0 4-0:1.0 6-0:1.0 8-0:1.0 usb2 usb4 usb6 usb8 */ // clang-format on if (colonPos) { prefix = std::string(assetUri, colonPos); } // on Linux the local filesystem will not contain ":" to extract a prefix from else { colonPos = std::strchr(assetUri, '/'); if (colonPos == nullptr) { CARB_LOG_ERROR("assetUri not a valid Uri: '%s'", assetUri); CARB_ASSERT(false); return false; } prefix = "/"; } #endif const std::string assetUriStr = assetUri; bool isClientLibPath = isPathPrefixed(assetUriStr, "omniverse:", 10) || isPathPrefixed(assetUriStr, "http:", 5) || isPathPrefixed(assetUriStr, "https:", 6) || isPathPrefixed(assetUriStr, "file:", 5); if (isClientLibPath) { if (!m_omniDataSourceMapping.dataSource) { using namespace carb::datasource; IDataSource* dataSource = carb::getFramework()->acquireInterface<IDataSource>("carb.datasource-omniclient.plugin"); Connection* connection = connectAndWait({ "" }, dataSource); if (connection) { m_omniDataSourceMapping.dataSource = dataSource; m_omniDataSourceMapping.connection = connection; } else { CARB_LOG_ERROR("Failed to establish omniverse connection!"); } } mapping.dataSource = m_omniDataSourceMapping.dataSource; mapping.connection = m_omniDataSourceMapping.connection; assetStr = assetUri; return (mapping.dataSource != nullptr); } // Look for the prefix in our dataSource mappings auto it = m_mapDataSources.find(prefix); if (it == m_mapDataSources.end()) { CARB_LOG_ERROR("assetUri '%s' contains unknown dataSource prefix '%s'", assetUri, prefix.c_str()); return false; } else { mapping = it->second; } // Return the extracted string and dataSource mapping // TODO1 - HACKHACK for GTC, this is more pathing fun to handle the various ways paths can get to this code if (colonPos[0] == '.' && (colonPos[1] == '/' || colonPos[1] == '\\')) { // We're going to try and use this as-is } else if (colonPos[0] == '/' || colonPos[0] == '\\') { // We're just going to try and see what happens here } else { while ((colonPos[0] == ':' || colonPos[1] == ':' || colonPos[1] == '/' || colonPos[0] == '\\') && colonPos[0] != '0') { colonPos++; } } assetStr = std::string(colonPos); // TODO??? return true; } using FileSystemConnectionPair = std::pair<char, carb::datasource::Connection*>; inline std::vector<FileSystemConnectionPair> getFileSystemConnections() { carb::filesystem::IFileSystem* fs = carb::getFramework()->acquireInterface<carb::filesystem::IFileSystem>(); carb::datasource::IDataSource* dataSourceFile = getDataSourceFile(); std::vector<FileSystemConnectionPair> vec; if (fs == nullptr || dataSourceFile == 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() }, dataSourceFile); 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{ "/" }, dataSourceFile); 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; } } } }
omniverse-code/kit/include/omni/timeline/ITimeline.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/InterfaceUtils.h> #include <carb/events/IEvents.h> namespace omni { namespace timeline { class Timeline; using TimelinePtr = std::shared_ptr<Timeline>; /** * Defines a timeline controller. */ class Timeline { public: /** * Plays animation with current timeCodePerSecond. if not set session start and end timecode, will play from global start time to end time in stage. * * @startTimeCode start timeCode of session play, won't change the global StartTime. * @endTimeCode start timeCode of session play, won't change the global EndTime. * @looping true to enable session play looping, false to disable, won't change the global Looping. */ virtual void play(double startTimeCode = 0, double endTimeCode = 0, bool looping = true) = 0; /** * Pauses animation. */ virtual void pause() = 0; /** * Stops animation. */ virtual void stop() = 0; /** * Rewinds the timeline by one frame. */ virtual void rewindOneFrame() = 0; /** * Forwards the timeline by one frame. */ virtual void forwardOneFrame() = 0; /** * Checks if animation is playing. * * @return true if animation is playing. */ virtual bool isPlaying() const = 0; /** * Checks if animation is stopped, as opposed to paused. * * @return true if animation is stopped. */ virtual bool isStopped() const = 0; /** * Turns on/off auto update * * @autoUpdate autoUpdate true to enable auto update, false to disable. */ virtual void setAutoUpdate(bool autoUpdate) = 0; /** * Checks if timeline auto updates the frame * * @return true if timeline is auto updating */ virtual bool isAutoUpdating() const = 0; /** * Turns on/off prerolling status * * @autoUpdate prerolling true to indicate timeline is in preroll state */ virtual void setPrerolling(bool autoUpdate) = 0; /** * Checks if timeline is in prerolling mode * * @return true if timeline is in preroll */ virtual bool isPrerolling() const = 0; /** * Sets animation looping mode. * * @looping looping true to enable looping, false to disable. */ virtual void setLooping(bool looping) = 0; /** * Checks if animation is looping. * * @return true if animation is looping. */ virtual bool isLooping() const = 0; /** * Sets current time of animation in seconds. * * @param timeInSeconds Current time of animation in seconds. */ virtual void setCurrentTime(double timeInSeconds) = 0; /** * Gets current time of animation in seconds. * * @return Current time of animation in seconds. */ virtual double getCurrentTime() const = 0; /** * Gets the start time of animation in seconds. * * @return Begin time of animation in seconds. */ virtual double getStartTime() const = 0; /** * Sets the start time of animation in seconds. This will write into current opened stage. * * @param startTime Begin time of animation in seconds. */ virtual void setStartTime(double startTime) = 0; /** * Gets the end time of animation in seconds. * * @return End time of animation in seconds. */ virtual double getEndTime() const = 0; /** * Sets the begin time of animation in seconds. This will write into current opened stage. * * @param beginTime Begin time of animation in seconds. */ virtual void setEndTime(double endTime) = 0; /** * Gets timeCodePerSecond metadata from currently opened stage. This is equivalent to calling GetTimeCodesPerSecond * on UsdStage. * * @return timeCodePerSecond for current UsdStage. */ virtual double getTimeCodesPerSecond() const = 0; /** * Sets timeCodePerSecond metadata to currently opened stage. This is equivalent to calling SetTimeCodesPerSecond on * UsdStage. * * @param timeCodesPerSecond TimeCodePerSecond to set into current stage. */ virtual void setTimeCodesPerSecond(double timeCodesPerSecond) = 0; /** * Gets TimelineEventStream, emitting TimelineEventType. * * @return IEventStream* of TimelineEventStream. */ virtual carb::events::IEventStream* getTimelineEventStream() = 0; /** * Sets a tentative time of animation in seconds. * * @param timeInSeconds A tentative current time of animation in seconds. */ virtual void setTentativeTime(double timeInSeconds) = 0; /** * Clear the tentative time of animation so it becomes invalid. * */ virtual void clearTentativeTime() = 0; /** * Gets the tentative time of animation in seconds. * * @return The tentative time if it is valid, current time if invalid. */ virtual double getTentativeTime() const = 0; /** * Sets the tick count per frame, i.e. how many times update event is ticked per frame. * * @param ticksPerFrame The tick per frame count. */ virtual void setTicksPerFrame(unsigned int ticksPerFrame) = 0; /** * Gets the tick count per frame, i.e. how many times update event is ticked per frame. * * @return The tick per frame count. */ virtual unsigned int getTicksPerFrame() const = 0; /** * Gets the tick count per seconds, i.e. how many times update event is ticked per second. * * @return The tick per second count. */ virtual double getTicksPerSecond() const = 0; /** * Gets the current tick index, starting from zero. Always returns zero when ticks per frame is one. * * @return The current tick index. */ virtual unsigned int getCurrentTick() const = 0; /** * Turns fast mode on or off. Deprecated, same as setPlayEveryFrame. * * @param fastMode true to turn on fast mode, false to turn it off. */ virtual void setFastMode(bool fastMode) = 0; /** * Checks if fast mode is on or off. Deprecated, same as getPlayEveryFrame. * * @return true is fast mode is on. */ virtual bool getFastMode() const = 0; /** * Sets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @param targetFrameRate The target frame rate. */ virtual void setTargetFramerate(float targetFrameRate) = 0; /** * Gets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @return The target frame rate. */ virtual float getTargetFramerate() const = 0; // These new methods have no equivalent in the deprecated interface to encourage the use of the new interface /** * Converts time in seconds to time codes, w.r.t. the current timeCodesPerSecond setting of the timeline. * * @return The converted time code. */ virtual double timeToTimeCode(double timeInSecs) const = 0; /** * Converts time codes to seconds, w.r.t. the current timeCodesPerSecond setting of the timeline. * * @return The converted time in seconds. */ virtual double timeCodeToTime(double timeCodes) const = 0; /** * Applies all pending state changes and invokes all callbacks. * * This method is not thread-safe, it should be called only from the main thread. * */ virtual void commit() = 0; /** * Applies all pending state changes but does not invoke any callbacks. * * This method is thread-safe. * */ virtual void commitSilently() = 0; /** * Turns frame skipping off (true) or on (false). Same as setFastMode. * * @param playEveryFrame true to turn frame skipping off. */ virtual void setPlayEveryFrame(bool playEveryFrame) = 0; /** * Checks if the timeline sends updates every frame. Same as getFastMode. * * @return true if the timeline does not skip frames. */ virtual bool getPlayEveryFrame() const = 0; /** * Sets a director Timeline. * * When a director is set, the timeline mimics its behavior and any * state changing call from all other sources are ignored. * @param timeline The timeline object to be set as the director. * Pass nullptr to clear the current director. */ virtual void setDirector(TimelinePtr timeline) = 0; /** * Returns the current director Timeline. * * @return The director timeline or nullptr if none is set. */ virtual TimelinePtr getDirector() const = 0; /** * Sets the zoom range, i.e. the playback interval. * * Values are truncated to the [getStartTime(), getEndTime()] interval, * which is also the default range. * A minimum of one frame long range is enforced. * * @startTime: start time of zoom in seconds. Must be less or equal than endTime. * @endTime: End time of zoom in seconds. Must be greater or equal than endTime. */ virtual void setZoomRange(double startTime, double endTime) = 0; /** * Clears the zoom state, i.e. sets the zoom range to [getStartTime(), getEndTime()]. */ virtual void clearZoom() = 0; /** * Returns whether a zoom is set, i.e. the zoom range is not the entire * [getStartTime(), getEndTime()] interval. * * @return true if getStartTime() < getZoomStartTime() or getZoomEndTime() < getEndTime() * (note that "<=" always holds). * false otherwise. */ virtual bool isZoomed() const = 0; /** * Gets the start time of zoomed animation in seconds. * * @return: The start time of zoomed animation in seconds. * When no zoom is set, this function returns getStartTime(). */ virtual double getZoomStartTime() const = 0; /** * Gets the end time of zoomed animation in seconds. * * @return: The end time of zoomed animation in seconds. * When no zoom is set, this function returns getEndTime(). */ virtual double getZoomEndTime() const = 0; }; /** * Defines a timeline controller factory. For compatibility reasons it also defines a timeline controller. */ class ITimeline { public: CARB_PLUGIN_INTERFACE("omni::timeline::ITimeline", 1, 0); //---------------------- // Deprecated interface //---------------------- /** * Deprecated Plays animation with current timeCodePerSecond. if not set session start and end timecode, will play from global start time to end time in stage. * * @startTimeCode start timeCode of session play, won't change the global StartTime. * @endTimeCode start timeCode of session play, won't change the global EndTime. * @looping true to enable session play looping, false to disable, won't change the global Looping. */ virtual void play(double startTimeCode = 0, double endTimeCode = 0, bool looping = true) = 0; /** * Deprecated. Pauses animation. */ virtual void pause() = 0; /** * Deprecated. Stops animation. */ virtual void stop() = 0; /** * Deprecated. Rewinds the timeline by one frame. */ virtual void rewindOneFrame() = 0; /** * Deprecated. Forwards the timeline by one frame. */ virtual void forwardOneFrame() = 0; /** * Deprecated. Checks if animation is playing. * * @return true if animation is playing. */ virtual bool isPlaying() const = 0; /** * Deprecated. Checks if animation is stopped, as opposed to paused. * * @return true if animation is stopped. */ virtual bool isStopped() const = 0; /** * Deprecated. Turns on/off auto update * * @autoUpdate autoUpdate true to enable auto update, false to disable. */ virtual void setAutoUpdate(bool autoUpdate) = 0; /** * Deprecated. Checks if timeline auto updates the frame * * @return true if timeline is auto updating */ virtual bool isAutoUpdating() const = 0; /** * Deprecated. Turns on/off prerolling status * * @autoUpdate prerolling true to indicate timeline is in preroll state */ virtual void setPrerolling(bool autoUpdate) = 0; /** * Deprecated. Checks if timeline is in prerolling mode * * @return true if timeline is in preroll */ virtual bool isPrerolling() const = 0; /** * Deprecated. Sets animation looping mode. * * @looping looping true to enable looping, false to disable. */ virtual void setLooping(bool looping) = 0; /** * Deprecated. Checks if animation is looping. * * @return true if animation is looping. */ virtual bool isLooping() const = 0; /** * Deprecated. Sets current time of animation in seconds. * * @param timeInSeconds Current time of animation in seconds. */ virtual void setCurrentTime(double timeInSeconds) = 0; /** * Deprecated. Gets current time of animation in seconds. * * @return Current time of animation in seconds. */ virtual double getCurrentTime() const = 0; /** * Deprecated. Gets the start time of animation in seconds. * * @return Begin time of animation in seconds. */ virtual double getStartTime() const = 0; /** * Deprecated. Sets the start time of animation in seconds. This will write into current opened stage. * * @param startTime Begin time of animation in seconds. */ virtual void setStartTime(double startTime) = 0; /** * Deprecated. Gets the end time of animation in seconds. * * @return End time of animation in seconds. */ virtual double getEndTime() const = 0; /** * Deprecated. Sets the begin time of animation in seconds. This will write into current opened stage. * * @param beginTime Begin time of animation in seconds. */ virtual void setEndTime(double endTime) = 0; /** * Deprecated. Gets timeCodePerSecond metadata from currently opened stage. This is equivalent to calling GetTimeCodesPerSecond * on UsdStage. * * @return timeCodePerSecond for current UsdStage. */ virtual double getTimeCodesPerSecond() const = 0; /** * Deprecated. Sets timeCodePerSecond metadata to currently opened stage. This is equivalent to calling SetTimeCodesPerSecond on * UsdStage. * * @param timeCodesPerSecond TimeCodePerSecond to set into current stage. */ virtual void setTimeCodesPerSecond(double timeCodesPerSecond) = 0; /** * Deprecated. Gets TimelineEventStream, emitting TimelineEventType. * * @return IEventStream* of TimelineEventStream. */ virtual carb::events::IEventStream* getTimelineEventStream() = 0; /** * Deprecated. Sets a tentative time of animation in seconds. * * @param timeInSeconds A tentative current time of animation in seconds. */ virtual void setTentativeTime(double timeInSeconds) = 0; /** * Deprecated. Clear the tentative time of animation so it becomes invalid. * */ virtual void clearTentativeTime() = 0; /** * Deprecated. Gets the tentative time of animation in seconds. * * @return The tentative time if it is valid, current time if invalid. */ virtual double getTentativeTime() const = 0; /** * Deprecated. Sets the tick count per frame, i.e. how many times update event is ticked per frame. * * @param ticksPerFrame The tick per frame count. */ virtual void setTicksPerFrame(unsigned int ticksPerFrame) = 0; /** * Deprecated. Gets the tick count per frame, i.e. how many times update event is ticked per frame. * * @return The tick per frame count. */ virtual unsigned int getTicksPerFrame() const = 0; /** * Deprecated. Gets the tick count per seconds, i.e. how many times update event is ticked per second. * * @return The tick per second count. */ virtual double getTicksPerSecond() const = 0; /** * Deprecated. Gets the current tick index, starting from zero. Always returns zero when ticks per frame is one. * * @return The current tick index. */ virtual unsigned int getCurrentTick() const = 0; /** * Deprecated. Turns fast mode on or off. * * @param fastMode true to turn on fast mode, false to turn it off. */ virtual void setFastMode(bool fastMode) = 0; /** * Deprecated. Checks if fast mode is on or off. * * @return true is fast mode is on. */ virtual bool getFastMode() const = 0; /** * Deprecated. Sets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @param targetFrameRate The target frame rate. */ virtual void setTargetFramerate(float targetFrameRate) = 0; /** * Deprecated. Gets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @return The target frame rate. */ virtual float getTargetFramerate() const = 0; //--------------- // New interface //--------------- /** * Gets timeline with the given name. Creates a new one if it is not exist. * * @param name Name of the timeline. * * @return The timeline */ virtual TimelinePtr getTimeline(const char* name = nullptr) = 0; /** * Destroys the timeline with the given name if nothing references it. Does not release the default timeline. * * @param name Name of the timeline. * * @return True if a timeline was deleted, false otherwise. The latter happens when the timeline does not exist, it is in use, or it is the default timeline. */ virtual bool destroyTimeline(const char* name) = 0; }; /** * Gets cached ITimeline interface. * * @return Cached ITimeline interface. */ inline TimelinePtr getTimeline(const char* name = nullptr) { auto manager = carb::getCachedInterface<omni::timeline::ITimeline>(); return manager == nullptr ? nullptr : manager->getTimeline(name); } } }
omniverse-code/kit/include/omni/timeline/TimelineTypes.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/InterfaceUtils.h> namespace omni { namespace timeline { /** * Defines timeline event types to be used by TimelineEventStream. */ enum class TimelineEventType { ePlay, ///! Timeline started to play. ePause, ///! Timeline paused eStop, ///! Timeline stopped eCurrentTimeChanged, ///! Current time is changed by user (isn't called when timeline ticked). eCurrentTimeTickedPermanent, ///! Current time is ticked by update function (called per subframe=tick even if not playing). eCurrentTimeTicked, ///! Current time is ticked by update function (called per subframe=tick when playing). eLoopModeChanged, ///! Looping mode changed. eStartTimeChanged, ///! Start time changed. eEndTimeChanged, ///! End time changed. eTimeCodesPerSecondChanged, ///! Timecode per second (animation framerate) changed. eAutoUpdateChanged, ///! Auto update changed ePrerollingChanged, ///! Prerolling changed eTentativeTimeChanged, ///! Tentative current time is changed by user (isn't called when timeline ticked). eTicksPerFrameChanged, ///! Ticks per frame count changed eFastModeChanged, ///! Fast mode changed. Same as eFastModeChanged, kept for backward compatibility. ePlayEveryFrameChanged = eFastModeChanged, ///! Play every frame (no frame skipping) changed eTargetFramerateChanged, ///! Target runloop frame rate changed eDirectorChanged, ///! Timeline is driven by a new director timeline eZoomChanged ///! Zoom range changed }; } }
omniverse-code/kit/include/omni/structuredlog/BinarySerializer.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 Module for serializing data into the structured logging queue. */ #pragma once #include "../structuredlog/StringView.h" #include "../../carb/extras/StringSafe.h" #include "../../carb/Defines.h" #include <stdint.h> namespace omni { namespace structuredlog { /** A helper class to calculate the required size of a binary blob. * To use this, just track all of the data that you want to insert into your * binary blob. */ class BinaryBlobSizeCalculator { public: /** The version of binary blob ABI * Headers that use these binary blobs should static assert on its version. * Do not modify the layout of the binary blob without incrementing this. */ static constexpr uint32_t kVersion = 0; /** Retrieve the tracked blob size. * @returns The memory size that is needed to store this blob. */ size_t getSize() { return m_counter; } /** Track a primitive type. * @param[in] v The value to track. * The actual value doesn't matter; only the type matters. */ template <typename T> void track(T v) { CARB_UNUSED(v); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_counter = alignOffset<T>(m_counter); m_counter += sizeof(T); } /** Track an array type. * @param[in] v The array of values to track. * This may also be a string. * @param[in] len The number of elements in array @p v. * If this is a string, this length *includes* the null terminator. */ template <typename T> void track(T* v, uint16_t len) { CARB_UNUSED(v); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); if (len > 0) { m_counter = alignOffset<T>(m_counter); m_counter += sizeof(T) * len; } } /** Track a @ref StringView. * @param[in] v The string view to track. */ void track(const StringView& v) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); m_counter += v.length() + 1; } /** Track a @ref StringView. * @param[in] v The string view to track. */ void track(StringView& v) { track(static_cast<const StringView&>(v)); } /** Track an array of strings into the buffer with pre-calculated lengths * @param[in] v The array of strings to track. * This may not be nullptr. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] stringLengths The length of each string in @p v. * These length must include the null terminator of the string. * This may not be nullptr. * @param[in] len The number of elements in array @p v and array @p stringLengths. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. * * @note This overload exists to avoid having to perform a strlen() on each * string in the array twice (once when calculating the buffer size * and once when writing the buffer). */ void track(const char* const* v, const uint16_t* stringLengths, uint16_t len) { CARB_UNUSED(v); m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); for (uint16_t i = 0; i < len; i++) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); m_counter += stringLengths[i]; } } /** Track an array of strings type. * @param[in] v The array of strings to track. * This may not be nullptr. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] len The number of elements in array @p v. */ void track(const char* const* v, uint16_t len) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); for (uint16_t i = 0; i < len; i++) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); if (v[i] != nullptr) { size_t size = strlen(v[i]) + 1; m_counter += CARB_MIN(size_t(UINT16_MAX), size); } } } /** Track an array of fixed size. * @param[in] v The array of values to track. * This may also be a string. * @param[in] len The fixed length of this data array as specified by * the data schema. This can be larger than @p v. */ template <typename T> void trackFixed(T* v, uint16_t len) { CARB_UNUSED(v); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_counter = alignOffset<T>(m_counter); m_counter += sizeof(T) * len; } /** Round an offset up to be aligned for a given type. * @param[in] offset The offset to align. * @returns @p offset rounded up to be aligned for the specified type. */ template <typename T> static size_t alignOffset(size_t offset) { size_t misalign = offset & (sizeof(T) - 1); if (misalign != 0) offset += sizeof(T) - misalign; return offset; } private: /** The length of the blob that's been tracked so far. */ size_t m_counter = 0; }; /** @{ * Constants to make the template specialization more readable. */ static constexpr bool kBlobWriterValidate = true; static constexpr bool kBlobWriterNoValidate = false; /** @} */ /** Anonymous namespace for a helper function */ namespace { void ignoreBlobWriterValidationError(const char* s) noexcept { CARB_UNUSED(s); } } // namespace /** The prototype of the function to call when a validation error occurs. * @param[in] message The error message explaining what went wrong. */ using OnBlobWriterValidationErrorFunc = void (*)(const char* message); /** A class to build a binary blob. * The binary blob only has internal markers for variable length fields; to * decode the binary blob, you will need some sort of external schema or fixed * layout to decode the binary blob. * * @param validate If this parameter is true, then the length of the blob will * be tracked while writing the blob and attempting to write * past the end of the buffer will cause methods to fail. * This is needed for the tests. * * @param onValidationError This is a callback that gets executed when a validation * error is triggered, so logging can be called. * Logging cannot be called directly from this class * because it is used inside the logging system. */ template <bool validate = false, OnBlobWriterValidationErrorFunc onValidationError = ignoreBlobWriterValidationError> class BlobWriter { public: /** The version of binary blob ABI * Headers that use these binary blobs should static assert on its version. * Do not modify the layout of the binary blob without incrementing this. */ static constexpr uint32_t kVersion = 0; /** Constructor. * @param[in] buffer The buffer to write into. * This buffer must be aligned to sizeof(void*). * @param[in] bytes The length of @p buffer. */ BlobWriter(void* buffer, size_t bytes) { CARB_ASSERT(buffer != nullptr); CARB_ASSERT((uintptr_t(buffer) & (sizeof(void*) - 1)) == 0); m_buffer = static_cast<uint8_t*>(buffer); m_bufferLen = bytes; } /** Copy a primitive type element into the buffer. * @param[in] v The value to copy into the buffer. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ template <typename T> bool copy(T v) { static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); alignBuffer<T>(); if (validate && m_bufferLen < m_written + sizeof(v)) { outOfMemoryErrorMessage(sizeof(v)); return false; } reinterpret_cast<T*>(m_buffer + m_written)[0] = v; m_written += sizeof(v); return true; } /** Copy an array of strings into the buffer with pre-calculated lengths * @param[in] v The array of strings to write into the buffer. * This may be nullptr if @p len is 0. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] stringLengths The length of each string in @p v. * These length must include the null terminator of the string. * This may be nullptr if @p len is 0. * @param[in] len The number of elements in array @p v and array @p stringLengths. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. * * @note This overload exists to avoid having to perform a strlen() on each * string in the array twice (once when calculating the buffer size * and once when writing the buffer). */ bool copy(const char* const* v, const uint16_t* stringLengths, uint16_t len) { CARB_ASSERT(v != nullptr || len == 0); CARB_ASSERT(stringLengths != nullptr || len == 0); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); for (uint16_t i = 0; i < len; i++) { alignBuffer<decltype(stringLengths[i])>(); if (validate && m_bufferLen < m_written + sizeof(stringLengths[i]) + stringLengths[i]) { outOfMemoryErrorMessage(sizeof(stringLengths[i]) + stringLengths[i]); return false; } reinterpret_cast<uint16_t*>(m_buffer + m_written)[0] = stringLengths[i]; m_written += sizeof(stringLengths[i]); memcpy(m_buffer + m_written, v[i], stringLengths[i]); m_written += stringLengths[i]; } return true; } /** Copy an array of strings into the buffer. * @param[in] v The array of strings to write into the buffer. * This may be nullptr if @p len is 0. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] len The number of elements in array @p v. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ bool copy(const char* const* v, uint16_t len) { CARB_ASSERT(v != nullptr || len == 0); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); for (uint16_t i = 0; i < len; i++) { size_t size; uint16_t s = 0; if (v[i] == nullptr) { alignBuffer<uint16_t>(); if (validate && m_bufferLen < m_written + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } reinterpret_cast<uint16_t*>(m_buffer + m_written)[0] = 0; m_written += sizeof(uint16_t); continue; } // this might silently truncate if a really long string is passed size = strlen(v[i]) + 1; s = uint16_t(CARB_MIN(size_t(UINT16_MAX), size)); alignBuffer<decltype(s)>(); if (validate && m_bufferLen < m_written + sizeof(s) + s) { outOfMemoryErrorMessage(sizeof(s) + s); return false; } reinterpret_cast<decltype(s)*>(m_buffer + m_written)[0] = s; m_written += sizeof(s); memcpy(m_buffer + m_written, v[i], s); m_written += s; } return true; } /** Copy an array of data into the buffer. * @param[in] v The array of values to copy. * This may also be a string. * This may be nullptr if @p len is 0. * @param[in] len The number of elements in array @p v. * If this is a string, this length *includes* the null terminator. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ template <typename T> bool copy(T* v, uint16_t len) { static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); CARB_ASSERT(v != nullptr || len == 0); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); if (len == 0) return true; alignBuffer<T>(); if (validate && m_bufferLen < m_written + sizeof(T) * len) { outOfMemoryErrorMessage(sizeof(T) * len); return false; } memcpy(m_buffer + m_written, v, sizeof(T) * len); m_written += sizeof(T) * len; return true; } /** Copy a @ref StringView into the blob. * @param[in] v The @ref StringView to copy in. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ bool copy(const StringView& v) { uint16_t len = uint16_t(CARB_MIN(size_t(UINT16_MAX), v.length() + 1)); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); if (len == 0) return true; if (validate && m_bufferLen < m_written + len) { outOfMemoryErrorMessage(len); return false; } // the string view may not be null terminated, so we need to write the // terminator separately if (len > 1) { memcpy(m_buffer + m_written, v.data(), len - 1); m_written += len - 1; } m_buffer[m_written++] = '\0'; return true; } /** Copy a @ref StringView into the buffer. * @param[in] v The string view to copy. */ bool copy(StringView& v) { return copy(static_cast<const StringView&>(v)); } /** Copy an array of data into the buffer. * @param[in] v The array of values to copy. * This may also be a string. * This may not be nullptr because that would imply * @p fixedLen is 0, which is not a valid use case. * @param[in] actualLen The length of array @p v. * This must be less than or equal to @p fixedLen. * @param[in] fixedLen The fixed length as specified by your data schema. * If this is greater than @p actualLen, then the * excess size at the end of the array will be zeroed. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ template <typename T> bool copy(T* v, uint16_t actualLen, uint16_t fixedLen) { const size_t total = sizeof(T) * fixedLen; const size_t written = sizeof(T) * actualLen; static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); CARB_ASSERT(v != nullptr); CARB_ASSERT(fixedLen >= actualLen); alignBuffer<T>(); if (validate && m_bufferLen < m_written + total) { outOfMemoryErrorMessage(total); return false; } // write out the actual values memcpy(m_buffer + m_written, v, written); // zero the padding at the end memset(m_buffer + m_written + written, 0, total - written); m_written += total; return true; } /** Align the buffer for a given type. * @remarks This will advance the buffer so that the next write is aligned * for the specified type. */ template <typename T> void alignBuffer() { size_t next = BinaryBlobSizeCalculator::alignOffset<T>(m_written); // there's no strict requirement for the padding to be 0 if (validate) memset(m_buffer + m_written, 0, next - m_written); m_written = next; } private: void outOfMemoryErrorMessage(size_t size) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "hit end of buffer while writing" " (tried to write %zu bytes, with %zd available)", size, m_bufferLen - m_written); onValidationError(tmp); } /** The buffer being written. */ uint8_t* m_buffer = nullptr; /** The length of @p m_buffer. */ size_t m_bufferLen = 0; /** The amount that has been written to @p m_buffer. */ size_t m_written = 0; }; /** @{ * Constants to make the template specialization more readable. */ static constexpr bool kBlobReaderValidate = true; static constexpr bool kBlobReaderNoValidate = false; /** @} */ /** A class to read binary blobs produced by the @ref BlobWriter. * You'll need some sort of external schema or fixed layout to be able to read * the blob. * * @param validate If this parameter is true, then the read position will * be tracked while reading the blob and attempting to read * past the end of the buffer will cause methods to fail. * Note that a message will not be logged because this class * is used in the log system. * This is needed for the tests. */ template <bool validate = false, OnBlobWriterValidationErrorFunc onValidationError = ignoreBlobWriterValidationError> class BlobReader { public: /** The version of binary blob ABI that this reader was built to read. */ static constexpr uint32_t kVersion = 0; /** Constructor. * @param[in] blob The buffer to read from. * @param[in] blobSize The length of @p buffer. */ BlobReader(const void* blob, size_t blobSize) { CARB_ASSERT(blob != nullptr || blobSize == 0); m_buffer = static_cast<const uint8_t*>(blob); m_bufferLen = blobSize; } /** read a primitive type element out of the buffer. * @param[out] out The value will be written to this. * This may not be nullptr. * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ template <typename T> bool read(T* out) { static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); CARB_ASSERT(out != nullptr); alignBuffer<T>(); if (validate && m_bufferLen < m_read + sizeof(T)) { outOfMemoryErrorMessage(sizeof(T)); return false; } *out = reinterpret_cast<const T*>(m_buffer + m_read)[0]; m_read += sizeof(T); return true; } /** Read an array of strings out of the buffer. * @param[out] out Receives the array of strings from the blob if @p maxLen is not 0. * This may be nullptr if @p maxLen is 0. * Note that the strings pointed to will point into the * data blob that's being read from. * @param[out] outLen Receives the length of the output array. * This may not be nullptr. * @param[in] maxLen The maximum length that can be read into @p out in this call. * If this is set to 0, then the array length with be * read into @p outLen and the buffer pointer will not * increment to point at the next member, so that an * array can be allocated and read in the next call to * this function. * An exception to this is the case where @p outLen * is set to 0; the buffer pointer will be incremented * to point at the next member in this case. * * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ bool read(const char** out, uint16_t* outLen, uint16_t maxLen) { uint16_t len = 0; alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_read + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } len = reinterpret_cast<const decltype(len)*>(m_buffer + m_read)[0]; *outLen = len; if (maxLen == 0 && len != 0) return true; m_read += sizeof(len); if (validate && len > maxLen) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "buffer is too small to read the data" " (length = %" PRIu16 ", needed = %" PRIu16 ")", maxLen, len); onValidationError(tmp); } for (uint16_t i = 0; i < len; i++) { uint16_t s = 0; alignBuffer<decltype(s)>(); if (validate && m_bufferLen < m_read + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } s = reinterpret_cast<const decltype(s)*>(m_buffer + m_read)[0]; m_read += sizeof(len); if (validate && m_bufferLen < m_read + s) { outOfMemoryErrorMessage(s); return false; } if (s == 0) { out[i] = nullptr; continue; } out[i] = reinterpret_cast<const char*>(m_buffer + m_read); m_read += s; } return true; } /** Read a string out of the buffer. * @param[out] out Receives the array from the binary blob. * This will be pointing to data from within the blob. * This may not be nullptr. * @param[out] outLen Receives the length of the array that was read. * This includes the null terminator if this was as string. * This may not be nullptr. * * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ template <typename T> bool read(const T** out, uint16_t* outLen) { CARB_ASSERT(out != nullptr); CARB_ASSERT(outLen != nullptr); alignBuffer<uint16_t>(); if (validate && m_bufferLen < m_read + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } *outLen = reinterpret_cast<const uint16_t*>(m_buffer + m_read)[0]; m_read += sizeof(*outLen); if (*outLen == 0) { *out = nullptr; return true; } alignBuffer<T>(); if (validate && m_bufferLen < m_read + *outLen) { outOfMemoryErrorMessage(*outLen); return false; } *out = reinterpret_cast<const T*>(m_buffer + m_read); m_read += *outLen * sizeof(T); return true; } /** Read a fixed length array out of the buffer. * @param[out] out Receives the array from the binary blob. * This will be pointing to data from within the blob. * This may not be nullptr. * @param[out] fixedLen The fixed length of the array/string. * This should not be 0. * * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ template <typename T> bool read(const T** out, uint16_t fixedLen) { CARB_ASSERT(out != nullptr); alignBuffer<T>(); if (validate && m_bufferLen < m_read + fixedLen) { outOfMemoryErrorMessage(fixedLen); return false; } *out = reinterpret_cast<const T*>(m_buffer + m_read); m_read += fixedLen * sizeof(T); return true; } /** Align the buffer for a given type. * @remarks This will advance the buffer so that the next write is aligned * for the specified type. */ template <typename T> void alignBuffer() { m_read = BinaryBlobSizeCalculator::alignOffset<T>(m_read); } protected: /** Send an error message to the onValidationError callback when the end of the buffer has been reached. * @param[in] size The size that was requested that would have extended past the end of the buffer. */ void outOfMemoryErrorMessage(size_t size) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "hit end of buffer while reading" " (tried to read %zu bytes, with %zd available)", size, m_bufferLen - m_read); onValidationError(tmp); } /** The buffer being written. */ const uint8_t* m_buffer = nullptr; /** The length of @p m_buffer. */ size_t m_bufferLen = 0; /** The amount that has been read from @p m_buffer. */ size_t m_read = 0; }; } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/Telemetry.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 Utilities for uploading telemetry events. */ #pragma once #include "IStructuredLogSettings.h" #include "../extras/UniqueApp.h" #include "../../carb/launcher/ILauncher.h" #include "../../carb/launcher/LauncherUtils.h" #include "../../carb/settings/ISettings.h" namespace omni { namespace telemetry { /** Telemetry transmitter app settings. These control the behavior of the transmitter * app. They can be specified either on the command line (prefixed by '--'), or in * the transmitter app's config file (`omni.telemetry.transmitter.toml`). * @{ */ /** This setting will cause the transmitter to stay alive until it is manually killed. * This setting is mostly meant for developer use, but could also be used in server * or farm environments where Omniverse apps are frequently run and exited. This will * bypass the normal exit condition check of testing whether all apps that tried to * launch the transmitter have exited on their own. When this option is disabled, * once all apps have exited, the transmitter will exit on its own. When this option * is enabled, this exit condition will simply be ignored. This defaults to `false`. * * Note that if no schemas are available for the transmitter to process, this option * is ignored. In that case, the transmitter will simply exit immediately after * trying to download the schemas package. */ constexpr const char* const kStayAliveSetting = "/telemetry/stayAlive"; /** The time, in seconds, that the transmitter will wait between polling the log files. * This determines how reactive the transmitter will be to checking for new messages and * how much work it potentially does in the background. This defaults to 60 seconds. */ constexpr const char* const kPollTimeSetting = "/telemetry/pollTime"; /** The mode to run the transmitter in. The value of this setting can be either "dev" or "test". * By default, the transmitter will run in "production" mode. In "dev" mode, the transmitter * will use the default development schemas URL. In "test" mode, the default staging endpoint * URL will be used. The "test" mode is only supported in debug builds. If "test" is used * in a release build, it will be ignored and the production endpoint will be used instead. * * Note that if the schemas package for the requested mode is empty, the transmitter will * just immediately exit since there is nothing for it to process. */ constexpr const char* const kTelemetryModeSetting = "/telemetry/mode"; /** Sets the run environment that determines which flavor of Kit is currently being run. * This should be either `Individual` (for OVI), `Cloud` (for OVC), or `Enterprise` (for * OVE). This helps to choose the appropriate schema ID when automatically adding the * `schemaid` field to messages being sent to an open endpoint. */ constexpr const char* const kTelemetryRunEnvironmentSetting = "/telemetry/runEnvironment"; /** This allows the transmitter to run as the root user on Linux. * The root user is disabled by default because it could make some of the transmitter's * files non-writable by regular users. By default, if the transmitter is launched as * the root user or with `sudo`, it will report an error and exit immediately. If it is * intended to launch as the root or super user, this option must be explicitly specified * so that there is a clear intention from the user. The default value is `false`. This * setting is ignored on Windows. */ constexpr const char* const kAllowRootSetting = "/telemetry/allowRoot"; /** The list of restricted regions for the transmitter. If the transmitter is launched * in one of these regions, it will exit immediately on startup. The entries in this * list are either the country names or the two-letter ISO 3166-1 alpha-2 country code. * Entries in the list are separated by commas (','), bars ('|'), slash ('/'), or whitespace. * Whitespace should not be used when specifying the option on the command line. It is * typically best to use the two-letter country codes in the list since they are standardized. * This defaults to an empty list. */ constexpr const char* const kRestrictedRegionsSetting = "/telemetry/restrictedRegions"; /** The assumption of success or failure that should be assumed if the country name and code * could not be retrieved. Set this to `true` if the transmitter should be allowed to run * if the country code or name could not be retrieved. Set this to `false` if the transmitter * should not be allowed to run in that error case. This defaults to `true`. */ constexpr const char* const kRestrictedRegionAssumptionSetting = "/telemetry/restrictedRegionAssumption"; /** The log file path that will be used for any transmitter processes launched. * If it is not specified, the log path from @ref IStructuredLogSettings::getLogOutputPath() * will be used; If @ref IStructuredLogSettings could not be acquired for some reason, * the CWD will be used. */ constexpr const char* const kLogFileSetting = "/telemetry/log/file"; /** The log level that will be used for any transmitter process launched. * If this is not specified, the parent process's log level will be used. */ constexpr const char* const kLogLevelSetting = "/telemetry/log/level"; /** This allows the telemetry transmitter to be launched in an 'open endpoint' mode. This will * point it to one of the Kratos open endpoint URLs, disable authentication, and set the event * processing protocol to @ref omni::telemetry::EndpointProtocol::eDefaultWithList. This mode * may only be used when the `/telemetry/extraFields/schemaid` value is also properly setup * and the rest of the app has been properly configured for use with an open endpoint. Without * a proper configuration, all events will be rejected from the open endpoint. */ constexpr const char* const kUseOpenEndpointSetting = "/telemetry/useOpenEndpoint"; /** This allows only a subset of the extra fields specified under `/structuredLog/extraFields/` * to be passed on to the transmitter when it is launched. By default all extra fields specified * under `/structuredLog/extraFields/` will be passed on to the transmitter to use, but will be * ignored by the transmitter. If a subset of those extra fields should be automatically added * to each message by the transmitter, they can be added to this setting's value in a single * comma separated list in a string. Any whitespace in the string will be ignored. If this * setting is undefined or contains an empty string, no extra fields will be automatically added * to each message. */ constexpr const char* const kExtraFieldsToAddSetting = "/telemetry/extraFieldsToAdd"; /** This controls whether the extra fields specified in @ref kExtraFieldsToAddSetting will be * replaced in each message if one or more of them already exists or if any fields that already * exist in the event will just be ignored. When set to `true`, the listed extra fields with * their given values will always overwrite any existing fields with the same name. When set * to `false`, if a field with the same name as one of the extra fields already exists in a * given event message, it will not be replaced. The default behavior is to never overwrite * existing fields (ie: set to `false`). */ constexpr const char* const kReplaceExtraFieldsSetting = "/telemetry/replaceExtraFields"; /** This settings key holds an object or an array of objects. * Each object is one transmitter instance. * In the settings JSON, this would look something like: * @code{JSON} * { * "telemetry": { * "transmitter": [ * { * "endpoint": "https://telemetry.not-a-real-url.nvidia.com", * }, * { * "endpoint": "https://metrics.also-not-a-real-url.nvidia.com" * } * ] * } * } * @endcode * You can also specify this on command line like this. * You must ensure that all entries under `/telemetry/transmitter` are contiguous numeric indices * otherwise `/telemetry/transmitter` will be interpreted as a single object. * @code{bash} * "--/telemetry/transmitter/0/endpoint=https://omniverse.kratos-telemetry.nvidia.com" \ * "--/telemetry/transmitter/1/endpoint=https://gpuwa.nvidia.com/dataflow/sandbox-jfeather-omniverse/posting" * @endcode * A transmitter instance sends data to a telemetry endpoint with a specific * configuration. * Each instance can be configured to use a different protocol and a different * set of schema URLs, so data sent to each endpoint can be substantially different. * To send data to multiple endpoints, you set up an array of objects under * this settings key. * Note that */ constexpr const char* const kTransmitterSetting = "/telemetry/transmitter"; /** This setting is an optional member of the @ref kTransmitterSetting object. * If this is set to `true`, the transmitter will ignore the `seek` field in the header * and start parsing from the start of each log again. This is only intended to be used * for testing purposes. This defaults to `false`. */ constexpr const char* const kResendEventsSettingLeaf = "resendEvents"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The maximum number of bytes to send in one transmission to the server. Event messages * will be sent in batches as large as possible up to this size. If more message data is * available than this limit, it will be broken up into multiple transmission units. This * must be less than or equal to the transmission limit of the endpoint the messages are * being sent to. If this is larger than the server's limit, large message buffers will * simply be rejected and dropped. This defaults to 10MiB. */ constexpr const char* const kTransmissionLimitSettingLeaf = "transmissionLimit"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This sets the maximum number of messages to process in a single pass on this transmitter. * The transmitter will stop processing log messages and start to upload messages when it * has found, validated, processed, and queued at most this number of messages on any given * transmitter object. Only validated and queued messages will count toward this limit. * This limit paired with @ref kTransmissionLimitSettingLeaf helps to limit how much of any * log file is processed and transmitted at any given point. This defaults to 10000 messages. */ constexpr const char* const kQueueLimitSettingLeaf = "queueLimit"; /** This setting is an optional member of the @ref kTransmitterSetting object. * Sets the URL to send the telemetry events to. This can be used to send the events to a * custom endpoint. This will override the default URL inferred by @ref kTelemetryModeSetting. * By default, the @ref kTelemetryModeSetting setting will determine the endpoint URL to use. * You can set this as an array if you want to specify multiple fallback endpoints * to use if the retry limit is exhausted; each endpoint will be tried in order * and will be abandoned if connectivity fails after the retry limit. * * This may also be a file URI if the output is to be written to a local log file. In this case, * this must be a "file:///" style URI since only local files are supported (ie: no server or * host name component). This file URI may also point to the special paths `/dev/stdout` or * `/dev/stderr` (ie: as "file:///dev/stdout") to output to stdout or stderr respectively * (supported on all platforms). When a local file or stdout/stderr is used as the destination * endpoint, all newly processed events will simply be appended to the end of the log file. * Exclusive write access to the local log file is expected while the transmitter is running. * The transmitter will lock the file (except stdout and stderr) while writing to it, but will * close the log after each write. If another process needs to read from it, advisory locking * should be used to guarantee the contents are not in a partial state. On Windows, this locking * should be done using one of the `LockFile*()` functions. On Posix platforms that support file * locking, this should be done using either `fcntl(f, F_SETLKW, ...)` for a blocking lock or * `fcntl(f, F_SETLK, ...)` for a non-blocking lock. Each line in the log file will represent * a single output event. * * @note Writing the transmitter output to a log file is only supported with the 'default' * and `defaultWithStringify` output protocols @ref kEventProtocolLeaf. If another * event protocol is used, it will be reverted to `default` instead. A warning message * will be output in this case. * * @note When outputting data to a file instead of a server URL, authentication will be * implicitly disabled since it is not needed. If the file URI should ever fail and * be removed from the transmitter (unlikely except in situations where for example the * device is full), the original specified state of the authentication flag will be * restored. In almost all situations, there is no need to authenticate with anything * when writing a local file. Leaving authentication enabled (the default behavior) would * just lead to that transmitter object simply sitting idle if the authentication * information could not be downloaded. The authentication can be disabled using the * @ref kTelemetryAuthenticateSettingLeaf setting. */ constexpr const char* const kTelemetryEndpointSettingLeaf = "endpoint"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the URL or URLs to download approved schemas from. This may be used to * override the default URL and the one specified by @ref kTelemetryModeSetting. This may * be treated either as a single URL string value or as an array of URL strings. The usage * depends on how the setting is specified by the user or config. If an array of URLs is * given, they are assumed to be in priority order starting with the first as the highest * priority URL. The first one that successfully downloads will be used as the schema * package. The others are considered to be backup URLs. This will be overridden by both * @ref kTelemetrySchemaFileSetting and @ref kTelemetrySchemasDirectorySetting. This * defaults to the Omniverse production schemas URL. * * @note In debug builds, this schemas package URL may also point to a local file. This * may be specified in both the single string and array forms of this setting. The * local file URI may be in the `file://` scheme form or as just a local (absolute) * or relative) filename. */ constexpr const char* const kTelemetrySchemasUrlSettingLeaf = "schemasUrl"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies that authentication should be enabled when sending event messages to the * telemetry endpoint. When disabled, this will prevent the auth token from being retrieved * from the Omniverse Launcher app. This should be used in situations where the Omniverse * Launcher app is not running or an endpoint that does not need or expect authorization is * used. If this is not used and the auth token cannot be retrieved from the Launcher app, the * transmitter will go into an idle mode where nothing is processed or sent. This mode is * expecting the Launcher app to become available at some future point. Setting this option * to `false` will disable the authentication checks and just attempt to push the events to * the specified telemetry endpoint URL. Note that the default endpoint URL will not work * if this option is used since it expected authentication. The default value is `true`. */ constexpr const char* const kTelemetryAuthenticateSettingLeaf = "authenticate"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the URL to download the authentication token from. This option will be * ignored if @ref kTelemetryAuthenticateSetting is `false`. A file will be expected to * be downloaded from this URL. The downloaded file is expected to be JSON formatted and * is expected to contain the authentication token in the format that the authentication * server expects. The name of the data property in the file that contains the actual * token to be sent with each message is specified in @ref kTelemetryAuthTokenKeyNameSetting. * The data property in the file that contains the token's expiry date is specified in * @ref kTelemetryAuthTokenExpiryNameSetting. Alternatively, this setting may also point * to a file on disk (either with the 'file://' protocol or by naming the file directly). * If a file on disk is named, it is assumed to either be JSON formatted and also contain * the token data and expiry under the same key names as given with * @ref kTelemetryAuthTokenKeyNameSetting and @ref kTelemetryAuthTokenExpiryNameSetting, * or it will be a file whose entire contents will be the token itself. The latter mode * is only used when the @ref kTelemetryAuthTokenKeyNameSetting setting is an empty string. * By default, the URL for the Omniverse Launcher's authentication web API will be used. */ constexpr const char* const kTelemetryAuthTokenUrlSettingLeaf = "authTokenUrl"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the name of the key in the downloaded authentication token's JSON data * that contains the actual token data to be sent with each set of uploaded messages. * This option will be ignored if @ref kTelemetryAuthenticateSetting is `false`. * This must be in the format that the authentication server expects. The token data * itself can be any length, but is expected to be string data in the JSON file. The * key is looked up in a case sensitive manner. This defaults to "idToken". */ constexpr const char* const kTelemetryAuthTokenKeyNameSettingLeaf = "authTokenKeyName"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the name of the key in the downloaded authentication token's JSON data * that contains the optional expiry date for the token. This option will be ignored if * @ref kTelemetryAuthenticateSetting is `false`.If this property exists, it will be used * to predict when the token should be retrieved again. If this property does not exist, * the token will only be retrieved again if sending a message results in a failure due * to a permission error. This property is expected to be string data in the JSON * file. Its contents must be formatted as an RFC3339 date/time string. This defaults to * "expires". */ constexpr const char* const kTelemetryAuthTokenExpiryNameSettingLeaf = "authTokenExpiryName"; /** This setting is an optional member of the @ref kTransmitterSetting object. * What serialization protocol is being used by the transmitter. * This can be set to one of three possible (case-insensitive) values: * - "default": This is the default protocol. The event will not be modified from its * original generated format and content. This includes leaving the `data` * field as a nested JSON object. This will send events in batches (as many * as are available at the time) to the server with each JSON event separated * by a newline (aka JSON lines format). * - "defaultWithStringify": This sends batches of events at a time to the server with each * JSON event separated by a newline (aka JSON lines format). Structuredlog * event format is largely left as-is; the only change is that the `data` * field's object is stringified. This is the only difference between this * protocol and the @ref `default` protocol above. * - "NVDF": This is also a batch serialization protocol, except that the event property * names are modified to follow the expectations of the server. * This flattens each event's `data` payload into the event base. * The `time` field is renamed to `ts_created` and its format * is changed to a *nix epoch time in milliseconds. * The `id` field is renamed to `_id`. * All data fields are also prefixed in a Hungarian-notation * style system. */ constexpr const char* const kEventProtocolLeaf = "eventProtocol"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The tag name that will be used to record how much of the file was processed. * Unless `kResendEventsSetting` is set to `true`, the seek tags are used to * tell the transmitter how much of the log has been processed so far so that * it won't try to send old events again. * The default value of this is "seek". * You may want to change the seek tag name if you need to send data to multiple * telemetry endpoints with separate transmitter processes. * * @note The telemetry log files have a 256 byte header. * Each seek tag will add 13 bytes to the header + the length of the tag * name. * When the log header space is exhausted, the header will not be updated, * which is equivalent to having `kResendEventsSetting` is set to `true`. * Please avoid long tag names to avoid this risk. */ constexpr const char* const kSeekTagNameLeaf = "seekTagName"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the expected type of the authentication token. This can be any of * "auto", "jwt", or "api-key". By default this is set to "auto" and will attempt to * detect the type of authentication token based on where the @ref kTelemetryAuthTokenUrlSetting * setting points. If the value points to a URL, a JWT will be assumed. If the value points * to a file on disk or directly contains the token itself, a long-lived API key will be assumed. * If an alternate storage method is needed but the assumed type doesn't match the actual * token type, this setting can be used to override the auto detection. The default value is * "auto". This setting will be ignored if @ref kTelemetryAuthenticateSetting is set to false. */ constexpr const char* const kTelemetryAuthTokenTypeLeaf = "authTokenType"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The number of days before the current time where events in a log start to be considered old. * When set to 0 (and this setting isn't overridden on a per-schema or per-event level), all * events are processed as normal and no events are considered old. When set to a non-zero * value, any events that are found to be older than this number of days will be processed * differently depending on the flags specified globally (@ref kIgnoreOldEventsSetting and * @ref kPseudonymizeOldEventsSetting), at the schema level (``fSchemaFlagIgnoreOldEvents`` * and ``fSchemaFlagPseudonymizeOldEvents``), and at the event level (``fEventFlagIgnoreOldEvents`` * and ``fEventFlagPseudonymizeOldEvents``). If no special flags are given, the default * behavior is to anonymize old events before transmitting them. This will only override the * old events threshold given at the schema (``#/oldEventsThreshold``) or event * (``#/events/<eventName>/oldEventsThreshold``) if it is a smaller non-zero value than the * values given at the lower levels. This defaults to 0 days (ie: disables checking for 'old' * events). */ constexpr const char* const kOldEventThresholdSettingLeaf = "oldEventThreshold"; /** This setting is an optional member of the @ref kTransmitterSetting object. * Flag to indicate that when an old event is detected, it should simply be discarded instead * of being anonymized or pseudonymized before transmission. This is useful if processing * old events is not interesting for analysis or if transmitting an old event will violate a * data retention policy. An event is considered old if it is beyond the 'old events threshold' * (see @ref kOldEventThresholdSetting). By default, old events will be anonymized before being * transmitted. If this flag is set here at the global level, it will override any old event * settings from the schema and event levels. */ constexpr const char* const kIgnoreOldEventsSettingLeaf = "ignoreOldEvents"; /** This setting is an optional member of the @ref kTransmitterSetting object. * Flag to indicate that when an old event is detected, it should be pseudonymized instead of * anonymized before transmission. This setting is ignored for any given event if the * @ref kIgnoreOldEventsSetting setting, ``fSchemaFlagIgnoreOldEvents`` flag, or * ``fEventFlagIgnoreOldEvents`` flag is used for that event. When not specified, the default * behavior is to anonymize old events before transmission. */ constexpr const char* const kPseudonymizeOldEventsSettingLeaf = "pseudonymizeOldEvents"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The number of attempts to transmit data that will be made before giving up. * This can be set to -1 to retry forever. * This setting is only important in a multi-endpoint context; if one endpoint * goes offline, a retry limit will allow the transmitter to give up and start * sending data to other endpoints. * There is an exponential backoff after every retry, so the first retry will * occur after 1 second, then 2 second, then 4 seconds, etc. * The backoff takes the transmission time into account, so the 4 second backoff * would only wait 1 second if the failed transmission took 3 seconds. * A setting of 5 will roughly wait for 1 minute in total. * A setting of 11 will roughly wait for 1 hour in total. * After the 12th wait, wait time will no longer increase, so each subsequent * wait will only last 4096 seconds. */ constexpr const char* const kRetryLimitSettingLeaf = "retryLimit"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This controls which messages will be considered by the transmitter and * which will be filtered out before validating against a schema. This is * intended to match each message's transmission mode against the mode that * the transmitter is currently running in. This value can be one of the * following: * * "all": allow all messages to be validated against schemas. * * "matching": allow messages whose source mode matches the transmitter's * current run mode. * * "matching+": allow messages whose source mode matches the transmitter's * current run mode or higher. * * "test": only consider messages from the 'test' source mode. * * "dev": only consider messages from the 'dev' source mode. * * "prod": only consider messages from the 'prod' source mode. * * "dev,prod" (or other combinations): only consider messages from the listed * source modes. * * This defaults to "all". This setting value may be used either on a * per-transmitter basis when using multiple transmitters, or it may be used in * the legacy setting `/telemetry/messageMatchMode`. If both the legacy and the * per-transmitter setting are present, the per-transmitter ones will always * override the legacy setting. * * @note Setting this to a value other than "all" would result in certain messages * not being transmitted because they were rejected during a previous run and * were skipped over in the log. It is intended that if this setting is used * for a given transmitter, it is likely to be used with that same matching * mode most often on any given machine. Note that multiple transmitters with * different matching modes can also be used. */ constexpr const char* const kMessageMatchingModeLeaf = "messageMatchMode"; /** @} */ /** Create a guard with the standard name and path for the transmitter. * @returns A UniqueApp guard that is used to let the transmitter know when * it should exit on its own. Telemetry clients should use this to * 'connect' to the transmitter (note that this does not require the * transmitter to be running yet). See launchTransmitter() for an * example usage. * @remarks This guard is needed by all telemetry clients to let the transmitter * know when all clients have shut down so it can exit as well. */ inline extras::UniqueApp createGuard() { constexpr const char* kLaunchGuardNameSetting = "/telemetry/launchGuardName"; carb::settings::ISettings* settings; const char* guardName = "omni.telemetry.transmitter"; auto getGuardPath = []() -> std::string { #if OMNI_PLATFORM_LINUX // XDG_RUNTIME_DIR is the standard place for putting runtime IPC objects on Linux const char* runDir = getenv("XDG_RUNTIME_DIR"); if (runDir != nullptr) { return runDir; } #endif core::ObjectPtr<omni::structuredlog::IStructuredLog> strucLog; core::ObjectPtr<omni::structuredlog::IStructuredLogSettings> settings; strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLog"); return ""; } settings = strucLog.as<structuredlog::IStructuredLogSettings>(); if (settings.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLogSettings"); return ""; } return settings->getLogOutputPath(); }; settings = carb::getCachedInterface<carb::settings::ISettings>(); if (settings != nullptr && settings->isAccessibleAs(carb::dictionary::ItemType::eString, kLaunchGuardNameSetting)) guardName = settings->getStringBuffer(kLaunchGuardNameSetting); return extras::UniqueApp(getGuardPath().c_str(), guardName); } /** Determine the directory where the logs of a launched transmitter process should go. * @returns The log output directory. */ inline std::string getTransmitterLogPath() { constexpr const char* kLogFileFallback = "./omni.telemetry.transmitter.log"; const char* logFile = nullptr; carb::settings::ISettings* settings = carb::getFramework()->tryAcquireInterface<carb::settings::ISettings>(); core::ObjectPtr<omni::structuredlog::IStructuredLog> strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); core::ObjectPtr<omni::structuredlog::IStructuredLogSettings> strucLogSettings; if (settings != nullptr) { settings->setDefaultString(kLogFileSetting, ""); logFile = settings->getStringBuffer(kLogFileSetting); if (logFile != nullptr && logFile[0] != '\0') return logFile; } else { CARB_LOG_ERROR("failed to acquire ISettings"); } if (strucLog.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLog - using CWD"); return kLogFileFallback; } strucLogSettings = strucLog.as<structuredlog::IStructuredLogSettings>(); if (strucLogSettings.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLogSettings - using CWD for the log file"); return kLogFileFallback; } return std::string(strucLogSettings->getLogOutputPath()) + "/omni.telemetry.transmitter.log"; } /** Launch the telemetry transmitter process. * @param[in] transmitterPath The path to the transmitter binary and .py file. * @param[in] pythonHome The path to your python install directory. * @param[in] pythonPath The path to the Carbonite python bindings. * @param[in] extraArgs Extra arguments to pass to the transmitter process. * @returns `true` if the transmitter child process is successfully launched. * Returns `false` otherwise. * * @remarks This function will launch an instance of the telemetry transmitter. * Any app using telemetry should launch the transmitter. * The transmitter process will upload telemetry events from the logs * to the Kratos endpoint. * The transmitter is currently dependent on the Omniverse Launcher to * obtain an authentication token to send telemetry. * Only one transmitter process will exist on a system at a time; if * one is launched while another exists, the new instance will exit. * The transmitter process will run until all telemetry client * processes have exited. * * @note The `/telemetry/log` tree of settings exists to specify log options for * the transmitter without affecting the parent process. * - `/telemetry/log/file` is passed to the transmitter as `/log/file'. * - `/telemetry/log/level` is passed to the transmitter as `/log/level'. * * @note This transmitter process won't log to the standard streams by default. * Logs will go to a standard log file path instead, but `--/log/file` can * be used to override this. * The transmitter process will exit after the host app, so logging to * the standard streams will result in messages being written into terminal * over the user's prompt. */ inline bool launchTransmitter(const char* transmitterPath, const std::vector<std::string> extraArgs = {}) { #if OMNI_PLATFORM_WINDOWS const char* ext = ".exe"; #else const char* ext = ""; #endif carb::launcher::ILauncher* launcher = carb::getFramework()->tryAcquireInterface<carb::launcher::ILauncher>(); carb::settings::ISettings* settings = carb::getFramework()->tryAcquireInterface<carb::settings::ISettings>(); extras::UniqueApp guard = createGuard(); carb::launcher::ArgCollector args; carb::launcher::EnvCollector env; carb::launcher::LaunchDesc desc = {}; size_t envCount; const char* logLevel = nullptr; if (launcher == nullptr) { OMNI_LOG_ERROR("failed to acquire ILauncher"); return false; } guard.connectClientProcess(); args.format("%s/omni.telemetry.transmitter%s", transmitterPath, ext); args.add("/telemetry", "--/", carb::launcher::fSettingsEnumFlagRecursive); args.add("/structuredLog/extraFields", "--/", 0); args.add("/log", "--/", carb::launcher::fSettingsEnumFlagRecursive, [](const char* path, void* ctx) { CARB_UNUSED(ctx); return strcmp(path, "/log/enableStandardStreamOutput") != 0 && strcmp(path, "/log/file") != 0 && strcmp(path, "/log/level") != 0; }); // output will not go to the standard streams because it's annoying if // output goes to your terminal after your process finishes and there is no // way to ensure the transmitter shuts down before your process args.add("--/log/enableStandardStreamOutput=false"); args.format("--/log/file=%s", getTransmitterLogPath().c_str()); if (settings == nullptr) { OMNI_LOG_ERROR("failed to acquire ISettings"); } else { settings->setDefaultString(kLogLevelSetting, ""); logLevel = settings->getStringBuffer(kLogLevelSetting); if (logLevel != nullptr && logLevel[0] != '\0') { args.format("--/log/level=%s", logLevel); } else { logLevel = settings->getStringBuffer("/log/level"); if (logLevel != nullptr && logLevel[0] != '\0') { args.format("--/log/level=%s", logLevel); } } } for (const std::string& arg : extraArgs) { args.add(arg); } // add the parent environment but remove the `CARB_APP_PATH` and `CARB_APP_NAME` variables // since they will negatively affect the behaviour of the transmitter. Note that since // we're explicitly adding the full parent environment here and just subtracting some // variables, we need to also use the `fLaunchFlagNoInheritEnv` flag when launching the // child process so that ILauncher doesn't implicitly add them back. env.add(); envCount = env.getCount(); env.remove("CARB_APP_PATH"); env.remove("CARB_APP_NAME"); if (env.getCount() != envCount) { desc.flags |= carb::launcher::fLaunchFlagAllowBadEnv | carb::launcher::fLaunchFlagNoInheritEnv; desc.env = env.getEnv(); desc.envCount = env.getCount(); } desc.argv = args.getArgs(&desc.argc); desc.flags |= carb::launcher::fLaunchFlagNoStdStreams; return launcher->launchProcessDetached(desc) != carb::launcher::kBadId; } } // namespace telemetry } // namespace omni
omniverse-code/kit/include/omni/structuredlog/StringView.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 A string_view wrapper to make telemetry calls easier. */ #pragma once #include "../../carb/cpp/StringView.h" #include <string> namespace omni { namespace structuredlog { /** An extension of carb::cpp::basic_string_view that can handle nullptr and * `std::basic_string` as inputs * * @tparam CharT The char type pointed to by the view. * @tparam Traits The type traits for @p CharT. */ template <class CharT, class Traits = std::char_traits<CharT>> class BasicStringView : public carb::cpp::basic_string_view<CharT, Traits> { public: constexpr BasicStringView() : base() { } /** Create a string view from a C string. * @param[in] s The C string to create a view into. * This original pointer continues to be used and nothing is copied. */ constexpr BasicStringView(const CharT* s) : base(s, s == nullptr ? 0 : Traits::length(s)) { } /** Create a string view from a char buffer * @param[in] s The char buffer to create a view into. * This does not need to be null terminated. * This original pointer continues to be used and nothing is copied. * @param[in] len The length of the view into @p s, in characters. */ constexpr BasicStringView(const CharT* s, size_t len) : base(s, len) { } /** Create a string view from a std::basic_string. * @param[in] s The string to create this string view for. */ constexpr BasicStringView(const std::basic_string<CharT>& s) : base(s.c_str(), s.size()) { } private: using base = carb::cpp::basic_string_view<CharT, Traits>; }; /** String view for `char` strings. */ using StringView = BasicStringView<char>; } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/StructuredLog.ProcessLifetime.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.ProcessLifetime.json // #pragma once #include <omni/log/ILog.h> #include <omni/structuredlog/IStructuredLog.h> #include <omni/structuredlog/JsonTree.h> #include <omni/structuredlog/BinarySerializer.h> #include <omni/structuredlog/StringView.h> #include <memory> namespace omni { namespace structuredlog { /** helper macro to send the 'event' event. * * @param[in] eventFlags_ The flags to pass directly to the event handling * function. This may be any of the AllocFlags flags that can * be passed to @ref omni::structuredlog::IStructuredLog::allocEvent(). * @param[in] event_ Parameter from schema at path '/event'. * the name of the process lifetime event that occurred. This may be * any string to identify the event. This event may be used by the * host app as well to measure its own startup times. * @param[in] context_ Parameter from schema at path '/context'. * extra information about the event that occurred. This may be * nullptr or an empty string if not needed for a particular event. * @returns no return value. * * @remarks Event to send when the app starts, exits, crashes, etc. This * event can also be used to measure other host app events by simply * sending different 'event' and 'context' strings. The main purpose * of this is to track session time and the relative frequency of * crashes. * * @sa @ref Schema_omni_processlifetime_1_1::event_sendEvent(). * @sa @ref Schema_omni_processlifetime_1_1::event_isEnabled(). */ #define OMNI_OMNI_PROCESSLIFETIME_1_1_EVENT(eventFlags_, event_, context_) \ OMNI_STRUCTURED_LOG(omni::structuredlog::Schema_omni_processlifetime_1_1::event, eventFlags_, event_, context_) /** helper macro to send the 'heartbeat' event. * * @returns no return value. * * @remarks Event to send periodically to give an indication that the process * is still alive and the session is still valid. This can also be * used to measure session lengths in the case where no 'exit' or * 'crash' event can be found (ie: power loss, user kill, BSOD/kernel * panic, etc). * * @sa @ref Schema_omni_processlifetime_1_1::heartbeat_sendEvent(). * @sa @ref Schema_omni_processlifetime_1_1::heartbeat_isEnabled(). */ #define OMNI_OMNI_PROCESSLIFETIME_1_1_HEARTBEAT() \ OMNI_STRUCTURED_LOG(omni::structuredlog::Schema_omni_processlifetime_1_1::heartbeat) class Schema_omni_processlifetime_1_1 { public: /** the event ID names used to send the events in this schema. These IDs * are used when the schema is first registered, and are passed to the * allocEvent() function when sending the event. */ enum : uint64_t { kEventEventId = OMNI_STRUCTURED_LOG_EVENT_ID( "omni.processlifetime", "com.nvidia.carbonite.processlifetime.event", "1.1", "0"), kHeartbeatEventId = OMNI_STRUCTURED_LOG_EVENT_ID( "omni.processlifetime", "com.nvidia.carbonite.processlifetime.heartbeat", "1.1", "0"), }; Schema_omni_processlifetime_1_1() = default; /** Register this class with the @ref omni::structuredlog::IStructuredLog interface. * @param[in] flags The flags to pass into @ref omni::structuredlog::IStructuredLog::allocSchema() * This may be zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @returns `true` if the operation succeeded. * @returns `false` if @ref omni::structuredlog::IStructuredLog couldn't be loaded. * @returns `false` if a memory allocation failed. */ static bool registerSchema(omni::structuredlog::IStructuredLog* strucLog) noexcept { return _registerSchema(strucLog); } /** Check whether this structured log schema is enabled. * @param[in] eventId the ID of the event to check the enable state for. * This must be one of the @a k*EventId symbols * defined above. * @returns Whether this client is enabled. */ static bool isEnabled(omni::structuredlog::EventId eventId) noexcept { return _isEnabled(eventId); } /** Enable/disable an event in this schema. * @param[in] eventId the ID of the event to enable or disable. * This must be one of the @a k*EventId symbols * defined above. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(omni::structuredlog::EventId eventId, bool enabled) noexcept { _setEnabled(eventId, enabled); } /** Enable/disable this schema. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(bool enabled) noexcept { _setEnabled(enabled); } /** event enable check helper functions. * * @param[in] strucLog The structured log object to use to send this event. This * must not be nullptr. It is the caller's responsibility * to ensure that a valid object is passed in. * @returns `true` if the specific event and this schema are both enabled. * @returns `false` if either the specific event or this schema is disabled. * * @remarks These check if an event corresponding to the function name is currently * enabled. These are useful to avoid parameter evaluation before calling * into one of the event emitter functions. These will be called from the * OMNI_STRUCTURED_LOG() macro. These may also be called directly if an event * needs to be emitted manually, but the only effect would be the potential * to avoid parameter evaluation in the *_sendEvent() function. Each * *_sendEvent() function itself will also internally check if the event * is enabled before sending it. * @{ */ static bool event_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kEventEventId); } static bool heartbeat_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kHeartbeatEventId); } /** @} */ /** Send the event 'com.nvidia.carbonite.processlifetime.event' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] eventFlags The flags to pass directly to the event handling * function. This may be any of the AllocFlags flags that can * be passed to @ref omni::structuredlog::IStructuredLog::allocEvent(). * @param[in] event Parameter from schema at path '/event'. * the name of the process lifetime event that occurred. This may be * any string to identify the event. This event may be used by the * host app as well to measure its own startup times. * @param[in] context Parameter from schema at path '/context'. * extra information about the event that occurred. This may be * nullptr or an empty string if not needed for a particular event. * @returns no return value. * * @remarks Event to send when the app starts, exits, crashes, etc. This * event can also be used to measure other host app events by simply * sending different 'event' and 'context' strings. The main purpose * of this is to track session time and the relative frequency of * crashes. */ static void event_sendEvent(omni::structuredlog::IStructuredLog* strucLog, AllocFlags eventFlags, const omni::structuredlog::StringView& event, const omni::structuredlog::StringView& context) noexcept { _event_sendEvent(strucLog, eventFlags, event, context); } /** Send the event 'com.nvidia.carbonite.processlifetime.heartbeat' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @returns no return value. * * @remarks Event to send periodically to give an indication that the process * is still alive and the session is still valid. This can also be * used to measure session lengths in the case where no 'exit' or * 'crash' event can be found (ie: power loss, user kill, BSOD/kernel * panic, etc). */ static void heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog) noexcept { _heartbeat_sendEvent(strucLog); } private: /** This will allow us to disable array length checks in release builds, * since they would have a negative performance impact and only be hit * in unusual circumstances. */ static constexpr bool kValidateLength = CARB_DEBUG; /** body for the registerSchema() public function. */ static bool _registerSchema(omni::structuredlog::IStructuredLog* strucLog) { omni::structuredlog::AllocHandle handle = {}; omni::structuredlog::SchemaResult result; uint8_t* buffer; omni::structuredlog::EventInfo events[2] = {}; size_t bufferSize = 0; size_t total = 0; omni::structuredlog::SchemaFlags flags = 0; if (strucLog == nullptr) { OMNI_LOG_WARN( "no structured log object! The schema " "'Schema_omni_processlifetime_1_1' " "will be disabled."); return false; } // calculate the tree sizes size_t event_size = _event_calculateTreeSize(); size_t heartbeat_size = _heartbeat_calculateTreeSize(); // calculate the event buffer size bufferSize += event_size; bufferSize += heartbeat_size; // begin schema creation buffer = strucLog->allocSchema("omni.processlifetime", "1.1", flags, bufferSize, &handle); if (buffer == nullptr) { OMNI_LOG_ERROR("allocSchema failed (size = %zu bytes)", bufferSize); return false; } // register all the events events[0].schema = _event_buildJsonTree(event_size, buffer + total); events[0].eventName = "com.nvidia.carbonite.processlifetime.event"; events[0].parserVersion = 0; events[0].eventId = kEventEventId; events[0].flags = omni::structuredlog::fEventFlagCriticalEvent | omni::structuredlog::fEventFlagUseLocalLog; total += event_size; events[1].schema = _heartbeat_buildJsonTree(heartbeat_size, buffer + total); events[1].eventName = "com.nvidia.carbonite.processlifetime.heartbeat"; events[1].parserVersion = 0; events[1].eventId = kHeartbeatEventId; events[1].flags = omni::structuredlog::fEventFlagCriticalEvent | omni::structuredlog::fEventFlagUseLocalLog; total += heartbeat_size; result = strucLog->commitSchema(handle, events, CARB_COUNTOF(events)); if (result != omni::structuredlog::SchemaResult::eSuccess && result != omni::structuredlog::SchemaResult::eAlreadyExists) { OMNI_LOG_ERROR( "failed to register structured log events " "{result = %s (%zu)}", getSchemaResultName(result), size_t(result)); return false; } return true; } /** body for the isEnabled() public function. */ static bool _isEnabled(omni::structuredlog::EventId eventId) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); return strucLog != nullptr && strucLog->isEnabled(eventId); } /** body for the setEnabled() public function. */ static void _setEnabled(omni::structuredlog::EventId eventId, bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(eventId, 0, enabled); } /** body for the setEnabled() public function. */ static void _setEnabled(bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(kEventEventId, omni::structuredlog::fEnableFlagWholeSchema, enabled); } #if OMNI_PLATFORM_WINDOWS # pragma warning(push) # pragma warning(disable : 4127) // warning C4127: conditional expression is constant. #endif /** body for the event_sendEvent() function. */ static void _event_sendEvent(omni::structuredlog::IStructuredLog* strucLog, AllocFlags eventFlags, const omni::structuredlog::StringView& event, const omni::structuredlog::StringView& context) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && event.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'event' exceeds max value 65535 - " "it will be truncated (size was %zu)", event.length() + 1); } // property event calc.track(event); if (kValidateLength && context.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'context' exceeds max value 65535 - " "it will be truncated (size was %zu)", context.length() + 1); } // property context calc.track(context); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kEventEventId, eventFlags, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.carbonite.processlifetime.event'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property event writer.copy(event); // property context writer.copy(context); } strucLog->commitEvent(handle); } /** body for the heartbeat_sendEvent() function. */ static void _heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog) noexcept { omni::structuredlog::AllocHandle handle = {}; // write out the event into the buffer if (strucLog->allocEvent(0, kHeartbeatEventId, 0, 0, &handle) == nullptr) { OMNI_LOG_ERROR( "failed to allocate a buffer for structured log event com.nvidia.carbonite.processlifetime.heartbeat"); return; } strucLog->commitEvent(handle); } #if OMNI_PLATFORM_WINDOWS # pragma warning(pop) #endif /** Calculate JSON tree size for structured log event: com.nvidia.carbonite.processlifetime.event. * @returns The JSON tree size in bytes for this event. */ static size_t _event_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(2); // object has 2 properties { // property event calc.trackName("event"); calc.track(static_cast<const char*>(nullptr)); // property context calc.trackName("context"); calc.track(static_cast<const char*>(nullptr)); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.carbonite.processlifetime.event. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _event_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.carbonite.processlifetime.event' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property event result = builder.setName(&base->data.objVal[0], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property context result = builder.setName(&base->data.objVal[1], "context"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.carbonite.processlifetime.heartbeat. * @returns The JSON tree size in bytes for this event. */ static size_t _heartbeat_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(0); // object has 0 properties { } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.carbonite.processlifetime.heartbeat. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _heartbeat_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.carbonite.processlifetime.heartbeat' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 0); // object has 0 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { } return base; } /** The callback that is used to report validation errors. * @param[in] s The validation error message. */ static void _onStructuredLogValidationError(const char* s) { OMNI_LOG_ERROR("error sending a structured log event: %s", s); } }; // asserts to ensure that no one's modified our dependencies static_assert(omni::structuredlog::BlobWriter<>::kVersion == 0, "BlobWriter version changed"); static_assert(omni::structuredlog::JsonNode::kVersion == 0, "JsonNode version changed"); static_assert(sizeof(omni::structuredlog::JsonNode) == 24, "unexpected size"); static_assert(std::is_standard_layout<omni::structuredlog::JsonNode>::value, "this type needs to be ABI safe"); static_assert(offsetof(omni::structuredlog::JsonNode, type) == 0, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, flags) == 1, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, len) == 2, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, nameLen) == 4, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, name) == 8, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, data) == 16, "struct layout changed"); } // namespace structuredlog } // namespace omni OMNI_STRUCTURED_LOG_ADD_SCHEMA(omni::structuredlog::Schema_omni_processlifetime_1_1, omni_processlifetime, 1_1, 0);
omniverse-code/kit/include/omni/structuredlog/IStructuredLog.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 /** Main structured log interface. This should be treated internally as a global singleton. Any * attempt to create or acquire this interface will return the same object just with a new * reference taken on it. * * There are three main steps to using this interface: * * Set up the interface. For most app's usage, all of the default settings will suffice. * The default log path will point to the Omniverse logs folder and the default user ID * will be the one read from the current user's privacy settings file (if it exists). If * the default values for these is not sufficient, a new user ID should be set with * @ref omni::structuredlog::IStructuredLogSettings::setUserId() and a log output path should be set with * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * If the privacy settings file is not present, * the user name will default to a random number. The other defaults should be sufficient * for most apps. This setup only needs to be performed once by the host app if at all. * The @ref omni::structuredlog::IStructuredLogSettings interface can be acquired either * by casting an @ref omni::structuredlog::IStructuredLog * object to that type or by directly creating the @ref omni::structuredlog::IStructuredLogSettings * object using omni::core::ITypeFactory_abi::createType(). * * Register one or more event schemas. * This is done with @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema(). * At least one event must be registered for any events to * be processed. Once a schema has been registered, it will remain valid until the * structured log module is unloaded from the process. There is no way to forcibly * unregister a set of events once registered. * * Send zero or more events. This is done with the @ref omni::structuredlog::IStructuredLog::allocEvent() and * @ref omni::structuredlog::IStructuredLog::commitEvent() functions. * * For the most part, the use of this interface will be dealt with in generated code. This * generated code will come from the 'omni.structuredlog' tool in the form of an inlined header * file. It is the host app's responsibility to call the header's schema registration helper * function at some point on startup before any event helper functions are called. * * All messages generated by this structured log system will be CloudEvents v1.0 compliant. * These should be parsable by any tool that is capable of understanding CloudEvents. * * Before an event can be sent, at least one schema describing at least one event must be * registered. This is done with the @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema() functions. * The @ref omni::structuredlog::IStructuredLog::allocSchema() function returns * a handle to a block of memory owned by the structured log system and a pointer to that block's * data. The caller is responsible for both calculating the required size of the buffer before * allocating, and filling it in with the schema data trees for each event that can be sent as * part of that schema. The helper functions in @ref omni::structuredlog::JsonTreeSizeCalculator and * @ref omni::structuredlog::JsonBuilder can be used to build these trees. Once these trees are built, they are * stored in a number of entries in an array of @ref omni::structuredlog::EventInfo objects. This array of event * info objects is then passed to @ref omni::structuredlog::IStructuredLog::commitSchema() to complete the schema * registration process. * * Sending of a message is split into two parts for efficiency. The general idea is that the * caller will allocate a block of memory in the event queue's buffer and write its data directly * there. * The allocation occurs with the @ref omni::structuredlog::IStructuredLog::allocEvent() call. * This will return a * handle to the allocated block and a pointer to the first byte to start writing the payload * data to. The buffer's header will already have been filled in upon return from * @ref omni::structuredlog::IStructuredLog::allocEvent(). * Once the caller has written its event payload information to * the buffer, it will call @ref omni::structuredlog::IStructuredLog::commitEvent() * to commit the message to the queue. At * this point, the message can be consumed by the event processing thread. * * Multiple events may be safely allocated from and written to the queue's buffer simultaneously. * There is no required order that the messages be committed in however. If a buffer is * allocated after one that has not been committed yet, and that newer event is committed first, * the only side effect will be that the event processing thread will be stalled in processing * new events until the first message is also committed. This is important since the events * would still need to be committed to the log in the correct order. * * All events that are processed through this interface will be written to a local log file. The * log file will be periodically consumed by an external process (the Omniverse Transmitter app) * that will send all the approved events to the telemetry servers. Only events that have been * approved by legal will be sent. All other messages will be rejected and only remain in the * log files on the local machine. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLog_abi> : public omni::structuredlog::IStructuredLog_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLog") /** Checks whether a specific event or schema is enabled. * * @param[in] eventId The unique ID of the event to check the enable state of. This * is the ID that was originally used to register the event. * @returns `true` if both the requested event and its schema is enabled. * @returns `false` if either the requested event or its schema is disabled. * * @remarks This checks if a named event or its schema is currently enabled in the structured * log system. Individual events or entire schemas may be disabled at any given * time. Both the schema and each event has its own enable state. A schema can be * disabled while still leaving its events' previous enable/disable states * unmodified. When the schema is enabled again, its events will still retain their * previous enable states. Set @ref omni::structuredlog::IStructuredLog::setEnabled() * for more information on how to enable and disable events and schemas. */ bool isEnabled(omni::structuredlog::EventId eventId) noexcept; /** Sets the enable state for a structured log event or schema, or the system globally. * * @param[in] eventId The ID of the event to change the enable state of. This is the ID * that was originally used to register the event. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this must be * set to @ref omni::structuredlog::kBadEventId. * @param[in] flags Flags to control the behavior of this function. This may be zero or * more of the @ref omni::structuredlog::EnableFlags flags. * If this includes the @ref omni::structuredlog::fEnableFlagAll * flag, @p eventId must be set to @ref omni::structuredlog::kBadEventId. * @param[in] enabled Set to true to enable the named event or schema. Set to false to * disable the named event or schema. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this sets the * new enable/disable state for the structured log system as a whole. * @returns No return value. * * @remarks This changes the current enable state for an event or schema. The scope of the * enable change depends on the flags that are passed in. When an event is * disabled (directly or from its schema or the structured log system being * disabled), it will also prevent it from being generated manually. In this case, * any attempt to call @ref omni::structuredlog::IStructuredLog::allocEvent() for * that disabled event or schema will simply fail immediately. * * @remarks When a schema is disabled, it effectively disables all of its events. Depending * on the flag usage however (ie: @ref omni::structuredlog::fEnableFlagOverrideEnableState), * disabling the schema may or may not change the enable states of each of its * individual events as well (see @ref omni::structuredlog::fEnableFlagOverrideEnableState * for more information). * * @note The @ref omni::structuredlog::fEnableFlagAll flag should only ever by used by the * main host app since this will affect the behavior of all modules' events regardless * of their own internal state. Disabling the entire system should also only ever be * used sparingly in cases where it is strictly necessary (ie: compliance with local * privacy laws). */ void setEnabled(omni::structuredlog::EventId eventId, omni::structuredlog::EnableFlags flags, bool enabled) noexcept; /** Allocates a block of memory for an event schema. * * @param[in] schemaName The name of the schema being registered. This may not be * nullptr or an empty string. There is no set format for this * schema name, but it should at least convey some information * about the app's name and current release version. This name * will be used to construct the log file name for the schema. * @param[in] schemaVersion The version number for the schema itself. This may not be * nullptr or an empty string. This should be the version number * of the schema itself, not of the app or component. This will * be used to construct the 'dataschema' name that gets passed * along with each CloudEvents message header. * @param[in] flags Flags to control the behavior of the schema. This may be * zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @param[in] size The size of the block to allocate in bytes. If this is 0, a * block will still be allocated, but its actual size cannot be * guaranteed. The @ref omni::structuredlog::JsonTreeSizeCalculator * helper class can be used to calculate the size needs for the new schema. * @param[out] outHandle Receives the handle to the allocated memory block on success. * On failure, this receives nullptr. Each successful call * must pass this handle to @ref omni::structuredlog::IStructuredLog::commitSchema() * even if an intermediate failure occurs. In the case of a schema * tree creation failure, nullptr should be passed for @a events * in the corresponding @ref omni::structuredlog::IStructuredLog::commitSchema() call. * This will allow the allocated block to be cleaned up. * @returns A pointer to the allocated block on success. This block does not need to be * explicitly freed - it will be managed internally. This pointer will point to * the first byte that can be written to by the caller and will be at least @p size * bytes in length. This pointer will always be aligned to the size of a pointer. * @returns `nullptr` if no more memory is available. * @returns `nullptr` if an invalid parameter is passed in. * * @remarks This allocates a block of memory that the schema tree(s) for the event(s) in a * schema can be created and stored in. Pointers to the start of each event schema * within this block are expected to be stored in one of the @ref omni::structuredlog::EventInfo objects * that will later be passed to @ref omni::structuredlog::IStructuredLog::commitSchema(). The caller is * responsible for creating and filling in returned block and the array of * @ref omni::structuredlog::EventInfo objects. * The @ref omni::structuredlog::BlockAllocator helper class may be used to * allocate smaller chunks of memory from the returned block. * * @note This should only be used in generated structured log source code. This should not * be directly except when absolutely necessary. This should also not be used as a * generic allocator. Failure to use this properly will result in memory being * leaked. * * @thread_safety This call is thread safe. */ uint8_t* allocSchema(const char* schemaName, const char* schemaVersion, omni::structuredlog::SchemaFlags flags, size_t size, omni::structuredlog::AllocHandle* outHandle) noexcept; /** Commits an allocated block and registers events for a single schema. * * @param[in] schemaBlock The block previously returned from * @ref omni::structuredlog::IStructuredLog::allocSchema() * that contains the built event trees for the schema to register. * These trees must be pointed to by the @ref omni::structuredlog::EventInfo::schema * members of the @p events array. * @param[in] events The table of events that belong to this schema. This provides * information about each event such as its name, control flags, * event identifier, and a schema describing how to interpret its * binary blob on the consumer side. This may not be nullptr. Each * of the trees pointed to by @ref omni::structuredlog::EventInfo::schema in this table * must either be set to nullptr or point to an address inside the * allocated schema block @p schemaBlock that was returned from the * corresponding call to @ref omni::structuredlog::IStructuredLog::allocSchema(). * If any of the schema trees point to an address outside of the schema block, * this call will fail. * @param[in] eventCount The total number of events in the @p events table. At least one * event must be registered. This may not be 0. * @retval omni::structuredlog::SchemaResult::eSuccess if the new schema * is successfully registered as a set of unique events. * @retval omni::structuredlog::SchemaResult::eAlreadyExists if the new * schema exactly matches one that has already been successfully registered. * This can be considered a successful result. * In this case, the schema block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eEventIdCollision if the new schema contains an event whose * identifier matches that of an event that has already been registered with another * schema. This indicates that the name of the event that was used to generate the * identifier was likely not unique enough, or that two different versions of the * same schema are trying to be registered without changing the schema's version * number first. No new events will be registered in this case and the schema * block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eFlagsDiffer if the new schema exactly matches another schema * that has already been registered except for the schema flags that were used * in the new one. This is not allowed without a version change in the new schema. * No new events will be registered in this case and the schema block will be * destroyed before return. * @returns Another @ref omni::structuredlog::SchemaResult error code for other types of failures. No new events * will be registered in this case and the schema block will be destroyed before * return. * * @remarks This registers a new schema and its events with the structured log system. This * will create a new set of events in the structured log system. These events * cannot be unregistered except by unloading the entire structured log system * altogether. Upon successful registration, the events in the schema can be * emitted using the event identifiers they were registered with. * * @remarks If the new schema matches one that has already been registered, The operation * will succeed with the result @ref omni::structuredlog::SchemaResult::eAlreadyExists. * The existing * schema's name, version, flags, and event table (including order of events) must * match the new one exactly in order to be considered a match. If anything differs * (even the flags for a single event or events out of order but otherwise the same * content), the call will fail. If the schema with the differing flags or event * order is to be used, its version or name must be changed to avoid conflict with * the existing schema. * * @remarks When generating the event identifiers for @ref omni::structuredlog::EventInfo::eventId it is * recommended that a string uniquely identifying the event be created then hashed * using an algorithm such as FNV1. The string should contain the schema's client * name, the event's name, the schema's version, and any other values that may * help to uniquely identify the event. Once hashed, it is very unlikely that * the event identifier will collide with any others. This is the method that the * code generator tool uses to create the unique event identifiers. * * @remarks Up to 65536 (ie: 16-bit index values) events may be registered with the * structured log system. The performance of managing a list of events this large * is unknown and not suggested however. Each module, app, or component should only * register its schema(s) once on startup. This can be a relatively expensive * operation if done frequently and unnecessarily. * * @thread_safety This call is thread safe. */ omni::structuredlog::SchemaResult commitSchema(omni::structuredlog::AllocHandle schemaBlock, const omni::structuredlog::EventInfo* events, size_t eventCount) noexcept; /** Allocates a block of memory to store an event's payload data in. * * @param[in] version The version of the parser that should be used to read this * event's payload data. This should be @ref omni::structuredlog::kParserVersion. * If the structured log system that receives this message does not * support this particular version (ie: a newer module is run * on an old structured log system), the event message will simply * be dropped. * @param[in] eventId the unique ID of the event that is being generated. This ID must * exactly match the event ID that was provided in the * @ref omni::structuredlog::EventInfo::eventId value when the event * was registered. * @param[in] flags Flags to control how the event's block is allocated. This may * be a combination of zero or more of the @ref omni::structuredlog::AllocFlags * flags. * @param[in] payloadSize The total number of bytes needed to store the event's payload * data. The caller is responsible for calculating this ahead * of time. If the event does not have a payload, this should be * 0. The number of bytes should be calculated according to how * the requested event's schema (ie: @ref omni::structuredlog::EventInfo::schema) lays * it out in memory. * @param[out] outHandle Receives the handle to the allocated block of memory. This * must be passed to IStructuredLog::commitEvent() once the caller * has finished writing all of the payload data to the returned * buffer. The IStructuredLog::commitEvent() call acts as the * cleanup function for this handle. * @returns A pointer to the buffer to use for the event's payload data if successfully * allocated. The caller should start writing its payload data at this address * according to the formatting information in the requested event's schema. This * returned pointer will always be aligned to the size of a pointer. * @returns `nullptr` if the requested event, its schema, or the entire system is currently * disabled. * @returns `nullptr` if the event queue's buffer is full and a buffer of the requested * size could not be allocated. In this case, a invalid handle will be returned * in @p outHandle. The IStructuredLog::commitEvent() function does not need to be * called in this case. * @returns `nullptr` if the event queue failed to be created or its processing thread failed * start up. * @returns `nullptr` if the given event ID is not valid. * * @remarks This is the main entry point for creating an event message. This allocates * a block of memory that the caller can fill in with its event payload data. * The caller is expected to fill in this buffer as quickly as possible. Once * the buffer has been filled, its handle must be passed to the * @ref omni::structuredlog::IStructuredLog::commitEvent() function to finalize and send. * Failing to pass a * valid handle to @ref omni::structuredlog::IStructuredLog::commitEvent() will stall the event queue * indefinitely. * * @remarks If the requested event has been marked as 'critical' by using the event flag * @ref omni::structuredlog::fEventFlagCriticalEvent, a blocking allocation will be used here instead. * In this case, this will not fail due to the event queue being out of space. * * @note This call will fail immediately if either the requested event, its schema, or * the entire system has been explicitly disabled. It is the caller's responsibility * to both check the enable state of the event before attempting to send it (ie: to * avoid doing unnecessary work), and to gracefully handle the potential of this * call failing. * * @note It is the caller's responsibility to ensure that no events are generated during * C++ static destruction time for the process during shutdown. Especially on * Windows, doing so could result in an event being allocated but not committed * thereby stalling the event queue. This could lead to a hang on shutdown. * * @thread_safety This call is thread safe. */ uint8_t* allocEvent(omni::structuredlog::ParserVersion version, omni::structuredlog::EventId eventId, omni::structuredlog::AllocFlags flags, size_t payloadSize, omni::structuredlog::AllocHandle* outHandle) noexcept; /** finishes writing a message's payload and queues it for processing. * * @param[in] handle The handle to the queue buffer block to be committed. This must not * be nullptr. This must be the same handle that was returned through * @a outHandle on a recent call to @ref omni::structuredlog::IStructuredLog::allocEvent() * on this same thread. Upon return, this handle will be invalid and should be * discarded by the caller. * @returns No return value. * * @remarks This commits a block that was previously allocated on this thread with * @ref omni::structuredlog::IStructuredLog::allocEvent(). * It is required that the commit call occur on the * same thread that the matching @ref omni::structuredlog::IStructuredLog::allocEvent() * call was made on. * Each successful @ref omni::structuredlog::IStructuredLog::allocEvent() call must * be paired with exactly one * @ref omni::structuredlog::IStructuredLog::commitEvent() call on the same thread. * Failing to do so would result in the event queue thread stalling. * * @thread_safety This call is thread safe. */ void commitEvent(omni::structuredlog::AllocHandle handle) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::isEnabled( omni::structuredlog::EventId eventId) noexcept { return isEnabled_abi(eventId); } inline void omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::setEnabled( omni::structuredlog::EventId eventId, omni::structuredlog::EnableFlags flags, bool enabled) noexcept { setEnabled_abi(eventId, flags, enabled); } inline uint8_t* omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::allocSchema( const char* schemaName, const char* schemaVersion, omni::structuredlog::SchemaFlags flags, size_t size, omni::structuredlog::AllocHandle* outHandle) noexcept { return allocSchema_abi(schemaName, schemaVersion, flags, size, outHandle); } inline omni::structuredlog::SchemaResult omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::commitSchema( omni::structuredlog::AllocHandle schemaBlock, const omni::structuredlog::EventInfo* events, size_t eventCount) noexcept { return commitSchema_abi(schemaBlock, events, eventCount); } inline uint8_t* omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::allocEvent( omni::structuredlog::ParserVersion version, omni::structuredlog::EventId eventId, omni::structuredlog::AllocFlags flags, size_t payloadSize, omni::structuredlog::AllocHandle* outHandle) noexcept { return allocEvent_abi(version, eventId, flags, payloadSize, outHandle); } inline void omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::commitEvent( omni::structuredlog::AllocHandle handle) noexcept { commitEvent_abi(handle); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::structuredlog::EventInfo>::value, "omni::structuredlog::EventInfo must be standard layout to be used in ONI ABI");
omniverse-code/kit/include/omni/structuredlog/IStructuredLogControl.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- 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 /** Structured log state control interface. This allows for some control over the processing of * events and log files for the structured log system. The structured log system's event queue * can be temporarily stopped if needed or the output log for a schema may be closed. Each of * these operations is only temporary as the event queue will be restarted and the log file * opened when the next event is queued with @ref omni::structuredlog::IStructuredLog::allocEvent(). * * This interface object can be acquired either by requesting it from the type factory or * by casting an @ref omni::structuredlog::IStructuredLog object to this type. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogControl_abi> : public omni::structuredlog::IStructuredLogControl_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogControl") /** Closes one or more schema's persistently open log file(s). * * @param[in] event The ID of the event to close the log for. This may also be * @ref omni::structuredlog::kAllSchemas to close all log file for * the process. The log file for the schema that the given event * belongs to will be closed. * @returns No return value. * * @remarks This closes the persistently open log file(s) for one or more schemas. This * operation will effectively be ignored for schemas that were not registered * using the @ref omni::structuredlog::fSchemaFlagKeepLogOpen schema flag since those schemas will * not leave their logs open. The named log files will only remain closed until * the next attempt to write an event message to it. It is the responsibility * of the host app to ensure no events are written to the effected log file(s) * for the duration that the log needs to remain closed. * * @note This call itself is thread safe. However the log file may be reopened if a * pending event is processed in the event queue or a new event is sent while * the calling thread expects the log to remain closed. It is the caller's * responsibility to either stop the event queue, disable structured logging, or * prevent other events from being sent while the log(s) need to remain closed. */ void closeLog(omni::structuredlog::EventId event) noexcept; /** Stop the structured log event consumer thread. * * @returns No return value. * * @remarks This stops the structured log event processing system. This will stop the * processing thread and flush all pending event messages to the log. The * processing system will be restarted when the next * @ref omni::structuredlog::IStructuredLog::allocEvent() * call is made to attempt to send a new message. This call is useful if the * structured log plugin needs to be unloaded. If the processing thread is left * running, it will prevent the plugin from being unloaded (or even being attempted * to be unloaded). This can also be used to temporarily disable the structured * log system if its not needed or wanted. If the structured log system needs to * be disabled completely, a call to @ref omni::structuredlog::IStructuredLog::setEnabled() * using the @ref omni::structuredlog::fEnableFlagAll flag should be made before stopping * the event queue. * * @thread_safety This call is thread safe. */ void stop() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::structuredlog::IStructuredLogControl_abi>::closeLog( omni::structuredlog::EventId event) noexcept { closeLog_abi(event); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogControl_abi>::stop() noexcept { stop_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/structuredlog/IStructuredLogControl.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 The structured log control interface. */ #pragma once #include "StructuredLogCommon.h" #include "../core/IObject.h" namespace omni { namespace structuredlog { class IStructuredLogControl; // ******************************* enums, types, and constants ************************************ /** A special value to indicate that an operation should affect all registered schemas. This * can be used when closing all persistently open log files with * @ref IStructuredLogControl::closeLog(). */ constexpr EventId kAllSchemas = ~2ull; // ******************************* IStructuredLogControl interface ******************************** /** Structured log state control interface. This allows for some control over the processing of * events and log files for the structured log system. The structured log system's event queue * can be temporarily stopped if needed or the output log for a schema may be closed. Each of * these operations is only temporary as the event queue will be restarted and the log file * opened when the next event is queued with @ref omni::structuredlog::IStructuredLog::allocEvent(). * * This interface object can be acquired either by requesting it from the type factory or * by casting an @ref omni::structuredlog::IStructuredLog object to this type. */ class IStructuredLogControl_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogControl")> { protected: /** Closes one or more schema's persistently open log file(s). * * @param[in] event The ID of the event to close the log for. This may also be * @ref omni::structuredlog::kAllSchemas to close all log file for * the process. The log file for the schema that the given event * belongs to will be closed. * @returns No return value. * * @remarks This closes the persistently open log file(s) for one or more schemas. This * operation will effectively be ignored for schemas that were not registered * using the @ref omni::structuredlog::fSchemaFlagKeepLogOpen schema flag since those schemas will * not leave their logs open. The named log files will only remain closed until * the next attempt to write an event message to it. It is the responsibility * of the host app to ensure no events are written to the effected log file(s) * for the duration that the log needs to remain closed. * * @note This call itself is thread safe. However the log file may be reopened if a * pending event is processed in the event queue or a new event is sent while * the calling thread expects the log to remain closed. It is the caller's * responsibility to either stop the event queue, disable structured logging, or * prevent other events from being sent while the log(s) need to remain closed. */ virtual void closeLog_abi(EventId event) noexcept = 0; /** Stop the structured log event consumer thread. * * @returns No return value. * * @remarks This stops the structured log event processing system. This will stop the * processing thread and flush all pending event messages to the log. The * processing system will be restarted when the next * @ref omni::structuredlog::IStructuredLog::allocEvent() * call is made to attempt to send a new message. This call is useful if the * structured log plugin needs to be unloaded. If the processing thread is left * running, it will prevent the plugin from being unloaded (or even being attempted * to be unloaded). This can also be used to temporarily disable the structured * log system if its not needed or wanted. If the structured log system needs to * be disabled completely, a call to @ref omni::structuredlog::IStructuredLog::setEnabled() * using the @ref omni::structuredlog::fEnableFlagAll flag should be made before stopping * the event queue. * * @thread_safety This call is thread safe. */ virtual void stop_abi() noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogControl.gen.h" /** @copydoc omni::structuredlog::IStructuredLogControl_abi */ class omni::structuredlog::IStructuredLogControl : public omni::core::Generated<omni::structuredlog::IStructuredLogControl_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogControl.gen.h"
omniverse-code/kit/include/omni/structuredlog/IStructuredLogSettings2.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/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 /** Interface for the second version of the IStructuredLogSettings interface. This interface * exposes more settings to control the behaviour of the structured logging system. This * object can be retrieved directly or by casting the main IStructuredLog interface to this * type using `omni::core::ObjectPtr::as<>()`. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi> : public omni::structuredlog::IStructuredLogSettings2_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogSettings2") /** Retrieves the current heartbeat message period in seconds. * * @returns The minimum time in seconds between heartbeat events. This will be * @ref omni::structuredlog::kHeartbeatDisabled if the heartbeat events are * disabled. When enabled, the heartbeat events will be generated within * ~100ms of this scheduled time. In general, it is expected that the heartbeat * period be on the scale of one minute or more to reduce the overall amount of * event traffic. */ uint64_t getHeartbeatPeriod() noexcept; /** Sets the new heartbeat event period in seconds. * * @param[in] period The minimum time in seconds between generated heartbeat events. * This may be @ref omni::structuredlog::kHeartbeatDisabled to disable * the heartbeat events. * @returns No return value. * * @remarks The heartbeat events can be used to get an estimate of a session's length even if * the 'exit' or 'crash' process lifetime events are missing (ie: power loss, user * kills the process, blue screen of death or kernel panic, etc). The session can * neither be assumed to have exited normally nor crashed with only these heartbeat * events present however. */ void setHeartbeatPeriod(uint64_t period) noexcept; /** Retrieves whether header objects will be added to each newly written log file. * * @returns `true` if headers will be written to each new log file. Returns `false` if * header objects will be omitted from new log files. */ bool getNeedLogHeaders() noexcept; /** Sets whether headers will be added to each newly written log file. * * @param[in] needHeaders Set to `true` to indicate that headers should be added to each * newly written log file. Set to `false` to indicate that the * header should be omitted. * @returns No return value. * * @remarks This sets whether log headers will be written out to each new log file. The * header is consumed and modified by the telemetry transmitter app to allow it * to store its progress in processing each log file. If the header is missing, * the transmitter app will simply ignore the log file. Omitting the headers * in log files allows the log output to purely just be the structured log event * messages so they can be more easily consumed wholesale by external apps. * * @note Changing this setting will only take effect the next time a new log file is written * out to disk. Disabling this will not remove the header object from an existing log * file. */ void setNeedLogHeaders(bool needHeaders) noexcept; /** Retrieves the current set of output flags for structured logging. * * @returns The current output flags for the structured logging system. These indicate how * various aspects of the logging system will function. Note that some flags may * affect whether the produced messages are compatible with the remainder of the * telemetry toolchain in Omniverse apps. By default, all output flags are off. */ omni::structuredlog::OutputFlags getOutputFlags() noexcept; /** Sets or clears one or more output flags for structured logging. * * @param[in] flagsToAdd A set of zero or more flag bits to set. These must be either * @ref omni::structuredlog::fOutputFlagNone or one or more of * the @ref omni::structuredlog::OutputFlags flags. * @param[in] flagsToRemove A set of zero or more flag bits to cleared. These must be * either @ref omni::structuredlog::fOutputFlagNone or one or * more of the @ref omni::structuredlog::OutputFlags flags. * @returns No return value. * * @remarks This sets or clears flags that affect the output from the structured logging * system. These flags are all disabled by default. These flags will take effect * the next time a message is emitted. */ void setOutputFlags(omni::structuredlog::OutputFlags flagsToAdd, omni::structuredlog::OutputFlags flagsToRemove) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline uint64_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::getHeartbeatPeriod() noexcept { return getHeartbeatPeriod_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::setHeartbeatPeriod(uint64_t period) noexcept { setHeartbeatPeriod_abi(period); } inline bool omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::getNeedLogHeaders() noexcept { return getNeedLogHeaders_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::setNeedLogHeaders(bool needHeaders) noexcept { setNeedLogHeaders_abi(needHeaders); } inline omni::structuredlog::OutputFlags omni::core::Generated< omni::structuredlog::IStructuredLogSettings2_abi>::getOutputFlags() noexcept { return getOutputFlags_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::setOutputFlags( omni::structuredlog::OutputFlags flagsToAdd, omni::structuredlog::OutputFlags flagsToRemove) noexcept { setOutputFlags_abi(flagsToAdd, flagsToRemove); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/structuredlog/JsonTree.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 ABI safe structure for specifying structured log schemas. */ #pragma once #include "../../carb/logging/Log.h" #include "../extras/ScratchBuffer.h" #include <cstdint> #include <cstddef> namespace omni { namespace structuredlog { /** The data type contained within a JsonNode. * @note For future maintainability, do not use `default` when switching on * this enum; we'll be able to catch all the places where the new type * needs to be handled in that case. */ enum class NodeType : uint8_t { eNull, /**< No type has been set. */ eBool, /**< bool type. */ eBoolArray, /**< bool array type. */ eInt32, /**< int32_t type. This corresponds to the JSON integer type. */ eInt32Array, /**< int32_t array type. This corresponds to the JSON integer type. */ eUint32, /**< uint32_t type. This corresponds to the JSON integer type. */ eUint32Array, /**< uint32_t array type. This corresponds to the JSON integer type. */ /** int64_t type. For interoperability, we cannot store a 64 bit int directly * in JSON, so the high and low 32 bits get stores in an array [high, low]. */ eInt64, /** int64_t array type. For interoperability, we cannot store a 64 bit int * directly in JSON, so each element of this array is itself an array * [high, low], where high is the top 32 bits and low is the bottom 32 bits. */ eInt64Array, eUint64, /**< uint64_t type. stored identically to @ref NodeType::eInt64. */ eUint64Array, /**< uint64_t array type. stored identically to @ref NodeType::eInt64Array. */ eFloat64, /**< double type. This corresponds to the JSON number type. */ eFloat64Array, /**< double array type. This corresponds to the JSON number type. */ eFloat32, /**< float type. This corresponds to the JSON number type. */ eFloat32Array, /**< float array type. This corresponds to the JSON number type. */ eBinary, /**< array of bytes that will be base64 encoded into JSON. */ eString, /**< char* type. */ eStringArray, /**< char ** type. */ eObject, /**< object type. */ eObjectArray, /**< array of objects type. */ }; /** A node in a JSON structure. * This is a standard layout type for @rstref{ABI safety <abi-compatibility>}. * Do not directly write this struct; use @ref JsonBuilder to set the members * to ensure the layout is as-expected by the consumers of this struct. */ struct JsonNode { /** The version of the structure. * Headers that use this struct should static assert on its version. * Do not modify the layout of this struct without incrementing this. */ static constexpr uint32_t kVersion = 0; /** The base type to be used for enums. */ using EnumBase = uint16_t; /** The type of the @ref flags member. */ using Flag = uint8_t; /** This specifies that the value is constant. * This is used for schemas to specify whether a property is constant. * This flag has no meaning when @p type is @ref NodeType::eObject or * @ref NodeType::eObjectArray; for an object to be constant, each * property of that object must be constant. */ static constexpr Flag fFlagConst = 0x01; /** This specifies that an array has a fixed length. * This is used for a schema node in a tree to specify that an array in * the tree has a fixed length (that length is specified by @p len). * This is only valid for array types and string. * This is ignored if combined with @ref fFlagConst. */ static constexpr Flag fFlagFixedLength = 0x02; /** This specifies that the parameter is an enum type. * An enum type is stored in the data blob as an @ref EnumBase. * The @ref EnumBase is used as an index into the array of values stored * in this node. * This flag is only valid for a @ref NodeType that is an array type other * than @ref NodeType::eObjectArray. */ static constexpr Flag fFlagEnum = 0x04; /** The type of this node. * This and @ref len decide which member of @ref data is in use. */ NodeType type = NodeType::eNull; /** Behavioral flags for this node. */ Flag flags = 0; /** The length of the data array. * This is ignored for non-array and non-object types. * For @ref NodeType::eString, this is the length of the stored string (as * an optimization). * For other values of @ref type, this is the length of the array stored * in @ref data. */ uint16_t len = 0; /** The length of @ref name in bytes. */ uint16_t nameLen = 0; /* 2 bytes of padding exists here (on x86_64 at least), which may be used * for something in the future without breaking the ABI. */ /** The JSON node name. * This will be nullptr when @ref type is @ref NodeType::eObjectArray. */ char* name = nullptr; /** The union of possible values that can be used. * This may not be accessed if @ref type is @ref NodeType::eNull. */ union { /** This is in use when @ref type is @ref NodeType::eBool. */ bool boolVal; /** This is in use when @ref type is @ref NodeType::eInt32 or @ref NodeType::eInt64. */ int64_t intVal; /** This is in use when @ref type is @ref NodeType::eUint32 or @ref NodeType::eUint64. */ uint64_t uintVal; /** This is in use when @ref type is @ref NodeType::eFloat32 or @ref NodeType::eFloat64. */ double floatVal; /** This is used when @ref type is @ref NodeType::eBinary. */ uint8_t* binaryVal; /** This is in use when @ref type is @ref NodeType::eString. */ char* strVal; /** This is in use when @ref type is @ref NodeType::eBoolArray. */ bool* boolArrayVal; /** This is in use when @ref type is @ref NodeType::eInt32Array. */ int32_t* int32ArrayVal; /** This is in use when @ref type is @ref NodeType::eInt64Array. */ int64_t* int64ArrayVal; /** This is in use when @ref type is @ref NodeType::eUint32Array */ uint32_t* uint32ArrayVal; /** This is in use when @ref type is @ref NodeType::eUint64Array */ uint64_t* uint64ArrayVal; /** This is in use when @ref type is @ref NodeType::eFloat32Array. */ float* float32ArrayVal; /** This is in use when @ref type is @ref NodeType::eFloat64Array. */ double* float64ArrayVal; /** This is in use when @ref type is @ref NodeType::eStringArray. */ char** strArrayVal; /** This is in use when @ref type is @ref NodeType::eObject or * @ref NodeType::eObjectArray. * In the case where @ref type is @ref NodeType::eObject, this node * is an object and each element in @ref objVal is a property of that * object. * In the case where @ref type is @ref NodeType::eObjectArray, this * node is an object array and each element is an entry in the object * array (each entry should have type @ref NodeType::eObject). */ JsonNode* objVal; } data; }; CARB_ASSERT_INTEROP_SAFE(JsonNode); static_assert(sizeof(JsonNode) == 24, "unexpected size"); static_assert(offsetof(JsonNode, type) == 0, "struct layout changed"); static_assert(offsetof(JsonNode, flags) == 1, "struct layout changed"); static_assert(offsetof(JsonNode, len) == 2, "struct layout changed"); static_assert(offsetof(JsonNode, nameLen) == 4, "struct layout changed"); static_assert(offsetof(JsonNode, name) == 8, "struct layout changed"); static_assert(offsetof(JsonNode, data) == 16, "struct layout changed"); /** Options to do a less of a strict comparison when comparing trees. */ enum class JsonTreeCompareFuzz { /** Strict comparison: trees must be identical. * Ordering of all elements in the tree must be identical. */ eStrict, /** Ignore the ordering of constant elements. */ eNoConstOrder, /** Ignore ordering of all elements. */ eNoOrder, }; /** Perform a deep comparison of two nodes. * @param[in] a The first node to compare. * @param[in] b The second node to compare. * @param[in] fuzz How strict this comparison will be. * @returns `true` of the objects are equal. * @returns `false` if the objects differ in any ways. * * @note This assumes a properly formed @ref JsonNode. An incorrectly set len * member will likely result in a crash. */ inline bool compareJsonTrees(const JsonNode* a, const JsonNode* b, JsonTreeCompareFuzz fuzz = JsonTreeCompareFuzz::eStrict) { if (a->flags != b->flags || a->type != b->type || a->len != b->len) return false; if ((a->name == nullptr && b->name != nullptr) || (a->name != nullptr && b->name == nullptr)) return false; if (a->name != nullptr && strcmp(a->name, b->name) != 0) return false; switch (a->type) { case NodeType::eNull: return true; case NodeType::eBool: return a->data.boolVal == b->data.boolVal; case NodeType::eInt32: case NodeType::eInt64: return a->data.intVal == b->data.intVal; case NodeType::eUint32: case NodeType::eUint64: return a->data.uintVal == b->data.uintVal; case NodeType::eFloat32: case NodeType::eFloat64: return a->data.floatVal == b->data.floatVal; case NodeType::eBoolArray: return a->len == 0 || memcmp(b->data.int32ArrayVal, a->data.int32ArrayVal, a->len * sizeof(bool)) == 0; case NodeType::eUint32Array: return a->len == 0 || memcmp(b->data.uint32ArrayVal, a->data.uint32ArrayVal, a->len * sizeof(uint32_t)) == 0; case NodeType::eInt32Array: return a->len == 0 || memcmp(b->data.int32ArrayVal, a->data.int32ArrayVal, a->len * sizeof(int32_t)) == 0; case NodeType::eFloat32Array: return a->len == 0 || memcmp(b->data.float32ArrayVal, a->data.float32ArrayVal, a->len * sizeof(float)) == 0; case NodeType::eInt64Array: return a->len == 0 || memcmp(b->data.int64ArrayVal, a->data.int64ArrayVal, a->len * sizeof(int64_t)) == 0; case NodeType::eUint64Array: return a->len == 0 || memcmp(b->data.uint64ArrayVal, a->data.uint64ArrayVal, a->len * sizeof(uint64_t)) == 0; case NodeType::eFloat64Array: return a->len == 0 || memcmp(b->data.float64ArrayVal, a->data.float64ArrayVal, a->len * sizeof(double)) == 0; case NodeType::eBinary: case NodeType::eString: return a->len == 0 || memcmp(b->data.binaryVal, a->data.binaryVal, a->len) == 0; case NodeType::eStringArray: for (uint16_t i = 0; i < a->len; i++) { if ((a->data.strArrayVal[i] == nullptr && b->data.strArrayVal[i] != nullptr) || (a->data.strArrayVal[i] != nullptr && b->data.strArrayVal[i] == nullptr)) return false; if (a->data.strArrayVal[i] != nullptr && strcmp(a->data.strArrayVal[i], b->data.strArrayVal[i]) != 0) return false; } return true; case NodeType::eObject: case NodeType::eObjectArray: switch (fuzz) { case JsonTreeCompareFuzz::eStrict: for (uint16_t i = 0; i < a->len; i++) { if (!compareJsonTrees(&a->data.objVal[i], &b->data.objVal[i])) return false; } break; case JsonTreeCompareFuzz::eNoConstOrder: { extras::ScratchBuffer<bool, 256> hits; if (!hits.resize(a->len)) { // shouldn't ever happen fprintf(stderr, "failed to allocate %u bytes\n", a->len); return false; } for (size_t i = 0; i < a->len; i++) { hits[i] = false; } // first compare the variable fields in order for (uint16_t i = 0, j = 0; i < a->len; i++, j++) { // skip to the next non-constant member while ((a->data.objVal[i].flags & JsonNode::fFlagConst) != 0) { i++; } if (i >= a->len) break; // skip to the next non-constant member while ((b->data.objVal[j].flags & JsonNode::fFlagConst) != 0) { j++; } if (j >= b->len) return false; if (!compareJsonTrees(&a->data.objVal[i], &b->data.objVal[j])) return false; } // compare the constants for (uint16_t i = 0; i < a->len; i++) { if ((a->data.objVal[i].flags & JsonNode::fFlagConst) == 0) continue; for (uint16_t j = 0; j < a->len; j++) { if (!hits[j] && (b->data.objVal[j].flags & JsonNode::fFlagConst) != 0 && compareJsonTrees(&a->data.objVal[i], &b->data.objVal[j])) { hits[j] = true; break; } } } for (uint16_t i = 0; i < a->len; i++) { if ((b->data.objVal[i].flags & JsonNode::fFlagConst) != 0 && !hits[i]) return false; } } break; case JsonTreeCompareFuzz::eNoOrder: { extras::ScratchBuffer<bool, 256> hits; if (!hits.resize(a->len)) { // shouldn't ever happen fprintf(stderr, "failed to allocate %u bytes\n", a->len); return false; } for (size_t i = 0; i < a->len; i++) { hits[i] = false; } for (uint16_t i = 0; i < a->len; i++) { for (uint16_t j = 0; j < a->len; j++) { if (!hits[j] && compareJsonTrees(&a->data.objVal[i], &b->data.objVal[j])) { hits[j] = true; break; } } } for (uint16_t i = 0; i < a->len; i++) { if (!hits[i]) return false; } } break; } return true; } return false; } /** A memory allocator interface, which can be overwritten with your custom allocator */ class Allocator { public: /** The alignment that each allocation must be */ static constexpr size_t kAlignment = alignof(void*); virtual ~Allocator() { } /** Allocated memory. * @param[in] size The number of bytes to allocate. * @returns The allocated memory. * @returns nullptr if memory was not available. * @remarks This should be overwritten by custom memory allocators to use * another allocation mechanism. */ virtual void* alloc(size_t size) { return malloc(size); } /** Deallocate a previously allocated block. * @param[in] mem A block previously allocated by alloc(). */ virtual void dealloc(void* mem) { free(mem); } /** Round a size up to be aligned to @ref kAlignment. * @param[in] size The size to align. * @returns @p size rounded up to the next multiple of @ref kAlignment. */ static size_t fixupAlignment(size_t size) { if (size % Allocator::kAlignment != 0) return size + (kAlignment - (size % Allocator::kAlignment)); else return size; } }; /** An implementation of @ref Allocator which will just allocate from a * preallocated block of memory and never deallocate memory until the full * preallocated block is freed. * This is useful for something like a structured log event, where the required * size of the tree can be preallocated. */ class BlockAllocator : public Allocator { public: /** Create the allocator from a preallocated block. * @param[in] block The block of memory to allocate from. * @param[in] len The length of @p block in bytes. */ BlockAllocator(void* block, size_t len) { m_block = static_cast<uint8_t*>(block); m_left = len; } void* alloc(size_t size) override { void* m = m_block; size = fixupAlignment(size); if (size > m_left) return nullptr; m_block += size; m_left -= size; return m; } void dealloc(void* mem) override { CARB_UNUSED(mem); // leak it - m_block will be freed when we're done with this allocator } private: /** The block being allocated from. * This has m_left bytes available. */ uint8_t* m_block = nullptr; /** The number of bytes available in m_left. */ size_t m_left = 0; }; /** Free any memory allocated to a @ref JsonNode and clear it out to an empty node. * @param[inout] node The node to clear out. * This node must be {} or have had its contents set by * createObject(), createObjectArray() or setNode(). * @param[in] alloc The allocator used to allocate @p node. */ static inline void clearJsonTree(JsonNode* node, Allocator* alloc) { switch (node->type) { case NodeType::eNull: case NodeType::eBool: case NodeType::eInt32: case NodeType::eUint32: case NodeType::eInt64: case NodeType::eUint64: case NodeType::eFloat32: case NodeType::eFloat64: break; case NodeType::eString: case NodeType::eBinary: case NodeType::eBoolArray: case NodeType::eInt32Array: case NodeType::eUint32Array: case NodeType::eInt64Array: case NodeType::eUint64Array: case NodeType::eFloat32Array: case NodeType::eFloat64Array: alloc->dealloc(node->data.strVal); node->data.strVal = nullptr; break; case NodeType::eStringArray: for (uint16_t i = 0; i < node->len; i++) { alloc->dealloc(node->data.strArrayVal[i]); } alloc->dealloc(node->data.strArrayVal); node->data.strArrayVal = nullptr; break; case NodeType::eObjectArray: // object arrays allocate their elements and their elements' // properties in the same allocation for (uint16_t i = 0; i < node->len; i++) { for (uint16_t j = 0; j < node->data.objVal[i].len; j++) clearJsonTree(&node->data.objVal[i].data.objVal[j], alloc); } alloc->dealloc(node->data.objVal); node->data.objVal = nullptr; break; case NodeType::eObject: for (uint16_t i = 0; i < node->len; i++) clearJsonTree(&node->data.objVal[i], alloc); alloc->dealloc(node->data.objVal); node->data.objVal = nullptr; break; } alloc->dealloc(node->name); node = {}; } /** A temporary JsonNode object that will be cleaned up at the end of a scope. */ class TempJsonNode : public JsonNode { public: /** Create a temporary @ref JsonNode. * @param[in] alloc The allocator used to allocate this tree. */ TempJsonNode(Allocator* alloc) { m_alloc = alloc; } ~TempJsonNode() { clearJsonTree(this, m_alloc); } private: Allocator* m_alloc; }; /** Class for determining the allocation size required to build a JSON tree in a * single block of memory. * To use this, you simply track all of the items that you will store in your * tree, then you can retrieve the size that is required to store this tree. * This final size can be used to allocate a block for a @ref BlockAllocator * to allocate a tree of the exact correct size. * * @note This size calculator rounds up all sizes to the nearest alignment so * that allocator can always return properly aligned allocations. * Because of this, ordering of the track calls does not have to exactly * match the ordering of the setNode() calls. */ class JsonTreeSizeCalculator { public: /** Get the size required for the tree. * @returns The size in bytes. */ size_t getSize() { return m_count; } /** Track the root node in the tree. * @remarks Call this if you're planning on allocating the root node of the * tree, rather than keeping it as a local variable or something * like that. */ void trackRoot() { m_count += sizeof(JsonNode); } /** Track the size of a JSON object node. * @param[in] propertyCount The number of properties that JSON node has. * For example `{"a": 0, "b": 2}` is an object * with 2 properties. */ void trackObject(size_t propertyCount) { m_count += Allocator::fixupAlignment(sizeof(JsonNode) * propertyCount); } /** Track the size for a JSON array of objects * @param[in] propertyCount The number of properties that each object * element has. This implies that each element * will be an object with the same layout. * For an array of objects with varying layouts, * trackObject() would need to be called for each * element. * @param[in] len The length of the object array. * (e.g. [{}, {}] is length 2). */ void trackObjectArray(size_t propertyCount, size_t len) { m_count += Allocator::fixupAlignment(sizeof(JsonNode) * (propertyCount + 1) * len); } /** Track the size occupied by the node name. * @param[in] name The node name. * @param[in] nameLen The length of @p name including the null terminator. */ void trackName(const char* name, uint16_t nameLen) { track(name, nameLen); } /** Track the size occupied by the node name. * @param[in] name The node name. * @returns The number of bytes required to encode @p name. */ void trackName(const char* name) { track(name); } /** Track the size of a node without any associated data. * @remarks This is useful when using the @ref JsonNode structure for * defining a schema, so each node may not store a value, just * type information and a name. */ void track() { } /** Track the size of an arithmetic type node. * @param[in] value The value that will be encoded in the future. */ template <typename T> void track(T value) { CARB_UNUSED(value); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); } /** track the size of a string array node. * @param[in] str The array of strings that will be encoded. * @param[in] len The length of array @p b. */ void track(const char* const* str, uint16_t len) { size_t size = 0; if (len == 0) return; for (uint16_t i = 0; i < len; i++) { if (str[i] != nullptr) size += Allocator::fixupAlignment(strlen(str[i]) + 1); } m_count += size + Allocator::fixupAlignment(sizeof(const char*) * len); } /** Track the size of an array node with the string length pre-calculated. * @param[in] value The array that will be used for the node. * @param[in] len The length of @p value. * If @p value is a string, this includes the null terminator. */ template <typename T> void track(const T* value, uint16_t len) { CARB_UNUSED(value); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_count += Allocator::fixupAlignment(len * sizeof(T)); } /** Track the size of a binary blob node. * @param[in] value The array of binary data that will be used for the node. * @param[in] len The length of @p value. */ void track(const void* value, uint16_t len) { track(static_cast<const uint8_t*>(value), len); } /** Track the size of a binary blob node. * @param[in] value The array of binary data that will be used for the node. * @param[in] len The length of @p value. */ void track(void* value, uint16_t len) { track(static_cast<const uint8_t*>(value), len); } /** track the size of a string node. * @param[in] str The string to be encoded. * This string must be less than 64KiB. */ void track(const char* str) { if (str != nullptr) track(str, uint16_t(strlen(str)) + 1); } /** track the size of a string node. * @param[in] str The string to be encoded. */ void track(char* str) { track(static_cast<const char*>(str)); } /** Track the size required for a deep copy of a node. * @param[in] node The node to calculate the size for. * @note This includes the size required for the root node. */ void track(const JsonNode* node) { trackName(node->name); switch (node->type) { case NodeType::eNull: track(); break; case NodeType::eBool: track(node->data.boolVal); break; case NodeType::eInt32: case NodeType::eInt64: track(node->data.intVal); break; case NodeType::eUint32: case NodeType::eUint64: track(node->data.uintVal); break; case NodeType::eFloat32: case NodeType::eFloat64: track(node->data.floatVal); break; case NodeType::eBinary: track(node->data.binaryVal, node->len); break; case NodeType::eBoolArray: track(node->data.boolArrayVal, node->len); break; case NodeType::eInt32Array: track(node->data.uint32ArrayVal, node->len); break; case NodeType::eUint32Array: track(node->data.int32ArrayVal, node->len); break; case NodeType::eInt64Array: track(node->data.uint64ArrayVal, node->len); break; case NodeType::eUint64Array: track(node->data.int64ArrayVal, node->len); break; case NodeType::eFloat32Array: track(node->data.float32ArrayVal, node->len); break; case NodeType::eFloat64Array: track(node->data.float64ArrayVal, node->len); break; case NodeType::eString: track(node->data.strVal, node->len); break; case NodeType::eStringArray: // if you don't cast this, it doesn't infer the template correctly track(static_cast<const char* const*>(node->data.strArrayVal), node->len); break; case NodeType::eObjectArray: if (node->len > 0) trackObjectArray(node->data.objVal[0].len, node->len); for (size_t i = 0; i < node->len; i++) { for (size_t j = 0; j < node->data.objVal[i].len; j++) // if you don't cast this, it doesn't infer the template correctly track(static_cast<const JsonNode*>(&node->data.objVal[i].data.objVal[j])); } break; case NodeType::eObject: trackObject(node->len); for (size_t i = 0; i < node->len; i++) // if you don't cast this, it doesn't infer the template correctly track(static_cast<const JsonNode*>(&node->data.objVal[i])); break; } } /** Track the size required for a deep copy of a node. * @param[in] node The node to calculate the size for. * @note This includes the size required for the root node. */ void track(JsonNode* node) { return track(static_cast<const JsonNode*>(node)); } private: size_t m_count = 0; }; /** A class to build JSON trees using @ref JsonNode structs. * These functions all expect an empty node to have been passed in, which * speeds up tree creation by avoiding unnecessary clearNode() calls. * * @note These functions do expect that memory allocation may fail. * This is used in the unit tests to verify that the node size * calculator is correct. */ class JsonBuilder { public: /** Constructor. * @param[in] alloc The allocator that will be used to create new @ref JsonNode objects. */ JsonBuilder(Allocator* alloc) { m_alloc = alloc; } /** Create a JSON object node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] propertyCount The number of properties that JSON node has. * For example `{"a": 0, "b": 2}` is an object * with 2 properties. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool createObject(JsonNode* node, uint16_t propertyCount) { void* b; CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); b = m_alloc->alloc(propertyCount * sizeof(*node->data.objVal)); if (b == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (node = '%s', requested %zu bytes)", node->name, propertyCount * sizeof(*node->data.objVal)); return false; } node->data.objVal = new (b) JsonNode[propertyCount]; node->len = propertyCount; node->type = NodeType::eObject; CARB_ASSERT((uintptr_t(node->data.objVal) & (alignof(JsonNode) - 1)) == 0); return true; } /** Create a JSON node that is an array of objects. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] propertyCount The number of properties that each object * element has. This implies that each element * will be an object with the same layout. * For an array of objects with varying layouts, * calcJsonObjectSize() would need to be called * for each element. * @param[in] len The length of the object array. * When defining an object array in a schema, * you should set this length to 1, then * specify the object layout in that element. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool createObjectArray(JsonNode* node, uint16_t propertyCount, uint16_t len) { void* b; CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); // allocate it all as one array b = m_alloc->alloc((len * (1 + propertyCount)) * sizeof(*node->data.objVal)); if (b == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (node = '%s', requested %zu bytes)", node->name, (len * (1 + propertyCount)) * sizeof(*node->data.objVal)); return false; } node->data.objVal = new (b) JsonNode[len]; CARB_ASSERT((uintptr_t(node->data.objVal) & (alignof(JsonNode) - 1)) == 0); b = static_cast<uint8_t*>(b) + sizeof(JsonNode) * len; for (size_t i = 0; i < len; i++) { node->data.objVal[i].data.objVal = new (b) JsonNode[propertyCount]; CARB_ASSERT((uintptr_t(node->data.objVal[i].data.objVal) & (alignof(JsonNode) - 1)) == 0); b = static_cast<uint8_t*>(b) + sizeof(JsonNode) * propertyCount; node->data.objVal[i].len = propertyCount; node->data.objVal[i].type = NodeType::eObject; } node->len = len; node->type = NodeType::eObjectArray; return true; } /** Set a bool node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] b The boolean value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, bool b) { return setNode(node, b, &node->data.boolVal, NodeType::eBool); } /** Set a bool array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The boolean array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const bool* data, uint16_t len) { return setNode(node, data, len, &node->data.boolArrayVal, NodeType::eBoolArray); } /** Set a 32 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] i The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, int32_t i) { return setNode(node, i, &node->data.intVal, NodeType::eInt32); } /** Set a 32 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const int32_t* data, uint16_t len) { return setNode(node, data, len, &node->data.int32ArrayVal, NodeType::eInt32Array); } /** Set an unsigned 32 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] u The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, uint32_t u) { return setNode(node, u, &node->data.uintVal, NodeType::eUint32); } /** Set an unsigned 32 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const uint32_t* data, uint16_t len) { return setNode(node, data, len, &node->data.uint32ArrayVal, NodeType::eUint32Array); } /** Set a 64 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] i The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, int64_t i) { return setNode(node, i, &node->data.intVal, NodeType::eInt64); } /** Set a 64 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const int64_t* data, uint16_t len) { return setNode(node, data, len, &node->data.int64ArrayVal, NodeType::eInt64Array); } /** Set an unsigned 64 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] u The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, uint64_t u) { return setNode(node, u, &node->data.uintVal, NodeType::eUint64); } /** Set an unsigned 64 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const uint64_t* data, uint16_t len) { return setNode(node, data, len, &node->data.uint64ArrayVal, NodeType::eUint64Array); } /** Set a float node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] f The float value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, float f) { return setNode(node, f, &node->data.floatVal, NodeType::eFloat32); } /** Set a float array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The double array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const float* data, uint16_t len) { return setNode(node, data, len, &node->data.float32ArrayVal, NodeType::eFloat32Array); } /** Set a double node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] f The double value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, double f) { return setNode(node, f, &node->data.floatVal, NodeType::eFloat64); } /** Set a double array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The double array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const double* data, uint16_t len) { return setNode(node, data, len, &node->data.float64ArrayVal, NodeType::eFloat64Array); } /** Set a string array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The string array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const char* const* data, uint16_t len) { CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); if (len == 0) { node->data.strArrayVal = nullptr; node->type = NodeType::eStringArray; node->len = len; return true; } // allocate each of the strings individually to avoid having to create // a temporary buffer of string lengths or call strlen() multiple times // on each string node->data.strArrayVal = static_cast<char**>(m_alloc->alloc(len * sizeof(*node->data.strArrayVal))); CARB_ASSERT((uintptr_t(node->data.strArrayVal) & (alignof(char*) - 1)) == 0); if (node->data.strArrayVal == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (node = '%s', requested %zu bytes)", node->name, len * sizeof(*node->data.strArrayVal)); return false; } for (uint16_t i = 0; i < len; i++) { if (data[i] == nullptr) { node->data.strArrayVal[i] = nullptr; } else { size_t s = strlen(data[i]) + 1; node->data.strArrayVal[i] = static_cast<char*>(m_alloc->alloc(s)); if (node->data.strArrayVal[i] == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (requested %zu bytes)", s); for (uint16_t j = 0; j < i; j++) m_alloc->dealloc(node->data.strArrayVal[j]); m_alloc->dealloc(node->data.strArrayVal); node->data.strArrayVal = nullptr; return false; } memcpy(node->data.strArrayVal[i], data[i], s); } } node->type = NodeType::eStringArray; node->len = len; return true; } /** Set a string node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] str The string to copy into this node. * @param[in] len The length of @p str including the null terminator. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const char* str, uint16_t len) { return setNode(node, str, len, &node->data.strVal, NodeType::eString); } /** Set a string node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] str The string to copy into this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. * @returns `false` if @p str was longer than 64KiB. */ bool setNode(JsonNode* node, const char* str) { size_t len; CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); if (str == nullptr) return setNode(node, str, 0); len = strlen(str) + 1; if (len > UINT16_MAX) { CARB_LOG_ERROR("string length exceeds 64KiB maximum (node = '%s', %zu characters, str = '%64s...')", node->name, len, str); return false; } return setNode(node, str, uint16_t(len)); } /** Set a binary blob node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] blob The data to copy into this node. * @param[in] len The number of bytes of data in @p blob. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const void* blob, uint16_t len) { return setNode<uint8_t>(node, static_cast<const uint8_t*>(blob), len, &node->data.binaryVal, NodeType::eBinary); } /** Set a binary blob node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] blob The data to copy into this node. * @param[in] len The number of bytes of data in @p blob. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const uint8_t* blob, uint16_t len) { return setNode<uint8_t>(node, blob, len, &node->data.binaryVal, NodeType::eBinary); } /** Set the name of a JSON node. * @param[inout] node The node to modify. * The previous name will be cleared out, if any. * @param[in] name The name to copy into the node. * This may be nullptr to just free the previous name. * @param[in] nameLen The length of @p name, including the null terminator. * This must be 0 if @p name is nullptr. * * @returns `true` if the node's name was successfully copied. * @returns `false` if a memory allocation failed. */ bool setName(JsonNode* node, const char* name, uint16_t nameLen) { m_alloc->dealloc(node->name); node->name = nullptr; if (nameLen == 0) return true; node->name = static_cast<char*>(m_alloc->alloc(nameLen)); if (node->name == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (name = '%s', requested %" PRIu16 " bytes)", name, nameLen); return false; } node->nameLen = nameLen; memcpy(node->name, name, nameLen); return true; } /** Set the name of a JSON node. * @param[inout] node The node to modify. * The previous name will be cleared out, if any. * @param[in] name The name to copy into the node. * This may be nullptr to just free the previous name. * * @returns `true` if the node's name was successfully copied. * @returns `false` if a memory allocation failed. */ bool setName(JsonNode* node, const char* name) { if (name == nullptr) return setName(node, nullptr, 0); return setName(node, name, uint16_t(strlen(name) + 1)); } /** Perform a deep copy of a node. * @param[in] node The node to deep copy. * This node must be equal to {} when passed in. * @param[inout] out The new node that was created. * @returns The deep copied node. */ bool deepCopy(const JsonNode* node, JsonNode* out) { bool result = true; CARB_ASSERT(out->type == NodeType::eNull); CARB_ASSERT(out->len == 0); if (!setName(out, node->name)) return false; out->flags = node->flags; switch (node->type) { case NodeType::eNull: break; case NodeType::eBool: result = setNode(out, node->data.boolVal); break; case NodeType::eBoolArray: result = setNode(out, node->data.boolArrayVal, node->len); break; case NodeType::eInt32: result = setNode(out, int32_t(node->data.intVal)); break; case NodeType::eInt64: result = setNode(out, node->data.intVal); break; case NodeType::eInt32Array: result = setNode(out, node->data.int32ArrayVal, node->len); break; case NodeType::eUint32: result = setNode(out, uint32_t(node->data.uintVal)); break; case NodeType::eUint64: result = setNode(out, node->data.uintVal); break; case NodeType::eUint32Array: result = setNode(out, node->data.uint32ArrayVal, node->len); break; case NodeType::eInt64Array: result = setNode(out, node->data.int64ArrayVal, node->len); break; case NodeType::eUint64Array: result = setNode(out, node->data.uint64ArrayVal, node->len); break; case NodeType::eFloat32: result = setNode(out, float(node->data.floatVal)); break; case NodeType::eFloat64: result = setNode(out, node->data.floatVal); break; case NodeType::eFloat32Array: result = setNode(out, node->data.float32ArrayVal, node->len); break; case NodeType::eFloat64Array: result = setNode(out, node->data.float64ArrayVal, node->len); break; case NodeType::eString: result = setNode(out, node->data.strVal, node->len); break; case NodeType::eStringArray: result = setNode(out, node->data.strArrayVal, node->len); break; case NodeType::eBinary: result = setNode(out, node->data.binaryVal, node->len); break; case NodeType::eObjectArray: if (node->len == 0) break; result = createObjectArray(out, node->data.objVal[0].len, node->len); if (!result) break; for (uint16_t i = 0; i < node->len; i++) { out->data.objVal[i].flags = node->data.objVal[i].flags; for (uint16_t j = 0; result && j < node->data.objVal[i].len; j++) { result = deepCopy(&node->data.objVal[i].data.objVal[j], &out->data.objVal[i].data.objVal[j]); } } break; case NodeType::eObject: result = createObject(out, node->len); if (!result) break; for (size_t i = 0; i < node->len; i++) { deepCopy(&node->data.objVal[i], &out->data.objVal[i]); } break; } if (!result) clearJsonTree(out, m_alloc); return result; } /** Set the flags on a @ref JsonNode. * @param[in] node The node to update the flags on. * This node must have already had its value and length set. * This may not be nullptr. * @param[in] flags The flags to set on @p node. * * @tparam failOnNonFatal If this is set to true, the function will return * false when a non-fatal flag error occurred. * This is intended for testing. * The behavior is not changed otherwise by this flag. * The only fatal cases are: passing in unknown * flags, setting an enum flag on an incorrect type * and setting an enum flag on an empty array. * * @returns `true` if the flags set were valid. * @returns `false` if the flags set were invalid for the given node. */ template <bool failOnNonFatal = false> static bool setFlags(JsonNode* node, JsonNode::Flag flags) { constexpr JsonNode::Flag fixedLengthConst = JsonNode::fFlagConst | JsonNode::fFlagFixedLength; constexpr JsonNode::Flag constEnum = JsonNode::fFlagEnum | JsonNode::fFlagConst; constexpr JsonNode::Flag validFlags = JsonNode::fFlagConst | JsonNode::fFlagFixedLength | JsonNode::fFlagEnum; bool result = true; CARB_ASSERT(node != nullptr); // filter out unknown flags because they pose an ABI risk if ((flags & ~validFlags) != 0) { CARB_LOG_ERROR("unknown flags were used %02x (node = '%s')", flags & ~validFlags, node->name); return false; } // a node cannot be fixed length and constant if ((flags & ~fixedLengthConst) == fixedLengthConst) { CARB_LOG_ERROR("attempted to set node to be both const and fixed length (node = '%s')", node->name); result = !failOnNonFatal; } if ((flags & constEnum) == constEnum) { CARB_LOG_ERROR("a node cannot be both constant and an enum (node = '%s')", node->name); flags &= ~JsonNode::fFlagConst; result = !failOnNonFatal; } if ((flags & JsonNode::fFlagEnum) != 0 && node->len == 0) { CARB_LOG_ERROR("an empty array can not be made into an enum (node = '%s')", node->name); return false; } // check for invalid enum type usage switch (node->type) { case NodeType::eNull: case NodeType::eBool: case NodeType::eInt32: case NodeType::eUint32: case NodeType::eInt64: case NodeType::eUint64: case NodeType::eFloat64: case NodeType::eFloat32: case NodeType::eObject: case NodeType::eObjectArray: case NodeType::eBinary: case NodeType::eString: if ((flags & JsonNode::fFlagEnum) != 0) { CARB_LOG_ERROR("an enum type must be on a non-object array type (node = '%s')", node->name); return false; } break; case NodeType::eBoolArray: case NodeType::eInt32Array: case NodeType::eUint32Array: case NodeType::eInt64Array: case NodeType::eUint64Array: case NodeType::eFloat64Array: case NodeType::eFloat32Array: case NodeType::eStringArray: // arrays can be const or fixed length break; } // check for invalid const or fixed length usage switch (node->type) { case NodeType::eNull: case NodeType::eBool: case NodeType::eInt32: case NodeType::eUint32: case NodeType::eInt64: case NodeType::eUint64: case NodeType::eFloat64: case NodeType::eFloat32: // fixed length is only valid on arrays if ((flags & JsonNode::fFlagFixedLength) != 0) { CARB_LOG_ERROR("fixed length cannot be set on a scalar node (node = '%s')", node->name); result = !failOnNonFatal; } break; case NodeType::eObject: if ((flags & JsonNode::fFlagConst) != 0) { CARB_LOG_ERROR("const is meaningless on an object node (node = '%s')", node->name); result = !failOnNonFatal; } if ((flags & JsonNode::fFlagFixedLength) != 0) { CARB_LOG_ERROR("const is meaningless on an object node (node = '%s')", node->name); result = !failOnNonFatal; } break; case NodeType::eObjectArray: if ((flags & JsonNode::fFlagConst) != 0) { CARB_LOG_ERROR("const is meaningless on an object array (node = '%s')", node->name); result = !failOnNonFatal; } break; case NodeType::eBinary: case NodeType::eString: case NodeType::eBoolArray: case NodeType::eInt32Array: case NodeType::eUint32Array: case NodeType::eInt64Array: case NodeType::eUint64Array: case NodeType::eFloat64Array: case NodeType::eFloat32Array: case NodeType::eStringArray: // arrays can be const or fixed length break; } node->flags = flags; return result; } private: template <typename T0, typename T1> bool setNode(JsonNode* node, T0 value, T1* dest, NodeType type) { CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); node->len = 1; node->type = type; *dest = value; return true; } template <typename T> bool setNode(JsonNode* node, const T* data, uint16_t len, T** dest, NodeType type) { CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); if (len == 0) { *dest = nullptr; node->type = type; node->len = len; return true; } *dest = static_cast<T*>(m_alloc->alloc(len * sizeof(**dest))); if (*dest == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (requested %zu bytes)", len * sizeof(**dest)); return false; } CARB_ASSERT((uintptr_t(*dest) & (alignof(bool) - 1)) == 0); node->type = type; node->len = len; memcpy(*dest, data, len * sizeof(*data)); return true; } Allocator* m_alloc; }; } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/IStructuredLogSettings.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/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 /** Structured log settings interface. This allows a host app to modify some behavior of the * structured log system for the process or to retrieve information about the current settings. * These settings control features such as the event queue size, log rotation, event ID * generation, the output log path, and the user ID. Most of the default settings should be * sufficient for most apps with the exception of the user ID. For host apps that use at * least one non-anonymized schema the only settings that must be set is the user ID. * * This interface object can be acquired either by requesting it from the type factory or * by casting an IStructuredLog object to this type. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi> : public omni::structuredlog::IStructuredLogSettings_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogSettings") /** Retrieves the current event queue size. * * @returns The current size of the event queue buffer in bytes. Note that once the first * event message is sent, the event queue will be running and this will continue * to return the 'active' size of the event queue regardless of any new size that * is passed to @ref omni::structuredlog::IStructuredLogSettings::setEventQueueSize(). * Any new size will only be made active once the event queue is stopped with * @ref omni::structuredlog::IStructuredLogControl::stop(). The default size is 2MiB. * * @thread_safety This call is thread safe. */ size_t getEventQueueSize() noexcept; /** Retrieves the current maximum log file size. * * @returns The current maximum log file size in bytes. This helps to control when log files * get rotated out and started anew for the process. The number of old logs that * are kept is controlled by the log retention count. The default size is 50MB. * * @thread_safety This call is thread safe. */ int64_t getLogSizeLimit() noexcept; /** Retrieves the current log retention count. * * @returns The maximum number of log files to retain when rotating log files. When a new * log is rotated out, the oldest one that is beyond this count will be deleted. * The default is 3. * * @thread_safety This call is thread safe. */ size_t getLogRetentionCount() noexcept; /** Retrieves the current event identifier mode. * * @returns The current event identifier mode. The default is @ref omni::structuredlog::IdMode::eFastSequential. * * @thread_safety This call is thread safe. */ omni::structuredlog::IdMode getEventIdMode() noexcept; /** Retrieves the current event identifier type. * * @returns The current event identifier type. The default is @ref omni::structuredlog::IdType::eUuid. * * @thread_safety This call is thread safe. */ omni::structuredlog::IdType getEventIdType() noexcept; /** Retrieves the current log output path. * * @returns The path that log files will be written to. This defaults to the launcher app's * default log directory. The host app should override that if that location is * not suitable. * * @thread_safety This call is thread safe to retrieve the path string. However, the string * itself may become invalidated after return if the log output path is * changed with a call to @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * It is * the host app's responsibility to ensure the log output path is not being * changed while this string is being used. The returned string generally * should not be cached anywhere. It should be retrieved from here any time * it is needed. */ const char* getLogOutputPath() noexcept; /** Retrieves the default log name if any has been set. * * @returns The default log file name that will be used to output all events that are not * explicitly marked with the @ref omni::structuredlog::fEventFlagUseLocalLog flag. * This name will include the log output path as set by * @ref omni::structuredlog::IStructuredLogSettings::getLogOutputPath(). * @returns `nullptr` if no default log name has been set with * @ref omni::structuredlog::IStructuredLogSettings::setLogDefaultName() * or the default log name has been cleared. * * @thread_safety This call itself is thread safe. However, the returned string is only * valid until either the log path or the default log name changes. It is * the caller's responsibility to ensure the returned string is used safely. */ const char* getLogDefaultName() noexcept; /** Retrieves the log path that a given event will be written to. * * @param[in] eventId The ID of the event to retrieve the log path for. This must be the * same ID used when the event was registered. This may also be * @ref omni::structuredlog::kDefaultLogPathEvent to retrieve the * path for the default log. * @returns The name and path of the log file that the requested event would go to if it * were emitted with current settings. * @returns the name and path of the default log file if kDefaultLogPathEvent is used for * for the event ID. * @returns `nullptr` if the given event ID is unknown or kDefaultLogPathEvent was used * and no default log name has been set. * * @thread_safety This call itself is thread safe. However, the returned string is only * valid until either the log path or the default log name changes. It is * the caller's responsibility to ensure the returned string is used safely. */ const char* getLogPathForEvent(omni::structuredlog::EventId eventId) noexcept; /** Retrieves the current user ID. * * @returns The current user ID. This may be a user name or user identification number. * The specific format and content is left entirely up to the host app itself. * By default, the user ID will either be the user ID listed in the privacy * settings file if present, or a random number if the user ID setting is not * present. When a random number is used for the user ID, it is useful for * anonymizing user event messages. * * @thread_safety This call is thread safe to retrieve the user ID. However, the string * itself may become invalidated after return if the user ID is changed with * a call to to @ref omni::structuredlog::IStructuredLogSettings::setUserId(). * It is the host app's responsibility to ensure the user ID is not being changed while this * string is being used. The returned string generally should not be cached * anywhere. It should be retrieved from here any time it is needed. */ const char* getUserId() noexcept; /** Retrieves the current session ID. * * @returns The identifier for the current session if the current privacy settings allow it. * * @remarks This retrieves the session ID for the current structured log session. This ID is * chosen when the structured log session starts and remains constant for its * lifetime. */ omni::structuredlog::SessionId getSessionId() noexcept; /** Sets the new event queue buffer size. * * @param[in] sizeInBytes the new event queue buffer size in bytes to use. This will be * silently clamped to an acceptable minimum size. The default is * 2MiB. * @returns No return value. * * @remarks This sets the new event queue buffer size. A larger buffer allows more events * to be sent and processed simultaneously in an app. If the buffer ever fills * up, events may be dropped if they cannot be processed fast enough. For host apps * that infrequently send small events, some memory can be saved by reducing this * buffer size. However, host apps that need to be able to send messages frequently, * especially simultaneously from multiple threads, should use a larger buffer size * to allow the event queue to keep up with the incoming event demand. * * @remarks Once the event queue is running (ie: the first message has been sent), changing * its size will cause a second queue to be created at the new size. The old queue * will be flushed and the new queue will be made active. There will be a short * period where two queues will be running simultaneously. Any new events that * are queued during this period will be added to the new queue. There is no need * to stop the old queue before changing the size, this will be handled * automatically. Note that during one of these queue transitions there may be * a short period where omni::structuredlog::getEventQueueSize() may return the * new queue's size even if the old queue is still active. * * @note Changing the queue size frequently will lead to stalls in the processing pipeline. * Generally the queue size should be set once on startup of an app and left at that * configured size for the process' lifetime. * * @thread_safety This call is thread safe. */ void setEventQueueSize(size_t sizeInBytes) noexcept; /** Sets the log size limit. * * @param[in] limitInBytes The new log size limit in bytes. This controls the maximum * size a log file can get up to before it is rotated out and * a new log is started. This will be silently clamped to an * acceptable minimum size. The default is 50MiB. * The minimum size limit is 256KiB. * @returns No return value. * * @remarks This sets the log size limit. When a log reaches (approximately) this size, * it will be rotated out and a new log file started. The number of old log files * that are kept is controlled by the log retention count. * * @thread_safety This call is thread safe. */ void setLogSizeLimit(int64_t limitInBytes) noexcept; /** Sets the log retention count. * * @param[in] count The maximum number of old log files to maintain. When a log file * grows beyond the current size limit, it will be renamed and a new * log opened with the original name. The oldest log file may be * deleted if there are more logs than this count. The default is 3. * @returns No return value. * * @thread_safety This call is thread safe. */ void setLogRetentionCount(size_t count) noexcept; /** Sets the current event identifier mode and type. * * @param[in] mode The new identifier mode to use. This will take effect on the next * event that is sent. The default is IdMode::eFastSequential. * @param[in] type The new identifier type to use. This will take effect on the next * event that is sent. The default is IdType::eUuid. * @returns No return value. * * @thread_safety This call is thread safe. */ void setEventIdMode(omni::structuredlog::IdMode mode, omni::structuredlog::IdType type) noexcept; /** Sets the new log output path. * * @param[in] path The new log file path to use. This may not be an empty string. The * default is the Launcher app's expected log file path. This may be * either a relative or absolute path. However, note that if this is * relative, the location of the log files may change if the process's * current working directory ever changes. It is highly suggested that * only absolute paths be used. This may also be * @ref omni::structuredlog::kDefaultLogPathName or nullptr to set the * log output path back to its default location. * @returns No return value. * * @remarks This changes the log file location for the calling process. The log file * locations for all registered schemas will be updated as well. If a schema has * been set to keep its log file open, it will be closed at this point (if already * open). The next event that is written to the log file will open a new log at * the new location. The old log file (if any) will not be moved from the previous * location. * * @note There is still a possible race condition with changing the log directory if events * are pending for processing. If the log file had been opened to write out a message * at the same time this is changing the log path, the change in log path will not take * effect until the next event message is being processed. * * @thread_safety This call is thread safe. However, it is the caller's responsibility to * ensure that no other host thread is simultaneously operating on the log * output path string returned from * @ref omni::structuredlog::IStructuredLogSettings::getLogOutputPath() * and that nothing else has cached that returned string since it could become * invalidated here. */ void setLogOutputPath(const char* path) noexcept; /** Sets the new default log name to use for message output. * * @param[in] name The new default name to set for the message log file. This may be * an empty string or nullptr to restore the default behavior of writing * each new message to its own schema's log file. This should just be * the name of the file and not include any path components. This may * also be one of the special values `/dev/stdout` or `/dev/stderr` to * send the output to only the stdout or stderr streams. In this case, * all events are output to these streams even if a given schema uses * the `fSchemaFlagUseLocalLog` or event uses the `fEventFlagUseLocalLog` * flag. Otherwise, if a filename is given and this name contains any * path components (ie: a '/'), setting the default log name will fail. * The log output path should be set using * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath() instead. * If this name does not have a file * extension, a ".log" extension will be added. If the ".log" extension * is not desired, this may be suppressed by ending the name in ".". In * this case, the final trailing "." will be removed from the name. This * name may also contain the token '${pid}' that will be replaced by the * current process ID. * @returns No return value. * * @remarks This sets the new default log file name. When set to a valid file name, all * messages coming from events that do not use the @ref omni::structuredlog::fEventFlagUseLocalLog flag * will be written to the log file using this name in the current log output * directory. When either this name or the log output directory changes, any * open log files will be closed and reopened under the new name and path when * the next event is written. * * @note When log rotation occurs, the rotation number is inserted before the file extension * (e.g. `filename.ext` is rotated to `filename.1.ext`). * If no extension is detected, the number is just appended to the file name. * A file extension is detected with the following regex: `\..{0,4}$`. */ void setLogDefaultName(const char* name) noexcept; /** Sets the user ID to use in messages. * * @param[in] userId The user ID to use with all event messages going forward. This may * not be nullptr or an empty string. The default is a random number. * @returns No return value. * * @remarks This sets the user ID to be used in the 'source' property of all event messages * going forward. This will not affect the user ID of any messages that are * currently being processed at the time of this call. This will affect all pending * messages that are not being immediately processed however. Only the host app * should set this user ID. External plugins and extensions should never change the * user ID. * * @thread_safety This call is thread safe. However, it is the caller's responsibility to * ensure that no other host thread is simultaneously operating on the user * ID string returned from @ref omni::structuredlog::IStructuredLogSettings::getUserId() and that * nothing else has cached that returned string since it could become * invalidated here. */ void setUserId(const char* userId) noexcept; /** Attempts to load the privacy settings file. * * @returns `true` if the privacy settings file was successfully loaded. * @returns `false` if the privacy settings file could not be loaded. This failure may be * caused by the file being missing, failing to open the file due to permissions, * failing to allocate memory to read in the file, the file not being formatted * correctly as a TOML file, or failing to merge the new values into the settings * registry. * * @remarks This will attempt to load the privacy settings file for the current user. Regardless * of whether the file is successfully loaded, appropriate defaults will always be set * for each of the expected privacy settings (as long as the ISettings interface is * available). * * @note This expects that some other system has already found and attempted to load the * plugin that implements the ISettings interface. */ bool loadPrivacySettings() noexcept; /** Checks app settings to see if any schemas or events should be disabled or enabled. * * @returns `true` if the settings registry was successfully checked for enable or disable * states. Returns `false` if the \ref carb::settings::ISettings or \ref carb::dictionary::IDictionary * plugins have not been loaded yet. * * @remarks This checks the settings registry to determine if any schemas or events should * be disabled initially. The keys in the settings registry that will be looked * at are under @ref omni::structuredlog::kSchemasStateListSetting, * @ref omni::structuredlog::kEventsStateListSetting, * @ref omni::structuredlog::kEventsStateArraySetting, * and @ref omni::structuredlog::kSchemasStateArraySetting. Each of these parts * of the settings registry expects the schema or event name to be specified in * a different way. Once the settings have been loaded, they are cached internally * and will be used as the initial state of any newly registered schemas or events. * Any state changes to events or schemas after these settings are cached can still * be done programmatically with @ref omni::structuredlog::IStructuredLog::setEnabled(). */ bool enableSchemasFromSettings() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getEventQueueSize() noexcept { return getEventQueueSize_abi(); } inline int64_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogSizeLimit() noexcept { return getLogSizeLimit_abi(); } inline size_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogRetentionCount() noexcept { return getLogRetentionCount_abi(); } inline omni::structuredlog::IdMode omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getEventIdMode() noexcept { return getEventIdMode_abi(); } inline omni::structuredlog::IdType omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getEventIdType() noexcept { return getEventIdType_abi(); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogOutputPath() noexcept { return getLogOutputPath_abi(); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogDefaultName() noexcept { return getLogDefaultName_abi(); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogPathForEvent( omni::structuredlog::EventId eventId) noexcept { return getLogPathForEvent_abi(eventId); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getUserId() noexcept { return getUserId_abi(); } inline omni::structuredlog::SessionId omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getSessionId() noexcept { return getSessionId_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setEventQueueSize(size_t sizeInBytes) noexcept { setEventQueueSize_abi(sizeInBytes); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogSizeLimit(int64_t limitInBytes) noexcept { setLogSizeLimit_abi(limitInBytes); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogRetentionCount(size_t count) noexcept { setLogRetentionCount_abi(count); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setEventIdMode( omni::structuredlog::IdMode mode, omni::structuredlog::IdType type) noexcept { setEventIdMode_abi(mode, type); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogOutputPath(const char* path) noexcept { setLogOutputPath_abi(path); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogDefaultName(const char* name) noexcept { setLogDefaultName_abi(name); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setUserId(const char* userId) noexcept { setUserId_abi(userId); } inline bool omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::loadPrivacySettings() noexcept { return loadPrivacySettings_abi(); } inline bool omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::enableSchemasFromSettings() noexcept { return enableSchemasFromSettings_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/structuredlog/IStructuredLogExtraFields.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 Interface to manage extra CloudEvent fields in all structured log messages. */ #pragma once #include "StructuredLogCommon.h" #include "../core/IObject.h" #include <omni/String.h> namespace omni { namespace structuredlog { class IStructuredLogExtraFields; /** Base type for flags that control how extra field flags are specified or retrieved in * omni::structuredlog::IStructuredLogExtraFields::getExtraCloudEventField() and * omni::structuredlog::IStructuredLogExtraFields::setExtraCloudEventField(). */ using ExtraFieldFlags = uint32_t; /** Value to indicate that no special flags are being specified. */ constexpr ExtraFieldFlags fExtraFieldFlagNone = 0; // ***************************** IStructuredLogExtraFields interface ****************************** /** Interface to manage extra CloudEvent fields to be included in each emitted message. This * allows for fields to be added and removed as needed. It also allows existing registered * fields to be enumerated at any given time. An extra field is a key/value pair that is * included at the top level of the JSON object for each message that follows. Only string * values are allowed for each key. */ class IStructuredLogExtraFields_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogExtraFields")> { protected: /** Adds, modifies, or removes an extra field key/value pair. * * @param[in] fieldName The name of the field to add, modify or remove. This may not be * `nullptr` or and empty string. The field name must only contain * alphabetic, numeric, or underscore ASCII characters. Any * characters outside these will cause the field to not be updated. * Further, this may not be one of the reserved CloudEvent field * names such as "specversion", "data", "time", "source", "session", * "dataschema", "type", or "subject". * @param[in] value The new value to set for the requested extra field. This may be * `nullptr` to indicate that the named field should be removed. * The value string may include any characters, but should be limited * to a small number of characters (ideally less than 64 characters). * @param[in] flags Flags to control how the new value is added, modified, or removed. * Currently no flags are defined. This must be set to * @ref omni::structuredlog::fExtraFieldFlagNone. * @returns `true` if the requested extra field is successfully added, modified, or removed. * Returns `false` if an invalid field name is given, or the operation could not * be completed for any reason. * * @remarks This adds, modifies, or removes a registered extra field and value. Any extra * fields that are registered at the time a message is emitted will be added to the * message on output. At least for the first version of this interface it is * expected that extra fields be largely static. * * @thread_safety This call is thread safe. */ virtual bool setValue_abi(OMNI_ATTR("c_str, in, not_null") const char* fieldName, OMNI_ATTR("c_str, in, not_null") const char* value, ExtraFieldFlags flags) noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogExtraFields.gen.h" // insert custom API functions here. /** @copydoc omni::structuredlog::IStructuredLogExtraFields_abi */ class omni::structuredlog::IStructuredLogExtraFields : public omni::core::Generated<omni::structuredlog::IStructuredLogExtraFields_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogExtraFields.gen.h"
omniverse-code/kit/include/omni/structuredlog/IStructuredLogSettings.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 Interface to querying and adjusting structured logging settings. */ #pragma once #include "StructuredLogCommon.h" #include "../../carb/settings/ISettings.h" #include "../core/IObject.h" #include "../extras/PrivacySettings.h" namespace omni { namespace structuredlog { class IStructuredLogSettings; // ******************************* enums, types, and constants ************************************ /** Base type for a session ID. This is an integer identifier that is chosen on startup and * remains constant for the entire structured log session. The session ID will be included in * each message that is sent. */ using SessionId = uint64_t; /** A special name for the default log output path. This may be used to restore the default * log path at any point with IStructuredLogSettings::setLogOutputPath(). This will never be * returned from IStructuredLogSettings::getLogOutputPath(). */ constexpr const char* kDefaultLogPathName = nullptr; /** A special name to request the log file path for the default log (if set). This may be passed * to @ref omni::structuredlog::IStructuredLogSettings::getLogPathForEvent() instead of a * specific event ID. */ constexpr EventId kDefaultLogPathEvent = 0; /** Base type for the flags for that can be passed in the @a flags parameter to the * @ref omni::structuredlog::IStructuredLogSettings::loadPrivacySettingsFromFile() function. */ using PrivacyLoadFlags = uint32_t; /** Flag to indicate that the privacy settings keys that the privacy settings that could affect * user privacy functionality should be explicitly reset to their default values before loading * the new privacy file. */ constexpr PrivacyLoadFlags fPrivacyLoadFlagResetSettings = 0x00000001; /** Names to control how the next event identifier is generated after each event message. */ enum class OMNI_ATTR("prefix=e") IdMode { /** Each event identifier will be completely random. There will be no ordering relationship * between any two events. This mode is useful when a sense of ordering is not needed but * a very small probability of an event identifier collision is needed. */ eRandom, /** Each event identifier will be incremented by one from the previous one. When using a * UUID identifier, this will increment the previous identifier by one starting from the * rightmost value. When using a 64-bit identifier, this the previous identifier will just * be incremented by one. This is useful when ordering is important and events may need * to be sorted. */ eSequential, /** Each event identifier will be incremented by one from the previous one, but a faster * method will be used. When using a UUID identifier, this will not produce an easily * sortable set of identifiers, but it will be faster to produce versus the other methods. * When using a 64-bit identifier, this mode is the same as @ref IdMode::eSequential and will * produce an easily sortable set of identifiers. This is useful when event handling * performance is the most important. */ eFastSequential, }; /** Names to control what type of event identifiers will be used for each message. */ enum class OMNI_ATTR("prefix=e") IdType { /** Generate a 128 bit UUID identifier. The probability of an identifier collision between * two events will be especially small with this type, especially when using random * identifiers. This however does have a small performance penalty to process these * identifiers and could result in the event processing thread getting backed up if * a large number of events are being pushed frequently. */ eUuid, /** Generate a 64-bit integer identifier. The probability of an identifier collision * between two events will be higher but still small with this type, especially when * using random identifiers. This identifier type is more performant and more easily * sortable however. This identifier type is useful when event processing performance * is most important. */ eUint64, }; // ****************************** IStructuredLogSettings interface ******************************** /** Structured log settings interface. This allows a host app to modify some behavior of the * structured log system for the process or to retrieve information about the current settings. * These settings control features such as the event queue size, log rotation, event ID * generation, the output log path, and the user ID. Most of the default settings should be * sufficient for most apps with the exception of the user ID. For host apps that use at * least one non-anonymized schema the only settings that must be set is the user ID. * * This interface object can be acquired either by requesting it from the type factory or * by casting an IStructuredLog object to this type. */ class IStructuredLogSettings_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogSettings")> { protected: // ****** host app structured log configuration accessor functions ****** /** Retrieves the current event queue size. * * @returns The current size of the event queue buffer in bytes. Note that once the first * event message is sent, the event queue will be running and this will continue * to return the 'active' size of the event queue regardless of any new size that * is passed to @ref omni::structuredlog::IStructuredLogSettings::setEventQueueSize(). * Any new size will only be made active once the event queue is stopped with * @ref omni::structuredlog::IStructuredLogControl::stop(). The default size is 2MiB. * * @thread_safety This call is thread safe. */ virtual size_t getEventQueueSize_abi() noexcept = 0; /** Retrieves the current maximum log file size. * * @returns The current maximum log file size in bytes. This helps to control when log files * get rotated out and started anew for the process. The number of old logs that * are kept is controlled by the log retention count. The default size is 50MB. * * @thread_safety This call is thread safe. */ virtual int64_t getLogSizeLimit_abi() noexcept = 0; /** Retrieves the current log retention count. * * @returns The maximum number of log files to retain when rotating log files. When a new * log is rotated out, the oldest one that is beyond this count will be deleted. * The default is 3. * * @thread_safety This call is thread safe. */ virtual size_t getLogRetentionCount_abi() noexcept = 0; /** Retrieves the current event identifier mode. * * @returns The current event identifier mode. The default is @ref omni::structuredlog::IdMode::eFastSequential. * * @thread_safety This call is thread safe. */ virtual IdMode getEventIdMode_abi() noexcept = 0; /** Retrieves the current event identifier type. * * @returns The current event identifier type. The default is @ref omni::structuredlog::IdType::eUuid. * * @thread_safety This call is thread safe. */ virtual IdType getEventIdType_abi() noexcept = 0; /** Retrieves the current log output path. * * @returns The path that log files will be written to. This defaults to the launcher app's * default log directory. The host app should override that if that location is * not suitable. * * @thread_safety This call is thread safe to retrieve the path string. However, the string * itself may become invalidated after return if the log output path is * changed with a call to @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * It is * the host app's responsibility to ensure the log output path is not being * changed while this string is being used. The returned string generally * should not be cached anywhere. It should be retrieved from here any time * it is needed. */ virtual const char* getLogOutputPath_abi() noexcept = 0; /** Retrieves the default log name if any has been set. * * @returns The default log file name that will be used to output all events that are not * explicitly marked with the @ref omni::structuredlog::fEventFlagUseLocalLog flag. * This name will include the log output path as set by * @ref omni::structuredlog::IStructuredLogSettings::getLogOutputPath(). * @returns `nullptr` if no default log name has been set with * @ref omni::structuredlog::IStructuredLogSettings::setLogDefaultName() * or the default log name has been cleared. * * @thread_safety This call itself is thread safe. However, the returned string is only * valid until either the log path or the default log name changes. It is * the caller's responsibility to ensure the returned string is used safely. */ virtual const char* getLogDefaultName_abi() noexcept = 0; /** Retrieves the log path that a given event will be written to. * * @param[in] eventId The ID of the event to retrieve the log path for. This must be the * same ID used when the event was registered. This may also be * @ref omni::structuredlog::kDefaultLogPathEvent to retrieve the * path for the default log. * @returns The name and path of the log file that the requested event would go to if it * were emitted with current settings. * @returns the name and path of the default log file if kDefaultLogPathEvent is used for * for the event ID. * @returns `nullptr` if the given event ID is unknown or kDefaultLogPathEvent was used * and no default log name has been set. * * @thread_safety This call itself is thread safe. However, the returned string is only * valid until either the log path or the default log name changes. It is * the caller's responsibility to ensure the returned string is used safely. */ virtual const char* getLogPathForEvent_abi(EventId eventId) noexcept = 0; /** Retrieves the current user ID. * * @returns The current user ID. This may be a user name or user identification number. * The specific format and content is left entirely up to the host app itself. * By default, the user ID will either be the user ID listed in the privacy * settings file if present, or a random number if the user ID setting is not * present. When a random number is used for the user ID, it is useful for * anonymizing user event messages. * * @thread_safety This call is thread safe to retrieve the user ID. However, the string * itself may become invalidated after return if the user ID is changed with * a call to to @ref omni::structuredlog::IStructuredLogSettings::setUserId(). * It is the host app's responsibility to ensure the user ID is not being changed while this * string is being used. The returned string generally should not be cached * anywhere. It should be retrieved from here any time it is needed. */ virtual const char* getUserId_abi() noexcept = 0; /** Retrieves the current session ID. * * @returns The identifier for the current session if the current privacy settings allow it. * * @remarks This retrieves the session ID for the current structured log session. This ID is * chosen when the structured log session starts and remains constant for its * lifetime. */ virtual SessionId getSessionId_abi() noexcept = 0; /** Sets the new event queue buffer size. * * @param[in] sizeInBytes the new event queue buffer size in bytes to use. This will be * silently clamped to an acceptable minimum size. The default is * 2MiB. * @returns No return value. * * @remarks This sets the new event queue buffer size. A larger buffer allows more events * to be sent and processed simultaneously in an app. If the buffer ever fills * up, events may be dropped if they cannot be processed fast enough. For host apps * that infrequently send small events, some memory can be saved by reducing this * buffer size. However, host apps that need to be able to send messages frequently, * especially simultaneously from multiple threads, should use a larger buffer size * to allow the event queue to keep up with the incoming event demand. * * @remarks Once the event queue is running (ie: the first message has been sent), changing * its size will cause a second queue to be created at the new size. The old queue * will be flushed and the new queue will be made active. There will be a short * period where two queues will be running simultaneously. Any new events that * are queued during this period will be added to the new queue. There is no need * to stop the old queue before changing the size, this will be handled * automatically. Note that during one of these queue transitions there may be * a short period where omni::structuredlog::getEventQueueSize() may return the * new queue's size even if the old queue is still active. * * @note Changing the queue size frequently will lead to stalls in the processing pipeline. * Generally the queue size should be set once on startup of an app and left at that * configured size for the process' lifetime. * * @thread_safety This call is thread safe. */ virtual void setEventQueueSize_abi(size_t sizeInBytes) noexcept = 0; /** Sets the log size limit. * * @param[in] limitInBytes The new log size limit in bytes. This controls the maximum * size a log file can get up to before it is rotated out and * a new log is started. This will be silently clamped to an * acceptable minimum size. The default is 50MiB. * The minimum size limit is 256KiB. * @returns No return value. * * @remarks This sets the log size limit. When a log reaches (approximately) this size, * it will be rotated out and a new log file started. The number of old log files * that are kept is controlled by the log retention count. * * @thread_safety This call is thread safe. */ virtual void setLogSizeLimit_abi(int64_t limitInBytes) noexcept = 0; /** Sets the log retention count. * * @param[in] count The maximum number of old log files to maintain. When a log file * grows beyond the current size limit, it will be renamed and a new * log opened with the original name. The oldest log file may be * deleted if there are more logs than this count. The default is 3. * @returns No return value. * * @thread_safety This call is thread safe. */ virtual void setLogRetentionCount_abi(size_t count) noexcept = 0; /** Sets the current event identifier mode and type. * * @param[in] mode The new identifier mode to use. This will take effect on the next * event that is sent. The default is IdMode::eFastSequential. * @param[in] type The new identifier type to use. This will take effect on the next * event that is sent. The default is IdType::eUuid. * @returns No return value. * * @thread_safety This call is thread safe. */ virtual void setEventIdMode_abi(IdMode mode, IdType type) noexcept = 0; /** Sets the new log output path. * * @param[in] path The new log file path to use. This may not be an empty string. The * default is the Launcher app's expected log file path. This may be * either a relative or absolute path. However, note that if this is * relative, the location of the log files may change if the process's * current working directory ever changes. It is highly suggested that * only absolute paths be used. This may also be * @ref omni::structuredlog::kDefaultLogPathName or nullptr to set the * log output path back to its default location. * @returns No return value. * * @remarks This changes the log file location for the calling process. The log file * locations for all registered schemas will be updated as well. If a schema has * been set to keep its log file open, it will be closed at this point (if already * open). The next event that is written to the log file will open a new log at * the new location. The old log file (if any) will not be moved from the previous * location. * * @note There is still a possible race condition with changing the log directory if events * are pending for processing. If the log file had been opened to write out a message * at the same time this is changing the log path, the change in log path will not take * effect until the next event message is being processed. * * @thread_safety This call is thread safe. However, it is the caller's responsibility to * ensure that no other host thread is simultaneously operating on the log * output path string returned from * @ref omni::structuredlog::IStructuredLogSettings::getLogOutputPath() * and that nothing else has cached that returned string since it could become * invalidated here. */ virtual void setLogOutputPath_abi(OMNI_ATTR("c_str, in") const char* path) noexcept = 0; /** Sets the new default log name to use for message output. * * @param[in] name The new default name to set for the message log file. This may be * an empty string or nullptr to restore the default behavior of writing * each new message to its own schema's log file. This should just be * the name of the file and not include any path components. This may * also be one of the special values `/dev/stdout` or `/dev/stderr` to * send the output to only the stdout or stderr streams. In this case, * all events are output to these streams even if a given schema uses * the `fSchemaFlagUseLocalLog` or event uses the `fEventFlagUseLocalLog` * flag. Otherwise, if a filename is given and this name contains any * path components (ie: a '/'), setting the default log name will fail. * The log output path should be set using * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath() instead. * If this name does not have a file * extension, a ".log" extension will be added. If the ".log" extension * is not desired, this may be suppressed by ending the name in ".". In * this case, the final trailing "." will be removed from the name. This * name may also contain the token '${pid}' that will be replaced by the * current process ID. * @returns No return value. * * @remarks This sets the new default log file name. When set to a valid file name, all * messages coming from events that do not use the @ref omni::structuredlog::fEventFlagUseLocalLog flag * will be written to the log file using this name in the current log output * directory. When either this name or the log output directory changes, any * open log files will be closed and reopened under the new name and path when * the next event is written. * * @note When log rotation occurs, the rotation number is inserted before the file extension * (e.g. `filename.ext` is rotated to `filename.1.ext`). * If no extension is detected, the number is just appended to the file name. * A file extension is detected with the following regex: `\..{0,4}$`. */ virtual void setLogDefaultName_abi(OMNI_ATTR("c_str, in") const char* name) noexcept = 0; /** Sets the user ID to use in messages. * * @param[in] userId The user ID to use with all event messages going forward. This may * not be nullptr or an empty string. The default is a random number. * @returns No return value. * * @remarks This sets the user ID to be used in the 'source' property of all event messages * going forward. This will not affect the user ID of any messages that are * currently being processed at the time of this call. This will affect all pending * messages that are not being immediately processed however. Only the host app * should set this user ID. External plugins and extensions should never change the * user ID. * * @thread_safety This call is thread safe. However, it is the caller's responsibility to * ensure that no other host thread is simultaneously operating on the user * ID string returned from @ref omni::structuredlog::IStructuredLogSettings::getUserId() and that * nothing else has cached that returned string since it could become * invalidated here. */ virtual void setUserId_abi(OMNI_ATTR("c_str, in, not_null") const char* userId) noexcept = 0; /** Attempts to load the privacy settings file. * * @returns `true` if the privacy settings file was successfully loaded. * @returns `false` if the privacy settings file could not be loaded. This failure may be * caused by the file being missing, failing to open the file due to permissions, * failing to allocate memory to read in the file, the file not being formatted * correctly as a TOML file, or failing to merge the new values into the settings * registry. * * @remarks This will attempt to load the privacy settings file for the current user. Regardless * of whether the file is successfully loaded, appropriate defaults will always be set * for each of the expected privacy settings (as long as the ISettings interface is * available). * * @note This expects that some other system has already found and attempted to load the * plugin that implements the ISettings interface. */ virtual bool loadPrivacySettings_abi() noexcept = 0; /** Checks app settings to see if any schemas or events should be disabled or enabled. * * @returns `true` if the settings registry was successfully checked for enable or disable * states. Returns `false` if the \ref carb::settings::ISettings or \ref carb::dictionary::IDictionary * plugins have not been loaded yet. * * @remarks This checks the settings registry to determine if any schemas or events should * be disabled initially. The keys in the settings registry that will be looked * at are under @ref omni::structuredlog::kSchemasStateListSetting, * @ref omni::structuredlog::kEventsStateListSetting, * @ref omni::structuredlog::kEventsStateArraySetting, * and @ref omni::structuredlog::kSchemasStateArraySetting. Each of these parts * of the settings registry expects the schema or event name to be specified in * a different way. Once the settings have been loaded, they are cached internally * and will be used as the initial state of any newly registered schemas or events. * Any state changes to events or schemas after these settings are cached can still * be done programmatically with @ref omni::structuredlog::IStructuredLog::setEnabled(). */ virtual bool enableSchemasFromSettings_abi() noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogSettings.gen.h" /** @copydoc omni::structuredlog::IStructuredLogSettings_abi */ class omni::structuredlog::IStructuredLogSettings : public omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi> { public: /** Attempts to load the privacy settings from a specific file. * * @param[in] filename The name and path to the privacy settings file to load. This is * expected to be a TOML formatted file. This may be `nullptr` or * an empty string to reload the user default privacy settings. * @param[in] flags Flags to affect the behavior of this operation. This must be * a combination of zero or more of the @ref PrivacyLoadFlags flags. * @returns `true` if the privacy settings are successfully loaded from the given file. * Returns `false` if the named file could not be found or the ISettings * interface is not available. * * @note This is not available when using structured logging in 'standalone' mode. * @note This should only be used for testing purposes. This should never be called * in a production app. */ bool loadPrivacySettingsFromFile(const char* filename, PrivacyLoadFlags flags) { carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>(); bool success; // The setting path to specify the path and filename of the privacy settings file to load. If // this setting is specified, the privacy settings will be loaded from the named file instead // of the default location. This file is expected to be TOML formatted and is expected to // provide the values for the "/privacy/" branch. This should only be used for testing purposes. // This value defaults to not being defined. // // Note: this value needs to be redefined here since including `StructuredLogSettingsUtils.h` // would introduce a dependency loop that would still leave this symbol undefined when // this is parsed. constexpr const char* kPrivacyFileSetting = "/structuredLog/privacySettingsFile"; if (settings == nullptr) return false; if (filename == nullptr) filename = ""; // explicitly reset the values that can affect whether 'internal' diagnostic data can be // sent. This prevents extra data from being inadvertently sent if the 'privacy.toml' // file is deleted and recreated, then reloaded by the running app. If the newly loaded // file also contains these settings, these values will simply be replaced. if ((flags & fPrivacyLoadFlagResetSettings) != 0) { settings->setString(omni::extras::PrivacySettings::kExtraDiagnosticDataOptInKey, ""); settings->setBool(omni::extras::PrivacySettings::kExternalBuildKey, true); } settings->setString(kPrivacyFileSetting, filename); success = loadPrivacySettings_abi(); settings->setString(kPrivacyFileSetting, ""); return success; } }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogSettings.gen.h"
omniverse-code/kit/include/omni/structuredlog/StructuredLogStandalone.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. // /** @file * @brief Helper header to be able to use the `omni.structuredlog.plugin` plugin in a standalone * mode. When using this mode, the rest of the Carbonite framework is not necessary. * Only the single module `omni.structuredlog.plugin` library will be needed. The main * feature of this header is the `omni::structuredlog::StructuredLogStandalone` helper * class. This manages loading the structured log library, registers all schemas for * the calling module, and allows access to the supported structured log interfaces. * * @note In order to use the structured logging system in standalone mode, this header must * be included instead of any other structured log headers. This header will pull in * all other structured log interface headers that are supported in standalone mode. * Other structured log headers are neither guaranteed to compile nor function as * expected in a non-Carbonite app. * * @note It is left up to the host app to handle launching the telemetry transmitter app * if that is needed. When used in standalone mode in a non-Carbonite app, this header * is only intended to provide the functionality for emitting log messages. The host * app can either rely on another external Omniverse app to launch the transmitter for * it, or launch it manually if needed. */ #pragma once #define STRUCTUREDLOG_STANDALONE_MODE 1 #include "../../carb/Defines.h" #include "IStructuredLog.h" #include "IStructuredLogSettings.h" #include "IStructuredLogControl.h" namespace omni { namespace structuredlog { /** Helper class to provide structured log functionality in non-Carbonite based apps. This * provides loading and shutdown functionality for the library and also allows for some * common setup in one easy call. This class is intended to be able to gracefully fail * if the structured log plugin isn't available or couldn't be loaded for any reason. * As long as the init() method returns `true`, it can be assumed that all functionality * and features are present and available. * * Once initialized, this object doesn't necessarily need to be interacted with directly * any further. As long as the object exists, the structured log functionality is available. * Once this object is destroyed however, the structured log functionality cannot be * guaranteed to be available any more. It is intended for this object to be instantiated * and initialized in main() or at the global scope in the process' main module. It can * also be used from other libraries if they want to integrate structured logging as well. * Only a single instance of this object should be necessary. * * Before any structured logging features can be used, the object must be initialized * with init(). This allows the log path and the default log filename to be specified * and will also load the library and register all the schemas for the calling module. * Note that if no schemas are registered, no log messages will be emitted, the calls * will just be silently ignored. If modules other than the process' main module also * have schemas to be registered, they can either call registerSchemas() from this * class (from the process's single instantiation) or they can make a call into * `omni::structuredlog::addModulesSchemas()` from within the other modules. It is * safe to call those functions even if no schemas are used in a module or if the * structured log system has not been initialized yet. If either are called before * the structured log system has been initialized, an attempt will be made to load * the library first. * * @note On Windows it is expected that this object be instantiated in the process' * main module. If it is instantiated from a DLL it will not be guaranteed * that all pending log messages will be flushed to disk before the process * exits. If instantiating this from a DLL is unavoidable, it is the app's * responsibility to call flush() before shutdown to ensure all messages have * been flushed to disk. * * This requirement is caused by the way that Windows processes shutdown and * is unfortunately not possible to work around. When exiting the process * by returning from main(), the CRT is shutdown completely before any DLLs * get a chance to do any kind of cleanup task, and ntdll will kill all threads * except the exiting one. This means that there is a possibility that attempting * to flush the queue could result in a deadlock. Further, if any cleanup code * tries to use a win32 locking primitive (ie: SRW lock, critical section, etc) * the process may just be terminated immediately even in the middle of cleanup. */ class StructuredLogStandalone { public: StructuredLogStandalone() = default; /** Destructor: flushes the logging queue to disk and cleans up. * * @remarks This ensures that all log messages have been flushed to disk and puts the * structured logging system in a state where it can safely be cleaned up * without issue. */ ~StructuredLogStandalone() { // stop the log queue to guarantee that all messages have been flushed to disk. flush(); // release the objects explicitly to make debugging any release issues easier. Note that // this isn't strictly necessary since they will be released anyway when cleaning up this // object. log.release(); settings.release(); control.release(); } bool init(const char* logPath = nullptr, const char* defaultLogName = nullptr) { // When in standalone mode, the structured log plugin is set to load itself when the // omniGetStructuredLogWithoutAcquire() function is called by anything. This is the main // entry point to grab its instance in standalone mode. It is called by (among other things) // `omni::structuredlog::addModuleSchemas()`. This function needs to be called regardless // in standalone mode in order to register the schemas that have been included in the // calling module. It must be called once by each module that wants to use structured // logging in standalone mode. In non-standalone mode (ie: with carb), this step is done // automatically on module load. registerSchemas(); // grab the structured log object so we can grab the settings interface from it and setup // the configuration that's needed here. There isn't strictly anything that we must do here, // but in our case we want to change the log directory and default log name. We can also do // things like change the user ID, the queue size, some of the message formatting, etc. All // of these additional tasks are done through the `omni::structuredlog::IStructuredLogSettings` // interface. This can be acquired with `strucLog.as<omni::structuredlog::IStructuredLogSettings>()`. log = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (log == nullptr) return false; settings = log.as<omni::structuredlog::IStructuredLogSettings>(); control = log.as<omni::structuredlog::IStructuredLogControl>(); if (settings != nullptr) { if (logPath != nullptr) settings->setLogOutputPath(logPath); if (defaultLogName != nullptr) settings->setLogDefaultName(defaultLogName); } return log != nullptr && settings != nullptr && control != nullptr; } /** Registers all schemas used by the calling module. * * @returns No return value. * * @remarks This registers all schemas that have been included in the calling module. When * any source file in any module includes a schema header, an entry for it is * automatically added to a list local to the module. When this is called from * within the context of that module, all schemas for that module will be registered * and become available for use. * * @remarks This must be called from each module that includes a schema header. If it is * not, emitting a log message for an unregistered schema will be silently ignored. * It is possible however that the same schema could be used in multiple modules. * If that is the case, it only needs to be registered once, then all modules in * the process may use it. It is safe to register any given schema multiple times. * After it is registered once, later attempts to re-register it will just succeed * immediately. * * @note This is called from init() as well. Any module that calls init() does not also have * to explicitly call this. */ void registerSchemas() { addModulesSchemas(); } /** Flushes all pending log messages to disk. * * @returns No return value. * * @remarks This flushes all pending log messages to disk. Upon return, any messages that * has been issued before the call will have made it to disk. If there is another * thread emitting a message during this call, it is undefined whether it will * be fully flushed to disk. This should be called in situations where the caller * can guarantee that no messages are in the process of being emitted. * * @note This should be called at points where messages must be guaranteed to be present on * disk. This includes process exit time. This will be called implicitly when this * object is destroyed, but if an exit path is taken that will not guarantee this * object is destroyed (ie: calling `_exit()`, `TerminateProcess()`, etc), this * can be called explicitly to accomplish the same result. */ void flush() { if (control != nullptr) control->stop(); } /** Various structured log objects. These are publicly accessible so that callers can use * them directly to get direct access to the structured log features that may be needed. * As long as init() succeeds, these objects will be valid. * @{ */ /** Main IStructuredLog instance object. This is a global singleton that provides direct * access to the functionality for registering new schemas (manually), enabling and disabling * events or schemas, and emitting messages. */ omni::core::ObjectPtr<omni::structuredlog::IStructuredLog> log; /** Structured log settings interface. This is used to make changes to the various settings * for the structured logging system and to retrieve information about its current settings. * The most common uses of this are to change the log directory or name (though that is * already done more easily through init()). */ omni::core::ObjectPtr<omni::structuredlog::IStructuredLogSettings> settings; /** Structured log control interface. This is used to stop and flush the message queue and * to ensure any open log files are closed. Closing a log file is only necessary for example * to ensure a log file would not prevent a directory from being deleted on Windows. */ omni::core::ObjectPtr<omni::structuredlog::IStructuredLogControl> control; /** @} */ }; } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/StructuredLogUtils.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 Utilities for structured log functionality. */ #pragma once #include "../extras/UniqueApp.h" #include "IStructuredLogSettings.h" #include "../../carb/extras/StringSafe.h" #if CARB_PLATFORM_WINDOWS # include "../../carb/CarbWindows.h" #elif CARB_POSIX # include <time.h> #else CARB_UNSUPPORTED_PLATFORM(); #endif namespace omni { namespace structuredlog { /** Base type for a CloudEvents timestamp. This will always be a value in nanoseconds. */ using TimestampNs = uint64_t; /** Generate the 'dataschema' field for events of a schema. * @param[in] clientName The client name specified in the schema's metadata. * @param[in] schemaVersion The version specified in the schema's metadata. * @returns The 'dataschema' field that will be emitted with the event. */ inline std::string generateDataSchema(const char* clientName, const char* schemaVersion) { return std::string(clientName) + '-' + schemaVersion; } /** retrieves a UTC timestamp relative to the system epoch in nanoseconds. * * @returns the number of system specific ticks that have elapsed since the system epoch. * The specifc epoch depends on the platform. On Windows, this is midnight Jan * 1, 1601. On Linux, this is midnight Jan 1, 1970. * * @thread_safety This is thread safe and only operates on local values. */ inline TimestampNs getUtcTimestamp() { #if CARB_PLATFORM_WINDOWS CARBWIN_FILETIME ft; // use GetSystemTimeAsFileTime() since that gives higher than millisecond resolution // (number of 100 nanosecond ticks since January 1, 1601). Other time functions // either do not have a reliable granularity, unknown epoch, or have a resolution // lower than milliseconds. This value has ~29247 years of space on it so overflow // should not be a concern. This then needs to be converted to nanoseconds for // return. GetSystemTimeAsFileTime(reinterpret_cast<FILETIME*>(&ft)); return ((((uint64_t)ft.dwHighDateTime) << 32) | ft.dwLowDateTime) * 100; #elif CARB_POSIX struct timespec ts; // use clock_gettime() since that gives higher than millisecond resolution (number // of nanoseconds since January 1, 1970). Other time functions either have an // unknown epoch, have a resolution lower than milliseconds, or are just built on // top of this function (ie: gettimeofday()). Storing this as a 64-bit integer // should give approximately 292 years worth of space. That is significantly more // than the 136 years of space that clock_gettime() gives in the first place. // Overflow of the value should not be an concern. clock_gettime(CLOCK_REALTIME, &ts); return (ts.tv_sec * 1'000'000'000ull) + ts.tv_nsec; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** Prints a UTC timestamp as an RfC3339 formatted string. * * @param[in] time The UTC timestamp to print. This should have been retrieved from a * previous call to getUtcTimestamp(). * @param[out] buffer Receives the printed timestamp string. This buffer must be large * enough to hold at least @p len characters. This buffer will always * be null terminated. This may not be nullptr. * @param[in] len The maximum number of characters that will fit in @p buffer including * the null terminator. * @returns The number of characters written to the output buffer. * This will truncate the timestamp if there was not enough buffer space. * * @thread_safety This is thread safe and only operates on local buffers. */ inline size_t printUtcTimestamp(TimestampNs time, char* buffer, size_t len) { size_t count; int32_t year; int32_t month; int32_t day; int32_t hour; int32_t minute; int32_t second; int32_t microseconds; #if CARB_PLATFORM_WINDOWS CARBWIN_FILETIME ft; CARBWIN_SYSTEMTIME st; TimestampNs t; // convert the given time index from nanoseconds back to NT ticks (100ns units). t = time / 100; // convert this back to a FILETIME object (a split 64-bit value representing the number // of 100 nanosecond ticks since January 1, 1601) so we can convert it to an adjusted // date/time stamp. The native call already provides milliseconds so we don't need to // calculate that separately. ft.dwLowDateTime = t & 0xffffffffull; ft.dwHighDateTime = t >> 32; FileTimeToSystemTime(reinterpret_cast<FILETIME*>(&ft), reinterpret_cast<SYSTEMTIME*>(&st)); year = st.wYear; month = st.wMonth; day = st.wDay; hour = st.wHour; minute = st.wMinute; second = st.wSecond; #elif CARB_POSIX struct tm tm; time_t t; // convert this back to a time_t and a count of remaining milliseconds. The input time // value will be the number of nanoseconds since January 1, 1970. This will convert it // to an adjusted date/time stamp. Since time_t values only hold times in seconds and // gmtime*() are the only functions that provide an adjusted date/time stamp, we'll // extract the microseconds count from the original value manually. Microseconds are // not affected by leaps (days or seconds), so they can be safely extracted from the // original time without having to adjust the date/time further. t = time / 1'000'000'000ull; gmtime_r(&t, &tm); year = tm.tm_year + 1900; month = tm.tm_mon + 1; day = tm.tm_mday; hour = tm.tm_hour; minute = tm.tm_min; second = tm.tm_sec; #else CARB_UNSUPPORTED_PLATFORM(); #endif microseconds = static_cast<int32_t>((time / 1'000ull) % 1'000'000ull); count = carb::extras::formatString( buffer, len, "%04d-%02d-%02dT%02d:%02d:%02d.%06dZ", year, month, day, hour, minute, second, microseconds); return count; } } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/IStructuredLogFromILog.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/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 /** This interface controls the ability to send Carbonite and Omniverse logging through the * structured log system. The output is equivalent to the standard logging output, except that it * is in JSON, so it will be easier for programs to consume. * * The default state of structured log logging is off, but it can be enabled by calling * @ref omni::structuredlog::IStructuredLogFromILog::enableLogging() or setting `/structuredLog/enableLogConsumer` * to true with ISettings. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi> : public omni::structuredlog::IStructuredLogFromILog_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogFromILog") /** Enable the structured log logger. * @remarks Enabling this will result in all Carbonite logging (e.g. CARB_LOG_*) and all * Omniverse logging (e.g. OMNI_LOG_*) going to the structured log log file. * This may be useful if you want the logs to be consumed by some sort of log reader * program. * These log events will be sent to the default structured log system's log file if * there is one; they will otherwise go to a log file named * "omni.structuredlog.logging-{version}". * These log events will not be sent to the collection servers. */ void enableLogging() noexcept; /** Disables the structured log logger. * @remarks After this is called, log messages will no longer be sent as structured log * events to the structured log system's log file. */ void disableLogging() noexcept; /** Get the @ref omni::structuredlog::EventId of the logging schema. * @retval omni::structuredlog::EventId of the logging schema. * * @remarks This is only needed if you need to query properties of the logging schema, * such as the log file name. * * @note The logging schema will still be valid when logging is disabled. */ omni::structuredlog::EventId getLoggingEventId() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi>::enableLogging() noexcept { enableLogging_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi>::disableLogging() noexcept { disableLogging_abi(); } inline omni::structuredlog::EventId omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi>::getLoggingEventId() noexcept { return getLoggingEventId_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/structuredlog/IStructuredLogFromILog.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 An interface for redirecting @ref omni::log::ILog messages to structured logging. */ #pragma once #include "StructuredLogCommon.h" #include "../core/IObject.h" namespace omni { namespace structuredlog { class IStructuredLogFromILog; // ****************************** IStructuredLogFromILog interface ******************************** /** This interface controls the ability to send Carbonite and Omniverse logging through the * structured log system. The output is equivalent to the standard logging output, except that it * is in JSON, so it will be easier for programs to consume. * * The default state of structured log logging is off, but it can be enabled by calling * @ref omni::structuredlog::IStructuredLogFromILog::enableLogging() or setting `/structuredLog/enableLogConsumer` * to true with ISettings. */ class IStructuredLogFromILog_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogFromILog")> { protected: // ****** structured logging functions ****** /** Enable the structured log logger. * @remarks Enabling this will result in all Carbonite logging (e.g. CARB_LOG_*) and all * Omniverse logging (e.g. OMNI_LOG_*) going to the structured log log file. * This may be useful if you want the logs to be consumed by some sort of log reader * program. * These log events will be sent to the default structured log system's log file if * there is one; they will otherwise go to a log file named * "omni.structuredlog.logging-{version}". * These log events will not be sent to the collection servers. */ virtual void enableLogging_abi() noexcept = 0; /** Disables the structured log logger. * @remarks After this is called, log messages will no longer be sent as structured log * events to the structured log system's log file. */ virtual void disableLogging_abi() noexcept = 0; /** Get the @ref omni::structuredlog::EventId of the logging schema. * @retval omni::structuredlog::EventId of the logging schema. * * @remarks This is only needed if you need to query properties of the logging schema, * such as the log file name. * * @note The logging schema will still be valid when logging is disabled. */ virtual EventId getLoggingEventId_abi() noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogFromILog.gen.h" /** @copydoc omni::structuredlog::IStructuredLogFromILog_abi */ class omni::structuredlog::IStructuredLogFromILog : public omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogFromILog.gen.h"
omniverse-code/kit/include/omni/structuredlog/IStructuredLogSettings2.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 Interface to querying and adjusting structured logging settings. */ #pragma once #include "StructuredLogCommon.h" #include "IStructuredLogSettings.h" #include "../core/IObject.h" namespace omni { namespace structuredlog { class IStructuredLogSettings2; /** Base type for the ouptut flags for the structured logging system. These flags are used * in the omni::structuredlog::IStructuredLogSettings2::getOutputFlags() and * omni::structuredlog::IStructuredLogSEttings2::setOutputFlags() functions. */ using OutputFlags = uint32_t; /** Special flag value to indicate that no output flags are being specified. */ constexpr OutputFlags fOutputFlagNone = 0; /** Flag to indicate that only emit the payload portion of each message as the full output instead * of including the CloudEvents wrapper as well. In this case, it is expected to be the host * app's responsibility to ensure all the useful or required information is included in the * payload itself (ie: timestamps, user information, etc). Also, when this flag is used, log * files created containing these messages cannot be consumed by the telemetry transmitter. * This flag should only be used when the host app wants to use structured logging messages * but does not want to use them as part of the telemetry toolchain. This flag is off by * default. Adding this flag will take effect the next time a message is emitted. */ constexpr OutputFlags fOutputFlagPayloadOnly = 0x00000001; /** Flag to indicate that no header should be written out to log files created by the structured * logging system. The header is consumed and modified by the telemetry transmitter app to allow * it to store its progress in processing each log file. If the header is missing, the * transmitter app will simply ignore the log file. Omitting the headers in log files allows the * log output to purely just be the structured log event messages so they can be more easily * consumed wholesale by external apps. Note that when this flag is used, the structured log * files created by the host app will be incompatible with the rest of the telemetry toolchain * in Omniverse. This flag is off by default. Adding this flag will take effect the next time * a new log file is created. */ constexpr OutputFlags fOutputFlagSkipLogHeaders = 0x00000002; /** Flag to indicate that the cloud heartbeat events should be emitted as well as the normal * heartbeat events. This cloud heartbeat event is effectively duplciate data and will only * be emitted when this flag is used and the normal heartbeat events are also enabled. This * defaults to off. */ constexpr OutputFlags fOutputFlagEmitCloudHeartbeat = 0x00000004; // ****************************** IStructuredLogSettings2 interface ******************************* /** Interface for the second version of the IStructuredLogSettings interface. This interface * exposes more settings to control the behaviour of the structured logging system. This * object can be retrieved directly or by casting the main IStructuredLog interface to this * type using `omni::core::ObjectPtr::as<>()`. */ class IStructuredLogSettings2_abi : public omni::core::Inherits<omni::structuredlog::IStructuredLogSettings_abi, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogSettings2")> { protected: /** Retrieves the current heartbeat message period in seconds. * * @returns The minimum time in seconds between heartbeat events. This will be * @ref omni::structuredlog::kHeartbeatDisabled if the heartbeat events are * disabled. When enabled, the heartbeat events will be generated within * ~100ms of this scheduled time. In general, it is expected that the heartbeat * period be on the scale of one minute or more to reduce the overall amount of * event traffic. */ virtual uint64_t getHeartbeatPeriod_abi() noexcept = 0; /** Sets the new heartbeat event period in seconds. * * @param[in] period The minimum time in seconds between generated heartbeat events. * This may be @ref omni::structuredlog::kHeartbeatDisabled to disable * the heartbeat events. * @returns No return value. * * @remarks The heartbeat events can be used to get an estimate of a session's length even if * the 'exit' or 'crash' process lifetime events are missing (ie: power loss, user * kills the process, blue screen of death or kernel panic, etc). The session can * neither be assumed to have exited normally nor crashed with only these heartbeat * events present however. */ virtual void setHeartbeatPeriod_abi(uint64_t period) noexcept = 0; /** Retrieves whether header objects will be added to each newly written log file. * * @returns `true` if headers will be written to each new log file. Returns `false` if * header objects will be omitted from new log files. */ virtual bool getNeedLogHeaders_abi() noexcept = 0; /** Sets whether headers will be added to each newly written log file. * * @param[in] needHeaders Set to `true` to indicate that headers should be added to each * newly written log file. Set to `false` to indicate that the * header should be omitted. * @returns No return value. * * @remarks This sets whether log headers will be written out to each new log file. The * header is consumed and modified by the telemetry transmitter app to allow it * to store its progress in processing each log file. If the header is missing, * the transmitter app will simply ignore the log file. Omitting the headers * in log files allows the log output to purely just be the structured log event * messages so they can be more easily consumed wholesale by external apps. * * @note Changing this setting will only take effect the next time a new log file is written * out to disk. Disabling this will not remove the header object from an existing log * file. */ virtual void setNeedLogHeaders_abi(bool needHeaders) noexcept = 0; /** Retrieves the current set of output flags for structured logging. * * @returns The current output flags for the structured logging system. These indicate how * various aspects of the logging system will function. Note that some flags may * affect whether the produced messages are compatible with the remainder of the * telemetry toolchain in Omniverse apps. By default, all output flags are off. */ virtual OutputFlags getOutputFlags_abi() noexcept = 0; /** Sets or clears one or more output flags for structured logging. * * @param[in] flagsToAdd A set of zero or more flag bits to set. These must be either * @ref omni::structuredlog::fOutputFlagNone or one or more of * the @ref omni::structuredlog::OutputFlags flags. * @param[in] flagsToRemove A set of zero or more flag bits to cleared. These must be * either @ref omni::structuredlog::fOutputFlagNone or one or * more of the @ref omni::structuredlog::OutputFlags flags. * @returns No return value. * * @remarks This sets or clears flags that affect the output from the structured logging * system. These flags are all disabled by default. These flags will take effect * the next time a message is emitted. */ virtual void setOutputFlags_abi(OutputFlags flagsToAdd, OutputFlags flagsToRemove) noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogSettings2.gen.h" // insert custom API functions here. /** @copydoc omni::structuredlog::IStructuredLogSettings2_abi */ class omni::structuredlog::IStructuredLogSettings2 : public omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogSettings2.gen.h"
omniverse-code/kit/include/omni/structuredlog/StructuredLogCommon.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 Common types/macros/functions for structured logging. */ #pragma once #include "../core/IObject.h" #include "../extras/ForceLink.h" namespace omni { namespace structuredlog { /** Helper macro to piece together a unique event name to generate an ID from. * * @param schemaName The name of the schema that the event belongs to. This should be * the name from the schema's "#/schemaMeta/clientName" property. * This value must be a string literal. * @param eventName The full name of the event that the ID is being generated for. * This should be the name of one of the objects in the * "#/definitions/events/" listing. This value must be a string * literal. * @param schemaVersion The version of the schema the event belongs to. This should be * the value from the schema's "#/schemaMeta/schemaVersion" property. * This value must be a string literal. * @param parserVersion The version of the object parser that this event ID is being built * for. This should be the value of kParserVersion expressed as * a string. This value must be a string literal. * @returns A string representing the full name of an event. This string is suitable for passing * to OMNI_STRUCTURED_LOG_EVENT_ID() to generate a unique event ID from. */ #define OMNI_STRUCTURED_LOG_EVENT_ID(schemaName, eventName, schemaVersion, parserVersion) \ CARB_HASH_STRING(schemaName "-" eventName "-" schemaVersion "." parserVersion) #ifndef DOXYGEN_SHOULD_SKIP_THIS // used internally in OMNI_STRUCTURED_LOG_ADD_SCHEMA(). Do not call directly. # define OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(name_, version_, parser_, line_) \ OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME_INNER(name_, version_, parser_, line_) // used internally in OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(). Do not call directly. # define OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME_INNER(name_, version_, parser_, line_) \ sSchema_##name_##_##version_##_##parser_##_##line_ #endif /** Sets that a schema should be registered on module load. * * @param schemaType_ The name and fully qualified namespace of the generated schema class * to be registered. This will be added to a list of schemas to be * registered when the module is initialized. * @param schemaName_ The name of the schema to be registered. This may be any valid C++ * token string, but should reflect the schema's name. This is used * to make the initialization symbol more unique to the generated schema * class. * @param version_ The schema's version expressed as a C++ token. This should replace * any dots ("."), dashes ("-"), colons (":"), whitespace (" "), or * commas (",") with an underscore ("_"). This is used to make the * initialization symbol more unique to the generated schema class. * @param parser_ The parser version being used for the generated schema expressed as * a C++ token. This should replace any dots ("."), dashes ("-"), colons * (":"), whitespace (" "), or commas (",") with an underscore ("_"). * This is used to make the initialization symbol more unique to the * generated schema class. * @returns No return value. * * @remarks This creates and registers a helper function that will call into a generated * schema's registerSchema() function during omni core or framework initialization. * The symbol used to force the registration at C++ initialization time is named * based on the schema's name, schema's version, parser version, and the line number * in the header file that this call appears on. All of these values are used to * differentiate this schema's registration from that of all others, even for * different versions of the same generated schema. */ #define OMNI_STRUCTURED_LOG_ADD_SCHEMA(schemaType_, schemaName_, version_, parser_) \ CARB_ATTRIBUTE(weak) \ CARB_DECLSPEC(selectany) \ bool OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(schemaName_, version_, parser_, __LINE__) = []() { \ omni::structuredlog::getModuleSchemas().push_back(&schemaType_::registerSchema); \ return true; \ }(); \ OMNI_FORCE_SYMBOL_LINK( \ OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(schemaName_, version_, parser_, __LINE__), schemaRegistration) /** Possible results from registering a new schema. These indicate whether the schema was * successfully registered or why it may have failed. Each result code can be considered a * failure unless otherwise noted. In all failure cases, the schema's allocated data block * will be destroyed before returning and no new events will be registered. */ enum class SchemaResult { /** The new schema was successfully registered with a unique set of event identifiers. */ eSuccess, /** The new schema exactly matches one that has already been successfully registered. The * events in the new schema are still valid and can be used, however no new action was * taken to register the schema again. This condition can always be considered successful. */ eAlreadyExists, /** The new schema contains an event identifier that collides with an event in another schema. * The schema that the existing event belongs to does not match this new one. This often * indicates that either the name of an event in the schema is not unique enough or that * another version of the schema had already been registered. This is often remedied by * bumping the version number of the schema so that its event identifiers no longer matches * the previous schema's event(s). */ eEventIdCollision, /** The same schema was registered multiple times, but with different schema flags. This is * not allowed and will fail the new schema's registration. This can be fixed by bumping * the version of the new schema. */ eFlagsDiffer, /** Too many events have been registered. There is an internal limit of unique events that * can be registered in any one process. Failed schemas or schemas that exactly match an * existing schema do not contribute their event count to this limit. When this is * returned, none of the new schema's events will be registered. There is no recovering * from this failure code. This is often an indication that the process's events should be * reorganized to not have so many. The internal limit will be at least 65536 events. */ eOutOfEvents, /** An invalid parameter was passed into IStructuredLog::commitSchema(). This includes a * nullptr @a schemaBlock parameter, a nullptr event table, or a zero event count. It is the * caller's responsibility to ensure valid parameters are passed in. */ eInvalidParameter, /** An event's schema payload information was not contained within the block of memory that * was returned from IStructuredLog::allocSchema(). This is a requirement to ensure all the * event's information memory is owned by the structured log core. */ eEventNotInBlock, /** Memory could not be allocated for the new schema information object. This can usually * be considered fatal. */ eOutOfMemory, }; /** Base type for a unique ID of a registered event. Each registered event is identified by an * integer value that is derived from its name, schema, and version number. */ using EventId = uint64_t; /** A special value to indicate a bad event identifier. This is used as a failure code * in some of the IStructuredLog accessor functions. */ constexpr EventId kBadEventId = ~1ull; /** Retrieves a string containing the name of a SchemaResult value. * * @param[in] result The result code to convert to a string. * @returns The result code's name as a string if a valid code is passed in. * @returns "<unknown_result>" if an invalid or unknown result code is passed in. */ constexpr const char* getSchemaResultName(SchemaResult result) { #ifndef DOXYGEN_SHOULD_SKIP_THIS # define OMNI_STRUCTUREDLOG_GETNAME(r, prefix) \ case r: \ return &(#r)[sizeof(#prefix) - 1] switch (result) { OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eSuccess, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eAlreadyExists, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eEventIdCollision, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eFlagsDiffer, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eOutOfEvents, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eInvalidParameter, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eEventNotInBlock, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eOutOfMemory, SchemaResult::e); default: return "<unknown_result>"; } # undef OMNI_STRUCTUREDLOG_GETNAME #endif } } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/StructuredLog.Cloud.python.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.Cloud.schema #pragma once #include <carb/BindingsPythonUtils.h> #include "StructuredLog.Cloud.gen.h" namespace omni { namespace telemetry { struct Struct_Wrap_startup_ident { /** The identifier of the cluster this pod is running on. */ std::string cluster; /** The identifier of the node this pod is running on. This will be * either a hostname or the IPv4/IPv6 address of the node. */ std::string node; }; struct Struct_Wrap_startup_application { /** The name of the app that is starting up. */ std::string name; /** The version of the app that is starting up. */ std::string version; }; struct Struct_Wrap_exit_application { /** The name of the app that is starting up. */ std::string name; /** The version of the app that is starting up. */ std::string version; }; class Wrap_omni_carb_cloud { public: Wrap_omni_carb_cloud() = default; ~Wrap_omni_carb_cloud() = default; void startup_sendEvent(std::string cloud_link_id, const Struct_Wrap_startup_ident& ident, const Struct_Wrap_startup_application& application) { Schema_omni_carb_cloud_1_0::Struct_startup_ident ident_ = {}; ident_.cluster = ident.cluster; ident_.node = ident.node; Schema_omni_carb_cloud_1_0::Struct_startup_application application_ = {}; application_.name = application.name; application_.version = application.version; OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::startup, cloud_link_id, ident_, application_); } void heartbeat_sendEvent(std::string cloud_link_id) { OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::heartbeat, cloud_link_id); } void exit_sendEvent(std::string cloud_link_id, const Struct_Wrap_exit_application& application, bool exit_abnormally) { Schema_omni_carb_cloud_1_0::Struct_exit_application application_ = {}; application_.name = application.name; application_.version = application.version; OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::exit, cloud_link_id, application_, exit_abnormally); } }; inline void definePythonModule_omni_carb_cloud(py::module& m) { using namespace omni::structuredlog; m.doc() = "bindings for structured log schema omni.carb.cloud"; { py::class_<Struct_Wrap_startup_ident> bind_ident(m, "Struct_startup_ident"); bind_ident.def(py::init<>()); bind_ident.def_readwrite("cluster", &Struct_Wrap_startup_ident::cluster); bind_ident.def_readwrite("node", &Struct_Wrap_startup_ident::node); } { py::class_<Struct_Wrap_startup_application> bind_application(m, "Struct_startup_application"); bind_application.def(py::init<>()); bind_application.def_readwrite("name", &Struct_Wrap_startup_application::name); bind_application.def_readwrite("version", &Struct_Wrap_startup_application::version); } { py::class_<Struct_Wrap_exit_application> bind_application(m, "Struct_exit_application"); bind_application.def(py::init<>()); bind_application.def_readwrite("name", &Struct_Wrap_exit_application::name); bind_application.def_readwrite("version", &Struct_Wrap_exit_application::version); } // the main structured log class py::class_<Wrap_omni_carb_cloud>(m, "Schema_omni_carb_cloud_1_0") .def(py::init<>()) .def("startup_sendEvent", &Wrap_omni_carb_cloud::startup_sendEvent, py::arg("cloud_link_id"), py::arg("ident"), py::arg("application")) .def("heartbeat_sendEvent", &Wrap_omni_carb_cloud::heartbeat_sendEvent, py::arg("cloud_link_id")) .def("exit_sendEvent", &Wrap_omni_carb_cloud::exit_sendEvent, py::arg("cloud_link_id"), py::arg("application"), py::arg("exit_abnormally")); } } // namespace telemetry } // namespace omni
omniverse-code/kit/include/omni/structuredlog/JsonTreeSerializer.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 Module for Serializing the @ref omni::structuredlog::JsonNode tree structures. */ #pragma once #include "JsonSerializer.h" #include "BinarySerializer.h" #include "JsonTree.h" namespace omni { namespace structuredlog { /** Default value for the onValidationError template parameter. * @param[in] s The validation error message. This is ignored. */ static inline void ignoreJsonTreeSerializerValidationError(const char* s) { CARB_UNUSED(s); } /** Serialize a scalar type from a JSON tree. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The node in the schema that represents this scalar value. * @param[in] constVal The constant value from the data union of @p root. * This is only read if root is marked as constant. * @param[inout] reader The blob reader, which will be read if @p root is not * marked as constant. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeScalar(JsonSerializerType* serial, const JsonNodeType* root, T constVal, BlobReaderType* reader) { if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValue(constVal); } else { T b = {}; bool result = reader->read(&b); if (validate && !result) return false; return serial->writeValue(b); } } /** Serialize an array type from a JSON tree. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The node in the schema that represents this scalar value. * @param[in] constVal The constant array value from the data union of @p root. * This is only read if root is marked as constant; * in that case, this is of length @p root->len. * @param[inout] reader The blob reader, which will be read if @p root is not * marked as constant. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeArray(JsonSerializerType* serial, const JsonNodeType* root, const T* constVal, BlobReaderType* reader) { bool result = true; result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagConst) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serial->writeValue(constVal[i]); if (validate && !result) return false; } } else { const T* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); if (validate && !result) return false; } else { result = reader->read(&b, &len); if (validate && !result) return false; } for (uint16_t i = 0; i < len; i++) { result = serial->writeValue(b[i]); if (validate && !result) return false; } } return serial->closeArray(); } template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeEnum(JsonSerializerType* serial, const JsonNodeType* root, T* enumChoices, BlobReaderType* reader) { JsonNode::EnumBase b = {}; bool result = reader->read(&b); if (validate && !result) return false; if (b > root->len) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "enum value is out of range" " {value = %" PRIu16 ", max = %" PRIu16 "}", b, root->len); serial->m_onValidationError(tmp); return false; } return serial->writeValue(enumChoices[b]); } /** Serialize JSON using a @ref JsonNode as the schema and a binary blob to read data. * * @remarks This overload uses a @ref BlobReader instead of the binary blob * directly, so that the read position from within the blob can be * tracked across recursive calls. * External code should use the other overload. * * @note If you use this overload, you must call @p serial->finish(), since this * is the recursive overload so there's no obvious point to finish at. */ template <bool validate = false, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeJsonTree(JsonSerializerType* serial, const JsonNodeType* root, BlobReaderType* reader) { bool result = true; if (root->name != nullptr) { result = serial->writeKey(root->name, root->nameLen - 1); if (validate && !result) return false; } switch (root->type) { case NodeType::eNull: return serial->writeValue(); case NodeType::eBool: return serializeScalar<validate>(serial, root, root->data.boolVal, reader); case NodeType::eInt32: return serializeScalar<validate>(serial, root, int32_t(root->data.intVal), reader); case NodeType::eUint32: return serializeScalar<validate>(serial, root, uint32_t(root->data.uintVal), reader); case NodeType::eInt64: return serializeScalar<validate>(serial, root, root->data.intVal, reader); case NodeType::eUint64: return serializeScalar<validate>(serial, root, root->data.uintVal, reader); case NodeType::eFloat32: return serializeScalar<validate>(serial, root, float(root->data.floatVal), reader); case NodeType::eFloat64: return serializeScalar<validate>(serial, root, root->data.floatVal, reader); case NodeType::eBinary: if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValueWithBase64Encoding(root->data.binaryVal, root->len); } else { const uint8_t* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); } else { result = reader->read(&b, &len); } if (validate && !result) return false; // null terminator is included in the length return serial->writeValueWithBase64Encoding(b, len); } case NodeType::eBoolArray: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.boolArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.boolArrayVal, reader); case NodeType::eInt32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.int32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.int32ArrayVal, reader); case NodeType::eUint32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.uint32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.uint32ArrayVal, reader); case NodeType::eInt64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.int64ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.int64ArrayVal, reader); case NodeType::eUint64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.uint64ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.uint64ArrayVal, reader); case NodeType::eFloat32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.float32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.float32ArrayVal, reader); case NodeType::eFloat64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum(serial, root, root->data.float64ArrayVal, reader); else return serializeArray(serial, root, root->data.float64ArrayVal, reader); case NodeType::eString: if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValue(root->data.strVal, (root->len == 0) ? 0 : root->len - 1); } else { const char* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); } else { result = reader->read(&b, &len); } if (validate && !result) return false; // null terminator is included in the length return serial->writeValue(b, (len == 0) ? 0 : len - 1); } case NodeType::eStringArray: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.strArrayVal, reader); result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagConst) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serial->writeValue(root->data.strArrayVal[i]); if (validate && !result) return false; } } else { const char** b = nullptr; uint16_t len = 0; // fixed length isn't supported here result = reader->read(b, &len, 0); if (validate && !result) return false; // FIXME: dangerous b = static_cast<const char**>(alloca(len * sizeof(*b))); result = reader->read(b, &len, len); if (validate && !result) return false; for (uint16_t i = 0; i < len; i++) { result = serial->writeValue(b[i]); if (validate && !result) return false; } } return serial->closeArray(); case NodeType::eObject: result = serial->openObject(); if (validate && !result) return false; for (uint16_t i = 0; i < root->len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[i], reader); if (validate && !result) return false; } return serial->closeObject(); case NodeType::eObjectArray: result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[i], reader); if (validate && !result) return false; } } else { uint16_t len = 0; // read the array length result = reader->read(&len); if (validate && !result) return false; // a variable length object array uses the same object schema for // each object in the array, so we just pass the 0th element here for (uint16_t i = 0; i < len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[0], reader); if (validate && !result) return false; } } return serial->closeArray(); } return false; } /** Serialize JSON using a @ref JsonNode as the schema and a binary blob to read data. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The JSON tree to use for the data schema. * @param[in] blob The binary blob to read data directly from. * @param[in] blobSize The length of @p blob in bytes. * * @tparam validate If this is true, validation will be performed. * This ensures the output JSON will be valid. * This also will add bounds checking onto @p blob. * If this is false, out of bounds reading is possible * when the blob was generated incorrectly. * @tparam prettyPrint If this is set to false, the output will be printed * with minimal spacing. * Human-readable spacing will be used otherwise. * @tparam onValidationError This callback will be used when a validation error * occurs, so that logging can be performed. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeJsonTree(JsonSerializerType* serial, const JsonNodeType* root, const void* blob, size_t blobSize) { BlobReaderType reader(blob, blobSize); return serializeJsonTree<validate>(serial, root, &reader) && serial->finish(); } /* we don't extract static symbols so this breaks exhale somehow */ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** @copydoc serializeJsonSchema */ template <typename JsonSerializerType = JsonSerializer<true, true>, typename JsonNodeType = JsonNode> static inline void serializeJsonSchema_(JsonSerializerType* serial, const JsonNodeType* root) { auto nodeTypeString = [](NodeType n) -> const char* { switch (n) { case NodeType::eNull: return "null"; case NodeType::eBool: return "boolean"; case NodeType::eInt32: return "integer"; case NodeType::eUint32: return "uint32"; case NodeType::eInt64: return "int64"; case NodeType::eUint64: return "uint64"; case NodeType::eFloat32: return "float"; case NodeType::eFloat64: return "double"; case NodeType::eBinary: return "binary"; case NodeType::eBoolArray: return "bool[]"; case NodeType::eInt32Array: return "integer[]"; case NodeType::eUint32Array: return "uint32[]"; case NodeType::eInt64Array: return "int64[]"; case NodeType::eUint64Array: return "uint64[]"; case NodeType::eFloat32Array: return "float[]"; case NodeType::eFloat64Array: return "double[]"; case NodeType::eString: return "string"; case NodeType::eStringArray: return "string[]"; case NodeType::eObject: return "object"; case NodeType::eObjectArray: return "object[]"; } return "unknown"; }; if (root->name != nullptr) { serial->writeKey(root->name, root->nameLen - 1); } serial->openObject(); serial->writeKey("type"); serial->writeValue(nodeTypeString(root->type)); serial->writeKey("flags"); serial->writeValue(root->flags); if ((root->flags & JsonNode::fFlagConst) != 0) { serial->writeKey("const"); switch (root->type) { case NodeType::eNull: serial->writeValue(); break; case NodeType::eBool: serial->writeValue(root->data.boolVal); break; case NodeType::eInt32: serial->writeValue(root->data.intVal); break; case NodeType::eUint32: serial->writeValue(root->data.uintVal); break; case NodeType::eInt64: serial->writeValue(root->data.intVal); break; case NodeType::eUint64: serial->writeValue(root->data.uintVal); break; case NodeType::eFloat32: serial->writeValue(root->data.floatVal); break; case NodeType::eFloat64: serial->writeValue(root->data.floatVal); break; case NodeType::eBinary: serial->writeValueWithBase64Encoding(root->data.binaryVal, root->len); break; case NodeType::eBoolArray: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.boolArrayVal[i]); } serial->closeArray(); break; case NodeType::eInt32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.int32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eUint32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.uint32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eInt64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.int64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eUint64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.uint64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eFloat32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.float32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eFloat64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.float64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eString: serial->writeValue(root->data.strVal, (root->len == 0) ? 0 : root->len - 1); break; case NodeType::eStringArray: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.strArrayVal[i]); } serial->closeArray(); break; case NodeType::eObject: serial->writeValue(); break; case NodeType::eObjectArray: serial->openArray(); serial->closeArray(); break; } } if ((root->flags & JsonNode::fFlagEnum) != 0) { serial->writeKey("enum"); serial->writeValue(true); } if (root->type == NodeType::eObject || root->type == NodeType::eObjectArray) { serial->writeKey("properties"); serial->openObject(); for (size_t i = 0; i < root->len; i++) { serializeJsonSchema_(serial, &root->data.objVal[i]); } serial->closeObject(); } serial->closeObject(); } /** Serialize a JSON schema to JSON. * @param[in] serial The serializer object to use. * @param[in] root The schema being serialized. * @remarks This function will serialize a JSON schema to JSON. * This is mainly intended to be used for debugging. * serializeJsonTree() can't be used for serializing the schema because * a binary blob is needed for the variable values in the schema. */ template <typename JsonSerializerType = JsonSerializer<true, true>, typename JsonNodeType = JsonNode> static inline void serializeJsonSchema(JsonSerializerType* serial, const JsonNodeType* root) { serializeJsonSchema_(serial, root); serial->finish(); } #endif } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/StructuredLog.Cloud.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.Cloud.schema // #pragma once #include <omni/log/ILog.h> #include <omni/structuredlog/IStructuredLog.h> #include <omni/structuredlog/JsonTree.h> #include <omni/structuredlog/BinarySerializer.h> #include <omni/structuredlog/StringView.h> #include <memory> namespace omni { namespace telemetry { /** helper macro to send the 'startup' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] ident_ Parameter from schema at path '/ident'. * The information of where this pod is running. * @param[in] application_ Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was launched, * its version, the user, node, and cluster information, and the * cloud session ID that needs to be linked to this telemetry session * ID. * * @sa @ref Schema_omni_carb_cloud_1_0::startup_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::startup_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_STARTUP(cloud_link_id_, ident_, application_) \ OMNI_STRUCTURED_LOG(omni::telemetry::Schema_omni_carb_cloud_1_0::startup, cloud_link_id_, ident_, application_) /** helper macro to send the 'heartbeat' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @returns no return value. * * @remarks This event notes that the app is still running. The intention is * that this event should be emitted periodically to provide a way to * estimate session lengths even in cases where the exit event is not * present (ie: unexpected exit, power loss, process killed by the * user, etc). * * @sa @ref Schema_omni_carb_cloud_1_0::heartbeat_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::heartbeat_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_HEARTBEAT(cloud_link_id_) \ OMNI_STRUCTURED_LOG(omni::telemetry::Schema_omni_carb_cloud_1_0::heartbeat, cloud_link_id_) /** helper macro to send the 'exit' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] application_ Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @param[in] exit_abnormally_ Parameter from schema at path '/exit_abnormally'. * A flag indicating whether a crash occurred (true) or if a normal * exit was used (false). * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was exited, its * version, whether the exit was clean or not, and the cloud session * ID that needs to be linked to this telemetry session ID. * * @sa @ref Schema_omni_carb_cloud_1_0::exit_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::exit_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_EXIT(cloud_link_id_, application_, exit_abnormally_) \ OMNI_STRUCTURED_LOG( \ omni::telemetry::Schema_omni_carb_cloud_1_0::exit, cloud_link_id_, application_, exit_abnormally_) class Schema_omni_carb_cloud_1_0 { public: /** struct definition for parameter ident of event com.nvidia.omni.carb.cloud.startup. */ struct Struct_startup_ident { /** The identifier of the cluster this pod is running on. */ omni::structuredlog::StringView cluster; /** The identifier of the node this pod is running on. This will be * either a hostname or the IPv4/IPv6 address of the node. */ omni::structuredlog::StringView node; /** Default constructor for @ref Struct_startup_ident. */ Struct_startup_ident() = default; /** Basic constructor for @ref Struct_startup_ident. */ Struct_startup_ident(omni::structuredlog::StringView cluster_, omni::structuredlog::StringView node_) { cluster = cluster_; node = node_; } /** Basic assignment operator for @ref Struct_startup_ident. */ Struct_startup_ident& operator=(const Struct_startup_ident& other) { cluster = other.cluster; node = other.node; return *this; } /** Basic copy constructor for @ref Struct_startup_ident. */ Struct_startup_ident(const Struct_startup_ident& other) { *this = other; } }; /** struct definition for parameter application of event com.nvidia.omni.carb.cloud.startup. */ struct Struct_startup_application { /** The name of the app that is starting up. */ omni::structuredlog::StringView name; /** The version of the app that is starting up. */ omni::structuredlog::StringView version; /** Default constructor for @ref Struct_startup_application. */ Struct_startup_application() = default; /** Basic constructor for @ref Struct_startup_application. */ Struct_startup_application(omni::structuredlog::StringView name_, omni::structuredlog::StringView version_) { name = name_; version = version_; } /** Basic assignment operator for @ref Struct_startup_application. */ Struct_startup_application& operator=(const Struct_startup_application& other) { name = other.name; version = other.version; return *this; } /** Basic copy constructor for @ref Struct_startup_application. */ Struct_startup_application(const Struct_startup_application& other) { *this = other; } }; /** struct definition for parameter application of event com.nvidia.omni.carb.cloud.exit. */ struct Struct_exit_application { /** The name of the app that is starting up. */ omni::structuredlog::StringView name; /** The version of the app that is starting up. */ omni::structuredlog::StringView version; /** Default constructor for @ref Struct_exit_application. */ Struct_exit_application() = default; /** Basic constructor for @ref Struct_exit_application. */ Struct_exit_application(omni::structuredlog::StringView name_, omni::structuredlog::StringView version_) { name = name_; version = version_; } /** Basic assignment operator for @ref Struct_exit_application. */ Struct_exit_application& operator=(const Struct_exit_application& other) { name = other.name; version = other.version; return *this; } /** Basic copy constructor for @ref Struct_exit_application. */ Struct_exit_application(const Struct_exit_application& other) { *this = other; } }; /** the event ID names used to send the events in this schema. These IDs * are used when the schema is first registered, and are passed to the * allocEvent() function when sending the event. */ enum : uint64_t { kStartupEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.startup", "1.0", "0"), kHeartbeatEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.heartbeat", "1.0", "0"), kExitEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.exit", "1.0", "0"), }; Schema_omni_carb_cloud_1_0() = default; /** Register this class with the @ref omni::structuredlog::IStructuredLog interface. * @param[in] flags The flags to pass into @ref omni::structuredlog::IStructuredLog::allocSchema() * This may be zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @returns `true` if the operation succeeded. * @returns `false` if @ref omni::structuredlog::IStructuredLog couldn't be loaded. * @returns `false` if a memory allocation failed. */ static bool registerSchema(omni::structuredlog::IStructuredLog* strucLog) noexcept { return _registerSchema(strucLog); } /** Check whether this structured log schema is enabled. * @param[in] eventId the ID of the event to check the enable state for. * This must be one of the @a k*EventId symbols * defined above. * @returns Whether this client is enabled. */ static bool isEnabled(omni::structuredlog::EventId eventId) noexcept { return _isEnabled(eventId); } /** Enable/disable an event in this schema. * @param[in] eventId the ID of the event to enable or disable. * This must be one of the @a k*EventId symbols * defined above. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(omni::structuredlog::EventId eventId, bool enabled) noexcept { _setEnabled(eventId, enabled); } /** Enable/disable this schema. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(bool enabled) noexcept { _setEnabled(enabled); } /** event enable check helper functions. * * @param[in] strucLog The structured log object to use to send this event. This * must not be nullptr. It is the caller's responsibility * to ensure that a valid object is passed in. * @returns `true` if the specific event and this schema are both enabled. * @returns `false` if either the specific event or this schema is disabled. * * @remarks These check if an event corresponding to the function name is currently * enabled. These are useful to avoid parameter evaluation before calling * into one of the event emitter functions. These will be called from the * OMNI_STRUCTURED_LOG() macro. These may also be called directly if an event * needs to be emitted manually, but the only effect would be the potential * to avoid parameter evaluation in the *_sendEvent() function. Each * *_sendEvent() function itself will also internally check if the event * is enabled before sending it. * @{ */ static bool startup_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kStartupEventId); } static bool heartbeat_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kHeartbeatEventId); } static bool exit_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kExitEventId); } /** @} */ /** Send the event 'com.nvidia.omni.carb.cloud.startup' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] ident Parameter from schema at path '/ident'. * The information of where this pod is running. * @param[in] application Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was launched, * its version, the user, node, and cluster information, and the * cloud session ID that needs to be linked to this telemetry session * ID. */ static void startup_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_startup_ident& ident, const Struct_startup_application& application) noexcept { _startup_sendEvent(strucLog, cloud_link_id, ident, application); } /** Send the event 'com.nvidia.omni.carb.cloud.heartbeat' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @returns no return value. * * @remarks This event notes that the app is still running. The intention is * that this event should be emitted periodically to provide a way to * estimate session lengths even in cases where the exit event is not * present (ie: unexpected exit, power loss, process killed by the * user, etc). */ static void heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id) noexcept { _heartbeat_sendEvent(strucLog, cloud_link_id); } /** Send the event 'com.nvidia.omni.carb.cloud.exit' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] application Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @param[in] exit_abnormally Parameter from schema at path '/exit_abnormally'. * A flag indicating whether a crash occurred (true) or if a normal * exit was used (false). * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was exited, its * version, whether the exit was clean or not, and the cloud session * ID that needs to be linked to this telemetry session ID. */ static void exit_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_exit_application& application, bool exit_abnormally) noexcept { _exit_sendEvent(strucLog, cloud_link_id, application, exit_abnormally); } private: /** This will allow us to disable array length checks in release builds, * since they would have a negative performance impact and only be hit * in unusual circumstances. */ static constexpr bool kValidateLength = CARB_DEBUG; /** body for the registerSchema() public function. */ static bool _registerSchema(omni::structuredlog::IStructuredLog* strucLog) { omni::structuredlog::AllocHandle handle = {}; omni::structuredlog::SchemaResult result; uint8_t* buffer; omni::structuredlog::EventInfo events[3] = {}; size_t bufferSize = 0; size_t total = 0; omni::structuredlog::SchemaFlags flags = 0; if (strucLog == nullptr) { OMNI_LOG_WARN( "no structured log object! The schema " "'Schema_omni_carb_cloud_1_0' " "will be disabled."); return false; } // calculate the tree sizes size_t startup_size = _startup_calculateTreeSize(); size_t heartbeat_size = _heartbeat_calculateTreeSize(); size_t exit_size = _exit_calculateTreeSize(); // calculate the event buffer size bufferSize += startup_size; bufferSize += heartbeat_size; bufferSize += exit_size; // begin schema creation buffer = strucLog->allocSchema("omni.carb.cloud", "1.0", flags, bufferSize, &handle); if (buffer == nullptr) { OMNI_LOG_ERROR("allocSchema failed (size = %zu bytes)", bufferSize); return false; } // register all the events events[0].schema = _startup_buildJsonTree(startup_size, buffer + total); events[0].eventName = "com.nvidia.omni.carb.cloud.startup"; events[0].parserVersion = 0; events[0].eventId = kStartupEventId; total += startup_size; events[1].schema = _heartbeat_buildJsonTree(heartbeat_size, buffer + total); events[1].eventName = "com.nvidia.omni.carb.cloud.heartbeat"; events[1].parserVersion = 0; events[1].eventId = kHeartbeatEventId; total += heartbeat_size; events[2].schema = _exit_buildJsonTree(exit_size, buffer + total); events[2].eventName = "com.nvidia.omni.carb.cloud.exit"; events[2].parserVersion = 0; events[2].eventId = kExitEventId; total += exit_size; result = strucLog->commitSchema(handle, events, CARB_COUNTOF(events)); if (result != omni::structuredlog::SchemaResult::eSuccess && result != omni::structuredlog::SchemaResult::eAlreadyExists) { OMNI_LOG_ERROR( "failed to register structured log events " "{result = %s (%zu)}", getSchemaResultName(result), size_t(result)); return false; } return true; } /** body for the isEnabled() public function. */ static bool _isEnabled(omni::structuredlog::EventId eventId) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); return strucLog != nullptr && strucLog->isEnabled(eventId); } /** body for the setEnabled() public function. */ static void _setEnabled(omni::structuredlog::EventId eventId, bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(eventId, 0, enabled); } /** body for the setEnabled() public function. */ static void _setEnabled(bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(kStartupEventId, omni::structuredlog::fEnableFlagWholeSchema, enabled); } #if OMNI_PLATFORM_WINDOWS # pragma warning(push) # pragma warning(disable : 4127) // warning C4127: conditional expression is constant. #endif /** body for the startup_sendEvent() function. */ static void _startup_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_startup_ident& ident, const Struct_startup_application& application) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); // property ident { if (kValidateLength && ident.cluster.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'ident.cluster' exceeds max value 65535 - " "it will be truncated (size was %zu)", ident.cluster.length() + 1); } // property ident.cluster calc.track(ident.cluster); if (kValidateLength && ident.node.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'ident.node' exceeds max value 65535 - " "it will be truncated (size was %zu)", ident.node.length() + 1); } // property ident.node calc.track(ident.node); } // property application { if (kValidateLength && application.name.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.name' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.name.length() + 1); } // property application.name calc.track(application.name); if (kValidateLength && application.version.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.version' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.version.length() + 1); } // property application.version calc.track(application.version); } } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kStartupEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.startup'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); // property ident { // property ident.cluster writer.copy(ident.cluster); // property ident.node writer.copy(ident.node); } // property application { // property application.name writer.copy(application.name); // property application.version writer.copy(application.version); } } strucLog->commitEvent(handle); } /** body for the heartbeat_sendEvent() function. */ static void _heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kHeartbeatEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.heartbeat'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); } strucLog->commitEvent(handle); } /** body for the exit_sendEvent() function. */ static void _exit_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_exit_application& application, bool exit_abnormally) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); // property application { if (kValidateLength && application.name.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.name' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.name.length() + 1); } // property application.name calc.track(application.name); if (kValidateLength && application.version.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.version' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.version.length() + 1); } // property application.version calc.track(application.version); } // property exit_abnormally calc.track(exit_abnormally); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kExitEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.exit'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); // property application { // property application.name writer.copy(application.name); // property application.version writer.copy(application.version); } // property exit_abnormally writer.copy(exit_abnormally); } strucLog->commitEvent(handle); } #if OMNI_PLATFORM_WINDOWS # pragma warning(pop) #endif /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.startup. * @returns The JSON tree size in bytes for this event. */ static size_t _startup_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(5); // object has 5 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property ident calc.trackName("ident"); calc.trackObject(2); // object has 2 properties { // property cluster calc.trackName("cluster"); calc.track(static_cast<const char*>(nullptr)); // property node calc.trackName("node"); calc.track(static_cast<const char*>(nullptr)); } // property application calc.trackName("application"); calc.trackObject(2); // object has 2 properties { // property name calc.trackName("name"); calc.track(static_cast<const char*>(nullptr)); // property version calc.trackName("version"); calc.track(static_cast<const char*>(nullptr)); } // property version calc.trackName("version"); calc.track("1", sizeof("1")); // property event calc.trackName("event"); calc.track("cloud-startup", sizeof("cloud-startup")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.startup. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _startup_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.startup' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 5); // object has 5 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property ident result = builder.setName(&base->data.objVal[1], "ident"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[1], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property cluster result = builder.setName(&base->data.objVal[1].data.objVal[0], "cluster"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property node result = builder.setName(&base->data.objVal[1].data.objVal[1], "node"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property application result = builder.setName(&base->data.objVal[2], "application"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[2], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property name result = builder.setName(&base->data.objVal[2].data.objVal[0], "name"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property version result = builder.setName(&base->data.objVal[2].data.objVal[1], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property version result = builder.setName(&base->data.objVal[3], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[3], "1", sizeof("1")); if (!result) { OMNI_LOG_ERROR("failed to copy string '1' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[3], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } // property event result = builder.setName(&base->data.objVal[4], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[4], "cloud-startup", sizeof("cloud-startup")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-startup' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[4], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.heartbeat. * @returns The JSON tree size in bytes for this event. */ static size_t _heartbeat_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(2); // object has 2 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property event calc.trackName("event"); calc.track("cloud-heartbeat", sizeof("cloud-heartbeat")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.heartbeat. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _heartbeat_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.heartbeat' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property event result = builder.setName(&base->data.objVal[1], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1], "cloud-heartbeat", sizeof("cloud-heartbeat")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-heartbeat' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[1], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.exit. * @returns The JSON tree size in bytes for this event. */ static size_t _exit_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(4); // object has 4 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property application calc.trackName("application"); calc.trackObject(2); // object has 2 properties { // property name calc.trackName("name"); calc.track(static_cast<const char*>(nullptr)); // property version calc.trackName("version"); calc.track(static_cast<const char*>(nullptr)); } // property exit_abnormally calc.trackName("exit_abnormally"); calc.track(bool(false)); // property event calc.trackName("event"); calc.track("cloud-exit", sizeof("cloud-exit")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.exit. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _exit_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.exit' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 4); // object has 4 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property application result = builder.setName(&base->data.objVal[1], "application"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[1], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property name result = builder.setName(&base->data.objVal[1].data.objVal[0], "name"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property version result = builder.setName(&base->data.objVal[1].data.objVal[1], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property exit_abnormally result = builder.setName(&base->data.objVal[2], "exit_abnormally"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2], bool(false)); if (!result) { OMNI_LOG_ERROR("failed to set type 'bool' (shouldn't be possible)"); return nullptr; } // property event result = builder.setName(&base->data.objVal[3], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[3], "cloud-exit", sizeof("cloud-exit")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-exit' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[3], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** The callback that is used to report validation errors. * @param[in] s The validation error message. */ static void _onStructuredLogValidationError(const char* s) { OMNI_LOG_ERROR("error sending a structured log event: %s", s); } }; // asserts to ensure that no one's modified our dependencies static_assert(omni::structuredlog::BlobWriter<>::kVersion == 0, "BlobWriter version changed"); static_assert(omni::structuredlog::JsonNode::kVersion == 0, "JsonNode version changed"); static_assert(sizeof(omni::structuredlog::JsonNode) == 24, "unexpected size"); static_assert(std::is_standard_layout<omni::structuredlog::JsonNode>::value, "this type needs to be ABI safe"); static_assert(offsetof(omni::structuredlog::JsonNode, type) == 0, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, flags) == 1, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, len) == 2, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, nameLen) == 4, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, name) == 8, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, data) == 16, "struct layout changed"); } // namespace telemetry } // namespace omni OMNI_STRUCTURED_LOG_ADD_SCHEMA(omni::telemetry::Schema_omni_carb_cloud_1_0, omni_carb_cloud, 1_0, 0);
omniverse-code/kit/include/omni/structuredlog/JsonSerializer.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 Module for manually serializing JSON data with low performance overhead. */ #pragma once #include "../../carb/extras/StringSafe.h" #include "../../carb/extras/Utf8Parser.h" #include "../../carb/extras/Base64.h" #include <stdint.h> #include <float.h> namespace omni { namespace structuredlog { /** An interface for consuming the output JSON from the @ref JsonSerializer. */ class JsonConsumer { public: virtual ~JsonConsumer() { } /** The function that will consume strings of JSON. * @param[in] json The string of JSON. * This string's lifetime ends after the return from this call. * @param[in] jsonLen The length of @p json, excluding the null terminator. * The null terminator will be included in the length * when the final call to this writes out a null terminator. * It is possible this may be 0 in some edge cases. * It's possible that @p jsonLen may be used to refer to * a substring of @p json. * @remarks This will be called when the @ref JsonSerializer wants to write * something to the output. * The @ref JsonSerializer will write very small units of text to * this function, so the implementation should plan accordingly. */ virtual void consume(const char* json, size_t jsonLen) noexcept = 0; /** Terminate the output, if needed. * @remarks This will be called to ensure the output is null terminated. */ virtual void terminate() noexcept = 0; }; /** An implementation of @ref JsonConsumer that just counts the length of the * output string. * You may serialize some JSON through this to find the required buffer length, * then allocate the buffer and serialize the JSON again with @ref JsonPrinter * using that allocated buffer. */ class JsonLengthCounter : public JsonConsumer { public: void consume(const char* json, size_t jsonLen) noexcept override { CARB_UNUSED(json); m_count += jsonLen; } void terminate() noexcept override { m_count++; } /** Get the number of bytes that have been consumed so far. * @returns the number of bytes that have been consumed so far. */ size_t getcount() noexcept { return m_count; } private: size_t m_count = 0; }; /** An implementation of @ref JsonConsumer that just prints to a fixed string. */ class JsonPrinter : public JsonConsumer { public: JsonPrinter() { reset(nullptr, 0); } /** Create a printer from a fixed string buffer. * @param[out] output The instance will write to this buffer. * @param[in] outputLen The number of bytes that can be written to @p output. */ JsonPrinter(char* output, size_t outputLen) noexcept { reset(output, outputLen); } /** Reinitialize the printer with a new buffer. * @param[out] output The instance will write to this buffer. * @param[in] outputLen The number of bytes that can be written to @p output. */ void reset(char* output, size_t outputLen) noexcept { m_output = (outputLen == 0) ? nullptr : output; m_left = outputLen; m_overflowed = false; } /** Write a string into the buffer. * @param[in] json The data to write into the buffer. * @param[in] jsonLen The length of @p json, excluding any null terminator. */ void consume(const char* json, size_t jsonLen) noexcept override { size_t w = CARB_MIN(m_left, jsonLen); memcpy(m_output, json, w); m_left -= w; m_output += w; m_overflowed = m_overflowed || w < jsonLen; } void terminate() noexcept override { if (m_output != nullptr) { if (m_left == 0) { m_output[-1] = '\0'; } else { m_output[0] = '\0'; m_output++; m_left--; } } } /** Check whether more data was printed than would fit in the printer's buffer. * @returns `true` if the buffer was too small to fit all the consumed data. * @returns `false` if the buffer was able to fit all the consumed data. */ bool hasOverflowed() noexcept { return m_overflowed; } /** Get the pointer to the next char to be written in the buffer. * @returns The pointer to the next character to be written. * If the buffer has overflowed, this will point past the end of * the buffer. */ char* getNextChar() const noexcept { return m_output; } private: char* m_output; size_t m_left; bool m_overflowed = false; }; /** Anonymous namespace for a helper function */ namespace { void ignoreJsonSerializerValidationError(const char* s) noexcept { CARB_UNUSED(s); } } // namespace /** The prototype of the function to call when a validation error occurs. */ using OnValidationErrorFunc = void (*)(const char*); /** A utility that allows you to easily encode JSON data. * This class won't allocate any memory unless you use an excessive number of scopes. * * @param validate If this is set to true, methods will return false when an * invalid operation is performed. * onValidationError is used for logging because this struct * is used in the logging system, so OMNI_LOG_* cannot be * directly called from within this class. * If this is set to false, methods will assume that all calls * will produce valid JSON data. Invalid calls will write out * invalid JSON data. Methods will only return false if an * unavoidable check failed. * * @tparam prettyPrint If this is set to true, the output will be pretty-printed. * If this is set to false, the output will have no added white space. * * @tparam onValidationError This is a callback that gets executed when a validation * error is triggered, so logging can be called. */ template <bool validate = false, bool prettyPrint = false, OnValidationErrorFunc onValidationError = ignoreJsonSerializerValidationError> class JsonSerializer { public: /** The function that will be called when a validation error occurs. */ OnValidationErrorFunc m_onValidationError = onValidationError; /** Constructor. * @param[in] consumer The object that will consume the output JSON data. * This may not be nullptr. * @param[in] indentLen The number of spaces to indent by when pretty printing is enabled. */ JsonSerializer(JsonConsumer* consumer, size_t indentLen = 4) noexcept { CARB_ASSERT(consumer != nullptr); m_consumer = consumer; m_indentLen = indentLen; } ~JsonSerializer() { // it starts to use heap memory at this point if (m_scopes != m_scopesBuffer) free(m_scopes); } /** Reset the internal state back to where it was after construction. */ void reset() { m_scopesTop = 0; m_firstInScope = true; m_hasKey = false; m_firstPrint = true; m_indentTotal = 0; } /** Write out a JSON key for an object property. * @param[in] key The string value for the key. * This can be nullptr. * @param[in] keyLen The length of @p key, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeKey(const char* key, size_t keyLen) noexcept { if (validate) { if (CARB_UNLIKELY(getCurrentScope() != ScopeType::eObject)) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "attempted to write a key outside an object" " {key name = '%s', len = %zu}", key, keyLen); onValidationError(tmp); return false; } if (CARB_UNLIKELY(m_hasKey)) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "attempted to write out two key names in a row" " {key name = '%s', len = %zu}", key, keyLen); onValidationError(tmp); return false; } } if (!m_firstInScope) m_consumer->consume(",", 1); prettyPrintHook(); m_consumer->consume("\"", 1); if (key != nullptr) m_consumer->consume(key, keyLen); m_consumer->consume("\":", 2); m_firstInScope = false; if (validate) m_hasKey = true; return true; } /** Write out a JSON key for an object property. * @param[in] key The key name for this property. * This may be nullptr. * @returns whether or not validation succeeded. */ bool writeKey(const char* key) noexcept { return writeKey(key, key == nullptr ? 0 : strlen(key)); } /** Write out a JSON null value. * @returns whether or not validation succeeded. */ bool writeValue() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("null", sizeof("null") - 1); if (validate) m_hasKey = false; return true; } /** Write out a JSON boolean value. * @param[in] value The boolean value. * @returns whether or not validation succeeded. */ bool writeValue(bool value) noexcept { const char* val = value ? "true" : "false"; size_t len = (value ? sizeof("true") : sizeof("false")) - 1; if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume(val, len); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeValue(int32_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRId32, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeValue(uint32_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRIu32, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. * @note 64 bit integers are stored as double precision floats in JavaScript's * JSON library, so a JSON library with BigInt support should be * used instead when reading 64 bit numbers. */ bool writeValue(int64_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRId64, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. * @note 64 bit integers are stored as double precision floats in JavaScript's * JSON library, so a JSON library with BigInt support should be * used instead when reading 64 bit numbers. */ bool writeValue(uint64_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRIu64, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON double (aka number) value. * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeValue(double value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString( buffer, CARB_COUNTOF(buffer), "%.*g", std::numeric_limits<double>::max_digits10, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON float (aka number) value. * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeValue(float value) noexcept { return writeValue(double(value)); } /** Write out a JSON string value. * @param[in] value The string value. * This can be nullptr if @p len is 0. * @param[in] len The length of @p value, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeValue(const char* value, size_t len) noexcept { size_t last = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("\"", 1); for (size_t i = 0; i < len;) { const carb::extras::Utf8Parser::CodeByte* next = carb::extras::Utf8Parser::nextCodePoint(value + i, len - i); if (next == nullptr) { m_consumer->consume(value + last, i - last); m_consumer->consume("\\u0000", 6); i++; last = i; continue; } // early out for non-escape characters // multi-byte characters never need to be escaped if (size_t(next - value) > i + 1 || (value[i] > 0x1F && value[i] != '"' && value[i] != '\\')) { i = next - value; continue; } m_consumer->consume(value + last, i - last); switch (value[i]) { case '"': m_consumer->consume("\\\"", 2); break; case '\\': m_consumer->consume("\\\\", 2); break; case '\b': m_consumer->consume("\\b", 2); break; case '\f': m_consumer->consume("\\f", 2); break; case '\n': m_consumer->consume("\\n", 2); break; case '\r': m_consumer->consume("\\r", 2); break; case '\t': m_consumer->consume("\\t", 2); break; default: { char tmp[] = "\\u0000"; tmp[4] = getHexChar(uint8_t(value[i]) >> 4); tmp[5] = getHexChar(value[i] & 0x0F); m_consumer->consume(tmp, CARB_COUNTOF(tmp) - 1); } break; } i++; last = i; } if (len > last) m_consumer->consume(value + last, len - last); m_consumer->consume("\"", 1); if (validate) m_hasKey = false; return true; } /** Write out a JSON string value. * @param[in] value The string value. * This can be nullptr. * @returns whether or not validation succeeded. */ bool writeValue(const char* value) noexcept { return writeValue(value, value == nullptr ? 0 : strlen(value)); } /** Write a binary blob into the output JSON as a base64 encoded string. * @param[in] value_ The binary blob to write in. * @param[in] size The number of bytes of data in @p value_. * @returns whether or not validation succeeded. * @remarks This will take the input string and encode it in base64, then * store that as base64 data in a string. */ bool writeValueWithBase64Encoding(const void* value_, size_t size) { char buffer[4096]; const size_t readSize = carb::extras::Base64::getEncodeInputSize(sizeof(buffer)); const uint8_t* value = static_cast<const uint8_t*>(value_); if (CARB_UNLIKELY(!writeValuePrologue())) return false; m_consumer->consume("\"", 1); for (size_t i = 0; i < size; i += readSize) { size_t written = m_base64Encoder.encode(value + i, CARB_MIN(readSize, size - i), buffer, sizeof(buffer)); m_consumer->consume(buffer, written); } m_consumer->consume("\"", 1); if (validate) m_hasKey = false; return true; } /** Begin a JSON array. * @returns whether or not validation succeeded. * @returns false if a memory allocation failed. */ bool openArray() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("[", 1); m_firstInScope = true; if (!pushScope(ScopeType::eArray)) return false; prettyPrintOpenScope(); if (validate) m_hasKey = false; return true; } /** Finish writing a JSON array. * @returns whether or not validation succeeded. */ bool closeArray() noexcept { if (validate && CARB_UNLIKELY(getCurrentScope() != ScopeType::eArray)) { onValidationError("attempted to close an array that was never opened"); return false; } popScope(); prettyPrintCloseScope(); prettyPrintHook(); m_consumer->consume("]", 1); m_firstInScope = false; if (validate) m_hasKey = false; return true; } /** Begin a JSON object. * @returns whether or not validation succeeded. * @returns false if a memory allocation failed. */ bool openObject() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("{", 1); m_firstInScope = true; pushScope(ScopeType::eObject); prettyPrintOpenScope(); if (validate) m_hasKey = false; return true; } /** Finish writing a JSON object. * @returns whether or not validation succeeded. */ bool closeObject() noexcept { if (validate && CARB_UNLIKELY(getCurrentScope() != ScopeType::eObject)) { onValidationError("attempted to close an object that was never opened"); return false; } popScope(); prettyPrintCloseScope(); prettyPrintHook(); m_consumer->consume("}", 1); m_firstInScope = false; if (validate) m_hasKey = false; return true; } /** Finish writing your JSON. * @returns whether or not validation succeeded. */ bool finish() noexcept { bool result = true; // check whether we are ending in the middle of an object/array if (validate && getCurrentScope() != ScopeType::eGlobal) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "finished writing in the middle of an %s", getCurrentScope() == ScopeType::eArray ? "array" : "object"); onValidationError(tmp); result = false; } if (prettyPrint) m_consumer->consume("\n", 1); m_consumer->terminate(); return result; } private: /** The type of a scope in the scope stack. */ enum class ScopeType : uint8_t { eGlobal, /**< global scope (not in anything). */ eArray, /**< JSON array type. (e.g. []) */ eObject, /**< JSON object type. (e.g. {}) */ }; /** A hook used before JSON elements to perform pretty print formatting. */ void prettyPrintHook() noexcept { if (prettyPrint) { const size_t s = CARB_COUNTOF(m_indent) - 1; if (!m_firstPrint) m_consumer->consume("\n", 1); m_firstPrint = false; for (size_t i = s; i <= m_indentTotal; i += s) m_consumer->consume(m_indent, s); m_consumer->consume(m_indent, m_indentTotal % s); } } /** A hook used before printing a value element to perform pretty print formatting. */ void prettyPrintValueHook() noexcept { if (prettyPrint) { if (getCurrentScope() != ScopeType::eObject) return prettyPrintHook(); else /* if it's in an object, a key preceded this so this should be on the same line */ m_consumer->consume(" ", 1); } } /** Track when a scope was opened for pretty print indenting. */ void prettyPrintOpenScope() noexcept { if (prettyPrint) m_indentTotal += m_indentLen; } /** Track when a scope was closed for pretty print indenting. */ void prettyPrintCloseScope() noexcept { if (prettyPrint) m_indentTotal -= m_indentLen; } /** A common prologue to writeValue() functions. * @returns Whether validation succeeded. */ inline bool writeValuePrologue() noexcept { if (validate) { // the global scope is only allowed to have one item in it if (CARB_UNLIKELY(getCurrentScope() == ScopeType::eGlobal && !m_firstInScope)) { onValidationError("attempted to put multiple values into the global scope"); return false; } // if we're in an object, a key needs to have been written before each value if (CARB_UNLIKELY(getCurrentScope() == ScopeType::eObject && !m_hasKey)) { onValidationError("attempted to write a value without a key inside an object"); return false; } } if (getCurrentScope() == ScopeType::eArray && !m_firstInScope) m_consumer->consume(",", 1); m_firstInScope = false; return true; } bool pushScope(ScopeType s) noexcept { if (m_scopesTop == m_scopesLen) { size_t newLen = m_scopesTop + 64; size_t size = sizeof(*m_scopes) * newLen; void* tmp; if (m_scopes == m_scopesBuffer) tmp = malloc(size); else tmp = realloc(m_scopes, size); if (tmp == nullptr) { char log[256]; carb::extras::formatString(log, sizeof(log), "failed to allocate %zu bytes", size); onValidationError(log); return false; } if (m_scopes == m_scopesBuffer) memcpy(tmp, m_scopes, sizeof(*m_scopes) * m_scopesLen); m_scopes = static_cast<ScopeType*>(tmp); m_scopesLen = newLen; } m_scopes[m_scopesTop++] = s; return true; } void popScope() noexcept { m_scopesTop--; } ScopeType getCurrentScope() noexcept { if (m_scopesTop == 0) return ScopeType::eGlobal; return m_scopes[m_scopesTop - 1]; } char getHexChar(uint8_t c) noexcept { char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; CARB_ASSERT(c < CARB_COUNTOF(lookup)); return lookup[c]; } ScopeType m_scopesBuffer[8]; ScopeType* m_scopes = m_scopesBuffer; size_t m_scopesLen = CARB_COUNTOF(m_scopesBuffer); size_t m_scopesTop = 0; /** The consumer of the output JSON data. */ JsonConsumer* m_consumer; /** This flag is the current key/value being written is the first one inside * the current scope (this decides comma placement). */ bool m_firstInScope = true; /** This is set when a key has been specified. * This is done for validation. */ bool m_hasKey = false; /** This is true when the first character has not been printed yet. * This is used for pretty printing. */ bool m_firstPrint = true; /** The indent buffer used for pretty printing. */ char m_indent[33] = " "; /** The length into m_indent to print for the pretty-printing indent. */ size_t m_indentTotal = 0; /** The length of an individual indent when pretty-printing. */ size_t m_indentLen = 4; /** The base64 encoder. This is just cached here to improve performance. */ carb::extras::Base64 m_base64Encoder; }; } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/StructuredLogSettingsUtils.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 Utilities for the carb::settings::ISettings settings for structured logging. */ #pragma once #include "IStructuredLog.h" #include "IStructuredLogExtraFields.h" #include "IStructuredLogSettings.h" #include "IStructuredLogSettings2.h" #include "IStructuredLogFromILog.h" #include "../../carb/extras/StringSafe.h" #include "../../carb/settings/ISettings.h" #include "../extras/PrivacySettings.h" #include "../extras/OmniConfig.h" #include "../log/ILog.h" namespace omni { namespace structuredlog { /** Constants for default and minimum values for various settings. * @{ */ /** The default value for the log size limit in bytes. * See IStructuredLogSettings::setLogSizeLimit() for details. */ constexpr int64_t kDefaultLogSizeLimit = 50ll * 1024ll * 1024ll; /** The minimum value that can be set for the log size limit in bytes. * See IStructuredLogSettings::setLogSizeLimit() for details. */ constexpr int64_t kMinLogSizeLimit = 256ll * 1024ll; /** The default log retention setting. * See IStructuredLogSettings::setLogRetentionCount() for details. */ constexpr size_t kDefaultLogRetentionCount = 3; /** The minimum allowed log retention setting. * See IStructuredLogSettings::setLogRetentionCount() for details. */ constexpr size_t kMinLogRetentionCount = 1; /** The default value for the event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kDefaultEventQueueSize = 2 * 1024 * 1024; /** The minimum allowed event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kMinEventQueueSize = 512 * 1024; /** The maximum allowed event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kMaxEventQueueSize = 1024 * 1024 * 1024; /** The default mode for generating event IDs. * See IStructuredLogSettings::setEventIdMode() for details. */ constexpr IdMode kDefaultIdMode = IdMode::eFastSequential; /** The default type of event ID to generate. * See IStructuredLogSettings::setEventIdMode() for details. */ constexpr IdType kDefaultIdType = IdType::eUuid; /** Special value to indicate that the heartbeat event should be disabled. Any other value * will indicate that the heartbeat events will be generated. */ constexpr uint64_t kHeartbeatDisabled = 0; /** The default minimum time between heartbeat events in seconds. This can be * @ref kHeartbeatDisabled to indicate that the heartbeat events are disabled. For more * details, please see IStructuredLogSettings2::setHeartbeatPeriod(). */ constexpr uint64_t kDefaultHeartbeatPeriod = kHeartbeatDisabled; /** The default state for whether headers will be added to each written log file. For * more details, please see IStructuredLogSettings2::setNeedsLogHeaders(). */ constexpr bool kDefaultNeedLogHeaders = true; /** The default state for whether the CloudEvents wrapper will be output with each message. * By default, all messages will be emitted as CloudEvents 1.0 compliant messages. The * omni::structuredlog::IStructuredLogSettings2::setOutputFlags() function or the * @ref kEmitPayloadOnlySettings setting can be used to change this setting. */ constexpr bool kDefaultEmitPayloadOnlySettings = false; /** The default state for whether the cloud heartbeat events will be emitted. For these * events to be emitted, the normal heartbeat event must also be enabled with * @ref kHeartbeatPeriodSetting. These cloud heartbeat events are effectively duplicate * data and are not strictly necessary. */ constexpr bool kDefaultEmitCloudHeartbeat = false; /** @} */ /** Names for various settings that can be used to override some of the default settings. Note * that these will not override any values that are explicitly set by the host app itself. * @{ */ /** Global enable/disable for structured logging. When set to `false`, the structured log system * will be disabled. This will prevent any event messages from being written out unless the * host app explicitly wants them to. When set to `true`, the structured log system will be * enabled and event messages will be emitted normally. This defaults to `false`. */ constexpr const char* kGlobalEnableSetting = "/structuredLog/enable"; /** Specifies the directory that log files should be written to. This is also the directory that * the telemetry transmitter app will check for when enumerating and consuming logs. This must * always be a local path and may be either absolute or relative. The default location is * `$HOME/.nvidia-omniverse/logs/` (where ``$HOME`` is ``%USERPROFILE%`` on Windows and the usual * meaning on POSIX platforms). This setting is mainly intended for testing and the default * directory should be used whenever possible. If this setting is used in a Kit launch (either * on command line or in a config file), it will be passed on to the telemetry transmitter app * when it gets launched. */ constexpr const char* kLogDirectory = "/structuredLog/logDirectory"; /** The default log name to use. If a default log name is set, all events that do not use the * @ref fEventFlagUseLocalLog flag will write their messages to this log file. Events that * do use the @ref fEventFlagUseLocalLog flag will write only to their schema's log file. This * value must be only the log file's name, not including its path. The logs will always be * created in the structured logging system's current log output path. As a special case, this * may also be set to either "/dev/stdout" or "/dev/stderr" (on all platforms) to output all * events directly to stdout or stderr respectively. When one of these log names are used, all * events will be unconditionally written to stdout/stderr regardless of their event or schema * flags. There will also be no log header written out when events are being sent to stdout or * stderr. This defaults to an empty string. */ constexpr const char* kDefaultLogNameSetting = "/structuredLog/defaultLogName"; /** The setting path for the privacy settings file to load. This allows the default location of * the privacy settings file to be overridden. The default location for the privacy settings * file is `$HOME/.nvidia-omniverse/config/privacy.toml` on all platforms, where `$HOME` on * Windows is `%USERPROFILE%). Note that even if this setting is used and it points to a valid * file, the settings from the default `privacy.toml` file will still be loaded first if it * is present. The settings in the file specified here will simply override any settings given * in the default file. This allows any missing settings in the new file to still be provided * by what was present in the default file's location. */ constexpr const char* kPrivacyFileSetting = "/structuredLog/privacySettingsFile"; /** The setting path for the log retention count. This controls how many log files will be * left in the log directory when a log rotation occurs. When a log file reaches its size * limit, it is renamed and a new empty log with the original name is created. A rolling * history of the few most recent logs is maintained after a rotation. This setting controls * exactly how many of each log will be retained after a rotation. This defaults to 3. */ constexpr const char* kLogRetentionCountSetting = "/structuredLog/logRetentionCount"; /** The setting path for the log size limit in megabytes. When a log file reaches this size, * it is rotated out by renaming it and creating a new log file with the original name. If * too many logs exist after this rotation, the oldest one is deleted. This defaults to 50MB. */ constexpr const char* kLogSizeLimitSetting = "/structuredLog/logSizeLimit"; /** The setting path for the size of the event queue buffer in kilobytes. The size of the * event queue controls how many messages can be queued in the message processing queue before * events start to get dropped (or a stall potentially occurs). The event queue can fill up * if the app is emitting messages from multiple threads at a rate that is higher than they * can be processed or written to disk. In general, there should not be a situation where * the app is emitting messages at a rate that causes the queue to fill up. However, this * may be beyond the app's control if (for example) the drive the log is being written to * is particularly slow or extremely busy. This defaults to 2048KB. */ constexpr const char* kEventQueueSizeSetting = "/structuredLog/eventQueueSize"; /** The setting path for the event identifier mode. This controls how event identifiers are * generated. Valid values are 'fast-sequential', `sequential`, and `random`. Each has its * own benefits and drawbacks: * * `sequential` ensures that all generated event IDs are in sequential order. When the * event ID type is set to `UUID`, this will ensure that each generated event ID can be * easily sorted after the previous one. With a UUID type ID, this mode can be expensive * to generate. With a `uint64` ID, this is the most performant to generate. * * `fast-sequential` is only effective when the event ID type is set to 'UUID'. In this * mode, the UUIDs that are generated are sequential, but in memory order, not lexicographical * order. It takes some extra effort to sort these events on the data analysis side, but * they are generated very quickly. When the event ID type is not 'UUID', this mode behaves * in the same way as `sequential`. * * `random` generates a random event ID for each new event. This does not preserve any * kind of order of events. If the app does not require sequential events, this can be * more performant to generate especially for UUIDs. * * This defaults to 'fast-sequential. This setting is not case sensitive. */ constexpr const char* kEventIdModeSetting = "/structuredLog/eventIdMode"; /** The setting path for the event identifier data type. This determines what kind of event * ID will be generated for each new event and how it will be printed out with each message. * The following types are supported: * * `UUID` generates a 128 bit universally unique identifier. The event ID mode determines * how one event ID will be related to the next. This is printed into each event message * in the standard UUID format ("00000000-0000-0000-0000-000000000000"). This type provides * the most uniqueness and room for scaling in large data sets. * * `uint64` generates a 64 bit integer identifier. The event ID mode determines how one * event ID will be related to the next. This is printed into each event message as a * simple decimal integer value. * * This defaults to 'UUID'. This setting is not case sensitive. */ constexpr const char* kEventIdTypeSetting = "/structuredLog/eventIdType"; /** The setting path for the log consumer toggle. This enables or disables the redirection * of normal Carbonite (ie: `CARB_LOG_*()`) and Omni (ie: `OMNI_LOG_*()`) messages as structured * log events as well. The log messages will still go to their original destination (stdout, * stderr, log file, MSVC output window, etc) as well. This defaults to `false`. */ constexpr const char* kEnableLogConsumerSetting = "/structuredLog/enableLogConsumer"; /** The setting path that will contain zero or more keys that will be used to disable schemas * when they are first registered. Each key under this setting will have a name that matches * zero or schema names. From a .schema file, this would match the "name" property. From a * JSON schema file, this would match the @a `#/schemaMeta/clientName` property. The key's * value is expected to be a boolean that indicates whether it is enabled upon registration. * * The names of the keys under this path may either be a schema's full name or a wildcard * string that matches to zero or more schema names. In either version, the case of the * non-wildcard portions of the key name is important. The wildcard characters '*' (match * to zero or more characters) and '?' (match to exactly one character) may be used. This * is only meant to be a simple wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml [structuredLog.state.schemas] "omni.test_schema" = false # disable 'omni.test_schema' on registration. "omni.other_schema" = true # enable 'omni.other_schema' on registration. "carb.*" = false # disable all schemas starting with 'carb.'. @endrst * * @note The keys in this setting path are inherently unordered. If a set of dependent * enable/disable settings is needed, the @ref kSchemasStateArraySetting setting path * should be used instead. This other setting allows an array to be specified that * preserves the order of keys. This is useful for doing things like disabling all * schemas then only enabling a select few. */ constexpr const char* kSchemasStateListSetting = "/structuredLog/state/schemas"; /** The setting path that will contain zero or more keys that will be used to disable events * when they are first registered. Each key under this setting will have a name that matches * zero or event names. From a .schema file, this would match the "namespace" property plus * one of the properties under @a `#/events/`. From a JSON schema file, this would match one * of the event properties under @a `#/definitions/events/`. The key's value is expected to * be a boolean that indicates whether it is enabled upon registration. * * The names of the keys under this path may either be an event's full name or a wildcard * string that matches to zero or more event names. In either version, the case of the * non-wildcard portions of the key name is important. The wildcard characters '*' (match * to zero or more characters) and '?' (match to exactly one character) may be used. This * is only meant to be a simple wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * events: * @rst .. code-block:: toml [structuredLog.state.events] "com.nvidia.omniverse.fancy_event" = false "com.nvidia.carbonite.*" = false # disable all 'com.nvidia.carbonite' events. @endrst * * @note The keys in this setting path are inherently unordered. If a set of dependent * enable/disable settings is needed, the @ref kEventsStateArraySetting setting path * should be used instead. This other setting allows an array to be specified that * preserves the order of keys. This is useful for doing things like disabling all * events then only enabling a select few. */ constexpr const char* kEventsStateListSetting = "/structuredLog/state/events"; /** The setting path to an array that will contain zero or more values that will be used to * disable or enable schemas when they are first registered. Each value in this array will * have a name that matches zero or more schema names. From a .schema file, this would match the * "name" property. From a JSON schema file, this would match the @a `#/schemaMeta/clientName` * property. The schema name may be optionally prefixed by either '+' or '-' to enable or * disable (respectively) matching schemas. Alternatively, the schema's name may be assigned * a boolean value to indicate whether it is enabled or not. If neither a '+'/'-' prefix nor * a boolean assignment suffix is specified, 'enabled' is assumed. * * The names in this array either be a schema's full name or a wildcard string that matches * to zero or more schema names. In either version, the case of the non-wildcard portions * of the key name is important. The wildcard characters '*' (match to zero or more characters) * and '?' (match to exactly one character) may be used. This is only meant to be a simple * wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml structuredLog.schemaStates = [ "-omni.test_schema", # disable 'omni.test_schema' on registration. "omni.other_schema = true", # enable 'omni.other_schema' on registration. "-carb.*" # disable all schemas starting with 'carb.'. ] @endrst * * @note TOML does not allow static arrays such as above to be appended to with later lines. * Attempting to do so will result in a parsing error. */ constexpr const char* kSchemasStateArraySetting = "/structuredLog/schemaStates"; /** The setting path to an array that will contain zero or more values that will be used to * disable or enable events when they are first registered. Each value in this array will * have a name that matches zero or more event names. From a .schema file, this would match one * of the property names under `#/events/`. From a JSON schema file, this would match one * of the event object names in @a `#/definitions/events/`. The event name may be optionally * prefixed by either '+' or '-' to enable or disable (respectively) matching event(s). * Alternatively, the event's name may be assigned a boolean value to indicate whether it is * enabled or not. If neither a '+'/'-' prefix nor a boolean assignment suffix is specified, * 'enabled' is assumed. * * The names in this array either be an event's full name or a wildcard string that matches * to zero or more event names. In either version, the case of the non-wildcard portions * of the array entry name is important. The wildcard characters '*' (match to zero or more characters) * and '?' (match to exactly one character) may be used. This is only meant to be a simple * wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml structuredLog.schemaStates = [ "-com.nvidia.omniverse.fancy_event", "com.nvidia.carbonite.* = false" # disable all 'com.nvidia.carbonite' events. ] @endrst * * @note that TOML does not allow static arrays such as above to be appended to with later lines. * Attempting to do so will result in a parsing error. */ constexpr const char* kEventsStateArraySetting = "/structuredLog/eventStates"; /** The setting path that will contain the minimum number of seconds between heartbeat events * A heartbeat event is one that is sent periodically to help calculate session lengths even * if the expected 'exit' or 'crash' process lifetime events are missing. These events can * be missing in such unavoidable cases as a power loss, the user killing the process, a blue * screen of death or kernel panic, etc. These situations cannot be assumed as either crashes * or normal exits, but at least these events can help indicate how long the actual session was. * This can be set to 0 to disable the heartbeat messages. By default the heartbeat events are * disabled (ie: set to @ref kHeartbeatDisabled). */ constexpr const char* kHeartbeatPeriodSetting = "/structuredLog/heartbeatPeriod"; /** The setting path that will indicate whether headers will be added to each log file that is * written to disk. Each log file will have one header on the first line that is a JSON object * that indicates the origin of the log and the version of the `omni.structuredlog.plugin` * plugin that created it. This header object is followed by whitespace to allow it to be * modified later as needed without having to rewrite the entire file. The telemetry transmitter * consumes this header object and modifies it to indicate its processing progress. Without * this header, the telemetry transmitter will ignore the log file. This setting defaults to * `true`. */ constexpr const char* kNeedLogHeadersSetting = "/structuredLog/needLogHeaders"; /** The setting path that will indicate whether the CloudEvents wrapper should be added to the * payload of each emitted event. By default, each event will be emitted as a CloudEvent * compliant JSON object. If this setting is enabled, the CloudEvent wrapper will be skipped * and only the schema's defined payload for the event will be emitted. The main payload will * be emitted as the top level object in the JSON output when this setting is enabled. * * Note that when this setting is used, the output will be incompatible with the telemetry * transmitter and the rest of the Omniverse telemetry toolchain. If a host app decides to * use this feature, they will be responsible for including all the relevant information that * would normally be part of the CloudEvents header. This includes fields such as the user * ID, event type, event schema, event ID, etc. This setting defaults to `false`. */ constexpr const char* kEmitPayloadOnlySettings = "/structuredLog/emitPayloadOnly"; /** The setting path that will indicate whether the cloud heartbeat events will be enabled. * These will only be emitted if the normal heartbeat events are also enabled * (with @ref kHeartbeatPeriodSetting). These events are effectively duplicate data and * are not strictly necessary. This defaults to `false`. */ constexpr const char* kEmitCloudHeartbeatSetting = "/structuredLog/emitCloudHeartbeat"; /** The settings branch that will be expected to contain zero or more key/value pairs for extra * fields to be added to each output message. This branch will only be parsed once on startup. * Any extra dynamic fields that need to be added at runtime need to be added or removed * programmatically using the `omni::structuredlog::IStructuredLogExtraFields` interface. * Only string values will be accepted under this branch. By default this settings branch * is expected to be empty and no extra fields will be added. * * Note that the number of extra fields added should be kept to a minimum required count and * size since they can affect both output and transmission performance. */ constexpr const char* kExtraFieldsSettingBranch = "/structuredLog/extraFields"; /** @} */ /** Enables or disables the structured logging log message redirection. * * @param[in] enabled Set to ``true`` to enable structured logging log message redirection. * Set to ``false`` to disable structured logging log message redirection. * @returns ``true`` if logging redirection was successfully enabled. Returns ``false`` * otherwise * * This enables or disables structured logging log message redirection. This system * will monitor log messages and emit them as structured log messages. */ inline bool setStructuredLogLoggingEnabled(bool enabled = true) { omni::core::ObjectPtr<IStructuredLog> strucLog; omni::core::ObjectPtr<IStructuredLogFromILog> log; strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) return false; log = strucLog.as<IStructuredLogFromILog>(); if (log.get() == nullptr) return false; if (enabled) log->enableLogging(); else log->disableLogging(); return true; } /** Checks the settings registry for structured log settings and makes them active. * * @param[in] settings The settings interface to use to retrieve configuration values. * This may not be `nullptr`. * @returns No return value. * * @remarks This sets appropriate default values for all the structured log related settings then * attempts to retrieve their current values and set them as active. This assumes * that the settings hive has already been loaded from disk and made active in the * main settings registry. * * @thread_safety This call is thread safe. */ inline void configureStructuredLogging(carb::settings::ISettings* settings) { omni::core::ObjectPtr<IStructuredLog> strucLog; omni::core::ObjectPtr<IStructuredLogSettings> ts; omni::core::ObjectPtr<IStructuredLogSettings2> ts2; omni::core::ObjectPtr<IStructuredLogFromILog> log; omni::core::ObjectPtr<IStructuredLogExtraFields> extraFields; const char* value; int64_t count; IdMode idMode = kDefaultIdMode; IdType idType = kDefaultIdType; if (settings == nullptr) return; // ****** set appropriate defaults for each setting ****** settings->setDefaultBool(kGlobalEnableSetting, false); settings->setDefaultString(kLogDirectory, ""); settings->setDefaultString(kDefaultLogNameSetting, ""); settings->setDefaultInt64(kLogRetentionCountSetting, kDefaultLogRetentionCount); settings->setDefaultInt64(kLogSizeLimitSetting, kDefaultLogSizeLimit / 1048576); settings->setDefaultInt64(kEventQueueSizeSetting, kDefaultEventQueueSize / 1024); settings->setDefaultString(kEventIdModeSetting, "fast-sequential"); settings->setDefaultString(kEventIdTypeSetting, "UUID"); settings->setDefaultBool(kEnableLogConsumerSetting, false); settings->setDefaultInt64(kHeartbeatPeriodSetting, kDefaultHeartbeatPeriod); settings->setDefaultBool(kNeedLogHeadersSetting, kDefaultNeedLogHeaders); settings->setDefaultBool(kEmitPayloadOnlySettings, kDefaultEmitPayloadOnlySettings); settings->setDefaultBool(kEmitCloudHeartbeatSetting, kDefaultEmitCloudHeartbeat); // ****** grab the structured log settings object so the config can be set ****** strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) return; ts = strucLog.as<IStructuredLogSettings>(); if (ts.get() == nullptr) return; // ****** retrieve the settings and make them active ****** strucLog->setEnabled(omni::structuredlog::kBadEventId, omni::structuredlog::fEnableFlagAll, settings->getAsBool(kGlobalEnableSetting)); // set the default log name. value = settings->getStringBuffer(kDefaultLogNameSetting); if (value != nullptr && value[0] != 0) ts->setLogDefaultName(value); value = settings->getStringBuffer(kLogDirectory); if (value != nullptr && value[0] != 0) { ts->setLogOutputPath(value); } else { // This setting needs to be reloaded after ISerializer has been loaded, since it can read // omniverse.toml now in case there are overrides there. extras::OmniConfig config; ts->setLogOutputPath(config.getBaseLogsPath().c_str()); } // set the log retention count. count = settings->getAsInt64(kLogRetentionCountSetting); ts->setLogRetentionCount(count); // set the log size limit. count = settings->getAsInt64(kLogSizeLimitSetting); ts->setLogSizeLimit(count * 1048576); // set the event queue size. count = settings->getAsInt64(kEventQueueSizeSetting); ts->setEventQueueSize(count * 1024); // set the event ID mode. value = settings->getStringBuffer(kEventIdModeSetting); if (carb::extras::compareStringsNoCase(value, "fast-sequential") == 0) idMode = IdMode::eFastSequential; else if (carb::extras::compareStringsNoCase(value, "sequential") == 0) idMode = IdMode::eSequential; else if (carb::extras::compareStringsNoCase(value, "random") == 0) idMode = IdMode::eRandom; else OMNI_LOG_WARN("unknown event ID mode '%s'. Assuming 'fast-sequential'.", value); // set the event ID type. value = settings->getStringBuffer(kEventIdTypeSetting); if (carb::extras::compareStringsNoCase(value, "UUID") == 0) idType = IdType::eUuid; else if (carb::extras::compareStringsNoCase(value, "uint64") == 0) idType = IdType::eUint64; else OMNI_LOG_WARN("unknown event ID type '%s'. Assuming 'UUID'.", value); ts->setEventIdMode(idMode, idType); // load the privacy settings and set the user ID from it. ts->loadPrivacySettings(); // load the enable states for each schema and event. ts->enableSchemasFromSettings(); value = omni::extras::PrivacySettings::getUserId(); if (value != nullptr && value[0] != 0) ts->setUserId(value); // setup the structured log logger. log = strucLog.as<IStructuredLogFromILog>(); if (log.get() == nullptr) return; if (settings->getAsBool(kEnableLogConsumerSetting)) log->enableLogging(); // setup the default heartbeat event period. ts2 = strucLog.as<IStructuredLogSettings2>(); if (ts2 != nullptr) { OutputFlags flags = fOutputFlagNone; count = settings->getAsInt64(kHeartbeatPeriodSetting); ts2->setHeartbeatPeriod(count); if (!settings->getAsBool(kNeedLogHeadersSetting)) flags |= fOutputFlagSkipLogHeaders; if (settings->getAsBool(kEmitPayloadOnlySettings)) flags |= fOutputFlagPayloadOnly; if (settings->getAsBool(kEmitCloudHeartbeatSetting)) flags |= fOutputFlagEmitCloudHeartbeat; ts2->setOutputFlags(flags, 0); } extraFields = strucLog.as<IStructuredLogExtraFields>(); if (extraFields != nullptr) { // walk through the extra fields branch of the settings registry and add an extra field // for each key/value pair in there. In general we don't expect there to be more than // a couple extra fields present. if (settings->isAccessibleAs(carb::dictionary::ItemType::eDictionary, kExtraFieldsSettingBranch)) { carb::dictionary::IDictionary* dictionary = carb::getCachedInterface<carb::dictionary::IDictionary>(); const carb::dictionary::Item* branch = settings->getSettingsDictionary(kExtraFieldsSettingBranch); size_t childCount = dictionary->getItemChildCount(branch); for (size_t i = 0; i < childCount; i++) { const carb::dictionary::Item* item = dictionary->getItemChildByIndex(branch, i); if (item == nullptr) continue; const char* key = dictionary->getItemName(item); value = dictionary->getStringBuffer(item); if (key != nullptr && value != nullptr) { extraFields->setValue(key, value, omni::structuredlog::fExtraFieldFlagNone); } } } } strucLog.release(); } } // namespace structuredlog } // namespace omni
omniverse-code/kit/include/omni/structuredlog/IStructuredLogExtraFields.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/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 /** Interface to manage extra CloudEvent fields to be included in each emitted message. This * allows for fields to be added and removed as needed. It also allows existing registered * fields to be enumerated at any given time. An extra field is a key/value pair that is * included at the top level of the JSON object for each message that follows. Only string * values are allowed for each key. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogExtraFields_abi> : public omni::structuredlog::IStructuredLogExtraFields_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogExtraFields") /** Adds, modifies, or removes an extra field key/value pair. * * @param[in] fieldName The name of the field to add, modify or remove. This may not be * `nullptr` or and empty string. The field name must only contain * alphabetic, numeric, or underscore ASCII characters. Any * characters outside these will cause the field to not be updated. * Further, this may not be one of the reserved CloudEvent field * names such as "specversion", "data", "time", "source", "session", * "dataschema", "type", or "subject". * @param[in] value The new value to set for the requested extra field. This may be * `nullptr` to indicate that the named field should be removed. * The value string may include any characters, but should be limited * to a small number of characters (ideally less than 64 characters). * @param[in] flags Flags to control how the new value is added, modified, or removed. * Currently no flags are defined. This must be set to * @ref omni::structuredlog::fExtraFieldFlagNone. * @returns `true` if the requested extra field is successfully added, modified, or removed. * Returns `false` if an invalid field name is given, or the operation could not * be completed for any reason. * * @remarks This adds, modifies, or removes a registered extra field and value. Any extra * fields that are registered at the time a message is emitted will be added to the * message on output. At least for the first version of this interface it is * expected that extra fields be largely static. * * @thread_safety This call is thread safe. */ bool setValue(const char* fieldName, const char* value, omni::structuredlog::ExtraFieldFlags flags) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<omni::structuredlog::IStructuredLogExtraFields_abi>::setValue( const char* fieldName, const char* value, omni::structuredlog::ExtraFieldFlags flags) noexcept { return setValue_abi(fieldName, value, flags); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/structuredlog/IStructuredLog.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 The core structured logging interface. */ #pragma once #include "StructuredLogCommon.h" #include "../core/BuiltIn.h" #include "../core/IObject.h" #include "../core/Api.h" #ifdef STRUCTUREDLOG_STANDALONE_MODE # include "../../carb/extras/Library.h" #endif #include <vector> namespace omni { /** Structured logging and Telemetry. */ namespace structuredlog { class IStructuredLog; // ******************************* enums, types, and constants ************************************ /** The expected base name for the structured log plugin. This isn't strictly necessary unless * the plugin needs to be explicitly loaded in standalone mode in an special manner. By default * the plugin is expected to be present in the same directory as the main executable. If it is * not in that location, it is the host app's responsibility to load the plugin dynamically * before attempting to call any structured log functions (even `addModuleSchemas()`). If the * module is not loaded before making any calls, all calls will just silently fail and the * structured log functionality will be in a disabled state. * * The structured log plugin can be loading using carb::extras::loadLibrary(). Using the * @ref carb::extras::fLibFlagMakeFullLibName flag will be useful unless the name is being * constructed manually using carb::extras::createLibraryNameForModule(). */ constexpr const char* OMNI_ATTR("no_py") kStructuredLogPluginName = "omni.structuredlog.plugin"; /** Base type for the version of the event payload parser to use. This is used as part of a * versioning scheme for the payload reader and event schema walker. */ using ParserVersion = uint16_t; /** Base type for the handle to an allocated block of memory returned from either the * @ref IStructuredLog::allocSchema() or @ref IStructuredLog::allocEvent() functions. * These handles uniquely identify the allocated block but should be treated as opaque handles. */ using AllocHandle = void*; /** A special string length value to indicate that a string parameter to a generated event * sending function is null terminated and should have its length calculated instead of * passing in an explicit length. */ constexpr size_t kNullTerminatedString = SIZE_MAX; /** The current event payload parser version that will be used in the IStructuredLog interface. * This symbol can be used by the generated code to set versioning information in each * event payload. This may be incremented in the future. */ constexpr ParserVersion kParserVersion = 0; /** Approximate size of the maximum data payload in bytes that a message can contain that can be * transmitted in a single message. This is a matter of the typical size of message that * can be sent to some data servers minus the average additional space needed for the message * body and other identifying information. Note that this is only an approximate guideline * and should not be taken as an exact limit. Also note that this does not account for the * change in size related to data encoding methods such as Base64. If a Base64 encoding is * to be used for the data payload, the @ref kMaxMessageLengthBase64 limit should be used * instead. */ constexpr size_t kMaxMessageLength = (10000000 - 256); /** Approximate size of the maximum data payload in bytes that a message can contain that can be * transmitted in a single message when the payload is encoded in Base64. This is a matter of * the typical message transmission limit for some data servers minus the average additional * space needed for the message body and other identifying information, then converted to * Base64's 6-to-8 bit encoding ratio (ie: every 6 bits of input data converts to 8 bits of * encoded data). Note that this is only an approximate guideline and should not be taken * as an exact limit. */ constexpr size_t kMaxMessageLengthBase64 = (kMaxMessageLength * 6) / 8; /** Base type for flags to control the behavior of the handling of a schema as a whole. A schema * encompasses the settings for a group of events that are all registered in a single call pair * to @ref IStructuredLog::allocSchema() and @ref IStructuredLog::commitSchema(). */ using SchemaFlags OMNI_ATTR("flag, prefix=fSchemaFlag") = uint32_t; /** Flag to indicate that the log file should remain open between messages. By default, each * event message will cause the log file to be opened, the message written, then the log file * closed. This flag can make writing a large number of frequent event messages more efficient * by avoiding the expense of opening and closing the log file repeatedly. However, using this * may also prevent the log file from being moved or deleted while an app is still running. To * work around that, all persistently open log files can be temporarily forced closed using * @ref IStructuredLogControl::closeLog(). */ constexpr SchemaFlags fSchemaFlagKeepLogOpen = 0x00000001; /** Flag to indicate that the log file for this schema should include the process ID in the * filename. Note that using this flag will likely lead to a lot of log files being generated * for an app since each session will create a [somewhat] unique file. This will however * reduce the possibility of potential performance issues related to many processes trying * to lock and access the same file(s) simultaneously. By default, the process ID is not * included in a schema's log filename. */ constexpr SchemaFlags fSchemaFlagLogWithProcessId = 0x00000002; /** Base type for flags to control the behavior of processing a single event. These flags * affect how events are processed and how they affect their log. */ using EventFlags OMNI_ATTR("flag, prefix=fEventFlag") = uint32_t; /** Use the log file specified by the owning event's schema instead of the default log for the * process. This can be controlled at the per-event level and would be specified by either * manually changing the flags in the generated event table or by passing a specific command * line option to the code generator tool that would set this flag on all of the schema's * events in the generated code. This can be useful if an external plugin would like to * have its events go to its own log file instead of the process's default log file. */ constexpr EventFlags fEventFlagUseLocalLog = 0x00000001; /** Flag to indicate that this event is critical to succeed and should potentially block the * calling thread on IStructuredLog::allocEvent() calls if the event queue is full. The call * will block until a buffer of the requested size can be successfully allocated instead of * failing immediately. This flag should be used sparingly since it could result in blocking * the calling thread. */ constexpr EventFlags fEventFlagCriticalEvent = 0x00000002; /** Flag to indicate that this event should be output to the stderr file. If the * @ref fEventFlagSkipLog flag is not also used, this output will be in addition to the * normal output to the schema's log file. If the @ref fEventFlagSkipLog flag is used, * the normal log file will not be written to. The default behavior is to only write the * event to the schema's log file. This can be combined with the @c fSchemaFlagOutputToStderr * and @c fSchemaFlagSkipLog flags. */ constexpr EventFlags fEventFlagOutputToStderr = 0x00000010; /** Flag to indicate that this event should be output to the stdout file. If the * @ref fEventFlagSkipLog flag is not also used, this output will be in addition to the * normal output to the schema's log file. If the @ref fEventFlagSkipLog flag is used, * the normal log file will not be written to. The default behavior is to only write the * event to the schema's log file. This can be combined with the @c fSchemaFlagOutputToStdout * and @c fSchemaFlagSkipLog flags. */ constexpr EventFlags fEventFlagOutputToStdout = 0x00000020; /** Flag to indicate that this event should not be output to the schema's specified log file. * This flag is intended to be used in combination with the @ref fEventFlagOutputToStdout * and @ref fEventFlagOutputToStderr flags to control which destination(s) each event log * message would be written to. The default behavior is to write each event message to * the schema's specified log file. Note that if this flag is used and neither the * @ref fEventFlagOutputToStderr nor @ref fEventFlagOutputToStdout flags are used, it is * effectively the same as disabling the event since there is no set destination for the * message. */ constexpr EventFlags fEventFlagSkipLog = 0x00000040; /** Base type for flags to control how events and schemas are enabled or disabled. These flags * can be passed to the @ref omni::structuredlog::IStructuredLog::setEnabled() function. */ using EnableFlags OMNI_ATTR("flag, prefix=fEnableFlag") = uint32_t; /** Flag to indicate that a call to @ref IStructuredLog::setEnabled() should * affect the entire schema that the named event ID belongs to instead of just the event. When * this flag is used, each of the schema's events will behave as though they are disabled. * However, each event's individual enable state will not be modified. When the schema is * enabled again, the individual events will retain their previous enable states. */ constexpr EnableFlags fEnableFlagWholeSchema = 0x00000002; /** Flag to indicate that the enable state of each event in a schema should be overridden when * the @ref fEnableFlagWholeSchema flag is also used. When this flag is used, the enable state * of each event in the schema will be modified instead of just the enable state of the schema * itself. When this flag is not used, the default behavior is to change the enable state * of just the schema but leave the enable states for its individual events unmodified. */ constexpr EnableFlags fEnableFlagOverrideEnableState = 0x00000004; /** Flag to indicate that an enable state change should affect the entire system, not just * one schema or event. When this flag is used in @ref IStructuredLog::setEnabled(), the @a eventId * parameter must be set to @ref kBadEventId. */ constexpr EnableFlags fEnableFlagAll = 0x00000008; /** Base type for flags to control how new events are allocated. These flags can be passed * to the @ref IStructuredLog::allocEvent() function. */ using AllocFlags OMNI_ATTR("flag, prefix=fAllocFlag") = uint32_t; /** Flag to indicate that the event should only be added to the queue on commit but that the * consumer thread should not be started yet if it is not already running. */ constexpr AllocFlags fAllocFlagOnlyQueue = 0x00000010; /** A descriptor for a single structured log event. This struct should not need to be used * externally but will be used by the generated code in the schema event registration helper * function. A schema consists of a set of one or more of these structs plus some additional * name and version information. The schema metadata is passed to @ref IStructuredLog::allocSchema(). * The array of these event info objects is passed to @ref IStructuredLog::commitSchema(). */ struct EventInfo { /** The fully qualified name of this event. While there is no strict formatting requirement * for this name, this should be an RDNS style name that specifies the full ownership chain * of the event. This should be similar to the following format: * "com.nvidia.omniverse.<appName>.<eventName>" */ const char* eventName; /** Flags controlling the behavior of this event when being generated or processed. Once * registered, these flags may not change. This may be zero or more of the @ref EventFlags * flags. */ EventFlags flags; /** Version of the schema tree building object that is passed in through @ref schema. This * is used to indicate which version of the event payload block helper classes will be used * to create and read the blocks. In general this should be @ref kParserVersion. */ ParserVersion parserVersion; /** The event ID that will be used to identify this event from external callers. This should * be a value that uniquely identifies the event's name, schema's version, and the JSON * parser version (ie: @ref parserVersion above) that will be used. Ideally this should be * a hash of a string containing all of the above information. It is the caller's * responsibility to ensure the event ID is globally unique enough for any given app's usage. */ uint64_t eventId; /** Schema tree object for this event. This tree object is expected to be built in the * block of memory that is returned from @ref IStructuredLog::allocSchema(). Optionally, this may * be nullptr to indicate that the event's payload is intended to be empty (ie: the event * is just intended to be an "I was here" event). */ const void* schema; }; // ********************************* IStructuredLog interface ************************************* /** Main structured log interface. This should be treated internally as a global singleton. Any * attempt to create or acquire this interface will return the same object just with a new * reference taken on it. * * There are three main steps to using this interface: * * Set up the interface. For most app's usage, all of the default settings will suffice. * The default log path will point to the Omniverse logs folder and the default user ID * will be the one read from the current user's privacy settings file (if it exists). If * the default values for these is not sufficient, a new user ID should be set with * @ref omni::structuredlog::IStructuredLogSettings::setUserId() and a log output path should be set with * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * If the privacy settings file is not present, * the user name will default to a random number. The other defaults should be sufficient * for most apps. This setup only needs to be performed once by the host app if at all. * The @ref omni::structuredlog::IStructuredLogSettings interface can be acquired either * by casting an @ref omni::structuredlog::IStructuredLog * object to that type or by directly creating the @ref omni::structuredlog::IStructuredLogSettings * object using omni::core::ITypeFactory_abi::createType(). * * Register one or more event schemas. * This is done with @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema(). * At least one event must be registered for any events to * be processed. Once a schema has been registered, it will remain valid until the * structured log module is unloaded from the process. There is no way to forcibly * unregister a set of events once registered. * * Send zero or more events. This is done with the @ref omni::structuredlog::IStructuredLog::allocEvent() and * @ref omni::structuredlog::IStructuredLog::commitEvent() functions. * * For the most part, the use of this interface will be dealt with in generated code. This * generated code will come from the 'omni.structuredlog' tool in the form of an inlined header * file. It is the host app's responsibility to call the header's schema registration helper * function at some point on startup before any event helper functions are called. * * All messages generated by this structured log system will be CloudEvents v1.0 compliant. * These should be parsable by any tool that is capable of understanding CloudEvents. * * Before an event can be sent, at least one schema describing at least one event must be * registered. This is done with the @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema() functions. * The @ref omni::structuredlog::IStructuredLog::allocSchema() function returns * a handle to a block of memory owned by the structured log system and a pointer to that block's * data. The caller is responsible for both calculating the required size of the buffer before * allocating, and filling it in with the schema data trees for each event that can be sent as * part of that schema. The helper functions in @ref omni::structuredlog::JsonTreeSizeCalculator and * @ref omni::structuredlog::JsonBuilder can be used to build these trees. Once these trees are built, they are * stored in a number of entries in an array of @ref omni::structuredlog::EventInfo objects. This array of event * info objects is then passed to @ref omni::structuredlog::IStructuredLog::commitSchema() to complete the schema * registration process. * * Sending of a message is split into two parts for efficiency. The general idea is that the * caller will allocate a block of memory in the event queue's buffer and write its data directly * there. * The allocation occurs with the @ref omni::structuredlog::IStructuredLog::allocEvent() call. * This will return a * handle to the allocated block and a pointer to the first byte to start writing the payload * data to. The buffer's header will already have been filled in upon return from * @ref omni::structuredlog::IStructuredLog::allocEvent(). * Once the caller has written its event payload information to * the buffer, it will call @ref omni::structuredlog::IStructuredLog::commitEvent() * to commit the message to the queue. At * this point, the message can be consumed by the event processing thread. * * Multiple events may be safely allocated from and written to the queue's buffer simultaneously. * There is no required order that the messages be committed in however. If a buffer is * allocated after one that has not been committed yet, and that newer event is committed first, * the only side effect will be that the event processing thread will be stalled in processing * new events until the first message is also committed. This is important since the events * would still need to be committed to the log in the correct order. * * All events that are processed through this interface will be written to a local log file. The * log file will be periodically consumed by an external process (the Omniverse Transmitter app) * that will send all the approved events to the telemetry servers. Only events that have been * approved by legal will be sent. All other messages will be rejected and only remain in the * log files on the local machine. */ class IStructuredLog_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLog")> { protected: /** Checks whether a specific event or schema is enabled. * * @param[in] eventId The unique ID of the event to check the enable state of. This * is the ID that was originally used to register the event. * @returns `true` if both the requested event and its schema is enabled. * @returns `false` if either the requested event or its schema is disabled. * * @remarks This checks if a named event or its schema is currently enabled in the structured * log system. Individual events or entire schemas may be disabled at any given * time. Both the schema and each event has its own enable state. A schema can be * disabled while still leaving its events' previous enable/disable states * unmodified. When the schema is enabled again, its events will still retain their * previous enable states. Set @ref omni::structuredlog::IStructuredLog::setEnabled() * for more information on how to enable and disable events and schemas. */ virtual bool isEnabled_abi(EventId eventId) noexcept = 0; /** Sets the enable state for a structured log event or schema, or the system globally. * * @param[in] eventId The ID of the event to change the enable state of. This is the ID * that was originally used to register the event. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this must be * set to @ref omni::structuredlog::kBadEventId. * @param[in] flags Flags to control the behavior of this function. This may be zero or * more of the @ref omni::structuredlog::EnableFlags flags. * If this includes the @ref omni::structuredlog::fEnableFlagAll * flag, @p eventId must be set to @ref omni::structuredlog::kBadEventId. * @param[in] enabled Set to true to enable the named event or schema. Set to false to * disable the named event or schema. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this sets the * new enable/disable state for the structured log system as a whole. * @returns No return value. * * @remarks This changes the current enable state for an event or schema. The scope of the * enable change depends on the flags that are passed in. When an event is * disabled (directly or from its schema or the structured log system being * disabled), it will also prevent it from being generated manually. In this case, * any attempt to call @ref omni::structuredlog::IStructuredLog::allocEvent() for * that disabled event or schema will simply fail immediately. * * @remarks When a schema is disabled, it effectively disables all of its events. Depending * on the flag usage however (ie: @ref omni::structuredlog::fEnableFlagOverrideEnableState), * disabling the schema may or may not change the enable states of each of its * individual events as well (see @ref omni::structuredlog::fEnableFlagOverrideEnableState * for more information). * * @note The @ref omni::structuredlog::fEnableFlagAll flag should only ever by used by the * main host app since this will affect the behavior of all modules' events regardless * of their own internal state. Disabling the entire system should also only ever be * used sparingly in cases where it is strictly necessary (ie: compliance with local * privacy laws). */ virtual void setEnabled_abi(EventId eventId, EnableFlags flags, bool enabled) noexcept = 0; // ****** schema registration function ****** /** Allocates a block of memory for an event schema. * * @param[in] schemaName The name of the schema being registered. This may not be * nullptr or an empty string. There is no set format for this * schema name, but it should at least convey some information * about the app's name and current release version. This name * will be used to construct the log file name for the schema. * @param[in] schemaVersion The version number for the schema itself. This may not be * nullptr or an empty string. This should be the version number * of the schema itself, not of the app or component. This will * be used to construct the 'dataschema' name that gets passed * along with each CloudEvents message header. * @param[in] flags Flags to control the behavior of the schema. This may be * zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @param[in] size The size of the block to allocate in bytes. If this is 0, a * block will still be allocated, but its actual size cannot be * guaranteed. The @ref omni::structuredlog::JsonTreeSizeCalculator * helper class can be used to calculate the size needs for the new schema. * @param[out] outHandle Receives the handle to the allocated memory block on success. * On failure, this receives nullptr. Each successful call * must pass this handle to @ref omni::structuredlog::IStructuredLog::commitSchema() * even if an intermediate failure occurs. In the case of a schema * tree creation failure, nullptr should be passed for @a events * in the corresponding @ref omni::structuredlog::IStructuredLog::commitSchema() call. * This will allow the allocated block to be cleaned up. * @returns A pointer to the allocated block on success. This block does not need to be * explicitly freed - it will be managed internally. This pointer will point to * the first byte that can be written to by the caller and will be at least @p size * bytes in length. This pointer will always be aligned to the size of a pointer. * @returns `nullptr` if no more memory is available. * @returns `nullptr` if an invalid parameter is passed in. * * @remarks This allocates a block of memory that the schema tree(s) for the event(s) in a * schema can be created and stored in. Pointers to the start of each event schema * within this block are expected to be stored in one of the @ref omni::structuredlog::EventInfo objects * that will later be passed to @ref omni::structuredlog::IStructuredLog::commitSchema(). The caller is * responsible for creating and filling in returned block and the array of * @ref omni::structuredlog::EventInfo objects. * The @ref omni::structuredlog::BlockAllocator helper class may be used to * allocate smaller chunks of memory from the returned block. * * @note This should only be used in generated structured log source code. This should not * be directly except when absolutely necessary. This should also not be used as a * generic allocator. Failure to use this properly will result in memory being * leaked. * * @thread_safety This call is thread safe. */ virtual uint8_t* allocSchema_abi(OMNI_ATTR("c_str, in, not_null") const char* schemaName, OMNI_ATTR("c_str, in, not_null") const char* schemaVersion, SchemaFlags flags, size_t size, OMNI_ATTR("out") AllocHandle* outHandle) noexcept = 0; /** Commits an allocated block and registers events for a single schema. * * @param[in] schemaBlock The block previously returned from * @ref omni::structuredlog::IStructuredLog::allocSchema() * that contains the built event trees for the schema to register. * These trees must be pointed to by the @ref omni::structuredlog::EventInfo::schema * members of the @p events array. * @param[in] events The table of events that belong to this schema. This provides * information about each event such as its name, control flags, * event identifier, and a schema describing how to interpret its * binary blob on the consumer side. This may not be nullptr. Each * of the trees pointed to by @ref omni::structuredlog::EventInfo::schema in this table * must either be set to nullptr or point to an address inside the * allocated schema block @p schemaBlock that was returned from the * corresponding call to @ref omni::structuredlog::IStructuredLog::allocSchema(). * If any of the schema trees point to an address outside of the schema block, * this call will fail. * @param[in] eventCount The total number of events in the @p events table. At least one * event must be registered. This may not be 0. * @retval omni::structuredlog::SchemaResult::eSuccess if the new schema * is successfully registered as a set of unique events. * @retval omni::structuredlog::SchemaResult::eAlreadyExists if the new * schema exactly matches one that has already been successfully registered. * This can be considered a successful result. * In this case, the schema block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eEventIdCollision if the new schema contains an event whose * identifier matches that of an event that has already been registered with another * schema. This indicates that the name of the event that was used to generate the * identifier was likely not unique enough, or that two different versions of the * same schema are trying to be registered without changing the schema's version * number first. No new events will be registered in this case and the schema * block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eFlagsDiffer if the new schema exactly matches another schema * that has already been registered except for the schema flags that were used * in the new one. This is not allowed without a version change in the new schema. * No new events will be registered in this case and the schema block will be * destroyed before return. * @returns Another @ref omni::structuredlog::SchemaResult error code for other types of failures. No new events * will be registered in this case and the schema block will be destroyed before * return. * * @remarks This registers a new schema and its events with the structured log system. This * will create a new set of events in the structured log system. These events * cannot be unregistered except by unloading the entire structured log system * altogether. Upon successful registration, the events in the schema can be * emitted using the event identifiers they were registered with. * * @remarks If the new schema matches one that has already been registered, The operation * will succeed with the result @ref omni::structuredlog::SchemaResult::eAlreadyExists. * The existing * schema's name, version, flags, and event table (including order of events) must * match the new one exactly in order to be considered a match. If anything differs * (even the flags for a single event or events out of order but otherwise the same * content), the call will fail. If the schema with the differing flags or event * order is to be used, its version or name must be changed to avoid conflict with * the existing schema. * * @remarks When generating the event identifiers for @ref omni::structuredlog::EventInfo::eventId it is * recommended that a string uniquely identifying the event be created then hashed * using an algorithm such as FNV1. The string should contain the schema's client * name, the event's name, the schema's version, and any other values that may * help to uniquely identify the event. Once hashed, it is very unlikely that * the event identifier will collide with any others. This is the method that the * code generator tool uses to create the unique event identifiers. * * @remarks Up to 65536 (ie: 16-bit index values) events may be registered with the * structured log system. The performance of managing a list of events this large * is unknown and not suggested however. Each module, app, or component should only * register its schema(s) once on startup. This can be a relatively expensive * operation if done frequently and unnecessarily. * * @thread_safety This call is thread safe. */ virtual SchemaResult commitSchema_abi(OMNI_ATTR("in, out, not_null") AllocHandle schemaBlock, OMNI_ATTR("in, *in, count=eventCount, not_null") const EventInfo* events, size_t eventCount) noexcept = 0; // ****** event message generation functions ****** /** Allocates a block of memory to store an event's payload data in. * * @param[in] version The version of the parser that should be used to read this * event's payload data. This should be @ref omni::structuredlog::kParserVersion. * If the structured log system that receives this message does not * support this particular version (ie: a newer module is run * on an old structured log system), the event message will simply * be dropped. * @param[in] eventId the unique ID of the event that is being generated. This ID must * exactly match the event ID that was provided in the * @ref omni::structuredlog::EventInfo::eventId value when the event * was registered. * @param[in] flags Flags to control how the event's block is allocated. This may * be a combination of zero or more of the @ref omni::structuredlog::AllocFlags * flags. * @param[in] payloadSize The total number of bytes needed to store the event's payload * data. The caller is responsible for calculating this ahead * of time. If the event does not have a payload, this should be * 0. The number of bytes should be calculated according to how * the requested event's schema (ie: @ref omni::structuredlog::EventInfo::schema) lays * it out in memory. * @param[out] outHandle Receives the handle to the allocated block of memory. This * must be passed to IStructuredLog::commitEvent() once the caller * has finished writing all of the payload data to the returned * buffer. The IStructuredLog::commitEvent() call acts as the * cleanup function for this handle. * @returns A pointer to the buffer to use for the event's payload data if successfully * allocated. The caller should start writing its payload data at this address * according to the formatting information in the requested event's schema. This * returned pointer will always be aligned to the size of a pointer. * @returns `nullptr` if the requested event, its schema, or the entire system is currently * disabled. * @returns `nullptr` if the event queue's buffer is full and a buffer of the requested * size could not be allocated. In this case, a invalid handle will be returned * in @p outHandle. The IStructuredLog::commitEvent() function does not need to be * called in this case. * @returns `nullptr` if the event queue failed to be created or its processing thread failed * start up. * @returns `nullptr` if the given event ID is not valid. * * @remarks This is the main entry point for creating an event message. This allocates * a block of memory that the caller can fill in with its event payload data. * The caller is expected to fill in this buffer as quickly as possible. Once * the buffer has been filled, its handle must be passed to the * @ref omni::structuredlog::IStructuredLog::commitEvent() function to finalize and send. * Failing to pass a * valid handle to @ref omni::structuredlog::IStructuredLog::commitEvent() will stall the event queue * indefinitely. * * @remarks If the requested event has been marked as 'critical' by using the event flag * @ref omni::structuredlog::fEventFlagCriticalEvent, a blocking allocation will be used here instead. * In this case, this will not fail due to the event queue being out of space. * * @note This call will fail immediately if either the requested event, its schema, or * the entire system has been explicitly disabled. It is the caller's responsibility * to both check the enable state of the event before attempting to send it (ie: to * avoid doing unnecessary work), and to gracefully handle the potential of this * call failing. * * @note It is the caller's responsibility to ensure that no events are generated during * C++ static destruction time for the process during shutdown. Especially on * Windows, doing so could result in an event being allocated but not committed * thereby stalling the event queue. This could lead to a hang on shutdown. * * @thread_safety This call is thread safe. */ virtual uint8_t* allocEvent_abi(ParserVersion version, EventId eventId, AllocFlags flags, size_t payloadSize, OMNI_ATTR("out") AllocHandle* outHandle) noexcept = 0; /** finishes writing a message's payload and queues it for processing. * * @param[in] handle The handle to the queue buffer block to be committed. This must not * be nullptr. This must be the same handle that was returned through * @a outHandle on a recent call to @ref omni::structuredlog::IStructuredLog::allocEvent() * on this same thread. Upon return, this handle will be invalid and should be * discarded by the caller. * @returns No return value. * * @remarks This commits a block that was previously allocated on this thread with * @ref omni::structuredlog::IStructuredLog::allocEvent(). * It is required that the commit call occur on the * same thread that the matching @ref omni::structuredlog::IStructuredLog::allocEvent() * call was made on. * Each successful @ref omni::structuredlog::IStructuredLog::allocEvent() call must * be paired with exactly one * @ref omni::structuredlog::IStructuredLog::commitEvent() call on the same thread. * Failing to do so would result in the event queue thread stalling. * * @thread_safety This call is thread safe. */ virtual void commitEvent_abi(OMNI_ATTR("in, not_null") const AllocHandle handle) noexcept = 0; }; // skipping this because exhale can't handle the function pointer type #ifndef DOXYGEN_SHOULD_SKIP_THIS /** 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*); /** Retrieves the local schema registration list for this module. * * @returns The static list of schemas to register for this module. This is intended to be * a static list that can be built up at compile time to collect schemas to * register. Each module will have its own copy of this list. */ inline std::vector<SchemaAddFn>& getModuleSchemas() { static std::vector<SchemaAddFn> sSchemas; return sSchemas; } #endif } // namespace structuredlog } // namespace omni #ifdef OMNI_COMPILE_AS_DYNAMIC_LIBRARY OMNI_API omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire(); #else /** * Retrieves the module's structured log object. omni::core::IObject::acquire() is **not** called on the returned * pointer. * * The global omni::structuredlog::IStructuredLog instance can be configured by passing an * @ref omni::structuredlog::IStructuredLog to omniCoreStart(). * If an instance is not provided, omniCoreStart() attempts to create one. * * @returns the calling module's structured log object. The caller will not own a reference to * the object. If the caller intends to store the object for an extended period, it * must take a reference to it using either a call to acquire() or by borrowing it into * an ObjectPtr<> object. This object must not be released by the caller unless a * reference to it is explicitly taken. */ # ifndef STRUCTUREDLOG_STANDALONE_MODE inline omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire() { return static_cast<omni::structuredlog::IStructuredLog*>(omniGetBuiltInWithoutAcquire(OmniBuiltIn::eIStructuredLog)); } # else inline omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire() { using GetFunc = omni::structuredlog::IStructuredLog* (*)(); static GetFunc s_get = nullptr; if (s_get == nullptr) { carb::extras::LibraryHandle module = carb::extras::loadLibrary( omni::structuredlog::kStructuredLogPluginName, carb::extras::fLibFlagMakeFullLibName); s_get = carb::extras::getLibrarySymbol<GetFunc>(module, "omniGetStructuredLogWithoutAcquire_"); if (s_get == nullptr) return nullptr; } return s_get(); } # endif #endif #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLog.gen.h" /** Common entry point for sending an event. * * @param event_ The name of the event to send. This is expected to be the 'short' * name for the event as named in its schema's *_sendEvent() function. * This short name will be the portion of the function name before the * '_sendEvent' portion of the name. * @param ... The set of parameters specific to the event to be sent. These are * potentially different for each event. Callers should refer to the * original schema to determine the actual set of parameters to send. * @returns No return value. * * @remarks This is intended to be used to send all structured log events instead of calling the * generated schema class's functions directly. This provides a consistent entry * point into sending event messages and allows parameter evaluation to be delayed * if either the event or schema is disabled. */ #define OMNI_STRUCTURED_LOG(event_, ...) \ do \ { \ auto strucLog__ = omniGetStructuredLogWithoutAcquire(); \ if (strucLog__) \ { \ if (event_##_isEnabled(strucLog__)) \ { \ event_##_sendEvent(strucLog__, ##__VA_ARGS__); \ } \ } \ } while (0) namespace omni { namespace structuredlog { //! A function that registers all schemas within a module. //! //! \note It is not necessary to call this function; it is automatically called by \ref carbOnPluginPreStartup inline void addModulesSchemas() noexcept { auto strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; for (auto& schemaAddFn : getModuleSchemas()) { schemaAddFn(strucLog); } } } // namespace structuredlog } // namespace omni /** @copydoc omni::structuredlog::IStructuredLog_abi */ class omni::structuredlog::IStructuredLog : public omni::core::Generated<omni::structuredlog::IStructuredLog_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLog.gen.h"
omniverse-code/kit/include/omni/audio/IAudioPlayer.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. // //! @file //! @brief Defines an interface to provide a simple audio player interface. #pragma once #include <carb/Interface.h> #include <carb/audio/IAudioData.h> namespace omni { namespace audio { /** Handle for a created audio player object. This will be `nullptr` to indicate an invalid * audio player object. */ struct AudioPlayer; /** Prototype of a callback function to signal that a sound data log operation completed. * * @param[in] success Set to `true` if the load operation was successful. Set to `false` * otherwise. * @param[in] context The original caller specified context value that was provided when * this callback was registered in either IAudioPlayer::playSound() or * IAudioPlayer::loadSound() families of functions. * @returns No return value. */ using OnLoadedCallback = void (*)(bool success, void* context); /** Prototype of a callback function to signal that a sound completed its playback. * * @param[in] context The original caller specified context value that was provided when * this callback was registered in either IAudioPlayer::playSound() * family of functions. * @returns No return value. */ using OnEndedCallback = void (*)(void* context); /** Base type for flags that can be provided to IAudioPlayer::loadSoundInMemory() or * IAudioPlayer::playSoundInMemory(). * @{ */ using AudioPlayerFlags = uint32_t; /** Flag to indicate that the data blob being passed in only contains the raw PCM data and * no header or format information. When this flag is used, the frame rate, channel count, * and sample data format must also be specified when passing the blob to either * IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory(). */ constexpr AudioPlayerFlags fPlayerFlagRawData = 0x01; /** Flag to indicate that the data blob should be reloaded even if it is already cached in * the audio player object. */ constexpr AudioPlayerFlags fPlayerFlagForceReload = 0x02; /** @} */ /** The supported PCM formats for loading or playing raw PCM data through the * IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory() functions. */ enum class RawPcmFormat { ePcm8, ///< unsigned 8-bits per sample integer PCM data. ePcm16, ///< signed 16-bits per sample integer PCM data. ePcm32, ///< signed 32-bits per sample integer PCM data. ePcmFloat, ///< 32-bits per sample floating point PCM data. }; /** The descriptor for IAudioPlayer::drawWaveform(). */ struct DrawWaveformDesc { /** The name for the output image file. * This path supports the standard path aliases (e.g. "${resources}") * The path must point to an existing directory on disk. * This must be nullptr to store the image in @p outputBuffer. */ const char* filename; /** The buffer to store the raw RGBA8888 in. * @p filename must be nullptr for this to be used. * This needs to be at least @p width * @p height * 4 bytes long. */ uint8_t* outputBuffer; /** The width of the output image, in pixels. */ size_t width; /** The height of the output image, in pixels. */ size_t height; /** The foreground color in normalized RGBA color. */ carb::Float4 fgColor; /** The background color in normalized RGBA color. */ carb::Float4 bgColor; }; /** Descriptor of a blob of audio data in memory. This data can either be a full supported sound * file in memory, or just simple raw PCM data. If raw PCM data is provided, the information * about the data format must also be provided. */ struct AudioDataInMemory { /** The name to be used to cache the file data in the audio player. This may be `nullptr` or * an empty string to indicate that it shouldn't be cached. If it is not cached, the sound * is only expected to be played once. If it is played again, it will be reloaded instead of * pulling a cached version that was previously loaded or played. */ const char* name = nullptr; /** The buffer of sound data to be loaded. This is interpreted according to the flags passed * to either IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory(). If the * flags indicate that raw data is passed in, the frame rate, channel count, and data format * values will also be required. This may not be `nullptr`. */ const void* buffer; /** The size of @ref buffer in bytes. This may not be 0. */ size_t byteCount; /** The frame rate to play the audio data back at. This must be a non-zero value if raw PCM * data is being provided. This is measured in Hertz. Typical values for this are 44100Hz, * or 48000Hz. Any value in the range from 1000Hz to 200000Hz is generally accepted. Though * note that if this value is not correct for the given sound data, it may play back either * to quickly or too slowly. The pitch of the sound will also be affected accordingly. This * value will be ignored if the blob in @ref buffer already contains format information. */ size_t frameRate = 0; /** The number of channels in each frame of data in the sound. This must be a non-zero value * if raw PCM data is being provided. If this is incorrect for the given data, the sound will * play incorrectly. This value will be ignored if the blob in @ref buffer already contains * format information. */ size_t channels = 0; /** The format of the PCM data. This must be a valid value if raw PCM data is being provided. * This must be well known by the caller otherwise the audio data will load incorrectly and * undefined output would be likely to result (it won't be generally problematic except to * the ears of listeners). This value will be ignored if the bob in @ref buffer already * contains format information. */ RawPcmFormat format = RawPcmFormat::ePcm16; }; /** Simple interface to be able to play audio assets. * All of the calls to this interface are internally serialized by a mutex. * This provides an interface for an audio player that has one voice and * allows individual assets to be played. * Multiple audio players can be opened per-process but they all share the same * IAudioPlayer backend which limits the number of simultaneously playing audio * players to 4. */ struct IAudioPlayer { CARB_PLUGIN_INTERFACE("omni::audio::IAudioPlayer", 0, 3); /** Create an audio player instance. * @returns A new audio player if creation succeeded. * @returns nullptr if creation failed. * * @remarks This creates an audio system with 1 voice that can play sound assets. */ AudioPlayer*(CARB_ABI* createAudioPlayer)(); /** Destroy an audio player instance. * @param[in] player The player to destroy. * * @remarks This will stop any audio playing, release all assets and free * the memory of @p player. */ void(CARB_ABI* destroyAudioPlayer)(AudioPlayer* player); /** Play a sound asset. * @param[in] player The player to play this sound on. * @param[in] path The path to the sound asset to play. * This must be an absolute file path to a sound asset. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished * playing or has been stopped. * The parameter passed is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset into the sound to start playing it * at. This is measured in seconds. * * @remarks This will spawn a task to play this sound asset once it has loaded. * This is intended to be used for auditioning sounds to a user * from something like the content window, to allow them to hear * a sound before they use it in their scene. * * @note If another sound is currently playing, it will be stopped before * playing this sound. * * @note The callbacks are called within an internal static recursive * mutex, so the callbacks must be careful to avoid deadlock if they * need to acquire another lock, such as the python GIL. * * @note Playing the sound will fail if too many other audio players are * playing simultaneously. */ void(CARB_ABI* playSound)(AudioPlayer* player, const char* path, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime); /** Load a sound asset for future playback * @param[in] player The player to play this sound on. * @param[in] path The path to the sound asset to play. * This must be an absolute file path to a sound asset. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * * @remarks This will fetch an asset so that the next call to playSound() * can begin playing the sound immediately. * This will also stop the currently playing sound, if any. * This function will also cause getSoundLength() to begin * returning the length of this sound. */ void(CARB_ABI* loadSound)(AudioPlayer* player, const char* path, OnLoadedCallback onLoaded, void* context); /** Stop playing the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* stopSound)(AudioPlayer* player); /** Pause playback of the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* pauseSound)(AudioPlayer* player); /** Unpause playback of the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* unpauseSound)(AudioPlayer* player); /** Get the length of the currently playing sound. * @param[in] player The player to play this sound on. * @returns The length of the currently playing sound in seconds. * @returns 0.0 if there is no playing sound. */ double(CARB_ABI* getSoundLength)(AudioPlayer* player); /** Get the play cursor position in the currently playing sound. * @param[in] player The player to play this sound on. * @returns The play cursor position in the currently playing sound in seconds. * @returns 0.0 if there is no playing sound. */ double(CARB_ABI* getPlayCursor)(AudioPlayer* player); /** Set the cursor in the sound. * @param[in] player The player to use to set the cursor in the sound. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished * playing or has been stopped. * The parameter passed is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset to set the cursor to. This is measured in seconds. * * @note The previous onEnded() callback that was passed to playSound() will * be called after @p onLoaded() is called. */ void(CARB_ABI* setPlayCursor)(AudioPlayer* player, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime); /** Render the waveform to an image to a file. * @param[in] player The player whose waveform image will be rendered. * @param[in] desc The descriptor for the waveform to draw. * @return true if the operation was successful. * @returns false if the file could not be generated. * * @note The functionality of writing to a file is a temporary workaround. * This will eventually be changed to output a memory buffer. */ bool(CARB_ABI* drawWaveform)(AudioPlayer* player, const DrawWaveformDesc* desc); /** Play a sound asset from data in memory. * * @param[in] player The player to play this sound on. * @param[in] data The descriptor of the data blob and its required format * information. This must include the format information for the * sound if the @ref fPlayerFlagRawData flag is given in @p flags. * This may not be `nullptr`. * @param[in] onLoaded A callback to execute once the asset has loaded and is about to * play. This may be used for something like turning off a spinner * icon to indicate that the asset has loaded. The first parameter * of this callback indicates whether the load request succeeded. * The second parameter is @p context. This may be `nullptr` if the * callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished playing or has * been stopped. The parameter passed is @p context. This may be * `nullptr` if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset into the sound to start playing it at. This is * measured in seconds. * @param[in] flags Flags to control how the sound data is loaded and cached. If the * data blob does not contain format information and is just raw PCM * sample data, the @ref fPlayerFlagRawData flag must be specified * and the @a frameRate, @a channels, and @a format values in @p data * must also be given. Without these, the sound data cannot be * properly loaded. * @returns No return value. * * @remarks The sound asset will start playing asynchronously when the asset has loaded. * The asset is given as a data blob in memory. The data may either be a full * file loaded into memory or just raw PCM data. If raw PCM data is given, * additional parameters must be used to specify the sample type, channel count, * and frame rate so that the data can be successfully decoded. * * @note If another sound is currently playing, it will be stopped before * playing this sound. * * @note The callbacks are called within an internal static recursive * mutex, so the callbacks must be careful to avoid deadlock if they * need to acquire another lock, such as the python GIL. * * @note Playing the sound will fail if too many other audio players are * playing simultaneously. */ void(CARB_ABI* playSoundInMemory)(AudioPlayer* player, const AudioDataInMemory* data, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime, AudioPlayerFlags flags); /** Play a sound asset from data in memory. * * @param[in] player The player to play this sound on. * @param[in] data The descriptor of the data blob and its required format * information. This must include the format information for the * sound if the @ref fPlayerFlagRawData flag is given in @p flags. * This may not be `nullptr`. * @param[in] onLoaded A callback to execute once the asset has loaded and is about to * play. This may be used for something like turning off a spinner * icon to indicate that the asset has loaded. The first parameter * of this callback indicates whether the load request succeeded. * The second parameter is @p context. This may be `nullptr` if the * callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] flags Flags to control how the sound data is loaded and cached. If the * data blob does not contain format information and is just raw PCM * sample data, the @ref fPlayerFlagRawData flag must be specified * and the @a frameRate, @a channels, and @a format values in @p data * must also be given. Without these, the sound data cannot be * properly loaded. * @returns No return value. * * @remarks This will fetch an asset in memory so that the next call to playSound() can begin * playing the sound immediately. In order for this to be useful, the @a name value * in @p data must be a non-empty string so that the loaded sound is cached. If no * name is given, the operation will just fail immediately. This will also stop the * currently playing sound, if any. This function will also cause getSoundLength() * to begin returning the length of this sound. */ void(CARB_ABI* loadSoundInMemory)(AudioPlayer* player, const AudioDataInMemory* data, OnLoadedCallback onLoaded, void* context, AudioPlayerFlags flags); }; } }
omniverse-code/kit/include/omni/audio/IAudioDeviceEnum.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. // //! @file //! @brief Provides an interface that allows the connected audio devices to be enumerated. #pragma once #include <carb/Interface.h> #include <carb/extras/Guid.h> namespace omni { namespace audio { /** The direction to collect device information for. This is passed to most functions in the * IAudioDeviceEnum interface to specify which types of devices are currently interesting. */ enum class Direction { ePlayback, ///< Enumerate audio playback devices only. eCapture, ///< Enumerate audio capture devices only. }; /** Names for the type of sample that an audio device can use. */ enum class SampleType { eUnknown, ///< Could not determine the sample type or an invalid device index was given. ePcmSignedInteger, ///< Signed integer PCM samples. This is usually used for 16-bit an up. ePcmUnsignedInteger, ///< Unsigned integer PCM samples. This is often used for 8-bit samples. ePcmFloat, ///< Single precision floating point PCM samples. eCompressed, ///< A compressed sample format such as ADPCM, MP3, Vorbis, etc. }; /** An interface to provide simple audio device enumeration functionality. This is able to * enumerate all audio devices attached to the system at any given point and collect the * information for each device. This is only intended to collect the device information * needed to display to the user for device selection purposes. If a device is to be * chosen based on certain needs (ie: channel count, frame rate, etc), it should be done * directly through the audio playback or capture context during creation. This is able * to collect information for both playback and capture devices. * * Note that audio devices in the system are generally volatile - they can be added or * removed at any time with no control from this interface. Because of this, it is * highly suggested that device information not be cached, but instead queried each time * it needs to be refreshed. * * Currently this interface does not expose a device change notifier. This is only * available from the `carb::audio::IAudioDevice` interface for the moment. A future * version of this interface may expose an event stream for device change notifications. * The caller may then use those notifications to decide when to refresh the cached * device information in the UI for example. */ struct IAudioDeviceEnum { CARB_PLUGIN_INTERFACE("omni::audio::IAudioDeviceEnum", 0, 1); /** Retrieves the total number of devices attached to the system of a requested type. * * @param[in] dir The audio direction to get the device count for. * @returns The total number of connected audio devices of the requested type. * @returns 0 if no audio devices are connected to the system. */ size_t(CARB_ABI* getDeviceCount)(Direction dir); /** Retrieves a descriptive string for a requested audio device. * * @param[in] dir The audio direction to get the description string for. * @param[in] index The index of the device to retrieve the description for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] desc Receives the description string for the requested device if * it is still present in the system and its information can be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device description was successfully created. * @returns `false` if the device index was out of range. * * @remarks This retrieves a descriptive string for the requested device. This string is * suitable for display to a user in a menu or selection list. */ bool(CARB_ABI* getDeviceDescription)(Direction dir, size_t index, char* desc, size_t maxLength); /** Retrieves the friendly name of a requested device. * * @param[in] dir The audio direction to get the device name for. * @param[in] index The index of the device to retrieve the name for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] name Receives the name of the requested device if it could be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device name was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceName)(Direction dir, size_t index, char* name, size_t maxLength); /** Retrieves the GUID of a requested device. * * @param[in] dir The audio direction to get the device GUID for. * @param[in] index The index of the device to retrieve the GUID for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] guid Receives the GUID of the requested device if it could be * retrieved. This may not be nullptr. * @returns `true` if the device GUID was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceGuid)(Direction dir, size_t index, carb::extras::Guid* guid); /** Retrieves the unique identifier for the requested device. * * @param[in] dir The audio direction to get the device name for. * @param[in] index The index of the device to retrieve the identifier for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] id Receives the identifier of the requested device if it could be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device identifier was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceId)(Direction dir, size_t index, char* id, size_t maxLength); /** Retrieves the closest matching device index from an identifier. * * @param[in] dir The audio direction to get the device index for. * @param[in] id The identifier of the device to match to the current device list. * @returns The index of the device that matches the given identifier if an exact match * was found. Note that the match may have been made either by the device's * friendly name or by its unique identifier. This should be an identifier * returned from a previous call to getDeviceId() or getDeviceName(). Note * that this identifier may be stored persistently to attempt access to the * same device in a future launch. * @returns 0 if no matching device was found and the system's default device was * chosen instead. * * @remarks This checks the current system device list to find a device that matches * the given identifier. The device identifiers returned from getDeviceId() * contain both the device's friendly name and its unique identifier code. * Matches will first check the unique identifier. If no match is found, * it will compare against the friendly name. If the unique identifier portion * is not present, a match by the friendly name will be attempted instead. Note * that the device's friendly name may not necessarily be unique, even among * different removeable devices. For example, multiple USB headsets may have * their output sides appear to the system as just simply "Speakers". If a * persistent storage of the device identifier is needed, the name returned * from getDeviceId() should be preferred over that of getDeviceName(). */ size_t(CARB_ABI* getDeviceIndexFromId)(Direction dir, const char* id); /** Retrieves the preferred frame rate of a requested device. * * @param[in] dir The audio direction to get the preferred frame rate for. * @param[in] index The index of the device to retrieve the frame rate for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @returns The preferred frame rate of the requested device if it could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the preferred frame rate of a requested device. The preferred * frame rate is the rate at which the device natively wants to process audio data. * Using the device at other frame rates may be possible but would require extra * processing time. Using a device at a different frame rate than its preferred * one may also result in degraded quality depending on what the processing versus * preferred frame rate is. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceFrameRate)(Direction dir, size_t index); /** Retrieves the maximum channel count for a requested device. * * @param[in] dir The audio direction to get the maximum channel count for. * @param[in] index The index of the device to retrieve the channel count for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The maximum channel count of the requested device if it could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the maximum channel count for a requested device. This count * is the maximum number of channels that the device can natively handle without * having to trim or reprocess the data. Using a device with a different channel * count than its maximum is allowed but will result in extra processing time to * upmix or downmix channels in the stream. Note that downmixing channel counts * (ie: 7.1 to stereo) will often result in multiple channels being blended * together and can result in an unexpected final signal in certain cases. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceChannelCount)(Direction dir, size_t index); /** Retrieves the native sample size for a requested device. * * @param[in] dir The audio direction to get the native sample size for. * @param[in] index The index of the device to retrieve the sample size for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The native sample size in bits per sample of the requested device if it * could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the bits per sample that a requested device prefers to process * its data at. It may be possible to use the device at a different sample size, * but that would likely result in extra processing time. Using a device at a * different sample rate than its native could degrade the quality of the final * signal. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceSampleSize)(Direction dir, size_t index); /** Retrieves the native sample data type for a requested device. * * @param[in] dir The audio direction to get the native sample data type for. * @param[in] index The index of the device to retrieve the sample data type for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The native sample data type of the requested device if it could be retrieved. * @returns @ref SampleType::eUnknown if the device index was out of range. * * @remarks This retrieves the sample data type that a requested device prefers to process * its data in. It may be possible to use the device with a different data type, * but that would likely result in extra processing time. Using a device with a * different sample data type than its native could degrade the quality of the * final signal. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ SampleType(CARB_ABI* getDeviceSampleType)(Direction dir, size_t index); /** Check if the audio device backend uses direct hardware access. * @returns `true` if this backend has direct hardware access. * This will be returned when ALSA is in use. * @returns `false` if the backend is an audio mixing server. * This will be returned when Pulse Audio or Window Audio Services * are in use. * * @remarks A direct hardware audio backend is capable of exclusively locking * audio devices, so devices are not guaranteed to open successfully * and opening devices to test their format may be disruptive to the system. * * @remarks ALSA is the only 'direct hardware' backend that's currently supported. * Some devices under ALSA will exclusively lock the audio device; * these may fail to open because they're busy. * Additionally, some devices under ALSA can fail to open because * they're misconfigured (Ubuntu's default ALSA configuration can * contain misconfigured devices). * In addition to this, opening some devices under ALSA can take * a substantial amount of time (over 100ms). * For these reasons, it is important to verify that you are not * using a 'direct hardware' backend if you are going to call certain * functions in this interface. */ bool(CARB_ABI* isDirectHardwareBackend)(); }; } }
omniverse-code/kit/include/omni/audio/AudioSettings.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/kit/SettingsUtils.h> /** audio setting group names. These provide the starting path to all of the common * audio settings. * @{ */ /** the group name for all playback audio settings in Kit. */ #define AUDIO_SETTING_GROUP_CONTEXT "/audio/context" /** @} */ /** setting leaf names. These must be prefixed by @ref AUDIO_SETTING_GROUP_CONTEXT * to be valid for a settings lookup. * @{ */ #define AUDIO_SETTING_NAME_MAXBUSES "maxBuses" #define AUDIO_SETTING_NAME_SPEAKERMODE "speakerMode" #define AUDIO_SETTING_NAME_STREAMERFILE "streamerFile" #define AUDIO_SETTING_NAME_ENABLESTREAMER "enableStreamer" #define AUDIO_SETTING_NAME_DEVICENAME "deviceName" #define AUDIO_SETTING_NAME_CAPTUREDEVICENAME "captureDeviceName" #define AUDIO_SETTING_NAME_AUTOSTREAM "autoStreamThreshold" #define AUDIO_SETTING_NAME_AUDIO_PLAYER_AUTOSTREAM "audioPlayerAutoStreamThreshold" #define AUDIO_SETTING_NAME_CLOSEONSOUNDSTOP "closeAudioPlayerOnStop" #define AUDIO_SETTING_NAME_MASTERVOLUME "masterVolume" #define AUDIO_SETTING_NAME_USDVOLUME "usdVolume" #define AUDIO_SETTING_NAME_SPATIALVOLUME "spatialVolume" #define AUDIO_SETTING_NAME_NONSPATIALVOLUME "nonSpatialVolume" #define AUDIO_SETTING_NAME_UIVOLUME "uiVolume" /** @} */ /********************************** Audio Settings Paths *****************************************/ namespace omni { namespace audio { /** full path suffixes for the Kit audio settings. For the app preferences settings values * that should persist between launches of Kit, these names should each be prefixed with * @ref PERSISTENT_SETTINGS_PREFIX. If a value should not persist but instead be reset * between launches, it should not have a prefix. * * Each of these settings paths should be created by concatenating an optional persistence * prefix, one AUDIO_SETTING_GROUP_* name, a group separator (ie: @ref SETTING_SEP), and one * AUDIO_SETTING_NAME_* value name. * * @{ */ /** the number of buses to create the main audio playback context with. This will control * the maximum number of simultaneous voices that can be heard during playback. Any playing * voices beyond this count will be 'virtual' and will only be heard when another voice * releases its bus. This defaults to 0 which lets the context decide on creation. */ constexpr const char* const kSettingMaxBuses = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_MAXBUSES; /** the standard speaker layout to use for playback. This defaults to the speaker mode that * most closely corresponds to the device's preferred channel count. */ constexpr const char* const kSettingSpeakerMode = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_SPEAKERMODE; /** the name of the file to stream output to. This will be written as a RIFF wave file in * the same data format that the playback context chooses. The file will not be created * unless audio (even silent audio) is written to it. The file will also only be created * if the @ref AUDIO_SETTING_NAME_ENABLESTREAMER setting is also enabled. This defaults * to an empty string. */ constexpr const char* const kSettingStreamerFile = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_STREAMERFILE; /** boolean option to control whether the streamer is used or not for the current session. * Note that this setting is intentionally not persistent. This should always be disabled * on launch. If it were persistent, it would lead to all audio being recorded even when * not intended, and potentially filling up the local drive. */ constexpr const char* const kSettingEnableStreamer = AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_ENABLESTREAMER; /** the identifier of the device that should be used for audio playback. This name can be * retrieved from the omni::audio::IAudioDeviceEnum interface using the getDeviceId() * function. This name may consist of a device GUID, a friendly device name, or a * combination of both. If a GUID is provided, a connected device using that name will * be chosen if found. If a GUID is not provided or no connected device matches the * given GUID, the device will attempt to match by its friendly name. Note that this * friendly name is not necessarily unique in the system and the wrong device may end * up being selected in this case (if multiple devices with the same friendly name * are connected). This defaults to an empty string indicating that the system's default * device should always be used. */ constexpr const char* const kSettingDeviceName = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_DEVICENAME; /** The identifier of the device that should be used for audio capture. * This functions identically to @ref kSettingDeviceName, except that it's used * to specify the capture device instead of the playback device. */ constexpr const char* const kSettingCaptureDeviceName = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_CAPTUREDEVICENAME; /** the current auto-stream threshold setting in kilobytes. This controls when the audio * data system decides to stream an encoded sound versus decode it fully on load. This * threshold represents the decoded size of a sound above which it will be streamed instead * of decoded. If the decoded size of the sound is less than this threshold, it will be * decoded on load instead. */ constexpr const char* const kSettingAutoStream = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_AUTOSTREAM; /** the current auto-stream threshold setting in kilobytes specifically for the audio player. * This controls when the audio data system decides to stream an encoded sound versus decode it fully on load. * This threshold represents the decoded size of a sound above which it will be streamed instead * of decoded. If the decoded size of the sound is less than this threshold, it will be * decoded on load instead. Note that this setting is only for the audio player. Use @ref kSettingAutoStream * for the Audio Manager's auto stream threshold. */ constexpr const char* const kSettingAudioPlayerAutoStream = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_AUDIO_PLAYER_AUTOSTREAM; /** The option to close the audio player window when the sound is stopped. * If this is enabled, then the audio player will be automatically closed when the user clicks * the stop button or when the sound reaches its natural end. */ constexpr const char* const kSettingCloseOnSoundStop = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_CLOSEONSOUNDSTOP; /** the master volume level setting to use. This master volume affects all audio output * from the USD stage audio manager, UI audio manager, and the audio player interfaces. * This level should be set to 1.0 for full volume and 0.0 for silence. The volume scale * is approximately linear. This defaults to 1.0. */ constexpr const char* const kSettingMasterVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_MASTERVOLUME; /** the master volume for the USD stage audio manager to use. This does not affect the * UI audio manager or the audio player interfaces. This level should be set to 1.0 for * full volume and 0.0 for silence. The volume scale is approximately linear. This * defaults to 1.0. */ constexpr const char* const kSettingUsdVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_USDVOLUME; /** the relative volume level for spatial audio sounds in the USD stage audio manager. This * volume level will effectively be multiplied by the master volume and USD volume levels * above to get the final effective volume level for spatial sounds. This level should be * set to 1.0 for full volume and 0.0 for silence. The volume scale is approximately linear. * This defaults to 1.0. */ constexpr const char* const kSettingSpatialVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_SPATIALVOLUME; /** the relative volume level for non-spatial audio sounds in the USD stage audio manager. This * volume level will effectively be multiplied by the master volume and USD volume levels above * to get the final effective volume level for non-spatial sounds. This level should be set to * 1.0 for full volume and 0.0 for silence. The volume scale is approximately linear. This * defaults to 1.0. */ constexpr const char* const kSettingNonSpatialVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_NONSPATIALVOLUME; /** the master volume level for the UI audio manager. This level should be set to 1.0 for full * volume, and 0.0 for silence. The volume scale is approximately linear. This defaults to * 1.0. */ constexpr const char* const kSettingUiVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_UIVOLUME; /** @} */ } }
omniverse-code/kit/include/omni/audio/IUiAudio.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/Interface.h> namespace omni { namespace audio { /** public container for a loaded editor UI sound. These objects are returned from * @ref IUiAudio::createSound(). These objects can be copied as needed. Once destroyed, * the sound itself will only be destroyed if the no other objects refer to it as well. */ class UiSound { public: UiSound() = default; UiSound(const UiSound&) = default; virtual ~UiSound() = default; virtual UiSound& operator=(const UiSound&) = 0; }; /** simple interface to manage editor UI sound objects. This allows new sound objects to be * created (and loaded) from local disk, sounds to be played, stopped, and queried. */ struct IUiAudio { CARB_PLUGIN_INTERFACE("omni::audio::IUiAudio", 0, 1); /** Loads an editor UI sound from local disk. * * @param[in] filename the path to the sound file to load. This should be an absolute * path, but can be a relative path that will be resolved using the * current working directory for the process. This may not be * nullptr. Parts of this path may include some special path * specifiers that will be resolved when trying to open the file. * See the remarks section below for more info. This may not be * nullptr or an empty string. * @return the sound object representing the new loaded sound. This sound can be passed to * playSound() later. Each sound object returned here must be destroyed by * deleting it when it is no longer needed. Note that destroying the sound object * will stop all playing instances of it. However, if more than one reference to * the same sound object still exists, deleting one of the sound objects will not * stop any of the instances from playing. It is best practice to always explicitly * stop a sound before destroying it. * @return nullptr if the file could not be loaded could not be loaded. * * @remarks This loads a sound that can be played with playSound() at a later time. This * sound only needs to be loaded once but can be played as many times as needed. * When no longer needed, the sound should be destroyed by deleting it. * * @remarks File names passed in here may contain special path markers. * * @note This operation is always thread safe. */ UiSound*(CARB_ABI* createSound)(const char* filename); /** Immediately plays the requested UI sound if it is loaded. * * @param[in] sound the name of the UI sound to be played. This may not be nullptr. * @return no return value. * * @remarks This plays a single non-looping instance of a UI sound immediately. The UI 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's * playback. This sound may be prematurely stopped with stopSound(). * * @note This operation is always thread safe. */ void(CARB_ABI* playSound)(UiSound* soundToPlay); /** Queries whether a sound object is currently playing. * * @param[in] sound the sound object to query the playing state for. This may not be * nullptr. * @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. */ bool(CARB_ABI* isSoundPlaying)(const UiSound* sound); /** Immediately stops the playback of a sound. * * @param[in] sound the sound object to stop playback for. This may not be nullptr. * @return no return value. * * @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. */ void(CARB_ABI* stopSound)(UiSound* sound); /** Retrieves length of a sound in seconds (if known). * * @param[in] sound the sound to retrieve the length for. This may not be nullptr. * @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 UI sound in seconds. This is just the length * of the sound asset in seconds. */ double(CARB_ABI* getSoundLength)(UiSound* sound); }; } }
omniverse-code/kit/include/omni/audio/IAudioRecorder.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/audio/IAudioCapture.h> namespace omni { namespace audio { /** The audio recorder instance. * This is created to reserve a device that can record audio. */ struct AudioRecorder; /** A callback to read data from the audio device. * @param[in] data The audio data that was recorded. * @param[in] frames The number of frames of audio that are available in @p data. * @param[inout] context A user-defined context that gets passed through to the callback. */ using ReadCallback = void (*)(const void* data, size_t frames, void* context); /** The descriptor used to create a recording session. */ struct AudioRecordDesc { /** Flags for future expansion. * This must be set to 0. */ uint32_t flags = 0; /** The filename to write the output audio to. * This can be nullptr to use @p callback to receive audio instead. */ const char* filename = nullptr; /** The read callback to receive data with. * This will be called periodically when data is available. * This can be nullptr if @ref filename is non-null. * If this is set to non-null and @ref filename is non-null, this callback * will be called after the data has been written to the file (the data may * not have been flushed at this point though). * Note that if this callback takes too long, it can cause a recording overrun. * This callback occurs asynchronously under the recursive mutex of the * @ref AudioRecorder; if a lock is acquired in @ref callback, it is * important to ensure this does not result in the two locks being * acquired in different orders, which could potentially cause deadlock. */ ReadCallback callback = nullptr; /** A parameter that gets passed into the callback. * This is ignored if @ref callback is nullptr. */ void* callbackContext = nullptr; /** The frame rate to capture audio at. * This may be set to 0 to use the default rate for the device. * You can query the device's rate with IAudioRecorder::getDeviceCaps(). * If this is not a frame rate supported by the device, a resampler will be * introduced, which adds a small performance cost. */ size_t frameRate = 0; /** The number of channels that the audio is being captured at. * This may be set to 0 to use the default channel count for the device. * You can query the device's channel count with IAudioRecorder::getDeviceCaps(). * If this is different than the device's channel count an up/downmixing * operation may have to be introduced, which add a small performance cost. * The channel mixing matrices chosen are chosen based on the set of * default speaker modes used by carb.audio for a given channel count; * see carb::audio::getSpeakerModeForCount() for this list of defaults. */ size_t channels = 0; /** The format that data will be produced by the capture device. * This may be @ref carb::audio::SampleFormat::eDefault to use the device's * preferred format. * You can query the device's rate with IAudioRecorder::getDeviceCaps(). * This must be set to a PCM format if @ref callback is non-null. * If this is not a format supported by the device, a format conversion * will be introduced which adds a very small performance cost. */ carb::audio::SampleFormat sampleFormat = carb::audio::SampleFormat::eDefault; /** The format that gets written to the file. * This is only used if @ref filename is non-null. * This can be any valid sample format. * If this is set to @ref carb::audio::SampleFormat::eDefault, @ref sampleFormat * is used. */ carb::audio::SampleFormat outputFormat = carb::audio::SampleFormat::eDefault; /** The length of the recording buffer. * This setting, combined with @ref period will allow you to choose the * recording latency, as well as the tolerance for variance in recording * latency. * It is important to set this to a large enough value that fluctuation * in system timing can be handled without the audio buffer filling up. * The length can be set to 0 to use the device's default buffer length. */ size_t bufferLength = 0; /** The time between read callbacks. * This value can be used to reduce latency without reducing the ability to * handle fluctuations in timing; for example, setting @ref bufferLength to * 64ms and setting @ref period to 8ms will result in roughly 8ms latency * but the ability to tolerate up to 56ms of lag. * The default value is @ref bufferLength / 2. * This will be clamped to the default period if it exceeds the default period. * Two callbacks may be sent for a given period to handle the end of the * ring buffer. * This may send more data than expected for a given period if the system's * timing fluctuates. */ size_t period = 0; /** Describes how @ref bufferLength and @ref period should be interpreted. * This value is ignored if @ref bufferLength and @ref period are 0. Note * that the buffer size will always be rounded up to the next frame * boundary even if the size is specified in bytes. */ carb::audio::UnitType lengthType = carb::audio::UnitType::eFrames; }; /** Simple interface to be able to record audio. */ struct IAudioRecorder { CARB_PLUGIN_INTERFACE("omni::audio::IAudioRecorder", 0, 1); /** Create an audio recorder instance. * @returns A new audio recorder if creation succeeded. * This must be passed to destroyAudioRecorder() when you are * finished with the instance. * @returns nullptr if creation failed. * * @remarks This creates an audio system that can record audio to a file or to a callback. * * @note Each call to createAudioRecorder() opens a connection to the audio * recording device set in the preferences (@ref kSettingCaptureDeviceName). * It is not recommended to open a large number of these connections. */ AudioRecorder*(CARB_ABI* createAudioRecorder)(); /** Destroy an audio recorder instance. * @param[inout] recorder The recorder to destroy. * * @remarks This function frees the memory allocated to the @ref AudioRecorder. * This will stop the recorder if it was recoding audio when this is called. */ void(CARB_ABI* destroyAudioRecorder)(AudioRecorder* recorder); /** Being recording audio. * @param[inout] recorder The audio recorder to begin recording with. * This should not be nullptr. * @param[in] desc The descriptor for how audio should be recorded. * This should not be nullptr. * * @returns true If recording has started. * @returns false if @p recorder or @p desc are nullptr. * @returns false if another error occurred. */ bool(CARB_ABI* beginRecording)(AudioRecorder* recorder, const AudioRecordDesc* desc); /** Stop recording audio. * @param[inout] recorder The audio recorder to stop recording on. * This should not be nullptr. * @param[in] flush Set this to true to flush the rest of the data * that is currently in the capture device's buffer. * Set this to false to discard any remaining queued * data. * * @remarks This should be called when beginRecording() has been previously * called and you want to stop recording. */ void(CARB_ABI* stopRecording)(AudioRecorder* recorder, bool flush); /** Retrieves the sound format for the recorder. * @param[in] recorder The recorder to retrieve the device information for. * This should not be nullptr. * @param[out] format Receives the format. * This should not be nullptr. * If beginRecording() was called, this will return * the current format that is being used for recording. * If beginRecording() has not been called yet, this * will return the default format specified by the device. * @returns true if the device info was successfully retrieved. * @returns false if either parameter was nullptr. * @returns false if the call fails for any other reason. */ bool(CARB_ABI* getFormat)(AudioRecorder* recorder, carb::audio::SoundFormat* format); }; } }
omniverse-code/kit/include/omni/audio/experimental/IAudioCapture.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/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 /** An individual audio capture stream. */ template <> class omni::core::Generated<omni::audio::experimental::ICaptureStream_abi> : public omni::audio::experimental::ICaptureStream_abi { public: OMNI_PLUGIN_INTERFACE("omni::audio::experimental::ICaptureStream") /** Starts capturing audio data from the stream. * * @param[in] flags Flags to alter the recording behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture is successfully started. * @returns An @ref AudioResult error code if the stream could not be started. * * @remarks Audio streams are in a stopped state when they're created. * You must call start() to start recording audio. * * @remarks Without @ref fCaptureStreamStartFlagOneShot, the stream will * perform looping capture. This means that once the ring buffer * has been filled, audio will start being recorded from the start * of the buffer again. * * @remarks Looping audio will not overwrite unread parts of the ring buffer. * Only parts of the buffer that have been unlocked can be overwritten * by the audio system. * Data written into the ring buffer must be unlocked periodically * when using looping capture or the ring buffer will fill up and * the device will overrun. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ omni::audio::experimental::AudioResult start(omni::audio::experimental::CaptureStreamStartFlags flags) noexcept; /** Stop capturing audio data from the stream. * * @param[in] flags Flags to alter the stopping behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture was successfully stopped. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream was already stopped. * @returns An @ref AudioResult error code if something else went wrong. * The stream is likely broken in this case. * * @remarks This will stop capturing audio. Any audio data that would have * been captured between this point and the next call to @ref ICaptureStream_abi::start_abi() * will be lost. * * @remarks If there is unread data in the buffer, that data can still be * read with lock() after the stream is stopped. * * @note If fCaptureStreamStopFlagSync was not specified, the stop call will not sync with the * device so you could still receive callbacks after. * * @note CC-1180: You cannot use fCaptureStreamStopFlagSync from a callback. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ omni::audio::experimental::AudioResult stop(omni::audio::experimental::CaptureStreamStopFlags flags) noexcept; /** Check if the stream is still capturing data. * @returns `true` if the stream is still capturing. * @returns `false` if the stream is stopped. * Callbacks will no longer be sent if `false` was returned unless the strema was * stoped with @ref ICaptureStream_abi::stop_abi() was called without fCaptureStreamStopFlagSync. */ bool isCapturing() noexcept; /** Get the available number of frames to be read. * * @param[out] available The number of frames that can be read from the buffer. * * @returns @ref carb::audio::AudioResult::eOk if the frame count was retrieved successfully. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast enough and * the buffer filled up. * @returns @ref carb::audio::AudioResult::eNotAllowed if callback recording is being used. * @returns An @ref AudioResult error code if the operation fails for any other reason. * * @remarks This will check how much data is available to be read from the buffer. * This call is only valid when polling style recording is in use. */ omni::audio::experimental::AudioResult getAvailableFrames(size_t* available) noexcept; /** Lock the next chunk of the buffer to be read. * * @param[in] request The length of the buffer to lock, in frames. * This may be 0 to lock as much data as possible. * This does not need to be a multiple of the fragment * length. * If you need to convert bytes to frames, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes() (note that this is * slow due to requiring a division). * @param[out] region Receives the audio data. * This can be `nullptr` to query the available data * in the buffer, rather than locking it. * This buffer can be held until unlock() is called; * after unlock is called, the stream can start writing * into this buffer. * @param[out] received The length of data available in @p buffer, in frames. * This will not exceed @p request. * Due to the fact that a ring buffer is used, you may * have more data in the buffer than is returned in one * call; a second call would be needed to read the full * buffer. * If you need to convert this to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * * @returns @ref carb::audio::AudioResult::eOk if the requested region is successfully locked. * @returns @ref carb::audio::AudioResult::eOutOfMemory if there is no audio data available * in the buffer yet. * @returns @ref carb::audio::AudioResult::eNotAllowed if a region is already locked * and needs to be unlocked. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream is using callback * style recording. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast * enough and the underlying device has overrun. * This will happen on some audio systems (e.g. ALSA) if the * capture buffer fills up. * This can also happen on some audio systems sporadically if the * device's timing characteristics are too aggressive. * @returns an carb::audio::AudioResult::e* error code if the region could not be locked. * * @remarks This is used to get data from the capture stream when polling * style recording is being used (ie: there is no data callback). * When using this style of recording, portions of the buffer must * be periodically locked and unlocked. * * @remarks This retrieves the next portion of the buffer. * This portion of the buffer is considered to be locked until * @ref ICaptureStream_abi::unlock_abi() is called. * Only one region of the buffer can be locked at a time. * When using a looping capture, the caller should ensure that data * is unlocked before the buffer fills up or overruns may occur. */ omni::audio::experimental::AudioResult lock(size_t request, const void** region, size_t* received) noexcept; /** Unlocks a previously locked region of the buffer. * * @param[in] consumed The number of frames in the previous buffer that were consumed. * Any frames that were not consumed will be returned in future * @ref ICaptureStream_abi::lock_abi() calls. * 0 is valid here if you want to have the same locked region * returned on the next lock() call. * * @returns @ref carb::audio::AudioResult::eOk if the region is successfully unlocked. * @returns @ref carb::audio::AudioResult::eOutOfRange if @p consumed was larger than * the locked region. * @returns @ref carb::audio::AudioResult::eNotAllowed if no region is currently locked. * @returns an carb::audio::AudioResult::e* error code if the region could not be unlocked. * * @remarks This unlocks a region of the buffer that was locked with a * previous call to ICaptureStream_abi::lock_abi(). * Now that this region is unlocked, the device can start writing to it, * so the caller should no longer access that region. * Once the buffer is unlocked, a new region may be locked with ICaptureStream_abi::lock_abi(). * * @note If the locked region is not fully unlocked, the part of the region that * was not unlocked will be returned on the next call to ICaptureStream_abi::lock_abi(). * A second call to unlock cannot be made in this situation, it will fail. */ omni::audio::experimental::AudioResult unlock(size_t consumed) noexcept; /** Retrieve the size of the capture buffer. * * @returns The size of the capture buffer, in frames. * You can use @ref ICaptureStream_abi::getSoundFormat_abi() and @ref carb::audio::convertUnits() * to convert to bytes or other units. * * @remarks If your code is dependent on the buffer's actual size, it is * better to retrieve it with this function since the buffer size * used with device creation can be adjusted. */ size_t getBufferSize() noexcept; /** Retrieve the number of fragments used in this stream. * * @returns The number of buffer fragments. * This is the number of regions the recording buffer is divided * into. */ size_t getFragmentCount() noexcept; /** Retrieve the format of the audio being captured. * * @param[out] format The format of the audio being captured. * This may not be `nullptr`. */ void getSoundFormat(omni::audio::experimental::SoundFormat* format) noexcept; /** Clear any data that is currently in the recording buffer. * * @returns @ref carb::audio::AudioResult::eOk if the buffer was successfully cleared. * @returns an carb::audio::AudioResult::e* error code if the buffer could not be cleared. * * @remarks This is a quick way to get rid of any data that is left in the * buffer. * This will also reset the write position on the buffer back to * 0, so the next lock call will return the start of the buffer * (this can be useful if you want to do a one shot capture of the * entire buffer). * * @note If this is called while the capture stream is recording, the stream * will be paused before it is reset. */ omni::audio::experimental::AudioResult reset() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::start( omni::audio::experimental::CaptureStreamStartFlags flags) noexcept { return start_abi(flags); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::stop( omni::audio::experimental::CaptureStreamStopFlags flags) noexcept { return stop_abi(flags); } inline bool omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::isCapturing() noexcept { return isCapturing_abi(); } inline omni::audio::experimental::AudioResult omni::core::Generated< omni::audio::experimental::ICaptureStream_abi>::getAvailableFrames(size_t* available) noexcept { return getAvailableFrames_abi(available); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::lock( size_t request, const void** region, size_t* received) noexcept { return lock_abi(request, region, received); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::unlock( size_t consumed) noexcept { return unlock_abi(consumed); } inline size_t omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getBufferSize() noexcept { return getBufferSize_abi(); } inline size_t omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getFragmentCount() noexcept { return getFragmentCount_abi(); } inline void omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getSoundFormat( omni::audio::experimental::SoundFormat* format) noexcept { getSoundFormat_abi(format); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::reset() noexcept { return reset_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::audio::experimental::Format>::value, "omni::audio::experimental::Format must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureDeviceDesc>::value, "omni::audio::experimental::CaptureDeviceDesc must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureInfoData>::value, "omni::audio::experimental::CaptureInfoData must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureStreamDesc>::value, "omni::audio::experimental::CaptureStreamDesc must be standard layout to be used in ONI ABI");
omniverse-code/kit/include/omni/audio/experimental/IAudioCapture.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 An updated audio capture interface. */ #pragma once #include <omni/core/BuiltIn.h> #include <omni/core/IObject.h> #include <omni/core/Api.h> #include <omni/log/ILog.h> #include <carb/audio/AudioTypes.h> namespace omni { /** Omniverse audio project. */ namespace audio { /** The omni::audio namespace is part of an audio refresh that is still in the experimental stages. * This currently only contains the IAudioCapture interface, which was created to address a number * of defects in carb::audio::IAudioCapture. * IAudioCapture is currently in beta stage; the interface is complete and unlikely to change * substantially but it has not been tested heavily in a real-world use case yet. * The ABI of IAudioCapture and ICaptureStream are stable and will not be broken without a * deprecation warning given in advance. */ namespace experimental { /******************************** renamed carb::audio types **************************************/ /** @copydoc carb::audio::AudioResult */ using AudioResult = carb::audio::AudioResult; /** @copydoc carb::audio::SpeakerMode */ using SpeakerMode = carb::audio::SpeakerMode; /** @copydoc carb::audio::SampleFormat */ using SampleFormat = carb::audio::SampleFormat; /** @copydoc carb::audio::SoundFormat */ using SoundFormat = carb::audio::SoundFormat; /******************************** typedefs, enums, & macros **************************************/ /** The minimal format needed to interpret an PCM audio stream. * Non-PCM (compressed) audio streams may need different format information or * no format information to interpret. */ struct Format { /** The rate at which this audio stream is intended to be played (number of * audio frames per second). * A frame is a group of @ref channels audio samples taken at a given time point; * this is often referred to as the 'sample rate'. */ size_t frameRate = 0; /** The number of channels in the audio stream. */ size_t channels = 0; /** This specifies the intended usage of each channel in the audio stream. * This will be a combination of one or more of the @ref carb::audio::Speaker names or * a @ref carb::audio::SpeakerMode name. */ SpeakerMode channelMask = carb::audio::kSpeakerModeDefault; /** The data type of each audio sample in this audio stream. */ SampleFormat format = SampleFormat::eDefault; }; /** Flags to indicate some additional behaviour of the device. * No flags are currently defined. */ using CaptureDeviceFlags = uint32_t; /** The parameters to use when opening a capture device. */ struct CaptureDeviceDesc { /** Flags to indicate some additional behaviour of the device. * No flags are currently defined. This should be set to 0. */ CaptureDeviceFlags flags = 0; /** The index of the device to be opened. * Index 0 will always be the system's default capture device. * These indices are the same as the ones used in @ref carb::audio::IAudioDevice, * so that interface should be used to enumerate the system's audio devices. * * This must be less than the return value of the most recent call to @ref * carb::audio::IAudioDevice::getDeviceCount() for capture devices. * Note that since the capture device list can change at any time * asynchronously due to external user action, setting any particular * value here is never guaranteed to be valid. * There is always the possibility the user could remove the device after * its information is collected but before it is opened. * * Additionally, there is always a possibility that a device will fail to * open or the system has no audio capture devices, so code must be able to * handle that possibility. * In particular, it is common to run into misconfigured devices under ALSA; * some distributions automatically configure devices that will not open. */ size_t index = 0; /** The format to use for the capture stream. * Leaving this struct at its default values will cause the audio device's * default format to be used * (This can be queried later with @ref ICaptureStream_abi::getSoundFormat_abi()). * The audio stream will accept any valid PCM format, even if the underlying * device does not support that format. */ Format format = {}; /** The length of the ring buffer to capture data into, in frames. * The buffer length in combination with @ref bufferFragments determines * the minimum possible latency of the audio stream, which the time to * record one fragment of audio. * The buffer length will be automatically adjusted to ensure that its size * is divisible by the fragment count. * * This will not determine the buffer size of the underlying audio device, * but if it is possible, the underlying audio device will be adjusted to * best match this buffer length and fragment combination. * * Setting this to 0 will choose the underlying device's buffer length or * a default value if the underlying device has no buffer. */ size_t bufferLength = 0; /** The number of fragments that the recording buffer is divided into. * When using callback based recording, one fragment of audio will be sent * to each callback. * When using polling based recording, data will become available in one * fragment increments. * One fragment of audio becomes the minimum latency for the audio stream. * Setting an excessive number of fragments will reduce the efficiency of * the audio stream. * * Setting this to 0 will choose the underlying device's fragment count or * a default value if the underlying device doesn't use a ring buffer system. */ size_t bufferFragments = 0; }; class ICaptureStream; /** A callback that's used to receive audio data from an audio capture stream. * @param[inout] stream The stream that this callback was fired from. * @param[in] buffer The audio data that's been captured. * The data in the buffer will be in the format specified * by ICaptureStream::getSoundFormat(). * If the stream was created with @ref fCaptureStreamFlagLowLatency, * this buffer will not be valid once the callback returns; * otherwise, the buffer will be invalidated once ICaptureStream::unlock() * is called for this portion of the buffer. * See the note on unlocking the buffer for more detail on this. * @param[in] frames The length of audio in @p buffer, in frames. * If the stream was created with @ref fCaptureStreamFlagLowLatency, * the frame count passed to each callback may differ; * otherwise, the frame count will be exactly one fragment long. * If you need to convert to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * @param[inout] context The user-specified callback data. * * @note If the stream was not created with @ref fCaptureStreamFlagLowLatency, * data returned from this function is considered *locked*. * For data to become unlocked, the caller needs to call * ICaptureStream::unlock() with the number of frames that have been * locked by this call. * If the data is not unlocked, that portion of the buffer cannot be overwritten. * It is not required to release the buffer before the callback ends, but * the data needs to be unlocked eventually otherwise you will stop receiving * data and an overrun may occur. * * @note This callback executes from its own thread, so thread safety will need * to be considered. * This is called on the same thread as CaptureInfoCallback, so these * two calls can access the same data without concurrency issues. * * @note This callback must return as fast as possible, since this is called * directly from the audio capture thread (e.g. under 1ms). * A callback that takes too long could cause capture overruns. * Doing anything that could involve substantial waits (e.g. calling into python) * should be avoided; in those cases you should copy the buffer somewhere else * or use a omni::extras::DataStreamer for a series of asynchronous * data packets. * * @note It is safe to call any @ref ICaptureStream function from within this * callback, but it is not safe to destroy the @ref ICaptureStream object * from within it. */ using CaptureDataCallback = void (*)(ICaptureStream* stream, const void* buffer, size_t frames, void* context); /** The reason that a CaptureInfoCallback was called. */ enum class CaptureInfoType { /** An overrun has occurred. * Overruns occur when data is not captured fast enough from the audio * device, the device's buffer fills up and data is lost. * An overrun can occur because a callback took too long, data was not * unlocked fast enough or the underlying audio device encountered an * overrun for other reasons (e.g. system latency). */ eOverrun, /** The audio device has encountered an unrecoverable issue, such as the * device being unplugged, so capture has stopped. */ eDeviceLost, }; /** Extra data for @ref CaptureInfoCallback. * The union member used is based off of the `type` parameter. */ union CaptureInfoData { /** Data for @ref CaptureInfoType::eOverrun. * Overruns have no additional data. */ struct { } overrun; /** Data for @ref CaptureInfoType::eDeviceLost. * Device lost events have no additional data. */ struct { } deviceLost; /** Size reservation to avoid ABI breaks. */ struct { OMNI_ATTR("no_py") uint8_t x[256]; } reserved; }; /** A callback that's used to signal capture stream events. * @param[inout] stream The stream that this callback was fired from. * @param[in] type What type of event occurred. * @param[in] data Data related to this error. * @param[inout] context The user-specified callback data. * * @remarks This callback is used to signal various events that a capture stream * can encounter. * Overrun events indicate that data from the capture stream has been lost. * The callee should do whatever is appropriate to handle this situation * (e.g. toggle a warning indicator on the UI). * Device lost events indicate that an unrecoverable issue has occurred * with the audio device (such as it being unplugged) and capture cannot * continue. * * @note This callback executes from its own thread, so thread safety will need * to be considered. * This is called on the same thread as @ref CaptureDataCallback, so these * two calls can access the same data without concurrency issues. * * @note Similarly to @ref CaptureDataCallback, this callback should return as * quickly as possible to avoid causing overruns. * After an overrun has occurred, the device will be restarted immediately, * so this callback taking too long could result in another overrun callback * happening immediately after your callback returns. */ using CaptureInfoCallback = void (*)(ICaptureStream* stream, CaptureInfoType type, const CaptureInfoData* data, void* context); /** Flags to indicate some additional behaviour of the stream. */ using CaptureStreamFlags = uint32_t; /** Bypass the stream's capture buffer entirely to minimize audio capture * latency as much as possible. * When this flag is set, audio buffers received from the underlying device * will be passed directly to the capture callback. * * @note In this mode, you are at the mercy of the underlying audio system. * The buffers sent to the callback may vary in size and timing. * The bufferLength and bufferFragments parameters passed to the device * are ignored when using this flag. * Since the buffer size may vary, your callbacks must complete as fast * as possible in case the device sends you very small buffers. * * @note The audio buffer *must* be discarded before the callback returns. * This will also cause @ref ICaptureStream_abi::unlock_abi() to be a noop. * * @note If a format conversion is required, the data will be written to an * intermediate buffer that will be sent to your callback. */ constexpr CaptureStreamFlags fCaptureStreamFlagLowLatency = 0x1; /** The descriptor used to create a new @ref ICaptureStream. */ struct CaptureStreamDesc { /** Flags to indicate some additional behaviour of the stream. */ CaptureStreamFlags flags = 0; /** A callback that can be used to receive captured data. * This can be nullptr if a polling style of capture is desired. * This may not be nullptr if @ref fCaptureStreamFlagLowLatency is specified * in @ref flags. */ CaptureDataCallback dataCallback = nullptr; /** A callback that can be used to receive notifications of when an overrun occurs. * This call be nullptr if these notifications are not needed. * This callback can be used when either polling or callback style recording * are being used. */ CaptureInfoCallback errorCallback = nullptr; /** An opaque context value to be passed to the callback whenever it is performed. * This is passed to @ref dataCallback and @ref errorCallback. */ void* callbackContext = nullptr; /** A descriptor of the capture device to use for this stream. */ CaptureDeviceDesc device; }; /** Flags that alter the behavior of @ref ICaptureStream_abi::start_abi(). */ using CaptureStreamStartFlags = uint32_t; /** This will cause recording to be stopped once the full buffer has been recorded. * This may be useful if you want to capture a fixed length of data without having * to time stopping the device. * After capture has stopped, you can use @ref ICaptureStream_abi::lock_abi() to grab * the whole buffer and just use it directly. */ constexpr CaptureStreamStartFlags fCaptureStreamStartFlagOneShot = 0x1; /** Flags that alter the behavior of @ref ICaptureStream_abi::stop_abi(). */ using CaptureStreamStopFlags = uint32_t; /** If this flag is passed, the call to @ref ICaptureStream_abi::stop_abi() will block * until the capture thread has stopped. * This guarantees that no more data will be captured and no more capture * callbacks will be sent. */ constexpr CaptureStreamStopFlags fCaptureStreamStopFlagSync = 0x1; /********************************** IAudioCapture Interface **************************************/ /** An individual audio capture stream. */ class ICaptureStream_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.audio.ICaptureStream")> { protected: /** Starts capturing audio data from the stream. * * @param[in] flags Flags to alter the recording behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture is successfully started. * @returns An @ref AudioResult error code if the stream could not be started. * * @remarks Audio streams are in a stopped state when they're created. * You must call start() to start recording audio. * * @remarks Without @ref fCaptureStreamStartFlagOneShot, the stream will * perform looping capture. This means that once the ring buffer * has been filled, audio will start being recorded from the start * of the buffer again. * * @remarks Looping audio will not overwrite unread parts of the ring buffer. * Only parts of the buffer that have been unlocked can be overwritten * by the audio system. * Data written into the ring buffer must be unlocked periodically * when using looping capture or the ring buffer will fill up and * the device will overrun. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ virtual AudioResult start_abi(CaptureStreamStartFlags flags) noexcept = 0; /** Stop capturing audio data from the stream. * * @param[in] flags Flags to alter the stopping behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture was successfully stopped. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream was already stopped. * @returns An @ref AudioResult error code if something else went wrong. * The stream is likely broken in this case. * * @remarks This will stop capturing audio. Any audio data that would have * been captured between this point and the next call to @ref ICaptureStream_abi::start_abi() * will be lost. * * @remarks If there is unread data in the buffer, that data can still be * read with lock() after the stream is stopped. * * @note If fCaptureStreamStopFlagSync was not specified, the stop call will not sync with the * device so you could still receive callbacks after. * * @note CC-1180: You cannot use fCaptureStreamStopFlagSync from a callback. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ virtual AudioResult stop_abi(CaptureStreamStopFlags flags) noexcept = 0; /** Check if the stream is still capturing data. * @returns `true` if the stream is still capturing. * @returns `false` if the stream is stopped. * Callbacks will no longer be sent if `false` was returned unless the strema was * stoped with @ref ICaptureStream_abi::stop_abi() was called without fCaptureStreamStopFlagSync. */ virtual bool isCapturing_abi() noexcept = 0; /** Get the available number of frames to be read. * * @param[out] available The number of frames that can be read from the buffer. * * @returns @ref carb::audio::AudioResult::eOk if the frame count was retrieved successfully. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast enough and * the buffer filled up. * @returns @ref carb::audio::AudioResult::eNotAllowed if callback recording is being used. * @returns An @ref AudioResult error code if the operation fails for any other reason. * * @remarks This will check how much data is available to be read from the buffer. * This call is only valid when polling style recording is in use. */ virtual AudioResult getAvailableFrames_abi(OMNI_ATTR("out") size_t* available) noexcept = 0; /** Lock the next chunk of the buffer to be read. * * @param[in] request The length of the buffer to lock, in frames. * This may be 0 to lock as much data as possible. * This does not need to be a multiple of the fragment * length. * If you need to convert bytes to frames, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes() (note that this is * slow due to requiring a division). * @param[out] region Receives the audio data. * This can be `nullptr` to query the available data * in the buffer, rather than locking it. * This buffer can be held until unlock() is called; * after unlock is called, the stream can start writing * into this buffer. * @param[out] received The length of data available in @p buffer, in frames. * This will not exceed @p request. * Due to the fact that a ring buffer is used, you may * have more data in the buffer than is returned in one * call; a second call would be needed to read the full * buffer. * If you need to convert this to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * * @returns @ref carb::audio::AudioResult::eOk if the requested region is successfully locked. * @returns @ref carb::audio::AudioResult::eOutOfMemory if there is no audio data available * in the buffer yet. * @returns @ref carb::audio::AudioResult::eNotAllowed if a region is already locked * and needs to be unlocked. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream is using callback * style recording. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast * enough and the underlying device has overrun. * This will happen on some audio systems (e.g. ALSA) if the * capture buffer fills up. * This can also happen on some audio systems sporadically if the * device's timing characteristics are too aggressive. * @returns an carb::audio::AudioResult::e* error code if the region could not be locked. * * @remarks This is used to get data from the capture stream when polling * style recording is being used (ie: there is no data callback). * When using this style of recording, portions of the buffer must * be periodically locked and unlocked. * * @remarks This retrieves the next portion of the buffer. * This portion of the buffer is considered to be locked until * @ref ICaptureStream_abi::unlock_abi() is called. * Only one region of the buffer can be locked at a time. * When using a looping capture, the caller should ensure that data * is unlocked before the buffer fills up or overruns may occur. */ virtual AudioResult lock_abi(size_t request, OMNI_ATTR("*in, out") const void** region, OMNI_ATTR("out") size_t* received) noexcept = 0; /** Unlocks a previously locked region of the buffer. * * @param[in] consumed The number of frames in the previous buffer that were consumed. * Any frames that were not consumed will be returned in future * @ref ICaptureStream_abi::lock_abi() calls. * 0 is valid here if you want to have the same locked region * returned on the next lock() call. * * @returns @ref carb::audio::AudioResult::eOk if the region is successfully unlocked. * @returns @ref carb::audio::AudioResult::eOutOfRange if @p consumed was larger than * the locked region. * @returns @ref carb::audio::AudioResult::eNotAllowed if no region is currently locked. * @returns an carb::audio::AudioResult::e* error code if the region could not be unlocked. * * @remarks This unlocks a region of the buffer that was locked with a * previous call to ICaptureStream_abi::lock_abi(). * Now that this region is unlocked, the device can start writing to it, * so the caller should no longer access that region. * Once the buffer is unlocked, a new region may be locked with ICaptureStream_abi::lock_abi(). * * @note If the locked region is not fully unlocked, the part of the region that * was not unlocked will be returned on the next call to ICaptureStream_abi::lock_abi(). * A second call to unlock cannot be made in this situation, it will fail. */ virtual AudioResult unlock_abi(size_t consumed) noexcept = 0; /** Retrieve the size of the capture buffer. * * @returns The size of the capture buffer, in frames. * You can use @ref ICaptureStream_abi::getSoundFormat_abi() and @ref carb::audio::convertUnits() * to convert to bytes or other units. * * @remarks If your code is dependent on the buffer's actual size, it is * better to retrieve it with this function since the buffer size * used with device creation can be adjusted. */ virtual size_t getBufferSize_abi() noexcept = 0; /** Retrieve the number of fragments used in this stream. * * @returns The number of buffer fragments. * This is the number of regions the recording buffer is divided * into. */ virtual size_t getFragmentCount_abi() noexcept = 0; /** Retrieve the format of the audio being captured. * * @param[out] format The format of the audio being captured. * This may not be `nullptr`. */ virtual void getSoundFormat_abi(OMNI_ATTR("out") SoundFormat* format) noexcept = 0; /** Clear any data that is currently in the recording buffer. * * @returns @ref carb::audio::AudioResult::eOk if the buffer was successfully cleared. * @returns an carb::audio::AudioResult::e* error code if the buffer could not be cleared. * * @remarks This is a quick way to get rid of any data that is left in the * buffer. * This will also reset the write position on the buffer back to * 0, so the next lock call will return the start of the buffer * (this can be useful if you want to do a one shot capture of the * entire buffer). * * @note If this is called while the capture stream is recording, the stream * will be paused before it is reset. */ virtual AudioResult reset_abi() noexcept = 0; }; /** Low-Level Audio Capture Plugin Interface. * * See these pages for more detail: * @rst * :ref:`carbonite-audio-label` * :ref:`carbonite-audio-capture-label` @endrst */ class IAudioCapture { public: CARB_PLUGIN_INTERFACE("omni::audio::IAudioCapture", 0, 0) /** ABI version of createStream() * * @param[in] desc A descriptor of the settings for the stream. * @param[out] stream The raw stream object. * * @returns @ref carb::audio::AudioResult::eOk on success. @see createStream() for failure codes. */ AudioResult (*internalCreateStream)(const CaptureStreamDesc* desc, ICaptureStream** stream); /** Creates a new audio capture stream. * * @param[in] desc A descriptor of the settings for the stream. * This may be nullptr to create a context that uses the * default capture device in its preferred format. * The device's format information may later be retrieved * with getSoundFormat(). * @param[out] stream The capture stream that is being created. * * @returns @ref carb::audio::AudioResult::eOk if the stream was successfully created. * @returns @ref carb::audio::AudioResult::eInvalidParameter if @p desc is `nullptr`. * @returns @ref carb::audio::AudioResult::eOutOfMemory if the stream's allocation failed. * @returns @ref carb::audio::AudioResult::eOutOfRange if the device's index does not * correspond to a device that exists. * @returns @ref carb::audio::AudioResult::eDeviceLost if the audio device selected fails * to open. */ inline AudioResult createStream(const CaptureStreamDesc* desc, omni::core::ObjectPtr<ICaptureStream>* stream) { if (stream == nullptr) { OMNI_LOG_ERROR("stream was null"); return carb::audio::AudioResult::eInvalidParameter; } ICaptureStream* raw = nullptr; AudioResult res = internalCreateStream(desc, &raw); *stream = omni::core::steal(raw); return res; } }; } // namespace experimental } // namespace audio } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IAudioCapture.gen.h" /** @copydoc omni::audio::experimental::ICaptureStream_abi */ class omni::audio::experimental::ICaptureStream : public omni::core::Generated<omni::audio::experimental::ICaptureStream_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IAudioCapture.gen.h"
omniverse-code/kit/include/omni/inspect/IInspector.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 <omni/core/Omni.h> #include <omni/core/IObject.h> namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspector); //! Base class for object inspection requests. class IInspector_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.inspect.IInspector")> { protected: /** Set the help information for the current invocation of the inspector. For when behavior == eHelp * @param[in] helpString The help information, describing the configuration of the inspector */ virtual void setHelp_abi(OMNI_ATTR("c_str, not_null")const char* helpString) noexcept = 0; /** Returns the help information currently available on the inspector. Note that this could change * from one invocation to the next so it's important to read it immediately after requesting it. * @returns String containing the help information describing the current configuration of the inspector */ virtual OMNI_ATTR("c_str")const char* helpInformation_abi() noexcept = 0; /** Returns the common flag used to tell the inspection process to put the help information into the * inspector using the setHelp_abi function. Using this approach avoids having every inspector/object * combination add an extra ABI function just for retrieving the help information, as well as providing a * consistent method for requesting it. * @returns String containing the name of the common flag used for help information */ virtual OMNI_ATTR("c_str, not_null")const char* helpFlag_abi() noexcept = 0; /** Enable or disable an inspection flag. It's up to the individual inspection operations or the derived * inspector interfaces to interpret the flag. * @param[in] flagName Name of the flag to set * @param[in] flagState New state for the flag */ virtual void setFlag_abi(OMNI_ATTR("c_str, not_null")const char* flagName, bool flagState) noexcept = 0; /** Checks whether a particular flag is currently set or not. * @param[in] flagName Name of the flag to check * @returns True if the named flag is set, false if not */ virtual bool isFlagSet_abi(OMNI_ATTR("c_str, not_null")const char* flagName) noexcept = 0; }; } // namespace inspect } // namespace omni #include "IInspector.gen.h"
omniverse-code/kit/include/omni/inspect/IInspector.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- 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 //! Base class for object inspection requests. template <> class omni::core::Generated<omni::inspect::IInspector_abi> : public omni::inspect::IInspector_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspector") /** Set the help information for the current invocation of the inspector. For when behavior == eHelp * @param[in] helpString The help information, describing the configuration of the inspector */ void setHelp(const char* helpString) noexcept; /** Returns the help information currently available on the inspector. Note that this could change * from one invocation to the next so it's important to read it immediately after requesting it. * @returns String containing the help information describing the current configuration of the inspector */ const char* helpInformation() noexcept; /** Returns the common flag used to tell the inspection process to put the help information into the * inspector using the setHelp_abi function. Using this approach avoids having every inspector/object * combination add an extra ABI function just for retrieving the help information, as well as providing a * consistent method for requesting it. * @returns String containing the name of the common flag used for help information */ const char* helpFlag() noexcept; /** Enable or disable an inspection flag. It's up to the individual inspection operations or the derived * inspector interfaces to interpret the flag. * @param[in] flagName Name of the flag to set * @param[in] flagState New state for the flag */ void setFlag(const char* flagName, bool flagState) noexcept; /** Checks whether a particular flag is currently set or not. * @param[in] flagName Name of the flag to check * @returns True if the named flag is set, false if not */ bool isFlagSet(const char* flagName) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::inspect::IInspector_abi>::setHelp(const char* helpString) noexcept { setHelp_abi(helpString); } inline const char* omni::core::Generated<omni::inspect::IInspector_abi>::helpInformation() noexcept { return helpInformation_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspector_abi>::helpFlag() noexcept { return helpFlag_abi(); } inline void omni::core::Generated<omni::inspect::IInspector_abi>::setFlag(const char* flagName, bool flagState) noexcept { setFlag_abi(flagName, flagState); } inline bool omni::core::Generated<omni::inspect::IInspector_abi>::isFlagSet(const char* flagName) noexcept { return isFlagSet_abi(flagName); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/inspect/PyIInspector.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. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspector(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspector_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspector_abi>>, omni::core::IObject> clsParent(m, "_IInspector"); py::class_<omni::inspect::IInspector, omni::core::Generated<omni::inspect::IInspector_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspector>, omni::core::IObject> cls(m, "IInspector", R"OMNI_BIND_RAW_(Base class for object inspection requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspector>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspector>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspector instantiation"); } return tmp; })); cls.def_property( "help", nullptr, [](omni::inspect::IInspector* self, const char* helpString) { self->setHelp(helpString); }); cls.def("help_information", &omni::inspect::IInspector::helpInformation, R"OMNI_BIND_RAW_(Returns the help information currently available on the inspector. Note that this could change from one invocation to the next so it's important to read it immediately after requesting it. @returns String containing the help information describing the current configuration of the inspector)OMNI_BIND_RAW_"); cls.def("help_flag", &omni::inspect::IInspector::helpFlag, R"OMNI_BIND_RAW_(Returns the common flag used to tell the inspection process to put the help information into the inspector using the setHelp_abi function. Using this approach avoids having every inspector/object combination add an extra ABI function just for retrieving the help information, as well as providing a consistent method for requesting it. @returns String containing the name of the common flag used for help information)OMNI_BIND_RAW_"); cls.def("set_flag", [](omni::inspect::IInspector* self, const char* flagName, bool flagState) { self->setFlag(flagName, flagState); }, R"OMNI_BIND_RAW_(Enable or disable an inspection flag. It's up to the individual inspection operations or the derived inspector interfaces to interpret the flag. @param[in] flagName Name of the flag to set @param[in] flagState New state for the flag)OMNI_BIND_RAW_", py::arg("flag_name"), py::arg("flag_state")); cls.def("is_flag_set", [](omni::inspect::IInspector* self, const char* flagName) { auto return_value = self->isFlagSet(flagName); return return_value; }, R"OMNI_BIND_RAW_(Checks whether a particular flag is currently set or not. @param[in] flagName Name of the flag to check @returns True if the named flag is set, false if not)OMNI_BIND_RAW_", py::arg("flag_name")); return omni::python::PyBind<omni::inspect::IInspector>::bind(cls); }
omniverse-code/kit/include/omni/inspect/IInspectMemoryUse.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 <omni/core/Omni.h> #include "IInspector.h" namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspectMemoryUse); //! Base class for object inspection requests. class IInspectMemoryUse_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectMemoryUse")> { protected: /** Add a block of used memory * Returns false if the memory was not recorded (e.g. because it was already recorded) * * @param[in] ptr Pointer to the memory location being logged as in-use * @param[in] bytesUsed Number of bytes in use at that location */ virtual bool useMemory_abi(OMNI_ATTR("in, not_null") const void* ptr, size_t bytesUsed) noexcept = 0; /** Reset the memory usage data to a zero state */ virtual void reset_abi() noexcept = 0; /** @returns the total number of bytes of memory used since creation or the last call to reset(). */ virtual size_t totalUsed_abi() noexcept = 0; }; } // namespace inspect } // namespace oni #include "IInspectMemoryUse.gen.h"
omniverse-code/kit/include/omni/inspect/IInspectSerializer.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 <omni/core/Omni.h> #include "IInspector.h" namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspectSerializer); //! Base class for object serialization requests. class IInspectSerializer_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectSerializer")> { protected: /** Write a fixed string to the serializer output location * * @param[in] toWrite String to be written to the serializer */ virtual void writeString_abi(OMNI_ATTR("c_str, not_null") const char* toWrite) noexcept = 0; /** Write a printf-style formatted string to the serializer output location * * @param[in] fmt Formatting string in the printf() style * @param[in] args Variable list of arguments to the formatting string */ virtual OMNI_ATTR("no_py") void write_abi(OMNI_ATTR("c_str, not_null") const char* fmt, va_list args) noexcept = 0; /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * Recognizes the special file paths "cout", "stdout", "cerr", and "stderr" as the standard output streams. * * @param[in] filePath New location of the output file */ virtual void setOutputToFilePath_abi(OMNI_ATTR("c_str, not_null") const char* filePath) noexcept = 0; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ virtual void setOutputToString_abi() noexcept = 0; /** Get the current location of the output data. * * @returns Current file path where the output is going. nullptr means the output is going to a string. */ virtual const char* getOutputLocation_abi() noexcept = 0; /** Get the current output as a string. * * @returns The output that has been sent to the serializer. If the output is being sent to a file path then read * the file at that path and return the contents of the file. If the output is being sent to stdout or stderr * then nothing is returned as that output is unavailable after flushing. */ virtual const char* asString_abi() noexcept = 0; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ virtual void clear_abi() noexcept = 0; }; } // namespace inspect } // namespace omni #include "IInspectSerializer.gen.h"