file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/extension_usdz.py
# 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. # from .layers_menu import layers_available from .layers_menu import LayersMenu import omni.ext import omni.kit.app class UsdzExportExtension(omni.ext.IExt): def on_startup(self, ext_id): # Setup a callback for the event app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() self.__extensions_subscription = ext_manager.get_change_event_stream().create_subscription_to_pop( self._on_event, name="omni.kit.usdz_export" ) self.__layers_menu = None self._on_event(None) def _on_event(self, event): # Create/destroy the menu in the Layers window if self.__layers_menu: if not layers_available(): self.__layers_menu.destroy() self.__layers_menu = None else: if layers_available(): self.__layers_menu = LayersMenu() def on_shutdown(self): self.__extensions_subscription = None if self.__layers_menu: self.__layers_menu.destroy() self.__layers_menu = None
1,530
Python
33.795454
106
0.65817
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/layers_menu.py
# 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. # from .utils import is_extension_loaded, copy, list_folder_async from pxr import Sdf, Usd from pathlib import Path from zipfile import ZipFile from functools import partial from typing import Callable, List from omni.kit.window.file_exporter import get_file_exporter from omni.kit.widget.prompt import PromptManager import carb import omni.kit.tool.collect as collect import omni.usd import asyncio import tempfile import os import shutil import omni.kit.app import omni.kit.notification_manager as nm def layers_available() -> bool: """Returns True if the extension "omni.kit.widget.layers" is loaded""" return is_extension_loaded("omni.kit.widget.layers") async def usdz_export(identifier, export_path): try: target_out = export_path carb.log_info(f"Starting to export layer '{identifier}' to '{target_out}'") prompt = PromptManager.post_simple_prompt("Please Wait", "Exporting to USDZ...", ok_button_info=None, modal=True) # Waits for prompt to be shown await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() layer = Sdf.Layer.FindOrOpen(identifier) if not layer: message = f"Failed to export layer {identifier} as it does not exist." carb.log_error(message) nm.post_notification(message, status=nm.NotificationStatus.WARNING) return with tempfile.TemporaryDirectory() as tmp_path: tmp_path = Path(tmp_path) collect_path = tmp_path.joinpath("collected") split_ext = os.path.splitext(identifier) # Can't collect USDZ files because MDLs can't be resolved if (split_ext[1] == '.usdz'): input_usdz_temp_path = str(tmp_path.joinpath('temp_copy.usdz')) await copy(identifier, str(input_usdz_temp_path)) with ZipFile(input_usdz_temp_path, 'r') as zip_ref: zip_ref.extractall(str(tmp_path)) tmp_file_path = str(tmp_path.joinpath("main.usdc")) layer.Export(tmp_file_path) entry_layer_to_collect = tmp_file_path elif not omni.usd.is_usd_writable_filetype(identifier) or identifier.startswith('anon'): tmp_file_path = str(tmp_path.joinpath("main.usdc")) layer.Export(tmp_file_path) entry_layer_to_collect = tmp_file_path else: entry_layer_to_collect = identifier collector = collect.Collector(entry_layer_to_collect, str(collect_path), flat_collection=True) await collector.collect(None, None) # must create USDZ locally because the UsdUtils package cannot handle omniverse:// URIs absolute_paths, relative_paths = await list_folder_async(str(collect_path)) local_out_path = collect_path.joinpath("local_out.usdz") # Create usdz package manually without using USD API as it cannot handle UDIM textures. zip_writer = Usd.ZipFileWriter.CreateNew(str(local_out_path)) with zip_writer: for absolute_path, relative_path in zip(absolute_paths, relative_paths): url = omni.client.break_url(absolute_path) absolute_path = url.path # FIXME: omni.client will return windows path prefixed with '/' if os.name == "nt" and absolute_path[0] == '/': absolute_path = absolute_path[1:] zip_writer.AddFile(absolute_path, relative_path) await copy(str(local_out_path), target_out) layer = None zip_writer = None finally: prompt.visible = False prompt = None carb.log_info(f"Finished exporting layer '{identifier}' to '{target_out}'") def export(objects): """Export the target layer to USDZ""" def on_export(callback: Callable, flatten: bool, filename: str, dirname: str, extension: str = '', selections: List[str] = []): nonlocal objects path = f"{dirname}/{filename}{extension}" item = objects["item"] identifier = item().identifier asyncio.ensure_future(usdz_export(identifier, path)) file_picker = get_file_exporter() file_picker.show_window( title="Export To USDZ", export_button_label="Export", export_handler=partial(on_export, None, False), file_extension_types=[(".usdz", "Zipped package")] ) class LayersMenu: """ When this object is alive, Layers 2.0 has an additional action for exporting the layer to USDZ. """ def __init__(self): import omni.kit.widget.layers as layers self.__menu_subscription = layers.ContextMenu.add_menu( [ {"name": ""}, { "name": "Export USDZ", "glyph": "menu_rename.svg", "show_fn": [ layers.ContextMenu.is_layer_item, layers.ContextMenu.is_not_missing_layer, layers.ContextMenu.is_layer_not_locked_by_other, layers.ContextMenu.is_layer_and_parent_unmuted ], "onclick_fn": export, } ] ) def destroy(self): """Remove the menu from Layers 2.0""" self.__menu_subscription = None
5,903
Python
38.891892
131
0.614942
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/utils.py
# 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. # import os import omni.kit.app import traceback import carb import omni.client import omni.client.utils as clientutils def is_extension_loaded(extansion_name: str) -> bool: """ Returns True if the extension with the given name is loaded. """ def is_ext(id: str, extension_name: str) -> bool: id_name = id.split("-")[0] return id_name == extension_name app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() extensions = ext_manager.get_extensions() loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None) return not not loaded async def copy(src_path: str, dest_path: str): carb.log_info(f"Copying from {src_path} to {dest_path}...") try: result = await omni.client.copy_async(src_path, dest_path, omni.client.CopyBehavior.OVERWRITE) if result != omni.client.Result.OK: carb.log_error(f"Cannot copy from {src_path} to {dest_path}, error code: {result}.") return False else: return True except Exception as e: traceback.print_exc() carb.log_error(str(e)) return False async def list_folder_async(folder_path): def compute_absolute_path(base_path, is_base_path_folder, path, is_path_folder): if is_base_path_folder and not base_path.endswith("/"): base_path += "/" if is_path_folder and not path.endswith("/"): path += "/" return clientutils.make_absolute_url_if_possible(base_path, path) def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix) :] return text absolute_paths = [] relative_paths = [] result, entry = await omni.client.stat_async(folder_path) if result == omni.client.Result.OK and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN: is_folder = True else: is_folder = False folder_path = clientutils.make_file_url_if_possible(folder_path) if not is_folder: absolute_paths = [folder_path] relative_paths = [os.path.basename(folder_path)] else: if not folder_path.endswith("/"): folder_path += "/" folder_queue = [folder_path] while len(folder_queue) > 0: folder = folder_queue.pop(0) (result, entries) = await omni.client.list_async(folder) if result != omni.client.Result.OK: break folders = set((e.relative_path for e in entries if e.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN)) for f in folders: folder_queue.append(compute_absolute_path(folder, True, f, False)) files = set((e.relative_path for e in entries if not e.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN)) for file in files: absolute_path = compute_absolute_path(folder, True, file, False) absolute_paths.append(absolute_path) relative_path = remove_prefix(absolute_path, folder_path[:-1]) relative_path = relative_path.replace("\\", "/") if relative_path != "/" and relative_path.startswith("/"): relative_path = relative_path[1:] if len(relative_path) > 0: relative_paths.append(relative_path) return absolute_paths, relative_paths
3,859
Python
36.115384
116
0.63177
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/tests/usdz_export_test.py
## 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. ## from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import Usd from pxr import UsdGeom import carb import omni.client import omni.kit import omni.usd import os import time import unittest from omni.kit.usdz_export import usdz_export OMNI_SERVER = "omniverse://ov-test" class TestUsdzExport(OmniUiTest): def get_test_dir(self): token = carb.tokens.get_tokens_interface() data_dir = token.resolve("${data}") return f"{data_dir}" async def test_export_usdz_file(self): usdz_size = 2600000 usdz_size_tc = 2675966 current_path = Path(__file__) test_data_path = current_path.parent.parent.parent.parent.parent.joinpath("data") test_stage_path = str(test_data_path.joinpath("test_stage").joinpath("scene.usd")) test_dir = self.get_test_dir() export_file_path = Path(test_dir).joinpath("out.usdz").resolve() await usdz_export(test_stage_path, export_file_path.__str__()) self.assertTrue(os.path.isfile(export_file_path.__str__()), 'out.usdz does not exist') size = os.stat(export_file_path).st_size self.assertTrue(size >= usdz_size and size <= usdz_size_tc, f'File size mismatch, expected {usdz_size} but got {size}')
1,702
Python
36.844444
127
0.706228
omniverse-code/kit/exts/omni.kit.usdz_export/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-11-08 - Add "omni.kit.window.file_exporter" as dependency. ## [1.0.0] - 2022-08-18 - Initial extension.
137
Markdown
14.333332
52
0.635036
omniverse-code/kit/fabric/include/carb/flatcache/IToken.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Interface.h> #ifndef __CUDACC__ // InterfaceUtils.h provides carb::getCachedInterface and is not CUDA-compatible #include <carb/InterfaceUtils.h> #endif // __CUDACC__ // Set to empty macro when IToken::iToken static member is removed #define FLATCACHE_ITOKEN_INIT \ const carb::flatcache::IToken* carb::flatcache::iToken = nullptr; namespace carb { namespace flatcache { // TokenC are integer keys that identify paths to C-ABI interfaces struct TokenC { uint64_t token; // Note that in the name comparisons below we mask off USD's lifetime bit. // For example, tokens created from the same string are considered equal even // if one was created with finite lifetime and the other infinite lifetime. constexpr bool operator<(const TokenC& other) const { return (token & ~1) < (other.token & ~1); } constexpr bool operator==(const TokenC& other) const { return (token & ~1) == (other.token & ~1); } constexpr bool operator!=(const TokenC& other) const { return (token & ~1) != (other.token & ~1); } }; static_assert(std::is_standard_layout<TokenC>::value, "Struct must be standard layout as it is used in C-ABI interfaces"); // We don't reference count the uninitialized (or empty) token, and we use // this fact to avoid unnecessary dll calls to addRef()/removeRef(), for // example during std::vector resize. To do this we need to check whether a // token is uninitialized without the dll call getEmptyToken(), so we store // its value here in a constant. // We run automated test "IToken::getEmptyToken() dll call can be replaced with // constant, kUninitializedToken" to ensure that this constant never // changes. static constexpr TokenC kUninitializedToken{0}; // C-ABI interface to pxr::TfToken struct IToken { CARB_PLUGIN_INTERFACE("carb::flatcache::IToken", 0, 1); TokenC (*getHandle)(const char* name); const char* (*getText)(TokenC handle); void (*addRef)(TokenC handle); void (*removeRef)(TokenC handle); TokenC (*getEmptyToken)(); uint64_t (*size)(TokenC handle); }; // C++ wrapper for IToken class Token { static carb::flatcache::IToken& sIToken(); public: // DEPRECATED: keeping for binary compatibility // Will be removed in October 2021 - @TODO set FLATCACHE_ITOKEN_INIT to empty macro when removed! // Still safe to use if initialized in a given dll static const carb::flatcache::IToken* iToken; Token() : mHandle(kUninitializedToken) { } Token(const char* string) { mHandle = sIToken().getHandle(string); } // Needs to be noexcept for std::vector::resize() to move instead of copy ~Token() noexcept { #ifndef __CUDACC__ if (mHandle != kUninitializedToken) { if (!carb::isFrameworkValid()) { return; } // IToken can be nullptr durin exit process if (auto iToken = carb::getCachedInterface<carb::flatcache::IToken>()) { iToken->removeRef(mHandle); } } #endif // __CUDACC__ } // Copy constructor Token(const Token& other) : mHandle(other.mHandle) { if (mHandle != kUninitializedToken) { sIToken().addRef(mHandle); } } // Copy construct from integer Token(TokenC token) : mHandle(token) { if (mHandle != kUninitializedToken) { sIToken().addRef(mHandle); } } // Move constructor // Needs to be noexcept for std::vector::resize() to move instead of copy Token(Token&& other) noexcept { // We are moving the src handle so don't need to change its refcount mHandle = other.mHandle; // Make source invalid other.mHandle = kUninitializedToken; } // Copy assignment Token& operator=(const Token& other) { if (this != &other) { if (mHandle != kUninitializedToken) { sIToken().removeRef(mHandle); } mHandle = other.mHandle; if (other.mHandle != kUninitializedToken) { sIToken().addRef(mHandle); } } return *this; } // Move assignment Token& operator=(Token&& other) noexcept { if (&other == this) return *this; // We are about to overwrite the dest handle, so decrease its refcount if (mHandle != kUninitializedToken) { sIToken().removeRef(mHandle); } // We are moving the src handle so don't need to change its refcount mHandle = other.mHandle; other.mHandle = kUninitializedToken; return *this; } const char* getText() const { return sIToken().getText(mHandle); } uint64_t size() const { return sIToken().size(mHandle); } std::string getString() const { return std::string(sIToken().getText(mHandle), sIToken().size(mHandle)); } // Note that in the name comparisons below TokenC masks off USD's lifetime bit. // In other words, tokens created from the same string are considered equal even // if one was created with finite lifetime and the other infinite lifetime. constexpr bool operator<(const Token& other) const { return mHandle < other.mHandle; } constexpr bool operator!=(const Token& other) const { return mHandle != other.mHandle; } constexpr bool operator==(const Token& other) const { return mHandle == other.mHandle; } constexpr operator TokenC() const { return mHandle; } private: TokenC mHandle; }; static_assert(std::is_standard_layout<Token>::value, "Token must be standard layout as it is used in C-ABI interfaces"); #ifndef __CUDACC__ inline carb::flatcache::IToken& Token::sIToken() { // Acquire carbonite interface on first use carb::flatcache::IToken* iToken = carb::getCachedInterface<carb::flatcache::IToken>(); CARB_ASSERT(iToken); return *iToken; } #endif // __CUDACC__ inline uint64_t swapByteOrder(uint64_t val) { #if !CARB_COMPILER_MSC // Compilers other than MSVC tend to turn the following into a single instruction like bswap val = ((val & 0xFF00000000000000u) >> 56u) | ((val & 0x00FF000000000000u) >> 40u) | ((val & 0x0000FF0000000000u) >> 24u) | ((val & 0x000000FF00000000u) >> 8u) | ((val & 0x00000000FF000000u) << 8u) | ((val & 0x0000000000FF0000u) << 24u) | ((val & 0x000000000000FF00u) << 40u) | ((val & 0x00000000000000FFu) << 56u); #else // MSVC does not currently optimize the above code, so we have to use an intrinsic to get bswap val = _byteswap_uint64(val); #endif return val; } inline size_t hash(TokenC token) { size_t tokenWithoutMortalityBit = token.token & ~1; // The following Hash function was chosen to match the one in pxr\base\tf\hash.h // This is based on Knuth's multiplicative hash for integers. The // constant is the closest prime to the binary expansion of the inverse // golden ratio. The best way to produce a hash table bucket index from // the result is to shift the result right, since the higher order bits // have the most entropy. But since we can't know the number of buckets // in a table that's using this, we just reverse the byte order instead, // to get the highest entropy bits into the low-order bytes. return swapByteOrder(tokenWithoutMortalityBit * 11400714819323198549ULL); } inline size_t hash(Token const& token) { return hash(TokenC(token)); } } } namespace std { template <> struct hash<carb::flatcache::Token> { std::size_t operator()(const carb::flatcache::Token& key) const { return carb::flatcache::hash(key); } }; template <> class hash<carb::flatcache::TokenC> { public: size_t operator()(const carb::flatcache::TokenC& key) const { return carb::flatcache::hash(key); } }; }
8,572
C
27.768456
122
0.640457
omniverse-code/kit/fabric/include/carb/flatcache/Defines.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once // Improved #define preprocessor directives that support compile-time checking for mispelled or missing // directives. Basically, the same as #define MY_FEATURE 0/1, but with a bit more compile-time safety, // and ease of use around mixing or combining boolean logic. // // Example usage: // #define MY_FEATURE_A IN_USE // #define MY_FEATURE_B NOT_IN_USE // #define MY_FEATURE_C USE_IF( USING( MY_FEATURE_A ) && USING( MY_FEATURE_B ) ) // ... // void doStuff() // { // #if USING( MY_FEATURE_C ) // doStuff_C(); // #else // #if USING( MY_FEATURE_C ) // doStuff_NotC(); // #endif // #if USING( MY_FEATURE_C ) // } #define IN_USE && #define NOT_IN_USE &&! #define USE_IF(X) &&((X)?1:0)&& #define USING(X) (1 X 1) #ifndef NDEBUG #define DEVELOPMENT_BUILD IN_USE #else // #ifndef NDEBUG #define DEVELOPMENT_BUILD NOT_IN_USE #endif // #ifndef NDEBUG #ifdef _WIN32 #define WINDOWS_BUILD IN_USE #define LINUX_BUILD NOT_IN_USE #elif defined(__linux__) // #ifdef _WIN32 #define WINDOWS_BUILD NOT_IN_USE #define LINUX_BUILD IN_USE #else // #elif defined(__linux__) // #ifdef _WIN32 #error "Unsupported platform" #endif #define ASSERTS USE_IF( USING( DEVELOPMENT_BUILD ) )
1,630
C
29.203703
103
0.707975
omniverse-code/kit/fabric/include/carb/flatcache/WrapperImpl.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 // The purpose of this file is to implement the C++ classes StageInProgress, // StageAtTime, StageAtTimeInterval and StageHistoryWindow by calling the // carbonite C-ABI interfaces, IStageInProgress, IStageAtTime, // IStageAtTimeWindow and IStageHistoryWindow. // // #include "StageWithHistory.h" #include <carb/InterfaceUtils.h> #include <carb/logging/Log.h> #include <type_traits> #include <cstdint> namespace carb { namespace flatcache { // StageInProgress implementation starts here // RAII constructor inline StageInProgress::StageInProgress(StageWithHistory& stageWithHistory, size_t simFrameNumber) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); m_stageInProgress = iStageInProgress->create(stageWithHistory.m_usdStageId, simFrameNumber); m_usdStageId = stageWithHistory.m_usdStageId; m_createdFromId = false; } // Non-RAII constructor inline StageInProgress::StageInProgress(StageInProgressId stageInProgressId) { m_stageInProgress = stageInProgressId; m_createdFromId = true; // m_usdStageId is not valid when m_createdFromId==true } inline StageInProgress::~StageInProgress() { if (!m_createdFromId) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->destroy(m_usdStageId); } } inline size_t StageInProgress::getFrameNumber() { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); return iStageInProgress->getFrameNumber(m_stageInProgress); } inline ValidMirrors StageInProgress::getAttributeValidBits(const Path& path, const Token& attrName) const { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); return iStageInProgress->getAttributeValidBits(m_stageInProgress, path, attrName); } inline RationalTime StageInProgress::getFrameTime() { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); return iStageInProgress->getFrameTime(m_stageInProgress); } template <typename T> T* StageInProgress::getAttribute(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC ptrAndSize = iStageInProgress->getAttribute(m_stageInProgress, path, attrName); if (sizeof(T) == ptrAndSize.elementSize) { return reinterpret_cast<T*>(ptrAndSize.ptr); } else { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), ptrAndSize.elementSize); return nullptr; } } template <typename T> const T* StageInProgress::getAttributeRd(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); ConstSpanC ptrAndSize = iStageInProgress->getAttributeRd(m_stageInProgress, path, attrName); if (sizeof(T) == ptrAndSize.elementSize) { return reinterpret_cast<const T*>(ptrAndSize.ptr); } else { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), ptrAndSize.elementSize); return nullptr; } } template <typename T> T* StageInProgress::getAttributeWr(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC ptrAndSize = iStageInProgress->getAttributeWr(m_stageInProgress, path, attrName); if (sizeof(T) == ptrAndSize.elementSize) { return reinterpret_cast<T*>(ptrAndSize.ptr); } else { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), ptrAndSize.elementSize); return nullptr; } } template <typename T> T* StageInProgress::getAttributeGpu(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC ptrAndSize = iStageInProgress->getAttributeGpu(m_stageInProgress, path, attrName); if (sizeof(T) == ptrAndSize.elementSize) { return reinterpret_cast<T*>(ptrAndSize.ptr); } else { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), ptrAndSize.elementSize); return nullptr; } } template <typename T> const T* StageInProgress::getAttributeRdGpu(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); ConstSpanC ptrAndSize = iStageInProgress->getAttributeRdGpu(m_stageInProgress, path, attrName); if (sizeof(T) == ptrAndSize.elementSize) { return reinterpret_cast<const T*>(ptrAndSize.ptr); } else { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), ptrAndSize.elementSize); return nullptr; } } template <typename T> T* StageInProgress::getAttributeWrGpu(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC ptrAndSize = iStageInProgress->getAttributeWrGpu(m_stageInProgress, path, attrName); if (sizeof(T*) == ptrAndSize.elementSize) { return reinterpret_cast<T*>(ptrAndSize.ptr); } else { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), ptrAndSize.elementSize); return nullptr; } } template <typename T> T& StageInProgress::getOrCreateAttributeWr(const Path& path, const Token& attrName, Type type) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC ptrAndSize = iStageInProgress->getOrCreateAttributeWr(m_stageInProgress, path, attrName, TypeC(type)); if (sizeof(T) != ptrAndSize.elementSize) { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), ptrAndSize.elementSize); } return *reinterpret_cast<T*>(ptrAndSize.ptr); } template <typename T> gsl::span<T> StageInProgress::getArrayAttribute(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC arrayData = iStageInProgress->getArrayAttributeWr(m_stageInProgress, path, attrName); if (sizeof(T) != arrayData.elementSize) { CARB_LOG_WARN_ONCE( "Trying to access array with elements of size %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), arrayData.elementSize); return gsl::span<T>(); } gsl::span<T> retval(reinterpret_cast<T*>(arrayData.ptr), arrayData.elementCount); return retval; } template <typename T> gsl::span<const T> StageInProgress::getArrayAttributeRd(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); ConstSpanC arrayData = iStageInProgress->getArrayAttributeRd(m_stageInProgress, path, attrName); if (sizeof(T) != arrayData.elementSize) { CARB_LOG_WARN_ONCE( "Trying to access array with elements of size %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), arrayData.elementSize); return gsl::span<const T>(); } gsl::span<const T> retval(reinterpret_cast<const T*>(arrayData.ptr), arrayData.elementCount); return retval; } template <typename T> gsl::span<T> StageInProgress::getArrayAttributeWr(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC arrayData = iStageInProgress->getArrayAttributeWr(m_stageInProgress, path, attrName); if (sizeof(T) != arrayData.elementSize) { CARB_LOG_WARN_ONCE( "Trying to access array with elements of size %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), arrayData.elementSize); return gsl::span<T>(); } gsl::span<T> retval(reinterpret_cast<T*>(arrayData.ptr), arrayData.elementCount); return retval; } inline size_t StageInProgress::getArrayAttributeSize(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); return iStageInProgress->getArrayAttributeSize(m_stageInProgress, path, attrName); } inline void StageInProgress::setArrayAttributeSize(const Path& path, const Token& attrName, size_t elemCount) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->setArrayAttributeSize(m_stageInProgress, path, attrName, elemCount); } template <typename T> inline gsl::span<T> StageInProgress::setArrayAttributeSizeAndGet(const PrimBucketList& primBucketList, size_t primBucketListIndex, size_t indexInBucket, const Token& attrName, size_t newElemCount) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); SpanC newArrayC = iStageInProgress->setArrayAttributeSizeAndGet( m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, indexInBucket, attrName, newElemCount); T* typedElementsPtr = reinterpret_cast<T*>(newArrayC.ptr); return { typedElementsPtr, newArrayC.elementCount }; } inline void StageInProgress::createPrim(const Path& path) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->createPrim(m_stageInProgress, path); } inline void StageInProgress::destroyPrim(const Path& path) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->destroyPrim(m_stageInProgress, path); } inline void StageInProgress::createAttribute(const Path& path, const Token& attrName, Type type) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->createAttribute(m_stageInProgress, path, attrName, TypeC(type)); } template <int n> inline void StageInProgress::createAttributes(const Path& path, std::array<AttrNameAndType, n> attributes) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); std::array<TokenC, n> names; std::array<TypeC, n> types; for (int c = 0; c < n; ++c) { names[c] = attributes[c].name; types[c] = TypeC(attributes[c].type); } iStageInProgress->createAttributes(m_stageInProgress, path, names.data(), types.data(), n); } inline void StageInProgress::destroyAttribute(const Path& path, const Token& attrName, Type) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->destroyAttribute2(m_stageInProgress, path, attrName); } inline void StageInProgress::destroyAttribute(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->destroyAttribute2(m_stageInProgress, path, attrName); } template <int n> inline void StageInProgress::destroyAttributes(const Path& path, const std::array<Token, n>& attributes) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); std::array<TokenC, n> names; for (int c = 0; c < n; ++c) { names[c] = TokenC(attributes[c]); } iStageInProgress->destroyAttributes(m_stageInProgress, path, names.data(), n); } inline void StageInProgress::destroyAttributes(const Path& path, const std::vector<Token>& attributes) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); const size_t n = attributes.size(); std::vector<TokenC> names(n); for (size_t c = 0; c < n; ++c) { names[c] = TokenC(attributes[c]); } iStageInProgress->destroyAttributes(m_stageInProgress, path, names.data(), (uint32_t)n); } inline PrimBucketList StageInProgress::findPrims(const carb::flatcache::set<AttrNameAndType>& all, const carb::flatcache::set<AttrNameAndType>& any, const carb::flatcache::set<AttrNameAndType>& none) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); PrimBucketListId primBucketListId = iStageInProgress->findPrims(m_stageInProgress, all, any, none); return { primBucketListId }; } inline void StageInProgress::attributeEnableChangeTracking(const Token& attrName, ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); iChangeTrackerConfig->attributeEnable(m_stageInProgress, attrName, listenerId); } inline void StageInProgress::enablePrimCreateTracking(ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); iChangeTrackerConfig->enablePrimCreateTracking(m_stageInProgress, listenerId); } inline void StageInProgress::attributeDisableChangeTracking(const Token& attrName, ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); iChangeTrackerConfig->attributeDisable(m_stageInProgress, attrName, listenerId); } inline void StageInProgress::pauseChangeTracking(ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); iChangeTrackerConfig->pause(m_stageInProgress, listenerId); } inline void StageInProgress::resumeChangeTracking(ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); iChangeTrackerConfig->resume(m_stageInProgress, listenerId); } inline bool StageInProgress::isChangeTrackingPaused(ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); return iChangeTrackerConfig->isChangeTrackingPaused(m_stageInProgress, listenerId); } inline bool StageInProgress::isListenerAttached(ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); return iChangeTrackerConfig->isListenerAttached(m_stageInProgress, listenerId); } inline void StageInProgress::detachListener(ListenerId listenerId) { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); iChangeTrackerConfig->detachListener(m_stageInProgress, listenerId); } inline size_t StageInProgress::getListenerCount() { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IChangeTrackerConfig>(); return iChangeTrackerConfig->getListenerCount(m_stageInProgress); } inline ChangedPrimBucketList StageInProgress::getChanges(ListenerId listenerId) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); PrimBucketListId changeListId = iStageInProgress->getChanges(m_stageInProgress, listenerId); return ChangedPrimBucketList(changeListId); } inline void StageInProgress::popChanges(ListenerId listenerId) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->popChanges(m_stageInProgress, listenerId); } template <typename T> gsl::span<T> StageInProgress::getAttributeArray(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) { SpanC array; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getAttributeArray( &array, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); T* typedElementsPtr = reinterpret_cast<T*>(array.ptr); gsl::span<T> retval(typedElementsPtr, array.elementCount); return retval; } template <typename T> gsl::span<const T> StageInProgress::getAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { ConstSpanC array; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getAttributeArrayRd( &array, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); const T* typedElementsPtr = reinterpret_cast<const T*>(array.ptr); gsl::span<const T> retval(typedElementsPtr, array.elementCount); return retval; } template <typename T> gsl::span<T> StageInProgress::getAttributeArrayWr(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) { SpanC array; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getAttributeArrayWr( &array, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); T* typedElementsPtr = reinterpret_cast<T*>(array.ptr); gsl::span<T> retval(typedElementsPtr, array.elementCount); return retval; } template <typename T> gsl::span<T> StageInProgress::getAttributeArrayGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) { SpanC array; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getAttributeArrayGpu( &array, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); T* typedElementsPtr = reinterpret_cast<T*>(array.ptr); gsl::span<T> retval(typedElementsPtr, array.elementCount); return retval; } template <typename T> gsl::span<const T> StageInProgress::getAttributeArrayRdGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { ConstSpanC array; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getAttributeArrayRdGpu( &array, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); const T* typedElementsPtr = reinterpret_cast<const T*>(array.ptr); gsl::span<const T> retval(typedElementsPtr, array.elementCount); return retval; } template <typename T> gsl::span<T> StageInProgress::getAttributeArrayWrGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) { SpanC array; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getAttributeArrayWrGpu( &array, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); T* typedElementsPtr = reinterpret_cast<T*>(array.ptr); gsl::span<T> retval(typedElementsPtr, array.elementCount); return retval; } template <typename T> gsl::span<T> StageInProgress::getOrCreateAttributeArrayWr(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName, Type type) { SpanC array; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getOrCreateAttributeArrayWr( &array, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName, TypeC(type)); T* typedElementsPtr = reinterpret_cast<T*>(array.ptr); gsl::span<T> retval(typedElementsPtr, array.elementCount); return retval; } template <typename T> std::vector<gsl::span<T>> StageInProgress::getArrayAttributeArray(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); ArrayPointersAndSizesC pointersAndSizes = iStageInProgress->getArrayAttributeArrayWithSizes( m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); size_t primCount = pointersAndSizes.elementCount; std::vector<gsl::span<T>> arrays(primCount); for (size_t i = 0; i != primCount; i++) { T* typedElementsPtr = reinterpret_cast<T*>(pointersAndSizes.arrayPtrs[i]); arrays[i] = { typedElementsPtr, pointersAndSizes.sizes[i] }; } return arrays; } template <typename T> std::vector<gsl::span<const T>> StageInProgress::getArrayAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); ConstArrayPointersAndSizesC pointersAndSizes = iStageInProgress->getArrayAttributeArrayWithSizesRd( m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); size_t primCount = pointersAndSizes.elementCount; std::vector<gsl::span<const T>> arrays(primCount); for (size_t i = 0; i != primCount; i++) { const T* typedElementsPtr = reinterpret_cast<const T*>(pointersAndSizes.arrayPtrs[i]); arrays[i] = { typedElementsPtr, pointersAndSizes.sizes[i] }; } return arrays; } template <typename T> std::vector<gsl::span<T>> StageInProgress::getArrayAttributeArrayWr(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); ArrayPointersAndSizesC pointersAndSizes = iStageInProgress->getArrayAttributeArrayWithSizesWr( m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex, attrName); size_t primCount = pointersAndSizes.elementCount; std::vector<gsl::span<T>> arrays(primCount); for (size_t i = 0; i != primCount; i++) { T* typedElementsPtr = reinterpret_cast<T*>(pointersAndSizes.arrayPtrs[i]); arrays[i] = { typedElementsPtr, pointersAndSizes.sizes[i] }; } return arrays; } inline gsl::span<const Path> StageInProgress::getPathArray(const PrimBucketList& primBucketList, size_t primBucketListIndex) const { ConstPathCSpan arrayC; auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->getPathArray(&arrayC, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex); const Path* array = reinterpret_cast<const Path*>(arrayC.ptr); gsl::span<const Path> retval(array, arrayC.elementCount); return retval; } inline void StageInProgress::printBucketNames() const { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->printBucketNames(m_stageInProgress); } inline void StageInProgress::logAttributeWriteForNotice(const Path& path, const Token& attrName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->logAttributeWriteForNotice(m_stageInProgress, path, attrName); } inline flatcache::set<AttrNameAndType> StageInProgress::getAttributeNamesAndTypes(const PrimBucketList& primBucketList, size_t primBucketListIndex) const { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); size_t attrCount = iStageInProgress->getBucketAttributeCount( m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex); flatcache::set<AttrNameAndType> namesAndTypes; namesAndTypes.v.resize(attrCount); // getBucketAttributeNamesAndTypes is guaranteed to return an ordered vector, so we don't have to sort namesAndTypes iStageInProgress->getBucketAttributeNamesAndTypes( namesAndTypes.data(), attrCount, m_stageInProgress, primBucketList.m_primBucketListId, primBucketListIndex); return namesAndTypes; } // Connection API inline void StageInProgress::createConnection(const Path& path, const Token& connectionName, const Connection& connection) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->createConnection(m_stageInProgress, path, connectionName, connection); } inline void StageInProgress::createConnections(const Path& path, const gsl::span<Token>& connectionNames, const gsl::span<Connection>& connections ) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); if(connectionNames.size() != connections.size()) return; const TokenC* namesC = reinterpret_cast<const TokenC*>(connectionNames.data()); iStageInProgress->createConnections(m_stageInProgress, path, namesC, connections.data(), connectionNames.size()); } inline void StageInProgress::destroyConnection(const Path& path, const Token& connectionName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->destroyConnection(m_stageInProgress, path, connectionName); } inline void StageInProgress::destroyConnections(const Path& path, const gsl::span<Token>& connectionNames) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); const TokenC* namesC = reinterpret_cast<const TokenC*>(connectionNames.data()); iStageInProgress->destroyConnections(m_stageInProgress, path, namesC, connectionNames.size()); } inline Connection* StageInProgress::getConnection(const Path& path, const Token& connectionName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); return iStageInProgress->getConnection(m_stageInProgress, path, connectionName); } inline const Connection* StageInProgress::getConnectionRd(const Path& path, const Token& connectionName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); return iStageInProgress->getConnectionRd(m_stageInProgress, path, connectionName); } inline Connection* StageInProgress::getConnectionWr(const Path& path, const Token& connectionName) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); return iStageInProgress->getConnectionWr(m_stageInProgress, path, connectionName); } inline void StageInProgress::copyAttributes(const Path& srcPath, const Path& dstPath) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); iStageInProgress->copyAllAttributes(m_stageInProgress, srcPath, dstPath); } inline void StageInProgress::copyAttributes(const Path& srcPath, const gsl::span<Token>& srcAttrs, const Path& dstPath) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); size_t n = srcAttrs.size(); const TokenC* srcAttrsC = reinterpret_cast<const TokenC*>(srcAttrs.data()); iStageInProgress->copySpecifiedAttributes(m_stageInProgress, srcPath, srcAttrsC, dstPath, srcAttrsC, n); } inline void StageInProgress::copyAttributes(const Path& srcPath, const gsl::span<Token>& srcAttrs, const Path& dstPath, const gsl::span<Token>& dstAttrs) { auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); if(srcAttrs.size() != dstAttrs.size()) { return; } size_t n = srcAttrs.size(); const TokenC* srcAttrsC = reinterpret_cast<const TokenC*>(srcAttrs.data()); const TokenC* dstAttrsC = reinterpret_cast<const TokenC*>(dstAttrs.data()); iStageInProgress->copySpecifiedAttributes(m_stageInProgress, srcPath, srcAttrsC, dstPath, dstAttrsC, n); } inline bool StageInProgress::primExists(const Path& path) { auto iStageReaderWriter = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); bool retval = iStageReaderWriter->getAttributeCount(m_stageInProgress, path) != 0; return retval; } // PrimBucketList implementation starts here inline carb::flatcache::IPrimBucketList* PrimBucketList::sIPrimBucketList() { // Acquire carbonite interface on first use return carb::getCachedInterface<carb::flatcache::IPrimBucketList>(); } inline size_t PrimBucketList::bucketCount() const { return sIPrimBucketList()->getBucketCount(m_primBucketListId); } inline size_t PrimBucketList::size() const { return sIPrimBucketList()->getBucketCount(m_primBucketListId); } inline void PrimBucketList::print() const { return sIPrimBucketList()->print(m_primBucketListId); } inline PrimBucketList::~PrimBucketList() { sIPrimBucketList()->destroy(m_primBucketListId); } inline BucketChanges ChangedPrimBucketList::getChanges(size_t index) { return BucketChanges(sIPrimBucketList()->getChanges(m_primBucketListId, index)); } inline AddedPrimIndices ChangedPrimBucketList::getAddedPrims(size_t index) { return AddedPrimIndices(sIPrimBucketList()->getAddedPrims(m_primBucketListId, index)); } // StageAtTimeInterval implementation starts here inline carb::flatcache::IStageAtTimeInterval* StageAtTimeInterval::sIStageAtTimeInterval() { return carb::getCachedInterface<carb::flatcache::IStageAtTimeInterval>(); } inline StageAtTimeInterval::StageAtTimeInterval(StageWithHistory& stageWithHistory, RationalTime beginTime, RationalTime endTime, bool includeEndTime) { m_stageAtTimeInterval = sIStageAtTimeInterval()->create(stageWithHistory.m_stageWithHistory, beginTime, endTime, includeEndTime); } inline StageAtTimeInterval::StageAtTimeInterval(StageWithHistoryId stageWithHistoryId, RationalTime beginTime, RationalTime endTime, bool includeEndTime) { m_stageAtTimeInterval = sIStageAtTimeInterval()->create(stageWithHistoryId, beginTime, endTime, includeEndTime); } inline ValidMirrors StageAtTimeInterval::getAttributeValidBits(const PathC& path, const TokenC& attrName) const { return sIStageAtTimeInterval()->getAttributeValidBits(m_stageAtTimeInterval, path, attrName); } template <typename T> std::vector<const T*> StageAtTimeInterval::getAttributeRd(const Path& path, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<const T*> retval(count); const void** retvalData = reinterpret_cast<const void**>(retval.data()); size_t bytesPerAttr = sIStageAtTimeInterval()->getAttributeRd(retvalData, count, m_stageAtTimeInterval, path, attrName); if (sizeof(T) == bytesPerAttr) { return retval; } else { CARB_LOG_WARN_ONCE("Trying to access %zu bytes from %s.%s, but flatcache has only %zu bytes", sizeof(T), path.getText(), attrName.getText(), bytesPerAttr); return std::vector<const T*>(); } } template <typename T> std::vector<const T*> StageAtTimeInterval::getAttributeRdGpu(const Path& path, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<const T*> retval(count); std::vector<ConstSpanC> arrays(count); sIStageAtTimeInterval()->getAttributeRdGpu(arrays.data(), count, m_stageAtTimeInterval, path, attrName); for (size_t i = 0; i != count; i++) { if (arrays[i].elementSize == sizeof(T)) { retval[i] = reinterpret_cast<const T*>(arrays[i].ptr); } else { retval[i] = nullptr; } } return retval; } inline std::vector<size_t> StageAtTimeInterval::getArrayAttributeSize(const Path& path, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<size_t> sizes(count); sIStageAtTimeInterval()->getArrayAttributeSize(sizes.data(), count, m_stageAtTimeInterval, path, attrName); return sizes; } template <typename T> std::vector<gsl::span<const T>> StageAtTimeInterval::getArrayAttributeRd(const Path& path, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<ConstSpanWithTypeC> arrays(count); std::vector<gsl::span<const T>> retval(count); sIStageAtTimeInterval()->getArrayAttributeWithSizeRd(arrays.data(), count, m_stageAtTimeInterval, path, attrName); for (size_t i = 0; i != count; i++) { if (arrays[i].elementSize != sizeof(T)) { retval[i] = gsl::span<T>(); continue; } const T* ptr = reinterpret_cast<const T*>(arrays[i].ptr); retval[i] = gsl::span<const T>(ptr, arrays[i].elementCount); } return retval; } inline std::vector<ConstArrayAsBytes> StageAtTimeInterval::getArrayAttributeRawRd(const Path& path, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<ConstSpanWithTypeC> arrays(count); std::vector<ConstArrayAsBytes> retval(count); sIStageAtTimeInterval()->getArrayAttributeWithSizeRd(arrays.data(), count, m_stageAtTimeInterval, path, attrName); for (size_t i = 0; i != count; i++) { const gsl::byte* ptr = reinterpret_cast<const gsl::byte*>(arrays[i].ptr); retval[i].arrayBytes = gsl::span<const gsl::byte>(ptr, arrays[i].elementCount * arrays[i].elementSize); retval[i].bytesPerElement = arrays[i].elementSize; retval[i].elementType = Type(arrays[i].type); } return retval; } inline std::vector<RationalTime> StageAtTimeInterval::getTimestamps() const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<RationalTime> retval(count); sIStageAtTimeInterval()->getTimestamps(retval.data(), count, m_stageAtTimeInterval); return retval; } inline size_t StageAtTimeInterval::getTimeSampleCount() const { return sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); } inline PrimBucketList StageAtTimeInterval::findPrims(const carb::flatcache::set<AttrNameAndType>& all, const carb::flatcache::set<AttrNameAndType>& any, const carb::flatcache::set<AttrNameAndType>& none) { PrimBucketListId primBucketListId = sIStageAtTimeInterval()->findPrims(m_stageAtTimeInterval, all, any, none); return { primBucketListId }; } template <typename T> std::vector<gsl::span<const T>> StageAtTimeInterval::getAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<ConstSpanC> outC(count); ConstSpanC* outCData = outC.data(); sIStageAtTimeInterval()->getAttributeArrayRd( outCData, count, m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex, attrName); std::vector<gsl::span<const T>> retval(count); size_t i = 0; for (ConstSpanC array : outC) { const T* typedElementsPtr = reinterpret_cast<const T*>(array.ptr); retval[i] = gsl::span<const T>(typedElementsPtr, array.elementCount); i++; } return retval; } template <typename T> std::vector<gsl::span<const T>> StageAtTimeInterval::getAttributeArrayRdGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<ConstSpanC> outC(count); ConstSpanC* outCData = outC.data(); sIStageAtTimeInterval()->getAttributeArrayRdGpu( outCData, count, m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex, attrName); std::vector<gsl::span<const T>> retval(count); size_t i = 0; for (ConstSpanC array : outC) { const T* typedElementsPtr = reinterpret_cast<const T*>(array.ptr); retval[i] = gsl::span<const T>(typedElementsPtr, array.elementCount); i++; } return retval; } template <typename T> std::vector<std::vector<gsl::span<const T>>> StageAtTimeInterval::getArrayAttributeArrayRd( const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<ConstArrayPointersAndSizesC> outC(count); ConstArrayPointersAndSizesC* outCData = outC.data(); sIStageAtTimeInterval()->getArrayAttributeArrayWithSizesRd( outCData, count, m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex, attrName); std::vector<std::vector<gsl::span<const T>>> retval(count); size_t i = 0; for (ConstArrayPointersAndSizesC pointersAndSizes : outC) { size_t primCount = pointersAndSizes.elementCount; retval[i].resize(primCount); for (size_t j = 0; j != primCount; j++) { const T* typedElementsPtr = reinterpret_cast<const T*>(pointersAndSizes.arrayPtrs[j]); retval[i][j] = { typedElementsPtr, pointersAndSizes.sizes[j] }; } i++; } return retval; } inline std::vector<gsl::span<const char>> StageAtTimeInterval::getAttributeArrayRawRd( const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<ConstSpanC> outC(count); ConstSpanC* outCData = outC.data(); sIStageAtTimeInterval()->getAttributeArrayRd( outCData, count, m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex, attrName); std::vector<gsl::span<const char>> retval(count); size_t i = 0; for (ConstSpanC array : outC) { const char* typedElementsPtr = reinterpret_cast<const char*>(array.ptr); retval[i] = gsl::span<const char>(typedElementsPtr, array.elementCount * array.elementSize); i++; } return retval; } inline std::vector<gsl::span<const Path>> StageAtTimeInterval::getPathArray(const PrimBucketList& primBucketList, size_t primBucketListIndex) const { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<ConstPathCSpan> outC(count); ConstPathCSpan* outCData = outC.data(); sIStageAtTimeInterval()->getPathArray( outCData, count, m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex); std::vector<gsl::span<const Path>> retval(count); size_t i = 0; for (ConstPathCSpan arrayC : outC) { const Path* array = reinterpret_cast<const Path*>(arrayC.ptr); retval[i] = gsl::span<const Path>(array, arrayC.elementCount); i++; } return retval; } inline std::vector<const Connection*> StageAtTimeInterval::getConnectionRd(const Path& path, const Token& connectionName) { size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<const Connection*> retval(count); const void** retvalData = reinterpret_cast<const void**>(retval.data()); sIStageAtTimeInterval()->getConnectionRd(retvalData, count, m_stageAtTimeInterval, path, connectionName); return retval; } inline void StageAtTimeInterval::printBucketNames() const { sIStageAtTimeInterval()->printBucketNames(m_stageAtTimeInterval); } inline std::vector<size_t> StageAtTimeInterval::getAttributeCounts(const PrimBucketList& primBucketList, size_t primBucketListIndex) const { std::vector<size_t> counts; size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); counts.resize(count); sIStageAtTimeInterval()->getAttributeCounts( m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex, count, counts.data()); return counts; } inline std::pair<std::vector<std::vector<Token>>, std::vector<std::vector<Type>>> StageAtTimeInterval::getAttributeNamesAndTypes( const PrimBucketList& primBucketList, size_t primBucketListIndex) const { std::vector<std::vector<Token>> outNames; std::vector<std::vector<Type>> outTypes; size_t count = sIStageAtTimeInterval()->getTimesampleCount(m_stageAtTimeInterval); std::vector<size_t> outSizes; outSizes.resize(count); sIStageAtTimeInterval()->getAttributeCounts( m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex, count, outSizes.data()); outNames.resize(count); outTypes.resize(count); // Make array of pointers to inner arrays to allow us to call // getAttributeNamesAndTypes, which takes a C-style 2D array // not a std::vector<std::vector>. // Also set size of inner arrays std::vector<Token*> outNamesPtrs(count); std::vector<Type*> outTypesPtrs(count); for (size_t i = 0; i < count; ++i) { outNames[i].resize(outSizes[i]); outTypes[i].resize(outSizes[i]); outNamesPtrs[i] = outNames[i].data(); outTypesPtrs[i] = outTypes[i].data(); } sIStageAtTimeInterval()->getAttributeNamesAndTypes(m_stageAtTimeInterval, primBucketList.m_primBucketListId, primBucketListIndex, count, outSizes.data(), outNamesPtrs.data(), outTypesPtrs.data()); return { outNames, outTypes }; } inline StageAtTimeInterval::~StageAtTimeInterval() { sIStageAtTimeInterval()->destroy(m_stageAtTimeInterval); } inline void StageAtTimeInterval::exportUsd(UsdStageId usdStageId) const { auto iStageAtTimeInterval = carb::getCachedInterface<carb::flatcache::IStageAtTimeInterval>(); iStageAtTimeInterval->exportUsd(m_stageAtTimeInterval, usdStageId); } /** * @brief Linear interpolation for carb types Double3, Float3, Float4 (color) * See InterpolationUsd.h for extended type support * * @details This is intended to be used internally by StageAtTime read methods in order * to calculate values that were not written by StageInProgress directly. * * Enables the decoupling of the sim and render threads by allowing them access * to ringbuffer values at various frequencies. */ template <typename T> const T interpolate(const T& a, const T& b, float theta) { T result = T(a * (1.0f - theta)) + T(b * theta); return result; // T result = std::lerp(a, b, theta); } template <> inline const carb::Double3 interpolate(const carb::Double3& a, const carb::Double3& b, float theta) { if (theta < 0.0 || theta > 1.0) { CARB_LOG_WARN_ONCE("WrapperImpl interpolate(): theta %f outside range [0.0, 1.0]", theta); } carb::Double3 result; double tmp = 1.0 - theta; result.x = (a.x * tmp) + (b.x * theta); result.y = (a.y * tmp) + (b.y * theta); result.z = (a.z * tmp) + (b.z * theta); return result; } template <> inline const carb::Float3 interpolate(const carb::Float3& a, const carb::Float3& b, float theta) { if (theta < 0.0f || theta > 1.0f) { CARB_LOG_WARN_ONCE("WrapperImpl interpolate(): theta %f outside range [0.0, 1.0]", theta); } carb::Float3 result; float tmp = 1.0f - theta; result.x = (a.x * tmp) + (b.x * theta); result.y = (a.y * tmp) + (b.y * theta); result.z = (a.z * tmp) + (b.z * theta); return result; } template <> inline const carb::Float4 interpolate(const carb::Float4& a, const carb::Float4& b, float theta) { if (theta < 0.0f || theta > 1.0f) { CARB_LOG_WARN_ONCE("WrapperImpl interpolate(): theta %f outside range [0.0, 1.0]", theta); } carb::Float4 result; float tmp = 1.0f - theta; result.x = (a.x * tmp) + (b.x * theta); result.y = (a.y * tmp) + (b.y * theta); result.z = (a.z * tmp) + (b.z * theta); result.w = (a.w * tmp) + (b.w * theta); return result; } template <> inline const carb::flatcache::Token interpolate(const carb::flatcache::Token& a, const carb::flatcache::Token& b, float theta) { if (theta < 0.0f || theta > 1.0f) { CARB_LOG_WARN_ONCE("WrapperImpl interpolate(): theta %f outside range [0.0, 1.0]", theta); } return theta < 0.5f ? a : b; } // Auxiliary function used when handling data that is not going to be interpolated (bool, string, int, uint) // Returns pair of values from first and second sampled frame, or the value found and nullptr if data is only available // in one frame template <typename T> inline optional<std::pair<optional<T>,optional<T>>> StageAtTime::getNonInterpolatableAttributeRd(const Path& path, const Token& attrName) const { auto rawSamples = m_historyWindow.getAttributeRd<T>(path, attrName); std::vector<RationalTime> sampleTimes = m_historyWindow.getTimestamps(); if (rawSamples.size() != sampleTimes.size()) { return carb::cpp17::nullopt; } // checking that if the rawSamples are not empty, we have something valid in rawSamples[0] CARB_ASSERT(rawSamples.empty() || rawSamples[0]); // Communicate zero samples found if ( rawSamples.empty() || !rawSamples[0] ) { return carb::cpp17::nullopt; } if (rawSamples.size() == 1) { std::pair<carb::cpp17::optional<T>, carb::cpp17::optional<T>> result(*rawSamples[0], carb::cpp17::nullopt); return result; } else if ( (rawSamples.size() == 2) && rawSamples[1] ) { std::pair<carb::cpp17::optional<T>, carb::cpp17::optional<T>> result(*rawSamples[0], *rawSamples[1]); return result; } return carb::cpp17::nullopt; } inline uint64_t StageAtTimeInterval::writeCacheToDisk(const char* file, uint8_t* workingBuffer, uint64_t workingBufferSize) const { return sIStageAtTimeInterval()->writeCacheToDisk(m_stageAtTimeInterval, file, workingBuffer, workingBufferSize); } inline void StageAtTimeInterval::addRefCount() { return sIStageAtTimeInterval()->addRefCount(m_stageAtTimeInterval); } inline bool StageAtTimeInterval::removeRefCount() { return sIStageAtTimeInterval()->removeRefCount(m_stageAtTimeInterval); } inline unsigned int StageAtTimeInterval::getRefCount() { return sIStageAtTimeInterval()->getRefCount(m_stageAtTimeInterval); } // StageAtTime implementation starts here // This is defined here rather than in Carbonite plugin to allow use of templates and inlining inline ValidMirrors StageAtTime::getAttributeValidBits(const PathC& path, const TokenC& attrName) const { return m_historyWindow.getAttributeValidBits(path, attrName); } // The method reports interpolatable data types, and is specialized as optional<pair<optional<T>,optional<T> // in order to report non-interpolatable data types as encountered in either or both samples template <typename T> inline optional<T> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const { auto rawSamples = m_historyWindow.getAttributeRd<T>(path, attrName); // Communicate zero samples found if (rawSamples.size() == 0) { return carb::cpp17::nullopt; } // Linear interpolation supports at most two samples CARB_ASSERT(rawSamples.size() <= 2); if (rawSamples.size() == 1) { CARB_ASSERT(rawSamples[0]); return *rawSamples[0]; } else if (rawSamples.size() == 2) { CARB_ASSERT(rawSamples[0]); CARB_ASSERT(rawSamples[1]); // Calculate linear approximation of f(time) T a_f = *rawSamples[0]; T b_f = *rawSamples[1]; return interpolate(a_f, b_f, (float)m_theta); } return carb::cpp17::nullopt; } // The following functions are marked for deletion since the specified types cannot be interpolated // StageAtTime reports the non-interpolatable types read from Flatcache as a pair<optional<T>, optional<T>> template <> inline optional<bool> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const = delete; template <> inline optional<int> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const = delete; template <> inline optional<unsigned int> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const = delete; template <> inline optional<unsigned char> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const = delete; template <> inline optional<int64_t> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const = delete; template <> inline optional<uint64_t> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const = delete; template <> inline optional<carb::flatcache::Token> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const = delete; // Specialize StageAtTime::getAttributeRd for non-interpolatable types: bool, int, uint // In these cases the returned type will be a pair of values from the samples found, or nullopt otherwise template <> inline optional<std::pair<optional<bool>, optional<bool>>> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const { auto result = getNonInterpolatableAttributeRd<bool>(path, attrName); return result; } template <> inline optional<std::pair<optional<int>, optional<int>>> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const { return getNonInterpolatableAttributeRd<int>(path, attrName); } template <> inline optional<std::pair<optional<unsigned int>, optional<unsigned int>>> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const { return getNonInterpolatableAttributeRd<unsigned int>(path, attrName); } template <> inline optional<std::pair<optional<unsigned char>, optional<unsigned char>>> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const { return getNonInterpolatableAttributeRd<unsigned char>(path, attrName); } template <> inline optional<std::pair<optional<int64_t>, optional<int64_t>>> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const { return getNonInterpolatableAttributeRd<int64_t>(path, attrName); } template <> inline optional<std::pair<optional<uint64_t>, optional<uint64_t>>> StageAtTime::getAttributeRd(const Path& path, const Token& attrName) const { return getNonInterpolatableAttributeRd<uint64_t>(path, attrName); } template <> inline optional<std::pair<optional<carb::flatcache::Token>, optional<carb::flatcache::Token>>> StageAtTime::getAttributeRd( const Path& path, const Token& attrName) const { return getNonInterpolatableAttributeRd<carb::flatcache::Token>(path, attrName); } template <typename T> const T* StageAtTime::getAttributeRdGpu(const Path& path, const Token& attrName) const { auto rawSamples = m_historyWindow.getAttributeRdGpu<T>(path, attrName); std::vector<RationalTime> sampleTimes = m_historyWindow.getTimestamps(); CARB_ASSERT(rawSamples.size() == sampleTimes.size()); // This API doesn't have a way to communicate zero samples found CARB_ASSERT(rawSamples.size() != 0); // Linear interpolation supports at most two samples CARB_ASSERT(rawSamples.size() <= 2); if (rawSamples.size() == 1) { CARB_ASSERT(rawSamples[0]); return rawSamples[0]; } else if (rawSamples.size() == 2) { // For GPU types there is no support for interpolation yet // Return first sample value instead for now CARB_LOG_WARN_ONCE("Support for interpolation of array attributes is not supported yet, returning first time sample instead!"); CARB_ASSERT(rawSamples[0]); return rawSamples[0]; } return nullptr; } inline size_t StageAtTime::getArrayAttributeSize(const Path& path, const Token& attrName) const { auto rawSamples = m_historyWindow.getArrayAttributeSize(path, attrName); std::vector<RationalTime> sampleTimes = m_historyWindow.getTimestamps(); CARB_ASSERT(rawSamples.size() == sampleTimes.size()); // This API doesn't have a way to communicate zero samples found CARB_ASSERT(rawSamples.size() != 0); // Linear interpolation supports at most two samples CARB_ASSERT(rawSamples.size() <= 2); if (rawSamples.size() == 1) { return rawSamples[0]; } else if (rawSamples.size() == 2) { // For GPU types there is no support for interpolation yet // Return first sample value instead for now return rawSamples[0]; } return 0; } template <typename T> inline gsl::span<const T> StageAtTime::getArrayAttributeRd(const Path& path, const Token& attrName) { auto rawSamples = m_historyWindow.getArrayAttributeRd<T>(path, attrName); std::vector<RationalTime> sampleTimes = m_historyWindow.getTimestamps(); CARB_ASSERT(rawSamples.size() == sampleTimes.size()); // This API doesn't have a way to communicate zero samples found CARB_ASSERT(rawSamples.size() != 0); // Linear interpolation supports at most two samples CARB_ASSERT(rawSamples.size() <= 2); if (rawSamples.size() == 1) { return rawSamples[0]; } else if (rawSamples.size() == 2) { // For array types there is no support for interpolation yet // Return first sample value instead for now CARB_LOG_WARN_ONCE("Support for interpolation of array attributes is not supported yet, returning first time sample instead!"); return rawSamples[0]; } return gsl::span<const T>(); } /** * @brief Auxiliary function used by AttributeArrayResult<T> and AttributeArrayResult<std::vector<T>> * * @details Used to assess if a prim is present in both of the sampled frames */ inline bool checkPathCorrespondence(std::vector<gsl::span<const carb::flatcache::Path>> paths, size_t index, size_t& pos_f0, size_t& pos_f1) { if (paths.size() > 1) { // in the common case, the prim exists in both frames if ((index < paths[1].size()) && (paths[0][index] == paths[1][index])) { pos_f0 = pos_f1 = index; return true; } auto pathIt = std::find(paths[1].begin(), paths[1].end(), paths[0][index]); if (pathIt != paths[1].end()) { pos_f0 = index; // TODO: this isn't needed, can infer it pos_f1 = std::distance(paths[1].begin(), pathIt); return true; } } return false; } /** * @brief Returned by StageAtTime.getAttributeArrayRd * * @details Holds at most two samples (one from frame n, and one from frame n+1) * checkPathCorrespondence verifies if the path in frame n exists in frame n+1 * If no corresponding path exists, the value will be returned and not interpolated */ template <typename T> class AttributeArrayResult { public: size_t size() const { return m_samples[0].size(); } bool empty() const { return (size() == 0); } std::vector<gsl::span<const T>> const* data() const { return &m_samples; } std::vector<gsl::span<const T>>* data() { return &m_samples; } T operator[](const size_t valueIndex) const { { if (valueIndex >= m_samples[0].size() || m_samples[0].empty()) { CARB_LOG_WARN_ONCE("AttributeArrayResult[] out of bounds"); return T(); } if (m_samples.size() == 1) { return m_samples[0][valueIndex]; } else if (m_samples.size() == 2) { size_t pos0, pos1; if (checkPathCorrespondence(m_paths, valueIndex, pos0, pos1)) { T a = (m_samples[0][pos0]); T b = (m_samples[1][pos1]); T result = interpolate<T>(a, b, m_theta); return result; } return m_samples[0][valueIndex]; } } return T(); }; std::vector<gsl::span<const carb::flatcache::Path>> m_paths; std::vector<gsl::span<const T>> m_samples; float m_theta; }; /** * @brief Returned by StageAtTime.getArrayAttributeArrayRd * * @details Enables access to a vector of readily interpolated attribute values */ template <typename T> class AttributeArrayResult<std::vector<T>> { public: size_t size() const { return m_samples[0].size(); } bool empty() const { return (size() == 0); } std::vector<std::vector<gsl::span<const T>>> const* data() const { return m_samples; } std::vector<std::vector<gsl::span<const T>>>* data() { return m_samples; } std::vector<T> operator[](const size_t primIndex) { std::vector<T> interpolatedAttributeValues; if (m_samples.size() == 1) { interpolatedAttributeValues.resize(m_samples[0][primIndex].size()); std::copy(m_samples[0][primIndex].begin(), m_samples[0][primIndex].end(), interpolatedAttributeValues.begin()); return interpolatedAttributeValues; } else if (m_samples.size() == 2) { size_t pos0, pos1; if (checkPathCorrespondence(m_paths, primIndex, pos0, pos1)) { auto values_f0 = m_samples[0][primIndex]; auto values_f1 = m_samples[1][primIndex]; interpolatedAttributeValues.reserve(values_f0.size()); // interpolate attrib values for the requested {prim index : attrib val index} for (size_t valueIndex = 0; valueIndex < values_f0.size(); ++valueIndex) { T a = (values_f0[valueIndex]); T b = (values_f1[valueIndex]); T result = interpolate<T>(a, b, m_theta); interpolatedAttributeValues.emplace_back(result); } return interpolatedAttributeValues; } interpolatedAttributeValues.resize(m_samples[0][primIndex].size()); std::copy(m_samples[0][primIndex].begin(), m_samples[0][primIndex].end(), interpolatedAttributeValues.begin()); return interpolatedAttributeValues; } return std::vector<T>(); } std::vector<gsl::span<const carb::flatcache::Path>> m_paths; std::vector<std::vector<gsl::span<const T>>> m_samples; float m_theta; }; template <typename T> AttributeArrayResult<T> StageAtTime::getAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { size_t sampleCount = m_historyWindow.getTimeSampleCount(); if (sampleCount > 0) { AttributeArrayResult<T> arrAttRes; arrAttRes.m_samples = m_historyWindow.getAttributeArrayRd<T>(primBucketList, primBucketListIndex, attrName); arrAttRes.m_paths = m_historyWindow.getPathArray(primBucketList, primBucketListIndex); arrAttRes.m_theta = (float)m_theta; return arrAttRes; } else { CARB_LOG_WARN_ONCE( "getAttributeArrayRd %s: Data not available at time, possible dropped frame", attrName.getText()); return AttributeArrayResult<T>(); } } template <typename T> AttributeArrayResult<T> StageAtTime::getAttributeArrayRdGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { size_t sampleCount = m_historyWindow.getTimeSampleCount(); if (sampleCount > 0) { AttributeArrayResult<T> arrAttRes; arrAttRes.m_samples = m_historyWindow.getAttributeArrayRdGpu<T>(primBucketList, primBucketListIndex, attrName); arrAttRes.m_paths = m_historyWindow.getPathArray(primBucketList, primBucketListIndex); arrAttRes.m_theta = (float)m_theta; return arrAttRes; } else { CARB_LOG_WARN_ONCE( "getAttributeArrayRdGpu %s: Data not available at time, possible dropped frame", attrName.getText()); return AttributeArrayResult<T>(); } } inline std::vector<gsl::span<const char>> StageAtTime::getAttributeArrayRawRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { return m_historyWindow.getAttributeArrayRawRd(primBucketList, primBucketListIndex, attrName); } template <typename T> AttributeArrayResult<std::vector<T>> StageAtTime::getArrayAttributeArrayRd( const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const { size_t sampleCount = m_historyWindow.getTimeSampleCount(); AttributeArrayResult<std::vector<T>> result; if (sampleCount > 0) { result.m_samples = m_historyWindow.getArrayAttributeArrayRd<T>(primBucketList, primBucketListIndex, attrName); result.m_paths = m_historyWindow.getPathArray(primBucketList, primBucketListIndex); result.m_theta = (float)m_theta; return result; } else { CARB_LOG_WARN_ONCE( "getAttributeArrayRd %s: Data not available at time, possible dropped frame", attrName.getText()); return AttributeArrayResult<std::vector<T>>(); } } inline gsl::span<const Path> StageAtTime::getPathArray(const PrimBucketList& primBucketList, size_t primBucketListIndex) const { size_t sampleCount = m_historyWindow.getTimeSampleCount(); if (sampleCount == 1) { return m_historyWindow.getPathArray(primBucketList, primBucketListIndex)[0]; } else if (sampleCount == 0) { CARB_LOG_WARN_ONCE("getPathArray: Data not available at time, possible dropped frame"); return gsl::span<const Path>(); } else if (sampleCount == 2) { // TODO: make this correct when prims are being added and deleted // To do this we need to make a new array out: // out[i] = in0[i] , if in0[i] == in1[i] // = kUninitializedPath, otherwise return m_historyWindow.getPathArray(primBucketList, primBucketListIndex)[0]; #if 0 gsl::span<const Path> in0 = m_historyWindow.getPathArray(primBucketList, primBucketListIndex)[0]; gsl::span<const Path> in1 = m_historyWindow.getPathArray(primBucketList, primBucketListIndex)[1]; std::vector<Path> multiframePaths; for (size_t i = 0; i < in0.size(); ++i) in0[i] == in1[i] ? multiframePaths.emplace_back(in0[i]) : multiframePaths.emplace_back(flatcache::kUninitializedPath); return multiframePaths; #endif } return gsl::span<const Path>(); } inline std::vector<const Connection*> StageAtTime::getConnectionRd(const Path& path, const Token& connectionName) { return m_historyWindow.getConnectionRd(path, connectionName); } inline void StageAtTime::printBucketNames() const { m_historyWindow.printBucketNames(); } inline size_t StageAtTime::getAttributeCount(const PrimBucketList& primBucketList, size_t primBucketListIndex) const { std::vector<size_t> counts = m_historyWindow.getAttributeCounts(primBucketList, primBucketListIndex); if (counts.size() == 1) { return counts[0]; } // Perform a set intersection to get a valid count size; if (counts.size() == 2) { // // TODO: The attributes are internally sorted vectors, see flatcache::set. // Ideally we'd make a C-ABI type that makes it clear that these are sorted, // wrap with flatcache::set in the C++ wrapper and then use the standard library set intersection. // auto namesAndTypes = m_historyWindow.getAttributeNamesAndTypes(primBucketList, primBucketListIndex); const std::vector<std::vector<Token>>& names = namesAndTypes.first; const std::vector<std::vector<Type>>& types = namesAndTypes.second; std::vector<Token> intersection; // Perform a set intersection but we need to track the types as we intersect const std::vector<Token>& workingNames = names[0].size() < names[1].size() ? names[0] : names[1]; const std::vector<Type>& workingTypes = names[0].size() < names[1].size() ? types[0] : types[1]; const std::vector<Token>& testingNames = names[0].size() < names[1].size() ? names[1] : names[0]; const std::vector<Type>& testingTypes = names[0].size() < names[1].size() ? types[1] : types[0]; // Since attribute vectors are sorted we can track last spotted locations to be more efficient. size_t last = 0; for (size_t i = 0; i < workingNames.size(); ++i) { for (size_t j = last; j < testingNames.size(); ++j) { if (workingNames[i] == testingNames[j]) { if (workingTypes[i] == testingTypes[j]) { intersection.push_back(workingNames[i]); } // Store hit location to start next search last = j; break; } } } return intersection.size(); } return 0; } inline std::pair<std::vector<Token>, std::vector<Type>> StageAtTime::getAttributeNamesAndTypes( const PrimBucketList& primBucketList, size_t primBucketListIndex) const { std::vector<Token> outNames; std::vector<Type> outTypes; std::vector<std::vector<Token>> names; std::vector<std::vector<Type>> types; std::tie(names, types) = m_historyWindow.getAttributeNamesAndTypes(primBucketList, primBucketListIndex); if (names.size() == 1) { outNames = std::move(names[0]); outTypes = std::move(types[0]); } if (names.size() == 2) { // Assuming that the invariant that names and types of the same slot are the same count holds. outNames.reserve(std::min(names[0].size(), names[1].size())); outTypes.reserve(std::min(types[0].size(), types[1].size())); // Perform a set intersection but we need to track the types as we intersect std::vector<Token>& workingNames = names[0].size() < names[1].size() ? names[0] : names[1]; std::vector<Type>& workingTypes = names[0].size() < names[1].size() ? types[0] : types[1]; std::vector<Token>& testingNames = names[0].size() < names[1].size() ? names[1] : names[0]; std::vector<Type>& testingTypes = names[0].size() < names[1].size() ? types[1] : types[0]; // Since attribute vectors are sorted we can track last spotted locations to be more efficient. size_t last = 0; for (size_t i = 0; i < workingNames.size(); ++i) { for (size_t j = last; j < testingNames.size(); ++j) { if (workingNames[i] == testingNames[j]) { if (workingTypes[i] == testingTypes[j]) { outNames.push_back(workingNames[i]); outTypes.push_back(workingTypes[i]); } // Store hit location to start next search last = j; break; } } } } return { outNames, outTypes }; } inline uint64_t StageAtTime::writeCacheToDisk(const char* file, uint8_t* workingBuffer, uint64_t workingBufferSize) const { size_t sampleCount = m_historyWindow.getTimeSampleCount(); if (sampleCount != 1) { CARB_LOG_ERROR_ONCE("Can't call StageAtTime::WriteCacheToDisk for interpolated values"); return 0; } return m_historyWindow.writeCacheToDisk(file, workingBuffer, workingBufferSize); } inline void StageAtTime::addRefCount() { m_historyWindow.addRefCount(); } inline bool StageAtTime::removeRefCount() { return m_historyWindow.removeRefCount(); } inline unsigned int StageAtTime::getRefCount() { return m_historyWindow.getRefCount(); } // StageWithHistory implementation starts here inline StageWithHistory::StageWithHistory(UsdStageId usdStageId, size_t historyFrameCount, RationalTime simPeriod, bool withCuda) { auto iStageWithHistory = carb::getCachedInterface<carb::flatcache::IStageWithHistory>(); m_stageWithHistory = iStageWithHistory->create2(usdStageId, historyFrameCount, simPeriod, withCuda); m_usdStageId = usdStageId; } inline StageWithHistory::~StageWithHistory() { auto iStageWithHistory = carb::getCachedInterface<carb::flatcache::IStageWithHistory>(); iStageWithHistory->destroy(m_usdStageId); } inline ListenerId StageWithHistory::createListener() { auto iChangeTrackerConfig = carb::getCachedInterface<carb::flatcache::IStageWithHistory>(); ListenerId newId = iChangeTrackerConfig->createListener(); return newId; } // Templated methods do not get compiled unless they are instantiated. // The following code is not intended to be executed, it just instantiates each // templated method once to make sure that they compile. inline void instantiationTest(StageInProgress& stage, StageAtTimeInterval& stageAtInterval, StageAtTime& stageAtTime, const Path& path, const Token& attrName) { int* x0 = stage.getAttribute<int>(path, attrName); CARB_UNUSED(x0); const int* x1 = stage.getAttributeRd<int>(path, attrName); CARB_UNUSED(x1); int* x2 = stage.getAttributeWr<int>(path, attrName); CARB_UNUSED(x2); gsl::span<int> x3 = stage.getArrayAttribute<int>(path, attrName); CARB_UNUSED(x3); gsl::span<const int> x4 = stage.getArrayAttributeRd<int>(path, attrName); CARB_UNUSED(x4); gsl::span<int> x5 = stage.getArrayAttributeWr<int>(path, attrName); CARB_UNUSED(x5); PrimBucketList pbl = stage.findPrims({}, {}, {}); gsl::span<int> x6 = stage.getAttributeArray<int>(pbl, 0, attrName); CARB_UNUSED(x6); std::vector<const int*> x7 = stageAtInterval.getAttributeRd<int>(path, attrName); CARB_UNUSED(x7); std::vector<gsl::span<const int>> x8 = stageAtInterval.getAttributeArrayRd<int>(pbl, 0, attrName); CARB_UNUSED(x8); optional<float> x9 = stageAtTime.getAttributeRd<float>(path, attrName); CARB_UNUSED(x9); optional<std::pair<optional<int>, optional<int>>> x10 = stageAtTime.getAttributeRd <std::pair<optional<int>, optional<int>>>(path, attrName); CARB_UNUSED(x10); carb::flatcache::AttributeArrayResult<int> x11 = stageAtTime.getAttributeArrayRd<int>(pbl, 0, attrName); CARB_UNUSED(x11); carb::flatcache::AttributeArrayResult<std::vector<int>> x12 = stageAtTime.getArrayAttributeArrayRd<int>(pbl, 0, attrName); CARB_UNUSED(x12); } } // namespace flatcache } // namespace carb
74,405
C
37.176501
153
0.672603
omniverse-code/kit/fabric/include/carb/flatcache/IPath.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Framework.h> #include <carb/Interface.h> #include <carb/flatcache/IToken.h> #include <carb/flatcache/Intrinsics.h> #include <functional> // Set to empty macro when IPath::iPath static member is removed #define FLATCACHE_IPATH_INIT \ const carb::flatcache::IPath* carb::flatcache::Path::iPath = nullptr; namespace carb { namespace flatcache { // PathC are integer keys that identify paths to C-ABI interfaces struct PathC { uint64_t path; constexpr bool operator<(const PathC& other) const { return path < other.path; } constexpr bool operator==(const PathC& other) const { return path == other.path; } constexpr bool operator!=(const PathC& other) const { return path != other.path; } }; static_assert(std::is_standard_layout<PathC>::value, "Struct must be standard layout as it is used in C-ABI interfaces"); // We don't reference count the uninitialized (or empty) path, and we use // this fact to avoid unnecessary dll calls to addRef()/removeRef(), for // example during std::vector resize. To do this we need to check whether a // path is uninitialized without the dll call getEmptyPath(), so we store // its value here in a constant. // We run automated test "IPath::getEmptyPath() dll call can be replaced with // constant, Path::kUninitializedPath" to ensure that this constant never // changes. static constexpr PathC kUninitializedPath{0}; // C-ABI interface to pxr::SdfPath struct IPath { CARB_PLUGIN_INTERFACE("carb::flatcache::IPath", 0, 1); PathC (*getHandle)(const char* name); const char* (*getText)(PathC handle); PathC (*getParent)(PathC handle); PathC (*appendChild)(PathC handle, TokenC childName); void (*addRef)(PathC handle); void (*removeRef)(PathC handle); PathC (*getEmptyPath)(); // Creates a path by appending a given relative path to this path. PathC (*appendPath)(PathC handle, PathC path); // Returns the number of path elements in this path. uint32_t (*getPathElementCount)(PathC handle); }; // C++ wrapper for IPath class Path { static carb::flatcache::IPath& sIPath(); public: // DEPRECATED: keeping for binary compatibility // Will be removed in October 2021 - @TODO set FLATCACHE_IPATH_INIT to empty macro when removed! // Still safe to use if initialized in a given dll static const carb::flatcache::IPath* iPath; Path() : mHandle(kUninitializedPath) { } Path(const char* path) { mHandle = sIPath().getHandle(path); } // Needs to be noexcept for std::vector::resize() to move instead of copy ~Path() noexcept { // We see the compiler construct and destruct many uninitialized // temporaries, for example when resizing std::vector. // We don't want to do an IPath dll call for these, so skip if handle // is uninitialized. if (mHandle != kUninitializedPath) { sIPath().removeRef(mHandle); } } // Copy constructor Path(const Path& other) : mHandle(other.mHandle) { if (mHandle != kUninitializedPath) { sIPath().addRef(mHandle); } } // Copy construct from integer Path(PathC handle) : mHandle(handle) { if (mHandle != kUninitializedPath) { sIPath().addRef(mHandle); } } // Move constructor // Needs to be noexcept for std::vector::resize() to move instead of copy Path(Path&& other) noexcept { // We are moving the src handle so don't need to change its refcount mHandle = other.mHandle; // Make source invalid other.mHandle = kUninitializedPath; } // Copy assignment Path& operator=(const Path& other) { if (this != &other) { if (mHandle != kUninitializedPath) { sIPath().removeRef(mHandle); } if (other.mHandle != kUninitializedPath) { sIPath().addRef(other.mHandle); } } mHandle = other.mHandle; return *this; } // Move assignment Path& operator=(Path&& other) noexcept { if (&other == this) return *this; // We are about to overwrite the dest handle, so decrease its refcount if (mHandle != kUninitializedPath) { sIPath().removeRef(mHandle); } // We are moving the src handle so don't need to change its refcount mHandle = other.mHandle; other.mHandle = kUninitializedPath; return *this; } const char* getText() const { return sIPath().getText(mHandle); } constexpr bool operator<(const Path& other) const { return mHandle < other.mHandle; } constexpr bool operator!=(const Path& other) const { return mHandle != other.mHandle; } constexpr bool operator==(const Path& other) const { return mHandle == other.mHandle; } constexpr operator PathC() const { return mHandle; } private: PathC mHandle; }; static_assert(std::is_standard_layout<Path>::value, "Path must be standard layout as it is used in C-ABI interfaces"); #ifndef __CUDACC__ inline carb::flatcache::IPath& Path::sIPath() { // Acquire carbonite interface on first use carb::flatcache::IPath* iPath = carb::getCachedInterface<carb::flatcache::IPath>(); CARB_ASSERT(iPath); return *iPath; } #endif // __CUDACC__ } } namespace std { template <> class hash<carb::flatcache::PathC> { public: inline size_t operator()(const carb::flatcache::PathC& key) const { // lower 8 bits have no entropy, so just remove the useless bits return key.path >> 8; } }; template <> class hash<carb::flatcache::Path> { public: inline size_t operator()(const carb::flatcache::Path& key) const { return std::hash<carb::flatcache::PathC>()(carb::flatcache::PathC(key)); } }; }
6,493
C
26.171548
121
0.639458
omniverse-code/kit/fabric/include/carb/flatcache/FlatCacheUSD.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/flatcache/IPath.h> #include <carb/logging/Log.h> #include <pxr/base/tf/token.h> #include <pxr/usd/sdf/path.h> namespace carb { namespace flatcache { // asInt() is the same as SdfPath::_AsInt() // Flatcache relies on asInt(a)==asInt(b) <=> a is same path as b, // which is how SdfPath::operator== is currently defined. // If USD changes sizeof(pxr::SdfPath), we will need to change PathC to make it // the same size. inline PathC asInt(const pxr::SdfPath& path) { static_assert(sizeof(pxr::SdfPath) == sizeof(PathC), "Change PathC to make the same size as pxr::SdfPath"); PathC ret; std::memcpy(&ret, &path, sizeof(pxr::SdfPath)); return ret; } inline const PathC* asInt(const pxr::SdfPath* path) { static_assert(sizeof(pxr::SdfPath) == sizeof(PathC), "Change PathC to make the same size as pxr::SdfPath"); return reinterpret_cast<const PathC*>(path); } inline TokenC asInt(const pxr::TfToken& token) { static_assert(sizeof(pxr::TfToken) == sizeof(TokenC), "Change TokenC to make the same size as pxr::TfToken"); TokenC ret; std::memcpy(&ret, &token, sizeof(pxr::TfToken)); return ret; } inline const TokenC* asInt(const pxr::TfToken* token) { static_assert(sizeof(pxr::TfToken) == sizeof(TokenC), "Change TokenC to make the same size as pxr::TfToken"); return reinterpret_cast<const TokenC*>(token); } // Return reference to ensure that reference count doesn't change inline const pxr::TfToken& intToToken(const TokenC& token) { static_assert(sizeof(pxr::TfToken) == sizeof(TokenC), "Change TokenC to make the same size as pxr::TfToken"); return reinterpret_cast<const pxr::TfToken&>(token); } inline const pxr::SdfPath& intToPath(const PathC& path) { static_assert(sizeof(pxr::SdfPath) == sizeof(PathC), "Change PathC to make the same size as pxr::SdfPath"); return reinterpret_cast<const pxr::SdfPath&>(path); } inline const pxr::SdfPath* intToPath(const Path* path) { static_assert(sizeof(pxr::SdfPath) == sizeof(Path), "Change Path to make the same size as pxr::SdfPath"); return reinterpret_cast<const pxr::SdfPath*>(path); } } }
2,585
C
31.325
113
0.716828
omniverse-code/kit/fabric/include/carb/flatcache/PrimChanges.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/flatcache/AttrNameAndType.h> #include <carb/flatcache/IFlatcache.h> #include <carb/flatcache/IPath.h> #include <gsl/span> #include <cstddef> namespace carb { namespace flatcache { struct AttrAndChangedIndices { AttrNameAndType attr; // For which prims did this attribute change? bool allIndicesChanged; gsl::span<const size_t> changedIndices; }; struct BucketChanges { // For each attribute, which prims changed? std::vector<AttrAndChangedIndices> attrChangedIndices; gsl::span<const Path> pathArray; BucketChanges() = default; BucketChanges(BucketChangesC in) : pathArray({ in.pathArray.ptr,in.pathArray.elementCount }) { size_t count = in.changedIndices.elementCount; attrChangedIndices.resize(count); for (size_t i = 0; i != count; i++) { const ConstChangedIndicesC& inAttrChanges = in.changedIndices.ptr[i]; attrChangedIndices[i].attr = in.changedAttributes.ptr[i]; attrChangedIndices[i].allIndicesChanged = inAttrChanges.allIndicesChanged; attrChangedIndices[i].changedIndices = gsl::span<const size_t>(inAttrChanges.changedIndices.ptr, inAttrChanges.changedIndices.elementCount); } } }; class AddedPrimIndices { // Which prims were added? gsl::span<const size_t> addedIndices; public: AddedPrimIndices(AddedPrimIndicesC in) { addedIndices = gsl::span<const size_t>(in.addedIndices.ptr, in.addedIndices.elementCount); } size_t size() const { return addedIndices.size(); } // This iterator first iterates over the deletedElements that were replaced // by new elements, then the contiguous range of elements added at the end // of the bucket struct iterator { using iterator_category = std::input_iterator_tag; using difference_type = size_t; using value_type = size_t; using reference = size_t; iterator( gsl::span<const size_t>::iterator _addedIndicesIterator, gsl::span<const size_t>::iterator _addedIndicesEnd) : addedIndicesIterator(_addedIndicesIterator), addedIndicesEnd(_addedIndicesEnd) {} reference operator*() const { return *addedIndicesIterator; } iterator& operator++() { addedIndicesIterator++; return *this; } bool operator==(iterator other) const { return addedIndicesIterator == other.addedIndicesIterator; } bool operator!=(iterator other) const { return !(*this == other); } difference_type operator-(iterator other) { return addedIndicesIterator - other.addedIndicesIterator; } private: gsl::span<const size_t>::iterator addedIndicesIterator; gsl::span<const size_t>::iterator addedIndicesEnd; }; iterator begin() { return iterator(addedIndices.begin(), addedIndices.end()); } iterator end() { return iterator(addedIndices.end(), addedIndices.end()); } }; } }
3,624
C
26.462121
117
0.656457
omniverse-code/kit/fabric/include/carb/flatcache/Intrinsics.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <cstdint> #include <cstdlib> #include <cstddef> #include <carb/flatcache/Defines.h> #if USING( WINDOWS_BUILD ) #include <intrin.h> #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) // no linux-specific includes at this time #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) namespace carb { namespace flatcache { inline uint32_t clz32( const uint32_t x ) { #if USING( WINDOWS_BUILD ) DWORD z; return _BitScanReverse( &z, x ) ? 31 - z : 32; #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) return x ? __builtin_clz( x ) : 32; #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) } inline uint32_t clz64( const uint64_t x ) { #if USING( WINDOWS_BUILD ) DWORD z; return _BitScanReverse64( &z, x ) ? 63 - z : 64; #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) return x ? __builtin_clzll( x ) : 64; #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) } inline uint32_t ctz32( const uint32_t x ) { #if USING( WINDOWS_BUILD ) DWORD z; return _BitScanForward( &z, x ) ? z : 32; #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) return x ? __builtin_ctz( x ) : 32; #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) } inline uint32_t ctz64( const uint64_t x ) { #if USING( WINDOWS_BUILD ) DWORD z; return _BitScanForward64( &z, x ) ? z : 64; #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) return x ? __builtin_ctzll( x ) : 64; #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) } inline uint64_t bswap64( const uint64_t x ) { #if USING( WINDOWS_BUILD ) return _byteswap_uint64( x ); #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) return __builtin_bswap64 ( x ); #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) } inline uint64_t rotr64( const uint64_t value, const int shift ) { #if USING( WINDOWS_BUILD ) return _rotr64( value, shift ); #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) return (value >> shift) | (value << (64 - shift)); #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) } inline uint64_t rotl64( const uint64_t value, const int shift ) { #if USING( WINDOWS_BUILD ) return _rotl64( value, shift ); #elif USING( LINUX_BUILD ) // #if USING( WINDOWS_BUILD ) return (value << shift) | (value >> (64 - shift)); #else // #if USING( WINDOWS_BUILD ) #error "Unsupported platform" #endif // #if USING( WINDOWS_BUILD ) } } // namespace flatcache } // namespace carb
3,199
C
27.318584
77
0.680213
omniverse-code/kit/fabric/include/carb/flatcache/FlatCache.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Interface.h> #include <carb/flatcache/PathToAttributesMap.h> namespace carb { namespace flatcache { // Callers of createCache() and getCache() can store anything they want in // UserId. For example, OmniGraph uses it to store the OmniGraph pointer. struct UserId { uint64_t id; bool operator<(UserId b) const { return id < b.id; } bool operator==(UserId b) const { return id == b.id; } bool operator!=(UserId b) const { return id != b.id; } }; constexpr UserId kDefaultUserId = { 0 }; constexpr UserId kInvalidUserId = { ~uint64_t(0) }; // Flatcache has the option to save a finite number of frames of history, // organized as a ringbuffer. This is typically used to buffer data between // simulation rendering. The simplest case, double buffering, allows simulation // and rendering to run in parallel, each running for the full frame. // Longer buffers can be used to feed one or more renderers running at // different rates to simulation. // To enable this feature, pass CacheType::eWithHistory to createCache(), // otherwise pass CacheType::eWithoutHistory. // Multiple caches can be created for each UsdStageId, but at most one can have // history. enum class CacheType { eWithHistory, eWithoutHistory, eWithoutHistoryAndWithCuda, eWithHistoryAndCuda }; struct FlatCache { CARB_PLUGIN_INTERFACE("carb::flatcache::FlatCache", 0, 4); // Abstractly, a flatcache maps USD paths to USD attributes, just like a // UsdStage does. // Concretely we represent a flatcache by objects of type PathToAttributesMap. // This method creates a PathToAttributesMap for a given stage, but doesn't // populate it with values. This allows the cache to be filled lazily as // values are needed. // Instead, it traverses the given Usd stage making an index of paths to // attributes. // The cache uses the index to organize data into contiguous arrays, // and also allows you to find prims by type and/or attribute without // traversing the stage. // This method also specifies the stage to be used by calls to usdToCache() // and cacheToUsd(). PathToAttributesMap&(CARB_ABI* createCache)(UsdStageId usdStageId, UserId userId, CacheType cacheType); void(CARB_ABI* addPrimToCache)(PathToAttributesMap& cache, const pxr::UsdPrim& prim, const std::set<TokenC>& filter); // Destroy the cache associated with the given stage. void(CARB_ABI* destroyCache)(UsdStageId usdStageId, UserId userId); // Prefetch the whole USD stage to the cache // Typically you only call this at stage load time, because the USD notify // handler updates the cache if the stage changes. void(CARB_ABI* usdToCache)(PathToAttributesMap& cache); // Write back all dirty cached data to the USD stage. // If your renderer doesn't use the cache then you need to do this // before rendering. void(CARB_ABI* cacheToUsd)(PathToAttributesMap& cache); // Write back only one bucket to usd void(CARB_ABI* cacheBucketToUsd)(PathToAttributesMap& cache, BucketId bucketId, bool skipMeshPoints); TypeC(CARB_ABI* usdTypeToTypeC)(pxr::SdfValueTypeName usdType); PathToAttributesMap*(CARB_ABI* getCache)(UsdStageId usdStageId, UserId userId); pxr::SdfValueTypeName(CARB_ABI* typeCtoUsdType)(TypeC typeC); size_t(CARB_ABI* getUsdTypeCount)(); void(CARB_ABI* getAllUsdTypes)(TypeC* outArray, size_t outArraySize); /** @brief Import a prim in cache */ void(CARB_ABI* addPrimToCacheNoOverwrite)(PathToAttributesMap& cache, const pxr::UsdPrim& prim, const std::set<TokenC>& filter); void(CARB_ABI* initStaticVariables)(); void(CARB_ABI* exportUsd)(PathToAttributesMap& cache, pxr::UsdStageRefPtr usdStage, const double* timeCode, const double* prevTimeCode); /** @brief Attempt to serialize the cache into the specified buffer. * * @cache[in] The cache to serialize * @dest[in/out] Pointer to buffer to be written to, will start writing to head * of pointer. dest will be left pointing to the point after the last write * @destSize Size of buffer that was allocated for the data (in bytes) * @pathStringCache - looking up strings is slow, yo * * @return Number of bytes written success is determined by (return <= @destSize) * * * @invariant It is safe to write to any memory within[dest, dest+size] for the * duration of the function call. * * @note If the cache will not fit into the size of memory allocated in * @dest then it will stop writing, but continue to run the serialize * algorithm to calculate the actual amount of data that needs to be * written * * @Todo : make cache const - not possible because serializeMirroredAray is not * const, however, that is because getArraySpanC is used which also doesn't * have a const version, so that needs to be addressed first, this is because * in the call stack we end up with a copy from GPU -> CPU which would need to * be avoided */ uint64_t(CARB_ABI* serializeCache)(PathToAttributesMap& cache, uint8_t* dest, size_t destSize, SerializationCache& pathStringCache); /** @brief Given a buffer that has the serialized version of a cache written * using the serialize function, this function will override all the data * in the cache with the data from the buffer * * @cache[in/out] Reference to the cache to be populated * @pathCache[in/out] Looking up SDFPath via string can be expensive to it * is worthwhile to cache this data across many repeated * calls. * @input[in] Pointer to buffer of data containing serialized cache * @inputSize[in] Size of data in the buffer * @skipStageConfirmation[in] Whether we should skip making sure the destination stage is open. * * @return True if buffer was successfully de-serialized * * @note : this currently has to clear the cache before it is populated which is a possibly * expensive operation * * @TODO: whould we care that it came from the same version of the USD file? */ bool(CARB_ABI* deserializeCache)( PathToAttributesMap& destStage, DeserializationCache& pathCache, const uint8_t* input, const size_t inputSize, bool skipStageConfirmation); /** @brief Write a cache file to disk at a specified location * * @note many parameters to this function are optional * @cache[in] That cache to be written to disk * @file[in The location the file is desired to be written to * @workingBuffer[in] [Optional] In order to avoid costly reallocations * the code will attempt to re-use the memory at the buffer * location if it is large enough. If the buffer isn't larg * enough the cost of allocation, and re-traversal may be paid * @workingBufferSize[in] [Optional] If workingBuffer is non null, then this desrcibes the length * of the buffer * @return The amount of data needed to serialize the cache, a return value of 0 indicates an error * */ uint64_t(CARB_ABI* writeCacheToDisk)(PathToAttributesMap& cache, const char* file, uint8_t* workingBuffer, uint64_t workingBufferSize); /** @brief Read a cache file from the specified location * * @file[in] The location the file is desired to be written to * @cache[in/out] That cache to be populates * @pathCache[in/out] Looking up SDFPath via string can be expensive to it * is worthwhile to cache this data across many repeated * calls. * @buffer[in/out] Buffer to use to read the cache file in to, passed to * allow reuse than allocate per call. Will be resized if not large enough. * @return Whether the read was successful * */ bool(CARB_ABI* readCacheFromDisk)(PathToAttributesMap& cache, const char* fileName, DeserializationCache& pathCache, std::vector<uint8_t>& buffer); /** @brief Enable/Disable change notifications on USD changes. * * @enable[in] True/False enable notifications * */ void(CARB_ABI* setEnableChangeNotifies)(bool enable); /** @brief Return whether change notifications on USD changes is enabled. * * @return True if change notifications on USD changes is enabled, else False. * */ bool(CARB_ABI* getEnableChangeNotifies)(); /** @brief make buckets for all prims on a USD stage, but only if this * hasn't been done before. * * This is used to lazily create an index of all prims on a stage, without * the time or memory cost of fetching all the attribute values. The user * can then use findPrims to, for example, find all the prims of a * particular type. * * If a SimStageWithHistory hasn't been created for this stage then a * warning will be printed and no population will be done. * * @cache[in] The PathToAttributesMap to populate */ void(CARB_ABI* minimalPopulateIfNecessary)(PathToAttributesMap& cache); }; } }
9,956
C
40.144628
140
0.677581
omniverse-code/kit/fabric/include/carb/flatcache/Allocator.h
#pragma once #include <cmath> #include <carb/logging/Log.h> #include <carb/Defines.h> #include <carb/flatcache/Defines.h> #include <carb/flatcache/Intrinsics.h> #define ALLOCATOR_HEADER USE_IF( USING( DEVELOPMENT_BUILD ) ) #define ALLOCATOR_STATS USE_IF( USING( ALLOCATOR_HEADER ) ) // requires Header's byte tracking per-allocation #define ALLOCATOR_LEAK_CHECK USE_IF( USING( ALLOCATOR_HEADER ) ) // requires Header's byte tracking per-allocation namespace carb { namespace flatcache { inline const char* humanReadableSize( const uint64_t bytes ) noexcept { auto va = [](auto ...params) -> const char* { static char tmp[1024]; #ifdef _WIN32 _snprintf_s(tmp, sizeof(tmp), params...); #else snprintf(tmp, sizeof(tmp), params...); #endif return (const char*)&tmp; }; constexpr const char SIZE_UNITS[64][3]{ " B", " B", " B", " B", " B", " B", " B", " B", " B", " B", "KB", "KB", "KB", "KB", "KB", "KB", "KB", "KB", "KB", "KB", "MB", "MB", "MB", "MB", "MB", "MB", "MB", "MB", "MB", "MB", "GB", "GB", "GB", "GB", "GB", "GB", "GB", "GB", "GB", "GB", "TB", "TB", "TB", "TB", "TB", "TB", "TB", "TB", "TB", "TB", "PB", "PB", "PB", "PB", "PB", "PB", "PB", "PB", "PB", "PB", "EB", "EB", "EB", "EB" }; static constexpr size_t B = 1ull; static constexpr size_t KB = 1024ull; static constexpr size_t MB = (1024ull*1024ull); static constexpr size_t GB = (1024ull*1024ull*1024ull); static constexpr size_t TB = (1024ull*1024ull*1024ull*1024ull); static constexpr size_t PB = (1024ull*1024ull*1024ull*1024ull*1024ull); static constexpr size_t EB = (1024ull*1024ull*1024ull*1024ull*1024ull*1024ull); constexpr const size_t SIZE_BASE[64]{ B, B, B, B, B, B, B, B, B, B, KB, KB, KB, KB, KB, KB, KB, KB, KB, KB, MB, MB, MB, MB, MB, MB, MB, MB, MB, MB, GB, GB, GB, GB, GB, GB, GB, GB, GB, GB, TB, TB, TB, TB, TB, TB, TB, TB, TB, TB, PB, PB, PB, PB, PB, PB, PB, PB, PB, PB, EB, EB, EB, EB }; const uint32_t power = bytes ? ( 64u - clz64( bytes ) ) - 1u : 0; const char *const units = SIZE_UNITS[power]; const size_t base = SIZE_BASE[power]; const size_t count = bytes / base; return va("%zu %s", count, units); } // A wrapper around malloc/free that aims to: // // * Cheaply track allocation counts and bytes, and detect leaks automatically at ~Allocator() // // * Cheaply track usage in terms of peak memory usage, and total lifetime usage broken down by size. Sample output: // dumped to console appears like so: // // == Allocator 0x000000E67BEFCEA0 Stats == // allocCount: 0 // allocBytes: 0 B // peakAllocCount: 4002 // peakAllocBytes: 4 GB // minAllocBytes: 312 B // maxAllocBytes: 6 MB // // Lifetime Allocation Histogram: // Normalized over TOTAL allocations: 13956 // < 512 B|***** 29% 4002 // < 1 KB| 0% 0 // < 2 KB| 0% 0 // < 4 KB| 0% 0 // < 8 KB|*** 14% 2000 // < 16 KB| 0% 0 // < 32 KB|*** 14% 1994 // < 64 KB| 0% 0 // < 128 KB|*** 14% 1976 // < 256 KB| 0% 0 // < 512 KB|*** 14% 1904 // < 1 MB| 0% 0 // < 2 MB|** 12% 1616 // < 4 MB| 0% 0 // < 8 MB|* 3% 464 // ======================== struct Allocator { Allocator(); ~Allocator(); void* alloc(const size_t bytes); void free(void *const ptr); template<typename T, typename ...Params> T* new_(Params&& ...params); template<typename T> void delete_(T*const t); void resetStats() noexcept; void reportUsage() noexcept; bool checkLeaks() noexcept; private: #if USING( ALLOCATOR_HEADER ) struct BlockHeader { size_t bytes; }; #endif // #if USING( ALLOCATOR_HEADER ) #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) size_t allocCount; size_t allocBytes; #endif // #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) #if USING( ALLOCATOR_STATS ) size_t peakAllocCount; size_t peakAllocBytes; size_t minAllocBytes; size_t maxAllocBytes; static constexpr size_t ALLOC_BUCKET_COUNT = 65; size_t lifetimeAllocCount; size_t lifetimeAllocBuckets[ALLOC_BUCKET_COUNT]; #endif // #if USING( ALLOCATOR_STATS ) }; struct AllocFunctor { Allocator *allocator; void* operator()(const size_t bytes) { CARB_ASSERT(allocator); return allocator->alloc(bytes); } }; struct FreeFunctor { Allocator *allocator; void operator()(void *const ptr) { CARB_ASSERT(allocator); return allocator->free(ptr); } }; inline Allocator::Allocator() { #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) allocCount = 0; allocBytes = 0; #endif // #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) resetStats(); } inline Allocator::~Allocator() { checkLeaks(); reportUsage(); } inline void* Allocator::alloc(const size_t bytes) { #if USING( ALLOCATOR_HEADER ) const size_t totalBytes = bytes + sizeof(BlockHeader); #endif // #if USING( ALLOCATOR_HEADER ) #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) CARB_ASSERT((allocCount + 1) > allocCount); CARB_ASSERT((allocBytes + totalBytes) > allocBytes); ++allocCount; allocBytes += totalBytes; #endif // #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) #if USING( ALLOCATOR_STATS ) if ( allocBytes > peakAllocBytes ) { peakAllocBytes = allocBytes; peakAllocCount = allocCount; } if ( totalBytes < minAllocBytes ) { minAllocBytes = totalBytes; } if ( totalBytes > maxAllocBytes ) { maxAllocBytes = totalBytes; } const uint32_t bucket = ( 64u - clz64( totalBytes - 1ull ) ); CARB_ASSERT(lifetimeAllocBuckets[bucket] + 1 > lifetimeAllocBuckets[bucket]); ++lifetimeAllocBuckets[bucket]; ++lifetimeAllocCount; #endif // #if USING( ALLOCATOR_STATS ) #if USING( ALLOCATOR_HEADER ) BlockHeader *const header = (BlockHeader*)malloc(totalBytes); CARB_ASSERT(header); header->bytes = totalBytes; return header+1; #else // #if USING( ALLOCATOR_HEADER ) return malloc(bytes); #endif // #if USING( ALLOCATOR_STATS ) } inline void Allocator::free(void *const ptr) { #if USING( ALLOCATOR_HEADER ) CARB_ASSERT(ptr); BlockHeader *header = (BlockHeader*)ptr; --header; #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) const size_t totalBytes = header->bytes; CARB_ASSERT((allocCount - 1) < allocCount); CARB_ASSERT((allocBytes - totalBytes) < allocBytes); --allocCount; allocBytes -= totalBytes; #endif // #if USING( ALLOCATOR_STATS ) || USING( ALLOCATOR_LEAK_CHECK ) ::free(header); #else // #if USING( ALLOCATOR_STATS ) ::free(ptr); #endif // #if USING( ALLOCATOR_STATS ) } template<typename T, typename ...Params> inline T* Allocator::new_(Params&& ...params) { T *const t = (T*)Allocator::alloc(sizeof(T)); new (t) T(std::forward<Params>(params)...); return t; } template<typename T> inline void Allocator::delete_(T*const t) { CARB_ASSERT(t); t->~T(); #if USING( ALLOCATOR_HEADER ) BlockHeader *header = (BlockHeader*)t; header--; CARB_ASSERT(header->bytes == (sizeof(BlockHeader) + sizeof(T))); #endif // #if USING( ALLOCATOR_HEADER ) Allocator::free(t); } inline void Allocator::resetStats() noexcept { #if USING( ALLOCATOR_STATS ) peakAllocCount = 0; peakAllocBytes = 0; minAllocBytes = SIZE_MAX; maxAllocBytes = 0; lifetimeAllocCount = 0; for ( size_t i = 0; i < ALLOC_BUCKET_COUNT; ++i ) { lifetimeAllocBuckets[i] = 0; } #endif // #if USING( ALLOCATOR_STATS ) } inline void Allocator::reportUsage() noexcept { #if USING( ALLOCATOR_STATS ) CARB_LOG_INFO("== Allocator 0x%p Stats ==", this); if (!lifetimeAllocCount) { CARB_LOG_INFO("<no stats to report; unused allocator>"); CARB_LOG_INFO("========================"); return; } CARB_LOG_INFO("allocCount: %12zu", allocCount); CARB_LOG_INFO("allocBytes: %15s", humanReadableSize(allocBytes)); CARB_LOG_INFO("peakAllocCount: %12zu", peakAllocCount); CARB_LOG_INFO("peakAllocBytes: %15s", humanReadableSize(peakAllocBytes)); CARB_LOG_INFO("minAllocBytes: %15s", humanReadableSize(minAllocBytes)); CARB_LOG_INFO("maxAllocBytes: %15s", humanReadableSize(maxAllocBytes)); CARB_LOG_INFO(""); CARB_LOG_INFO("Lifetime Allocation Histogram:"); size_t begin = 0; for ( ; begin < ALLOC_BUCKET_COUNT; ++begin ) { if ( lifetimeAllocBuckets[begin] ) { break; } } size_t end = 0; for ( ; end < ALLOC_BUCKET_COUNT; ++end ) { if ( lifetimeAllocBuckets[ALLOC_BUCKET_COUNT - end - 1] ) { end = ALLOC_BUCKET_COUNT - end; break; } } CARB_LOG_INFO(" Normalized over TOTAL allocations: %zu", lifetimeAllocCount); size_t i; float normalized[ALLOC_BUCKET_COUNT]; for ( i = begin; i < end; ++i ) { normalized[i] = (float)lifetimeAllocBuckets[i] / (float)lifetimeAllocCount; } constexpr size_t WIDTH = 16; for ( i = begin; i < end; ++i ) { char buf[WIDTH+1] = {}; const size_t w = ( size_t )std::ceil(WIDTH * normalized[i]); for( size_t j = 0; j < w; ++j) { buf[j] = '*'; } static_assert(WIDTH == 16, "Fix CARB_LOG_INFO below"); CARB_LOG_INFO(" <%7s|%-16s %3.0f%% %12zu", humanReadableSize(1ull<<i), buf, (normalized[i] * 100.f), lifetimeAllocBuckets[i]); } CARB_LOG_INFO("========================"); #endif // #if USING( ALLOCATOR_STATS ) } inline bool Allocator::checkLeaks() noexcept { #if USING( ALLOCATOR_LEAK_CHECK ) if (allocCount || allocBytes) { CARB_LOG_ERROR("PathToAttributesMap detected a memory leak of %s!\n", humanReadableSize(allocBytes)); CARB_ASSERT(false, "PathToAttributesMap detected a memory leak of %s!\n", humanReadableSize(allocBytes)); return true; } #endif // #if USING( ALLOCATOR_LEAK_CHECK ) return false; } } // namespace flatcache } // namespace carb
10,798
C
28.425068
135
0.571217
omniverse-code/kit/fabric/include/carb/flatcache/InterpolationUsd.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once // This include must come first // clang-format off #include "UsdPCH.h" // clang-format on #include <pxr/base/gf/matrix4d.h> #include <pxr/base/gf/quatf.h> #include "carb/logging/Log.h" /** * @brief Defined in a separate location to the other lerp functions * in order to avoid breaking C-ABI compatibility */ namespace carb { namespace flatcache { /** * @brief Spherical interpolation specialization relying on pxr native * interpolation for quaternions */ template <> inline const pxr::GfQuatf interpolate(const pxr::GfQuatf& q0, const pxr::GfQuatf& q1, float theta) { if (theta < 0.0f || theta > 1.0f) { CARB_LOG_WARN_ONCE("InterpolationUsd interpolate(): theta %f outside range [0.0, 1.0]", theta); } pxr::GfQuatf result = pxr::GfSlerp(theta, q0, q1); return result; } /** * @brief pxr::Matrix4d interpolation specialization Used in Kit by OmniHydraDelegate */ template <> inline const pxr::GfMatrix4d interpolate(const pxr::GfMatrix4d& m0, const pxr::GfMatrix4d& m1, float theta) { if (theta < 0.0f || theta > 1.0f) { CARB_LOG_WARN_ONCE("InterpolationUsd interpolate(): theta %f outside range [0.0, 1.0]", theta); } pxr::GfMatrix4d r0, r1; // rotations, where -r is inverse of r pxr::GfVec3d s0, s1; // scale pxr::GfMatrix4d u0, u1; // rotations, may contain shear info pxr::GfVec3d t0, t1; // translations pxr::GfMatrix4d p0, p1; // p is never modified; can contain projection info // Account for rotation, translation, scale // (order is mat = r * s * -r * u * t), eps=1e-10 used to avoid zero values m0.Factor(&r0, &s0, &u0, &t0, &p0); m1.Factor(&r1, &s1, &u1, &t1, &p1); // Interpolate component-wise pxr::GfVec3d tResult = pxr::GfLerp(theta, t0, t1); pxr::GfVec3d sResult = pxr::GfLerp(theta, s0, s1); pxr::GfQuatd rResult = pxr::GfSlerp(u0.ExtractRotationQuat(), u1.ExtractRotationQuat(), theta); pxr::GfMatrix4d result = pxr::GfMatrix4d(pxr::GfRotation(rResult), pxr::GfCompMult(sResult, tResult)); return result; } } }
2,530
C
29.865853
107
0.686166
omniverse-code/kit/fabric/include/carb/flatcache/RationalTime.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 <map> #include <stdint.h> namespace carb { namespace flatcache { // Each frame in the history buffer is timestamped with a frame time, stored as // a rational number to minimize rounding issues. See threadgate::TimeRatio. struct RationalTime { int64_t numerator; uint64_t denominator; // Minimize denominator small by dividing by gcd(numerator,denominator) RationalTime reduce() const { RationalTime result{0, 0}; int64_t gcdNumDen = gcd(numerator, denominator); if (gcdNumDen != 0) { result.numerator = numerator / gcdNumDen; result.denominator = denominator / gcdNumDen; } return result; } bool operator==(RationalTime rhs) const { RationalTime thisReduced = reduce(); RationalTime rhsReduced = rhs.reduce(); return (thisReduced.numerator == rhsReduced.numerator) && (thisReduced.denominator == rhsReduced.denominator); } bool operator!=(RationalTime rhs) const { return !(*this == rhs); } static int64_t gcd(int64_t a, int64_t b) { while (b != 0) { int64_t t = b; b = a % b; a = t; } return std::max(a, -a); } RationalTime operator-(RationalTime b) const { RationalTime result; result.numerator = numerator * int64_t(b.denominator) - b.numerator * int64_t(denominator); result.denominator = denominator * b.denominator; return result.reduce(); } RationalTime operator*(int64_t b) const { RationalTime result; result.numerator = numerator * b; result.denominator = denominator; return result.reduce(); } }; static const RationalTime kInvalidTime = { 0, 0 }; } // namespace flatcache } // namespace carb
2,308
C
24.94382
118
0.642548
omniverse-code/kit/fabric/include/carb/flatcache/ApiLogger.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/flatcache/IPath.h> #include <carb/flatcache/IToken.h> #include <iostream> // To log all FlatCache methods that access a particular path and attribute, // set the following three defines #define ENABLE_FLATCACHE_API_LOG 0 #if ENABLE_FLATCACHE_API_LOG #define attrToTrace "attrToLog" #define pathToTrace "/primToLog" namespace carb { namespace flatcache { struct ApiLogger { bool& enabled; const char* desc; ApiLogger(const char* desc, bool& enabled, const TokenC& attrNameC) : desc(desc), enabled(enabled) { Token attrName(attrNameC); if (attrName == Token(attrToTrace)) { std::cout << "begin " << desc << "\n"; enabled = true; } } ApiLogger(const char* desc, bool& enabled, const PathC& pathC, const TokenC& attrNameC) : desc(desc), enabled(enabled) { Path path(pathC); Token attrName(attrNameC); if (path == Path(pathToTrace) && attrName == Token(attrToTrace)) { std::cout << "begin " << desc << "\n"; enabled = true; } } ~ApiLogger() { if (enabled) { std::cout << "end " << desc << "\n"; } enabled = false; } }; #define APILOGGER(...) ApiLogger logger(__VA_ARGS__) } } #else #define APILOGGER(...) #endif
1,789
C
23.861111
122
0.636669
omniverse-code/kit/fabric/include/carb/flatcache/underlying.h
#pragma once #include <type_traits> namespace carb { namespace flatcache { template <typename EnumT> constexpr inline typename std::underlying_type<EnumT>::type underlying(const EnumT& t) { return static_cast<typename std::underlying_type<EnumT>::type>(t); } } // namespace flatcache } // namespace carb
312
C
18.562499
86
0.740385
omniverse-code/kit/fabric/include/carb/flatcache/Ordered_Set.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 <algorithm> #include <functional> #include <initializer_list> #include <vector> namespace carb { namespace flatcache { template <class T, class Compare = std::less<T>> struct set { using value_type = T; std::vector<T> v; Compare cmp; using iterator =typename std::vector<T>::iterator; using const_iterator =typename std::vector<T>::const_iterator; iterator begin() { return v.begin(); } iterator end() { return v.end(); } const_iterator begin() const { return v.begin(); } const_iterator end() const { return v.end(); } set(const Compare& c = Compare()) : v(), cmp(c) { } template <class InputIterator> set(InputIterator first, InputIterator last, const Compare& c = Compare()) : v(first, last), cmp(c) { std::sort(begin(), end(), cmp); } set(std::initializer_list<T> _Ilist) : set(_Ilist.begin(), _Ilist.end()) { } void reserve(size_t newCapacity) { v.reserve(newCapacity); } void clear() { v.clear(); } iterator insert(const T& t) { iterator i = std::lower_bound(begin(), end(), t, cmp); if (i == end() || cmp(t, *i)) i = v.insert(i, t); return i; } iterator insert(T&& t) { iterator i = std::lower_bound(begin(), end(), t, cmp); if (i == end() || cmp(t, *i)) i = v.insert(i, std::move(t)); return i; } template <class _Iter> void insert(_Iter _First, _Iter _Last) { // insert [_First, _Last) one at a time for (; _First != _Last; ++_First) { insert(*_First); } } iterator insert(const_iterator hint, const value_type& value) { // Measurements show it is faster to ignore hint in this application return insert(value); } void insert(std::initializer_list<T> _Ilist) { insert(_Ilist.begin(), _Ilist.end()); } size_t erase(const T& key) { iterator removeElement = find(key); if (removeElement != v.end()) { v.erase(removeElement); return 1; } else { return 0; } } iterator erase(iterator iter) { return v.erase(iter); } const_iterator find(const T& t) const { const_iterator i = std::lower_bound(begin(), end(), t, cmp); return i == end() || cmp(t, *i) ? end() : i; } iterator find(const T& t) { iterator i = std::lower_bound(begin(), end(), t, cmp); return i == end() || cmp(t, *i) ? end() : i; } bool contains(const T& t) const { const_iterator i = std::lower_bound(begin(), end(), t, cmp); return i != end() && !cmp(t, *i); } bool operator==(const set<T>& other) const { return v == other.v; } bool operator!=(const set<T>& other) const { return v != other.v; } size_t size() const { return v.size(); } T* data() { return v.data(); } const T* data() const { return v.data(); } }; template <class T, class Compare = std::less<T>> bool operator<(const set<T, Compare>& left, const set<T, Compare>& right) { return left.v < right.v; } template<typename T> flatcache::set<T> nWayUnion(std::vector<flatcache::set<T>>& srcBuckets) { flatcache::set<T> retval; // Calculate the maximum number of destination attributes // We could instead calculate it exactly by finding union of attribute names size_t maxDestAttrCount = 0; for (flatcache::set<T>& srcBucket : srcBuckets) { maxDestAttrCount += srcBucket.size(); } retval.reserve(maxDestAttrCount); auto currentDest = std::back_inserter(retval.v); size_t bucketCount = srcBuckets.size(); // Initialize invariant that nonEmpty is the vector of buckets that have // non-zero attribute counts struct NonEmptySegment { // Invariant is current!=end typename std::vector<T>::iterator current; typename std::vector<T>::iterator end; }; std::vector<NonEmptySegment> nonEmpty; nonEmpty.reserve(bucketCount); for (size_t i = 0; i != bucketCount; i++) { if (srcBuckets[i].begin() != srcBuckets[i].end()) { nonEmpty.push_back({ srcBuckets[i].begin(), srcBuckets[i].end() }); } } // Keep going until there's only 1 non-empty bucket // At that point we can just copy its attributes to the output while (1 < nonEmpty.size()) { // Find all the buckets that have the minimum element // These are the ones whose iterators will get advanced // By the loop guard and the invariant, we know that nonEmpty[0] exists // and that nonEmpty[0].current!=nonEmpty[0].end. // So *nonEmpty[0].current is a safe dereference T minSoFar = *nonEmpty[0].current; std::vector<size_t> indicesAtMin; indicesAtMin.reserve(nonEmpty.size()); indicesAtMin.push_back(0); for (size_t i = 1; i != nonEmpty.size(); i++) { if (*nonEmpty[i].current < minSoFar) { minSoFar = *nonEmpty[i].current; indicesAtMin = { i }; } else if (*nonEmpty[i].current == minSoFar) { indicesAtMin.push_back(i); } } // Copy minimum element to the output *currentDest = minSoFar; ++(*currentDest); // Advance the iterators that pointed to the min std::vector<NonEmptySegment> tempNonEmpty; tempNonEmpty.reserve(indicesAtMin.size()); for (size_t i = 0; i != indicesAtMin.size(); i++) { nonEmpty[indicesAtMin[i]].current++; } // Maintain the invariant that nonEmpty are the non empty ones // Replace with O(n) copy into a temporary if necessary auto it = nonEmpty.begin(); while (it != nonEmpty.end()) { if (it->current == it->end) { it = nonEmpty.erase(it); } else { ++it; } } } // By the negation of the guard we know that nonEmpty has zero or one elements if (nonEmpty.size() == 1) { // If one bucket is left, copy its elements to the output std::copy(nonEmpty[0].current, nonEmpty[0].end, currentDest); } return retval; } } }
7,055
C
24.381295
103
0.556768
omniverse-code/kit/fabric/include/carb/flatcache/StageWithHistory.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 "IFlatcache.h" #include <carb/Framework.h> #include <carb/Interface.h> #include <carb/flatcache/AttrNameAndType.h> #include <carb/flatcache/IPath.h> #include <carb/flatcache/IToken.h> #include <carb/flatcache/PrimChanges.h> #include <carb/logging/Log.h> #include <gsl/span> #include <carb/flatcache/Type.h> #include <map> #include <stdint.h> #include "carb/cpp17/Optional.h" using carb::cpp17::optional; namespace carb { namespace flatcache { // The comments in this file are intended to be read top to bottom, like a book. // This file defines flatcache::StageWithHistory, an instance of which stores // the current stage and a configurable number of frames of state history. It // is thread safe, in the sense that the current state can be safely read and // written in parallel with multiple threads reading the history. The class // definition is towards the end of this file. We first define some basic types, // a read/write accessor class for use by the main/game/sim thread, and two // read-only accessor classes for use on render threads. These classes provide // access to an interpolated state and a window of state history respectively. // To specify paths, attribute names, and attribute types we use // flatcache::Path, flatcache::Token and graph::Type types, rather than // USD's SdfPath, TfToken and TfType. This allows us to access the stage and // history without including USD headers. // The main class is this file is StageWithHistory, which is defined towards // the end of the file. class StageWithHistory; template<typename T> class AttributeArrayResult; /** * @invariant arrayBytes.size() must be a multiple of bytesPerElement */ class ConstArrayAsBytes { public: gsl::span<const gsl::byte> arrayBytes; size_t bytesPerElement; Type elementType; }; // findPrims() returns a list of buckets of prims, represented by PrimBucketList. class PrimBucketList { friend class StageAtTimeInterval; friend class StageInProgress; protected: PrimBucketListId m_primBucketListId; static carb::flatcache::IPrimBucketList* sIPrimBucketList(); PrimBucketList(PrimBucketListId id) : m_primBucketListId(id) { } public: // PrimBucketList is opaque, you have to use the getAttributesArray methods // of StageInProgress, StageAtTime or StageAtTimeInterval to read the // attributes of its elements. size_t bucketCount() const; size_t size() const; void print() const; PrimBucketListId getId() const { return m_primBucketListId; } ~PrimBucketList(); }; // ChangedPrimBucketList is a PrimBucketList that has changes stored for a // particular listener. It is returned by StageInProgress::getChanges(). class ChangedPrimBucketList : public PrimBucketList { ChangedPrimBucketList(PrimBucketListId id) : PrimBucketList(id) {} friend class StageInProgress; public: BucketChanges getChanges(size_t index); AddedPrimIndices getAddedPrims(size_t index); }; // The main/game/sim thread uses the following class to read and write the // state at the current frame. // // StageInProgress can either be used RAII style, you construct it from a frameNumber, // or non-RAII style, where you construct it from an existing stageInProgressId. class StageInProgress { StageInProgressId m_stageInProgress; bool m_createdFromId; UsdStageId m_usdStageId; // Only valid if m_createFromId == false public: // The constructor creates a new frame and locks it for read/write StageInProgress(StageWithHistory& stageWithHistory, size_t simFrameNumber); // Create from an already locked frame StageInProgress(StageInProgressId stageInProgressId); // Returns the frame number allocated by constructor size_t getFrameNumber(); // Returns the frame time allocated by constructor RationalTime getFrameTime(); // Returns which mirrored array is valid: CPU, GPU, etc. ValidMirrors getAttributeValidBits(const Path& path, const Token& attrName) const; // getAttribute returns a read/write pointer to a non-array attribute // If it returns nullptr then the attribute doesn't exist in the stage template <typename T> T* getAttribute(const Path& path, const Token& attrName); // getAttribute returns a read-only pointer to a non-array attribute // If it returns nullptr then the attribute doesn't exist in the stage template <typename T> const T* getAttributeRd(const Path& path, const Token& attrName); // getAttribute returns a write-only pointer to a non-array attribute // If it returns nullptr then the attribute doesn't exist in the stage template <typename T> T* getAttributeWr(const Path& path, const Token& attrName); // getAttribute returns a read/write pointer to a non-array attribute // If it returns nullptr then the attribute doesn't exist in the stage template <typename T> T* getAttributeGpu(const Path& path, const Token& attrName); // getAttribute returns a read-only pointer to a non-array attribute // If it returns nullptr then the attribute doesn't exist in the stage template <typename T> const T* getAttributeRdGpu(const Path& path, const Token& attrName); // getAttribute returns a write-only pointer to a non-array attribute // If it returns nullptr then the attribute doesn't exist in the stage template <typename T> T* getAttributeWrGpu(const Path& path, const Token& attrName); // getOrCreateAttributeWr returns a write-only pointer to a non-array // attribute. If the attribute doesn't exist, then it will create it. // The return type is a reference rather than a pointer because the // attribute is guaranteed to exist on exit template <typename T> T& getOrCreateAttributeWr(const Path& path, const Token& attrName, Type type); // getAttribute returns a read/write span of an array attribute // The span allows the array size to be read, but not written // To set the array size, use setArrayAttributeSize template <typename T> gsl::span<T> getArrayAttribute(const Path& path, const Token& attrName); // getAttributeRd returns a read-only span of an array attribute // The array size is also read only template <typename T> gsl::span<const T> getArrayAttributeRd(const Path& path, const Token& attrName); // getAttributeRd returns a write-only span of an array attribute // The array size is read only, to resize use setArrayAttributeSize template <typename T> gsl::span<T> getArrayAttributeWr(const Path& path, const Token& attrName); // Get the size of an array attribute. When writing CPU code, it isn't // normally necessary to use this method, as getArrayAttribute returns a // span containing the data pointer and the size. // However, when writing mixed CPU/GPU code it is wasteful to copy the // array data from GPU to CPU when just the size is required, so use this // method in that case. size_t getArrayAttributeSize(const Path& path, const Token& attrName); // Set the size of an array attribute void setArrayAttributeSize(const Path& path, const Token& attrName, size_t elemCount); template <typename T> gsl::span<T> setArrayAttributeSizeAndGet(const PrimBucketList& primBucketList, size_t primBucketListIndex, size_t indexInBucket, const Token& attrName, size_t newElemCount); // createPrim, destroyPrim, createAttribute and destroyAttribute do what // you'd expect void createPrim(const Path& path); void destroyPrim(const Path& path); void createAttribute(const Path& path, const Token& attrName, Type type); template<int n> void createAttributes(const Path& path, std::array<AttrNameAndType, n> attributes); // Deprecated: type argument is not used. void destroyAttribute(const Path& path, const Token& attrName, Type type); void destroyAttribute(const Path& path, const Token& attrName); template <int n> void destroyAttributes(const Path& path, const std::array<Token, n>& attributes); void destroyAttributes(const Path& path, const std::vector<Token>& attributes); // findPrims() finds prims that have all the attributes in "all", and any // of the attributes in "any", and none of the attributes in "none". // The attributes of the resulting prims can be accessed as piecewise // contiguous arrays, using getAttributeArray() below, which is typically // faster than calling getAttribute for each prim. PrimBucketList findPrims(const carb::flatcache::set<AttrNameAndType>& all, const carb::flatcache::set<AttrNameAndType>& any = {}, const carb::flatcache::set<AttrNameAndType>& none = {}); /** * Tell a listener to log changes for an attribute. * Attaches listener to stage if not already attached * * @param[in] attrName The attribute's name * @param[in] listenerId The listener */ void attributeEnableChangeTracking(const Token& attrName, ListenerId listenerId); /** * Tell a listener to stop logging changes for an attribute. * Attaches listener to stage if not already attached * * @param[in] attrName The attribute's name * @param[in] listenerId The listener */ void attributeDisableChangeTracking(const Token& attrName, ListenerId listenerId); /** * Tell a listener to log prim creates * Attaches listener to stage if not already attached * * @param[in] attrName The attribute's name * @param[in] listenerId The listener */ void enablePrimCreateTracking(ListenerId listenerId); /** * Pause change tracking. * * @param[in] listenerId The listener to pause */ void pauseChangeTracking(ListenerId listenerId); /** * Resume change tracking. * * @param[in] listenerId The listener to resume */ void resumeChangeTracking(ListenerId listenerId); /** * Is change tracking paused? * * @param[in] listenerId The listener * @return Whether the listener is paused */ bool isChangeTrackingPaused(ListenerId listenerId); /** * Get changes * * @param[in] listenerId The listener * @return The changes that occured since the last time the listener was popped */ ChangedPrimBucketList getChanges(ListenerId listenerId); /** * Clear the list of changes * * @param[in] listenerId The listener */ void popChanges(ListenerId listenerId); /** * Get the number of listeners * * @return The number of listeners listening to this stage */ size_t getListenerCount(); /** * Is the listener attached to this stage * * @return Whether the listener is attached to this stage */ bool isListenerAttached(ListenerId listenerId); /** * Detach the listener from the stage. Future changes will not be logged for this listener. * * @param[in] listenerId The listener * @return Whether the listener is attached to this stage */ void detachListener(ListenerId listenerId); // getAttributeArray(primBucketList, index, attrName) returns a read/write // contiguous array of the values of attribute "attrName" for each prim of // bucket "index" of "primBucketList". // "index" must be in the range [0..primBucketList.getBucketCount()) template <typename T> gsl::span<T> getAttributeArray(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName); template <typename T> gsl::span<const T> getAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; template <typename T> gsl::span<T> getAttributeArrayWr(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName); template <typename T> gsl::span<T> getAttributeArrayGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName); template <typename T> gsl::span<const T> getAttributeArrayRdGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; template <typename T> gsl::span<T> getAttributeArrayWrGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName); template <typename T> gsl::span<T> getOrCreateAttributeArrayWr(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName, Type type); // getAttributeArray(primBucketList, index, attrName) returns a vector of // array-valued attributes "attrName" for the prims of bucket "index" of // "primBucketList". "index" must be in the range [0..primBucketList.getBucketCount()) // It gives read/write access to the values of each prim's array template <typename T> std::vector<gsl::span<T>> getArrayAttributeArray(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; // getAttributeArray(primBucketList, index, attrName) returns a vector of // array-valued attributes "attrName" for the prims of bucket "index" of // "primBucketList". "index" must be in the range [0..primBucketList.getBucketCount()) // It gives read-only access to the values of each prim's array template <typename T> std::vector<gsl::span<const T>> getArrayAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; // getAttributeArray(primBucketList, index, attrName) returns a vector of // array-valued attributes "attrName" for the prims of bucket "index" of // "primBucketList". "index" must be in the range [0..primBucketList.getBucketCount()) // It gives write-only access to the values of each prim's array template <typename T> std::vector<gsl::span<T>> getArrayAttributeArrayWr(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; // getPathArray(primBucketList, index) returns a read-only contiguous array // of the paths of the prims of bucket "index" of "primBucketList". // "index" must be in the range [0..primBucketList.getBucketCount()) gsl::span<const Path> getPathArray(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; flatcache::set<AttrNameAndType> getAttributeNamesAndTypes(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; // TODO: replace with an iterator for iterating over bucket names void printBucketNames() const; // Record that the attribute at path.attrName has been modified. Right now this is // done explicitly to give a high degree of control over which attributes get // passed to the notice. void logAttributeWriteForNotice(const Path& path, const Token& attrName); // Construct and send a TfNotice with a vector of objects paths // that have changed, much like the ObjectsChanged notice from USD void broadcastTfNoticeForAttributesChanged() const; // Connection API /** * @brief Create a connection on the target prim * * @param path the target prim on which to create a connection * @param connectionName specifies the connections attribute name on the prim * @param connection specifies the target prim and attribute of the connection */ void createConnection(const Path& path, const Token& connectionName, const Connection& connection); /** * @brief Create an arbitrary number of connections on the target prim * * @param path the target prim on which to create a connection * @param connectionNames a span of attribute names. Must match the size of the connections vector * @param connections a span of connections. Must match the size of the connectionNames vector */ void createConnections(const Path& path, const gsl::span<Token>& connectionNames, const gsl::span<Connection>& connections ); /** * @brief removes a connection from a prim * * @param path the target prim from which to remove a connection * @param connectionName the name of the connection to remove */ void destroyConnection(const Path& path, const Token& connectionName); /** * @brief removes an arbitary number of connections from a prim * * @param path the target prim from which to remove the connections * @param connectionNames the names of the connections to be removed */ void destroyConnections(const Path& path, const gsl::span<Token>& connectionNames); /** * @brief Get a R/W pointer to a connection on the target prim * * @param path the target prim * @param connectionName the target connection name * @return a R/W pointer to the connection */ Connection* getConnection(const Path& path, const Token& connectionName); /** * @brief Get a read only pointer to a connection on the target prim * * @param path the target prim * @param connectionName the target connection name * @return a read only pointer to the connection */ const Connection* getConnectionRd(const Path& path, const Token& connectionName); /** * @brief Get a write only pointer to a connection on the target prim * * @param path the target prim * @param connectionName the target connection name * @return a write only pointer to the connection */ Connection* getConnectionWr(const Path& path, const Token& connectionName); /** * @brief Copy all attributes from the source prim to the destination prim * Will create attributes if they do not exist on the destination prim * If an attribute exists on both prims they must have compatible types to copy. * * @param[in] srcPath the source prim * @param[in] dstPath the destination prim */ void copyAttributes(const Path& srcPath, const Path& dstPath); /** * @brief Copy the specified attributes from the source prim to the destination prim * Will create attributes if they do not exist on the destination prim * If an attribute exists on both prims they must have compatible types to copy. * * @param[in] srcPath the source prim * @param[in] srcAttrs a span of attributes to be copied. * @param[in] dstPath the destination prim */ void copyAttributes(const Path& srcPath, const gsl::span<Token>& srcAttrs, const Path& dstPath); /** * @brief Copy the specified attributes from the source prim to the the specified * attributes on the destination prim * Will create attributes if they do not exist on the destination prim * If an attribute exists on both prims they must have compatible types to copy. * Note: The srcAttrs and dstAttrs must be the same size as the function assumes * that the copy is 1 to 1 in terms of name alignment * * @param[in] srcPath the source prim * @param[in] srcAttrs a span of attributes to be copied. * @param[in] dstPath the destination prim * @param[in] dstAttrs a span of attributes to be copied. */ void copyAttributes(const Path& srcPath, const gsl::span<Token>& srcAttrs, const Path& dstPath, const gsl::span<Token>& dstAttrs); StageInProgressId getId() const { return m_stageInProgress; } /** * @brief Check whether a prim exists at a given path * @param[in] the path * @return true if a prim exists at the path */ bool primExists(const Path& path); // If StageInProgress was created from an Id, then do nothing // Else unlock the current sim frame, allowing it to be read by // other threads ~StageInProgress(); }; // The following two classes, StageAtTime and StageAtTimeInterval // are used by reader threads to read the history. StageAtTime is // used when the state of a stage is needed at a particular point in time. // StageAtTimeInterval is used when we need all the stage history in a given time // window. // // There can be multiple threads reading the history buffer, for example // multiple sensor renderers running at different rates. We use shared locks // to allow multiple threads to read the same frame of history. // // StageAtTimeInterval takes an RAII approach to locking, constructing one locks // a range of slots for reading, and destructing unlocks them. class StageAtTimeInterval { StageAtTimeIntervalId m_stageAtTimeInterval; static carb::flatcache::IStageAtTimeInterval* sIStageAtTimeInterval(); public: // The constructor locks frames of history StageAtTimeInterval(StageWithHistory& stageWithHistory, RationalTime beginTime, RationalTime endTime, bool includeEndTime = false); StageAtTimeInterval(StageWithHistoryId stageWithHistoryId, RationalTime beginTime, RationalTime endTime, bool includeEndTime = false); ValidMirrors getAttributeValidBits(const PathC& path, const TokenC& attrName) const; // Get values of locked elements template <typename T> std::vector<const T*> getAttributeRd(const Path& path, const Token& attrName) const; // Get GPU pointer and size of locked elements template <typename T> std::vector<const T*> getAttributeRdGpu(const Path& path, const Token& attrName) const; // Get the size of an array attribute. When writing CPU code, it isn't // normally necessary to use this method, as getArrayAttribute returns a // span containing the data pointer and the size. // However, when writing mixed CPU/GPU code it is wasteful to copy the // array data from GPU to CPU when just the size is required, so use this // method in that case. std::vector<size_t> getArrayAttributeSize(const Path& path, const Token& attrName) const; /** * @brief Get an array-valued attribute for reading from a single prim * * @param path The path of the prim * @param attrName The name of the attribute * * @return a vector of array spans, one for each time sample within the current StageAtTimeInterval */ template <typename T> std::vector<gsl::span<const T>> getArrayAttributeRd(const Path& path, const Token& attrName) const; /** * @brief Get an array-valued attribute as bytes for reading from a single prim. * This is useful for converting to VtValue * * @param path The path of the prim * @param attrName The name of the attribute * * @return a vector of array spans, one for each time sample within the * current StageAtTimeInterval */ std::vector<ConstArrayAsBytes> getArrayAttributeRawRd(const Path& path, const Token& attrName) const; // Get timestamps of locked elements std::vector<RationalTime> getTimestamps() const; size_t getTimeSampleCount() const; // findPrims() finds prims that have all the attributes in "all", and any // of the attributes in "any", and none of the attributes in "none". // The attributes of the resulting prims can be accessed as piecewise // contiguous arrays, using getAttributeArray() below, which is typically // faster than calling getAttribute for each prim. PrimBucketList findPrims(const carb::flatcache::set<AttrNameAndType>& all, const carb::flatcache::set<AttrNameAndType>& any = {}, const carb::flatcache::set<AttrNameAndType>& none = {}); // getAttributeArray(primBucketList, index, attrName) returns for each // timesample, a read-only, contiguous array of the values of attribute // "attrName" for each prim of bucket "index" of "primBucketList". // "index" must be in the range [0..primBucketList.getBucketCount()) template <typename T> std::vector<gsl::span<const T>> getAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; template <typename T> std::vector<gsl::span<const T>> getAttributeArrayRdGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; template <typename T> std::vector<std::vector<gsl::span<const T>>> getArrayAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; /** * @brief Read a raw byte representation for a given attribute from a given bucket. This is useful for doing things such as batched type conversions. * * @param primBucketList the list of buckets * @param primBucketListIndex the specific bucket to search * @param attrName the token describing the desired attribute * * @return a vector of byte arrays, one for each time sample within the current StageAtTimeInterval */ std::vector<gsl::span<const char>> getAttributeArrayRawRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; // getPathArray(primBucketList, index) returns for each timesample a // read-only contiguous array of the paths of the prims of bucket "index" // of "primBucketList". // "index" must be in the range [0..primBucketList.getBucketCount()) // The reason a separate path array is returned per sample is that prims // can be added and deleted from frame to frame, and we need to check which // prim a sample corresponds to when interpolating. std::vector<gsl::span<const Path>> getPathArray(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; /** * @brief Get a Connection on a target prim * * @param path the target prim * @param connectionName the connection name * @return a vector of read only pointers to connections */ std::vector<const Connection*> getConnectionRd(const Path& path, const Token& connectionName); // TODO: replace with an iterator for iterating over bucket names void printBucketNames() const; /** * @brief write the current data for this stageInProgress to the specified UsdStage * this will write all attributes at the currentTime in getFrameNumber() * * @param usdStageId Valid usdStage in the stage cache * * @return none */ void exportUsd(UsdStageId usdStageId) const; // Get the number of attributes for a given bucket. std::vector<size_t> getAttributeCounts(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; // Get the name and type of each attribute for a given bucket. std::pair< std::vector<std::vector<Token>>, std::vector<std::vector<Type>>> getAttributeNamesAndTypes(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; /** @brief Write a cache file to disk at a specified location * * @note Many parameters to this function are optional * @note This currently only writes the first time in the interval * * @file[in The location the file is desired to be written to * @workingBuffer[in] [Optional] In order to avoid costly reallocations * the code will attempt to re-use the memory at the buffer * location if it is large enough. If the buffer isn't larg * enough the cost of allocation, and re-traversal may be paid * @workingBufferSize[in] [Optional] If workingBuffer is non null, then this desrcibes the length * of the buffer * @return The amount of data needed to serialize the cache, a return value of 0 indicates an error * */ uint64_t writeCacheToDisk(const char* file, uint8_t* workingBuffer, uint64_t workingBufferSize) const; /** @brief Add a ref count to any data backed by the StageAtTimeIntercal * * @note The ref count will not enforce any behavior currently, but will * print a warning if backing data is deleted before all ref counts * are cleared * * @return None * */ void addRefCount(); /** @brief Remove a ref count from an existing timeInterval * * @return True if ref count was removed successfully, failure conditions may * include * (1) StageAtTimeInterval doesn't exist * (2) RefCount was already 0 */ bool removeRefCount(); /** @brief Query ref count for a stage at time * * @note A stage at time might be represented by multiple actual data sources * in that case we return the largest refcount of all the data sources * * @return number of reference counts */ unsigned int getRefCount(); // Unlocks elements to allow them to be reused. ~StageAtTimeInterval(); }; // StageAtTime is used when the state of a stage is needed at // a particular point in time, which may or may not be one of the times sampled // in the history. If it is, then getAttributeRd returns the exact value sampled. // If not, it linearly interpolates using the two closest samples in the history. // // StageAtTime takes an RAII approach to locking, constructing one // locks one or two frames in the history (depending on whether interpolation // is needed), and destructing unlocks them. class StageAtTime { // Invariants: // I0: if sampleTimes.size()==2, m_theta = (m_time - sampleTimes[0]) / // (sampleTimes[1] - sampleTimes[0]) // where sampleTimes = m_historyWindow.getTimestamps() // // In particular, m_theta increases linearly from 0 to 1 as m_time // increases from sampleTimes[0] to sampleTimes[1] // // TODO: do we need to delay conversion from rational number to double? StageAtTimeInterval m_historyWindow; RationalTime m_time; double m_theta; void initInterpolation() { std::vector<RationalTime> sampleTimes = m_historyWindow.getTimestamps(); if (sampleTimes.size() == 2) { if ((double)sampleTimes[0].denominator == 0.0 || (double)sampleTimes[1].denominator == 0.0) { CARB_LOG_WARN_ONCE("StageWithHistory initInterpolation(): cannot divide by a denominator with a value of zero."); m_theta = 0.0; } else { double a_t = (double)sampleTimes[0].numerator / (double)sampleTimes[0].denominator; double b_t = (double)sampleTimes[1].numerator / (double)sampleTimes[1].denominator; if (a_t == b_t) m_theta = 0.0; else { double c_t = (double)m_time.numerator / (double)m_time.denominator; m_theta = (c_t - a_t) / (b_t - a_t); } } } else if (sampleTimes.size() == 1) m_theta = 0.0; } public: // Locks one or two history elements for read. StageAtTime(StageWithHistory& stageWithHistory, RationalTime time) : m_historyWindow(stageWithHistory, time, time, true), m_time(time) { initInterpolation(); } StageAtTime(StageWithHistoryId stageWithHistoryId, RationalTime time) : m_historyWindow(stageWithHistoryId, time, time, true), m_time(time) { initInterpolation(); } // Auxiliary method to communicate attributes of types which will not be interpolated // Supported types: bool, int, uint // no samples found: return nullopt // samples found: return pair{value of sample in frame n, value of sample in frame n+1} template <typename T> optional<std::pair<optional<T>, optional<T>>> getNonInterpolatableAttributeRd(const Path& path, const Token& attrName) const; ValidMirrors getAttributeValidBits(const PathC& path, const TokenC& attrName) const; // Read interpolated elements template <typename T> optional<T> getAttributeRd(const Path& path, const Token& attrName) const; // Read GPU elements (interpolation not supported yet!) template <typename T> const T* getAttributeRdGpu(const Path& path, const Token& attrName) const; // Get array attribute size, useful for GPU attributes size_t getArrayAttributeSize(const Path& path, const Token& attrName) const; // Get arrau attribute read template <typename T> gsl::span<const T> getArrayAttributeRd(const Path& path, const Token& attrName); // findPrims() finds prims that have all the attributes in "all", and any // of the attributes in "any", and none of the attributes in "none". // The attributes of the resulting prims can be accessed as piecewise // contiguous arrays, using getAttributeArray() below, which is typically // faster than calling getAttribute for each prim. PrimBucketList findPrims(const carb::flatcache::set<AttrNameAndType>& all, const carb::flatcache::set<AttrNameAndType>& any = {}, const carb::flatcache::set<AttrNameAndType>& none = {}) { return m_historyWindow.findPrims(all, any, none); } // getAttributeArray(primBucketList, index, attrName) returns a read-only // contiguous array of the values of attribute "attrName" for each prim of // bucket "index" of "primBucketList". // "index" must be in the range [0..primBucketList.getBucketCount()) template <typename T> AttributeArrayResult<T> getAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; template <typename T> AttributeArrayResult<T> getAttributeArrayRdGpu(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; template <typename T> AttributeArrayResult<std::vector<T>> getArrayAttributeArrayRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; /** * @brief Read a raw byte representation for a given attribute from a given bucket. This is useful for doing things such as batched type conversions. * * @param primBucketList the list of buckets * @param primBucketListIndex the specific bucket to search * @param attrName the token describing the desired attribute * * @return a vector of byte arrays, one for each time sample underlying the current StageAtTime. Note: Does not perform any interpolation. */ std::vector<gsl::span<const char>> getAttributeArrayRawRd(const PrimBucketList& primBucketList, size_t primBucketListIndex, const Token& attrName) const; // getPathArray(primBucketList, index) returns a read-only contiguous array // of the paths of the prims of bucket "index" of "primBucketList". // "index" must be in the range [0..primBucketList.getBucketCount()) gsl::span<const Path> getPathArray(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; /** * @brief Get a read only pointer to a connection on a prim * * @param path the target prim * @param connectionName the target connection * @return returns a vector read only pointers to connections, one per time sample */ std::vector<const Connection*> getConnectionRd(const Path& path, const Token& connectionName); // TODO: replace with an iterator for iterating over bucket names void printBucketNames() const; // Get the number of attributes for a given bucket. size_t getAttributeCount(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; // Get the name and type of each attribute for a given bucket. std::pair< std::vector<Token>, std::vector<Type>> getAttributeNamesAndTypes(const PrimBucketList& primBucketList, size_t primBucketListIndex) const; // Unlocks elements to allow them to be reused. ~StageAtTime() = default; /** @brief Write a cache file to disk at a specified location * * @note Many parameters to this function are optional * * @file[in The location the file is desired to be written to * @workingBuffer[in] [Optional] In order to avoid costly reallocations * the code will attempt to re-use the memory at the buffer * location if it is large enough. If the buffer isn't larg * enough the cost of allocation, and re-traversal may be paid * @workingBufferSize[in] [Optional] If workingBuffer is non null, then this desrcibes the length * of the buffer * @return The amount of data needed to serialize the cache, a return value of 0 indicates an error * */ uint64_t writeCacheToDisk(const char* file, uint8_t* workingBuffer, uint64_t workingBufferSize) const; /** @brief Add a ref count to any data backed by the StageAtTimeInterval * * @note The ref count will not enforce any behavior currently, but will * print a warning if backing data is deleted before all ref counts * are cleared * * @return None * */ void addRefCount(); /** @brief Remove a ref count from an existing timeInterval * * @return True if ref count was removed successfully, failure conditions may * include * (1) StageAtTimeInterval doesn't exist * (2) RefCount was already 0 */ bool removeRefCount(); /** @brief Query ref count for a stage at time * * @note A stage at time might be represented by multiple actual data sources * in that case we return the largest refcount of all the data sources * * @return number of reference counts */ unsigned int getRefCount(); }; // Finally, here is the main class, StageWithHistory. class StageWithHistory { StageWithHistoryId m_stageWithHistory; UsdStageId m_usdStageId; friend class StageInProgress; friend class StageAtTimeInterval; public: StageWithHistory(UsdStageId usdStageId, size_t historyFrameCount, RationalTime simPeriod, bool withCuda=false); ~StageWithHistory(); /** * Create a listener * This just creates a listener ID, you have to attach it to a stage to use it. * Note that there is no destroyListener method. To stop using an ID, detach it from all stages it is attached to. * @return The listener */ ListenerId createListener(); }; const ListenerId kInvalidListenerId = { 0 }; } // namespace flatcache } // namespace carb // Implement above C++ methods by calling C-ABI interfaces #include "WrapperImpl.h"
41,215
C
41.799585
153
0.664855
omniverse-code/kit/fabric/include/carb/flatcache/USDValueAccessors.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 "UsdPCH.h" #include <carb/Defines.h> #include <carb/InterfaceUtils.h> #include <carb/Types.h> #include <carb/flatcache/FlatCacheUSD.h> #include <carb/flatcache/IPath.h> #include <carb/flatcache/PathToAttributesMap.h> #include <carb/flatcache/StageWithHistory.h> #include <iostream> #include <vector> namespace carb { namespace flatcache { // A TfNotice sent with a vector of paths for attribute that // have changed. Sent by StateInProgress upon request, contains // the paths of attributes that the StageInProgress has flagged // as modified during it's lifetime, which is typically one frame. // // primPaths and attributeNames are required to the same length, // the prim and attribute name within that prim whose value // changed class AttributeValuesChangedNotice : public pxr::TfNotice { public: AttributeValuesChangedNotice(const std::vector<pxr::SdfPath>& primPaths, const std::vector<pxr::TfToken>& attributeNames) : _primPaths(primPaths), _attributeNames(attributeNames) { } ~AttributeValuesChangedNotice() { } const std::vector<pxr::SdfPath>& GetPrimPaths() const { return _primPaths; } const std::vector<pxr::TfToken>& GetAttributeNames() const { return _attributeNames; } private: const std::vector<pxr::SdfPath> _primPaths; const std::vector<pxr::TfToken> _attributeNames; }; void broadcastTfNoticeForAttributesChanged(StageInProgressId stageInProgressId); template <typename T> T getValue(const pxr::UsdAttribute& attribute, const pxr::UsdTimeCode& timeCode) { // First, look in flatcache to see if a value is present. If not, fall back // to read USD's composed attribute value. { // read from flatcache via StageInProgress, this is called during a run // loop where extensions are modifying one timeslice within StageWithHisotry // Look up the long int identifier for the attribute's UsdStage auto usdStageId = PXR_NS::UsdUtilsStageCache::Get().GetId(attribute.GetStage()).ToLongInt(); // grab the carb interface for StageInProgress and use it to access the // (potentially NULL) current stageInProgress for the UsdStage auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); auto stageInProgress = iStageInProgress->get(usdStageId); if (stageInProgress.id) { // Grab a pointer to in-memory representation for the attribute value, in this // case a pointer to a T. Will be NULL if attribute doesn't exist in flatcache auto valueSpan = iStageInProgress->getAttribute(stageInProgress, carb::flatcache::asInt(attribute.GetPrimPath()), carb::flatcache::asInt(attribute.GetName())); T* valuePtr = (T*)valueSpan.ptr; if (valuePtr) { // We have a value stored for this attribute in flatcache, return it return *valuePtr; } } } // If we get here we didn't find a value stored for this attribute in flatcache, // so call USD API pxr::VtValue val; attribute.Get(&val, timeCode); return val.UncheckedGet<T>(); } template <typename T_VALUETYPE> void setFlatCacheValue(const pxr::UsdAttribute& attribute, T_VALUETYPE value, bool writeToUSD) { if (writeToUSD) { // write to the USD layer attribute.Set(value); } else { // write to flatcache, via StageInProgress // grab const references to the path of the attribute's parent // prim and the name of the attribute. Avoid copies here. const pxr::SdfPath& path = attribute.GetPrimPath(); const pxr::TfToken& name = attribute.GetName(); const pxr::SdfPath& attrPath = attribute.GetPath(); // Convert the bits into a carb-safe value auto pathId = carb::flatcache::asInt(path); auto nameId = carb::flatcache::asInt(name); // Look up the long int identifier for the attribute's UsdSage auto usdStageId = carb::flatcache::UsdStageId{ (uint64_t)PXR_NS::UsdUtilsStageCache::Get().GetId(attribute.GetStage()).ToLongInt() }; // grab the carb interface for StageInProgress and use it to access the // (potentially NULL) current stageInProgress for the UsdStage auto iStageInProgress = carb::getCachedInterface<carb::flatcache::IStageInProgress>(); auto stageInProgress = iStageInProgress->get(usdStageId); if (!stageInProgress.id) { // No one created a stageInProgress, we're expecting this // to be created by another extension or run loop // // XXX: warn, or return falsse? return; } // Grab a pointer to in-memory representation for the attribute value, in this // case a pointer to a float auto valuePtr = iStageInProgress->getAttribute(stageInProgress, pathId, nameId); // Set the value within stageInProgress ((T_VALUETYPE*)valuePtr.ptr)[0] = value; } } // This should be in UsdValueAccessors.cpp, but when it goes there // clients in DriveSim can't find the symbol. Needs fixing. inline void setFlatCacheValueFloat(const pxr::UsdAttribute& attribute, float value, bool writeToUSD) { setFlatCacheValue<float>(attribute, value, writeToUSD); } } }
5,939
C
33.941176
112
0.675535
omniverse-code/kit/fabric/include/carb/flatcache/IFlatcache.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 "IPath.h" #include <carb/Interface.h> #include <carb/flatcache/AttrNameAndType.h> #include <carb/flatcache/IdTypes.h> #include <carb/flatcache/Ordered_Set.h> #include <carb/flatcache/RationalTime.h> #include <map> #include <stdint.h> namespace carb { namespace flatcache { struct UsdStageId { uint64_t id; constexpr bool operator<(const UsdStageId& other) const { return id < other.id; } constexpr bool operator==(const UsdStageId& other) const { return id == other.id; } constexpr bool operator!=(const UsdStageId& other) const { return id != other.id; } }; static_assert(std::is_standard_layout<UsdStageId>::value, "Struct must be standard layout as it is used in C-ABI interfaces"); static constexpr UsdStageId kUninitializedStage{ 0 }; } } namespace std { template <> class hash<carb::flatcache::UsdStageId> { public: size_t operator()(const carb::flatcache::UsdStageId& key) const { return key.id; } }; } namespace carb { namespace flatcache { struct BucketId { uint64_t id; constexpr bool operator<(const BucketId& other) const { return id < other.id; } constexpr bool operator<=(const BucketId& other) const { return id <= other.id; } constexpr bool operator==(const BucketId& other) const { return id == other.id; } constexpr bool operator!=(const BucketId& other) const { return id != other.id; } constexpr BucketId& operator++() { ++id; return *this; } constexpr BucketId& operator--() { --id; return *this; } constexpr explicit operator size_t() const { return id; } }; static_assert(std::is_standard_layout<BucketId>::value, "Struct must be standard layout as it is used in C-ABI interfaces"); static constexpr BucketId kInvalidBucketId{ 0xffff'ffff'ffff'ffff }; // A struct that represents a subset of a bucket struct BucketSubset { BucketId bucket; // The target bucket from which we define a subset set<TokenC>* attributes; // The subset of attributes to consider - only used if allAttributes == false, MUST be set otherwise set<PathC>* paths; // The subset of paths to consider - only used if allPaths == false, MUST be set otherwise bool allAttributes; //attribute filtering or not bool allPaths; //path filtering or not }; static_assert(std::is_standard_layout<BucketSubset>::value, "BucketSubset must be standard layout as it is used in C-ABI interfaces"); } } namespace std { template <> class hash<carb::flatcache::BucketId> { public: size_t operator()(const carb::flatcache::BucketId& key) const { return key.id; } }; } namespace carb { namespace flatcache { // Flatcache stores data in untyped (byte) arrays. // For conversion back to typed arrays, getArraySpan methods return the // element size in bytes. They also return elementCount to allow the caller to // wrap the array in std::span, or bounds check array access themselves. // Flatcache methods can't return std::span or gsl::span directly, because they // are not C-ABI compatible. So we define SpanC/ConstSpanC, which are. struct ConstSpanC { const uint8_t* ptr; size_t elementCount; size_t elementSize; }; struct SpanC { uint8_t* ptr; size_t elementCount; size_t elementSize; // Casting SpanC to ConstSpanC is allowed, but not vice versa operator ConstSpanC() const { return { ptr, elementCount, elementSize }; } }; struct ConstSpanWithTypeC { const uint8_t* ptr; size_t elementCount; size_t elementSize; TypeC type; }; struct SpanWithTypeC { uint8_t* ptr; size_t elementCount; size_t elementSize; TypeC type; // Casting SpanWithTypeC to ConstSpanWithTypeC is allowed, but not vice versa operator ConstSpanWithTypeC() const { return { ptr, elementCount, elementSize, type }; } }; struct SpanSizeC { size_t* ptr; size_t elementCount; }; struct ConstSpanSizeC { const size_t* ptr; size_t elementCount; }; // An ArrayPointersAndSizesC is an array of immutably sized mutable // data arrays // // Rules (enforced by const): // { // ArrayPointersAndSizesC ps; // // // Allowed: Changing inner array values // ps.arrayPtrs[0][0] = 1 // // // Disallowed: Changing array pointers // ps.arrayPtrs[0] = (uint8_t*)p; // // // Disallowed: Changing inner array sizes // ps.sizes[0] = 1; // } struct ArrayPointersAndSizesC { uint8_t* const* arrayPtrs; const size_t* sizes; const size_t elementCount; }; // A ConstArrayPointersAndSizesC is an array of immutably sized immutable // data arrays // // Rules (enforced by const): // { // ConstArrayPointersAndSizesC ps; // // // Disallowed: Changing inner array values // ps.arrayPtrs[0][0] = 1 // // // Disallowed: Changing array pointers // ps.arrayPtrs[0] = (uint8_t*)p; // // // Disallowed: Changing inner array sizes // ps.sizes[0] = 1; // } struct ConstArrayPointersAndSizesC { const uint8_t* const* arrayPtrs; const size_t* sizes; size_t elementCount; }; static_assert(std::is_standard_layout<Path>::value, "Path must be standard layout as it is used in C-ABI interfaces"); struct ConstPathCSpan { const Path* ptr; size_t elementCount; }; struct ConstAttrNameAndTypeSpanC { const AttrNameAndType* ptr; size_t elementCount; }; struct ConstChangedIndicesC { bool allIndicesChanged; ConstSpanSizeC changedIndices; }; struct ConstChangedIndicesSpanC { const ConstChangedIndicesC* ptr; size_t elementCount; }; struct BucketChangesC { // Which attributes changed flatcache::ConstAttrNameAndTypeSpanC changedAttributes; // For each attribute, which prims changed? flatcache::ConstChangedIndicesSpanC changedIndices; flatcache::ConstPathCSpan pathArray; }; struct AddedPrimIndicesC { // Which prims were added? flatcache::ConstSpanSizeC addedIndices; }; struct StageWithHistorySnapshot { bool valid; size_t id; }; enum class ValidMirrors { eNone = 0, eCPU = 1, eCudaGPU = 2, eGfxGPU = 4 }; constexpr enum ValidMirrors operator|(const enum ValidMirrors a, const enum ValidMirrors b) { return (enum ValidMirrors)(uint32_t(a) | uint32_t(b)); } constexpr enum ValidMirrors operator&(const enum ValidMirrors a, const enum ValidMirrors b) { return (enum ValidMirrors)(uint32_t(a) & uint32_t(b)); } using PrimBucket = carb::flatcache::set<AttrNameAndType>; // // Note when extending the interface please add to the end so // that dependencies don't break as easily before they are rebuilt // struct IStageInProgress { CARB_PLUGIN_INTERFACE("carb::flatcache::IStageInProgress", 0, 2); StageInProgressId(CARB_ABI* create)(UsdStageId usdStageId, size_t simFrameNumber); StageInProgressId(CARB_ABI* get)(UsdStageId usdStageId); void(CARB_ABI* destroy)(UsdStageId usdStageId); size_t(CARB_ABI* getFrameNumber)(StageInProgressId stageId); // Prefetch prim from USD stage // This guarantees that subsequent gets of the prim from the cache will succeed void(CARB_ABI* prefetchPrim)(UsdStageId usdStageId, PathC path); // Get attribute for read/write access SpanC(CARB_ABI* getAttribute)(StageInProgressId stageId, PathC path, TokenC attrName); // Get attribute for read only access ConstSpanC(CARB_ABI* getAttributeRd)(StageInProgressId stageId, PathC path, TokenC attrName); // Get attribute for write only access SpanC(CARB_ABI* getAttributeWr)(StageInProgressId stageId, PathC path, TokenC attrName); // Get attribute for write only access, creating it if necessary SpanC(CARB_ABI* getOrCreateAttributeWr)(StageInProgressId stageId, PathC path, TokenC attrName, TypeC typeC); size_t(CARB_ABI* getArrayAttributeSize)(StageInProgressId stageId, PathC path, TokenC attrName); void(CARB_ABI* setArrayAttributeSize)(StageInProgressId stageId, PathC path, TokenC attrName, size_t elemCount); SpanC(CARB_ABI* setArrayAttributeSizeAndGet)(StageInProgressId stageId, PrimBucketListId primBucketList, size_t primBucketListIndex, size_t indexInBucket, TokenC attrName, size_t newElemCount); // Get an attribute's type Type(CARB_ABI* getType)(StageInProgressId stageId, PathC path, TokenC attrName); // Get prim's attribute count size_t(CARB_ABI* getAttributeCount)(StageInProgressId stageId, PathC path); // Get the names of a prim's attributes void(CARB_ABI* getAttributeNamesAndTypes)(Token* outNames, Type* outTypes, size_t outCount, StageInProgressId stageInProgressId, PathC path); // Attribute/prim create/destroy void(CARB_ABI* createPrim)(StageInProgressId stageId, PathC path); void(CARB_ABI* destroyPrim)(StageInProgressId stageId, PathC path); void(CARB_ABI* createAttribute)(StageInProgressId stageId, PathC path, TokenC attrName, TypeC type); void(CARB_ABI* createAttributes)( StageInProgressId stageId, PathC path, TokenC* attrNames, TypeC* types, uint32_t attrNameAndTypeCount); // Deprecated as type attribute is not required! void(CARB_ABI* destroyAttribute)(StageInProgressId stageId, PathC path, TokenC attrName, TypeC type); // see new destroyAttribute and destroyAttributes functions at end of IFlatcache // Attribute SOA accessors PrimBucketListId(CARB_ABI* findPrims)(StageInProgressId stageInProgressId, const carb::flatcache::set<AttrNameAndType>& all, const carb::flatcache::set<AttrNameAndType>& any, const carb::flatcache::set<AttrNameAndType>& none); void(CARB_ABI* getAttributeArray)(SpanC* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getAttributeArrayRd)(ConstSpanC* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getAttributeArrayWr)(SpanC* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getOrCreateAttributeArrayWr)(SpanC* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName, TypeC typeC); size_t(CARB_ABI* getBucketPrimCount)(StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); size_t(CARB_ABI* getBucketAttributeCount)(StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex); void(CARB_ABI* getBucketAttributeNamesAndTypes)(AttrNameAndType* out, size_t outCount, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex); ConstSpanSizeC(CARB_ABI* getArrayAttributeSizeArrayRd)(StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); ArrayPointersAndSizesC(CARB_ABI* getArrayAttributeArrayWithSizes)(StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); ConstArrayPointersAndSizesC(CARB_ABI* getArrayAttributeArrayWithSizesRd)(StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); ArrayPointersAndSizesC(CARB_ABI* getArrayAttributeArrayWithSizesWr)(StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getPathArray)(ConstPathCSpan* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex); void(CARB_ABI* printBucketNames)(StageInProgressId stageInProgressId); void(CARB_ABI* createForAllStages)(size_t simFrameNumber); void(CARB_ABI* destroyForAllStages)(); void(CARB_ABI* logAttributeWriteForNotice)(StageInProgressId stageId, PathC path, TokenC attrName); // Broadcast a USD TfNotice to all registered listeners containing paths of // all attributes passed to logAttributeWriteForNotice since this StageInProgress was constructed. // This is used, for example, to send changes to PhysX. void(CARB_ABI* broadcastTfNoticeForAttributesChanged)(StageInProgressId stageInProgressId); PrimBucketListId(CARB_ABI* getChanges)(StageInProgressId stageInProgressId, ListenerId listenerId); void(CARB_ABI* popChanges)(StageInProgressId stageInProgressId, ListenerId listenerId); RationalTime(CARB_ABI* getFrameTime)(StageInProgressId stageId); /** @brief Get a Span with a pointer to the head of the relevant array of data * with elementCount and elementSize reflecting the underlying data * * @stageId[in] Id for the stage to look in * @path[in] Path to the prim holding the attribute * @name[in] Name of the array attribute * * @return If a valid prim/attribute that hold an array returns a valid span, otherwise * returns an empty span. * */ SpanC(CARB_ABI* getArrayAttribute)(StageInProgressId stageId, PathC path, TokenC attrName); /** @brief Get a const Span with a pointer to the head of the relevant array of data * with elementCount and elementSize reflecting the underlying data * * @stageId[in] Id for the stage to look in * @path[in] Path to the prim holding the attribute * @name[in] Name of the array attribute * * @return If a valid prim/attribute that hold an array returns a valid span, otherwise * returns an empty span. * */ ConstSpanC(CARB_ABI* getArrayAttributeRd)(StageInProgressId stageId, PathC path, TokenC attrName); /** @brief Get a Span with a pointer to the head of the relevant array of data * with elementCount and elementSize reflecting the underlying data * * @stageId[in] Id for the stage to look in * @path[in] Path to the prim holding the attribute * @name[in] Name of the array attribute * * @return If a valid prim/attribute that hold an array returns a valid span, otherwise * returns an empty span. * */ SpanC(CARB_ABI* getArrayAttributeWr)(StageInProgressId stageId, PathC path, TokenC attrName); /** @brief Destroy attribute with matching name * * Overloads and superseeds destroyAttribute which takes a unnecessary attribute type. * * @stageId[in] Id for the stage to look in * @path[in] Path to the prim holding the attribute * @attrNames[in] Attribute name * */ void(CARB_ABI* destroyAttribute2)(StageInProgressId stageId, PathC path, TokenC attrName); /** @brief Destroy all attributes with matching names * * @stageId[in] Id for the stage to look in * @path[in] Path to the prim holding the attribute * @attrNames[in] Attribute name array * @attrNames[in] Attribute name array count * */ void(CARB_ABI* destroyAttributes)(StageInProgressId stageId, PathC path, TokenC* attrNames, uint32_t attrNameCount); void(CARB_ABI* getAttributeArrayGpu)(SpanC* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getAttributeArrayRdGpu)(ConstSpanC* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getAttributeArrayWrGpu)(SpanC* out, StageInProgressId stageInProgressId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); // Get GPU attribute for read/write access SpanC(CARB_ABI* getAttributeGpu)(StageInProgressId stageId, PathC path, TokenC attrName); // Get GPU attribute for read only access ConstSpanC(CARB_ABI* getAttributeRdGpu)(StageInProgressId stageId, PathC path, TokenC attrName); // Get GPU attribute for write only access SpanC(CARB_ABI* getAttributeWrGpu)(StageInProgressId stageId, PathC path, TokenC attrName); /** @brief Returns which mirrors of the array are valid: CPU, GPU, etc. * * @stageId[in] The stage to query validity from * @path[in] The prim path * @attrName[in] The attribute name * * @return ValidMirrors struct * */ ValidMirrors(CARB_ABI* getAttributeValidBits)(StageInProgressId stageId, const PathC& path, const TokenC& attrName); // Connection API /** * @brief Create a connection on a prim * * @param[in] stageId the stage to work on * @param[in] path the prim to create the connection on * @param[in] connectionName the name of the connection attribute * @param[in] connection the target prim and attribute for the connection */ void(CARB_ABI* createConnection)(StageInProgressId stageId, PathC path, TokenC connectionName, Connection connection); /** * @brief Create multiple connections on a prim * * @param[in] stageId the stage to work on * @param[in] path the prim to create the connection on * @param[in] connectionNames the name of the connection attributes to create * @param[in] connection the target prim and attribute for the connections * @param[in] connectionCount the number of connections to be created. */ void(CARB_ABI* createConnections)(StageInProgressId stageId, PathC path, const TokenC* connectionNames, const Connection* connections, size_t connectionCount); /** * @brief remove a connection on a prim * * @param[in] stageId the stage to work on * @param[in] path the prim to remove the connection from * @param[in] connectionName the name of the connection attribute */ void(CARB_ABI* destroyConnection)(StageInProgressId stageId, PathC path, TokenC connectionName); /** * @brief Remove multiple connections from a prim * * @param[in] stageId the stage to work on * @param[in] path the prim to remove the connections from * @param[in] connectionNames the name of the connection attributes to be removed * @param[in] connectionCount the number of connections to be removed. */ void(CARB_ABI* destroyConnections)(StageInProgressId stageId, PathC path, const TokenC* connectionNames, size_t connectionCount); /** * @brief Retrieves a connection attribute from a prim * * @param[in] stageId the stage to work on * @param[in] path the prim to fetch the connection from * @param[in] connectionName the name of the connection attribute to fetch * @return a read/write pointer to the connection */ Connection*(CARB_ABI* getConnection)(StageInProgressId stageId, PathC path, TokenC connectionName); /** * @brief Retrieves a connection attribute from a prim * * @param[in] stageId the stage to work on * @param[in] path the prim to fetch the connection from * @param[in] connectionName the name of the connection attribute to fetch * @return a read only pointer to the connection */ const Connection*(CARB_ABI* getConnectionRd)(StageInProgressId stageId, PathC path, TokenC connectionName); /** * @brief Retrieves a connection attribute from a prim * * @param[in] stageId the stage to work on * @param[in] path the prim to fetch the connection from * @param[in] connectionName the name of the connection attribute to fetch * @return a write only pointer to the connection */ Connection*(CARB_ABI* getConnectionWr)(StageInProgressId stageId, PathC path, TokenC connectionName); /** * @brief Copy all attributes from the source prim to the destination prim * Will create attributes if they do not exist on the destination prim * If an attribute exists on both prims they must have compatible types to copy. * * @param[in] stageId the stage id to use for copying * @param[in] srcPath the source prim * @param[in] dstPath the destination prim */ void(CARB_ABI* copyAllAttributes)(StageInProgressId stageId, PathC srcPath, PathC dstPath); /** * @brief Copy the specified attributes from the source prim to the the specified * attributes on the destination prim * Will create attributes if they do not exist on the destination prim * If an attribute exists on both prims they must have compatible types to copy. * Note: The srcAttrs and dstAttrs must be the same size as the function assumes * that the copy is 1 to 1 in terms of name alignment * * @param[in] stageId the stage id to use for copying * @param[in] srcPath the source prim * @param[in] srcAttrs a vector of attributes to be copied. * @param[in] dstPath the destination prim * @param[in] dstAttrs a vector of attributes to be copied. * @param[in] count the number of attributes to copy */ void(CARB_ABI* copySpecifiedAttributes)(StageInProgressId stageId, PathC srcPath, const TokenC* srcAttrs, PathC dstPath, const TokenC* dstAttrs, size_t count); }; struct IStageAtTimeInterval { CARB_PLUGIN_INTERFACE("carb::flatcache::IStageAtTimeInterval", 0, 1); StageAtTimeIntervalId(CARB_ABI* create)(StageWithHistoryId stageWithHistoryId, RationalTime beginTime, RationalTime endTime, bool includeEndTime); void(CARB_ABI* destroy)(StageAtTimeIntervalId stageAtTimeIntervalId); size_t(CARB_ABI* getTimesampleCount)(StageAtTimeIntervalId stageAtTimeIntervalId); void(CARB_ABI* getTimestamps)(RationalTime* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId); // Single attribute accessor size_t(CARB_ABI* getAttributeRd)(const void** out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PathC path, TokenC attrName); // Attribute SOA accessors PrimBucketListId(CARB_ABI* findPrims)(StageAtTimeIntervalId stageAtTimeIntervalId, const carb::flatcache::set<AttrNameAndType>& all, const carb::flatcache::set<AttrNameAndType>& any, const carb::flatcache::set<AttrNameAndType>& none); void(CARB_ABI* getAttributeArrayRd)(ConstSpanC* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getArrayAttributeArrayWithSizesRd)(ConstArrayPointersAndSizesC* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); void(CARB_ABI* getPathArray)(ConstPathCSpan* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex); void(CARB_ABI* printBucketNames)(StageAtTimeIntervalId stageAtTimeIntervalId); void(CARB_ABI* exportUsd)(StageAtTimeIntervalId stageAtTimeIntervalId, UsdStageId usdStageId); RationalTime(CARB_ABI* getSimPeriod)(UsdStageId usdStageId); void(CARB_ABI* getAttributeCounts)(StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex, size_t timesamples, size_t* outCounts); void(CARB_ABI* getAttributeNamesAndTypes)(StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex, size_t timesamples, const size_t* attributeCounts, Token** outNames, Type** outTypes); size_t(CARB_ABI* getAttributeCountForTimesample)(StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex, size_t timesampleIndex); void(CARB_ABI* getAttributeNamesAndTypesForTimesample)(StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex, size_t timesampleIndex, size_t attributeCount, Token* outNames, Type* outTypes); void(CARB_ABI* getArrayAttributeWithSizeRd)(ConstSpanWithTypeC* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, carb::flatcache::PathC path, carb::flatcache::TokenC attrName); /** @brief Write a cache file to disk at a specified location * * @note Many parameters to this function are optional * @note This currently only writes the first time in the interval * @stageAtTimeIntervalId[in] The stage at time to be written to disk * @file[in The location the file is desired to be written to * @workingBuffer[in] [Optional] In order to avoid costly reallocations * the code will attempt to re-use the memory at the buffer * location if it is large enough. If the buffer isn't larg * enough the cost of allocation, and re-traversal may be paid * @workingBufferSize[in] [Optional] If workingBuffer is non null, then this desrcibes the length * of the buffer * @return The amount of data needed to serialize the cache, a return value of 0 indicates an error * */ uint64_t(CARB_ABI* writeCacheToDisk)( StageAtTimeIntervalId stageAtTimeIntervalId, const char* file, uint8_t* workingBuffer, uint64_t workingBufferSize); /** @brief Add a ref count to any data backed by the StageAtTimeIntercal * * @note The ref count will not enforce any behavior currently, but will * print a warning if backing data is deleted before all ref counts * are cleared * * @stageAtTimeIntervalId[in] The stage at time tracked for the ref counting * * @return None * */ void(CARB_ABI* addRefCount)(StageAtTimeIntervalId stageAtTimeIntervalId); /** @brief Remove a ref count from an existing timeInterval * * * @stageAtTimeIntervalId[in] The stage at time tracked for the ref counting * * @return True if ref count was removed successfully, failure conditions may * include * (1) StageAtTimeInterval doesn't exist * (2) RefCount was already 0 * */ bool(CARB_ABI* removeRefCount)(StageAtTimeIntervalId stageAtTimeIntervalId); /** @brief Query ref count for a stage at time * * @note A stage at time might be represented by multiple actual data sources * in that case we return the largest refcount of all the data sources * * @stageAtTimeIntervalId[in] The stage at time tracked for the ref counting * * @return number of reference counts * */ unsigned int(CARB_ABI* getRefCount)(StageAtTimeIntervalId stageAtTimeIntervalId); // Access GPU Array attribute void(CARB_ABI* getAttributeArrayRdGpu)(ConstSpanC* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PrimBucketListId primBucketList, size_t primBucketListIndex, TokenC attrName); // Access GPU pointer attribute void(CARB_ABI* getAttributeRdGpu)(ConstSpanC* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PathC path, TokenC attrName); // Get array size, useful for GPU attributes size_t(CARB_ABI* getArrayAttributeSize)(size_t* out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PathC path, TokenC attrName); /** @brief Returns which mirrors of the array are valid: CPU, GPU, etc. * * @stageAtTimeIntervalId[in] The stage to query validity from * @path[in] The prim path * @attrName[in] The attribute name * * @return ValidMirrors struct * */ ValidMirrors(CARB_ABI* getAttributeValidBits)(StageAtTimeIntervalId stageAtTimeIntervalId, const PathC& path, const TokenC& attrName); /** * @brief * */ void(CARB_ABI* getConnectionRd)(const void** out, size_t outCount, StageAtTimeIntervalId stageAtTimeIntervalId, PathC path, TokenC connectionName); }; struct IStageWithHistory { CARB_PLUGIN_INTERFACE("carb::flatcache::IStageWithHistory", 0, 1); StageWithHistoryId(CARB_ABI* create)(UsdStageId usdStageId, size_t historyFrameCount, RationalTime simPeriod); StageWithHistoryId(CARB_ABI* get)(UsdStageId usdStageId); void(CARB_ABI* destroy)(UsdStageId usdStageId); // // Create a snapshot of the stageWIthHistory for the usdStageId, this currently just resets // the stage in progress, but it probably should be extended to copy the entire ringbuffer if we intend to // so anything other than reset to the start frame. // StageWithHistorySnapshot(CARB_ABI* saveSnapshot)(UsdStageId usdStageId); bool(CARB_ABI* deleteSnapshot)(UsdStageId usdStageId, size_t snapshotId); bool(CARB_ABI* restoreFromSnapshot)(UsdStageId usdStageId, size_t snapshotId); RationalTime(CARB_ABI* getSimPeriod)(UsdStageId usdStageId); // For multi-process replication. Stores the link between the stage id on the master process and the local stage id. void(CARB_ABI* setStageIdMapping)(UsdStageId usdStageIdMaster, UsdStageId usdStageIdLocal); ListenerId(CARB_ABI* createListener)(); /** @brief Get the last frame that was written to the StageWithHistory * * @usdStageId[in] The identifier for the statge * * @return the time, and period of the last valid data written to the StageWithHistory * */ RationalTime(CARB_ABI* getLatestFrame)(UsdStageId usdStageId); StageWithHistoryId(CARB_ABI* create2)(UsdStageId usdStageId, size_t historyFrameCount, RationalTime simPeriod, bool withCuda); UsdStageId(CARB_ABI* getLocalStageId)(UsdStageId usdStageIdMaster); }; struct IStageWithHistoryDefaults { CARB_PLUGIN_INTERFACE("carb::flatcache::IStageWithHistoryDefaults", 0, 1); void(CARB_ABI* setStageHistoryFrameCount)(size_t historyFrameCount); void(CARB_ABI* setStageHistoryUpdatePeriod)(uint64_t periodNumerator, uint64_t periodDenominator); }; struct IPrimBucketList { CARB_PLUGIN_INTERFACE("carb::flatcache::IPrimBucketList", 0, 2); void(CARB_ABI* destroy)(PrimBucketListId primBucketListId); size_t(CARB_ABI* getBucketCount)(PrimBucketListId primBucketListId); void(CARB_ABI* print)(PrimBucketListId primBucketListId); BucketChangesC(CARB_ABI* getChanges)(PrimBucketListId changeListId, size_t index); AddedPrimIndicesC(CARB_ABI* getAddedPrims)(PrimBucketListId changeListId, size_t index); }; struct IChangeTrackerConfig { CARB_PLUGIN_INTERFACE("carb::flatcache::IChangeTrackerConfig", 0, 3); void(CARB_ABI* pause)(StageInProgressId stageInProgressId, ListenerId listenerId); void(CARB_ABI* resume)(StageInProgressId stageInProgressId, ListenerId listenerId); bool(CARB_ABI* isChangeTrackingPaused)(StageInProgressId stageInProgressId, ListenerId listenerId); void(CARB_ABI* attributeEnable)(StageInProgressId stageInProgressId, TokenC attrName, ListenerId listenerId); void(CARB_ABI* attributeDisable)(StageInProgressId stageInProgressId, TokenC attrName, ListenerId listenerId); bool(CARB_ABI* isListenerAttached)(StageInProgressId stageInProgressId, ListenerId listenerId); void(CARB_ABI* detachListener)(StageInProgressId stageInProgressId, ListenerId listenerId); size_t(CARB_ABI* getListenerCount)(StageInProgressId stageInProgressId); void(CARB_ABI* enablePrimCreateTracking)(StageInProgressId stageInProgressId, ListenerId listenerId); }; /** @brief The Serializer interface provides the C-ABI compatible functions for * working with all serialization of SWH and workflows. This covers * (1) In-memory serialization/deserialization * (2) Serialization to Disk and From * (3) Functions to support replication based on serialization * Because of the nature of SWH there are multiple places one might want to * actually serialize the cache from, we provide some convenience functions * that wrap this up, but also the direct functionality to serialize a * PathToAttributesMap directly to/from a buffer for convenience. * */ struct ISerializer { CARB_PLUGIN_INTERFACE("carb::flatcache::ISerializer", 0, 2); // // deprecated for more appropriately named serializeRingBuffer // uint64_t(CARB_ABI* serializeStage)(StageWithHistoryId stageWithHistoryId, size_t slot, uint8_t* dest, size_t destSize); // // deprecated for more appropriately named deserializeIntoRingBuffer // bool (CARB_ABI* deserializeStage)(StageWithHistoryId stageWithHistoryId, size_t slot, const uint8_t* input, const size_t inputSize, size_t simFrameNumber, carb::flatcache::RationalTime simFrameTime); /** @brief Attempt to serialize the stage into the provided buffer. This function * is intended to be used when you want to serialize all the data within a * ring buffer entry, however this is often more data than needs to be sent. * * @stage[in] The StageWithHistory with the ring buffer to be serialized * @slot[in] The slot from the ring buffer to send * @dest[in/out] Pointer to buffer to be written to, will start writing to head * of pointer. dest will be left pointing to the point after the last write * @destSize Size of buffer that was allocated for the data (in bytes) * * @return Number of bytes written success is determined by (return <= @destSize) * * * @invariant It is safe to write to any memory within[dest, dest+size] for the * duration of the function call. * * @note If the cache will not fit into the size of memory allocated in * @dest then it will stop writing, but continue to run the serialize * algorithm to calculate the actual amount of data that needs to be * written * */ uint64_t(CARB_ABI* serializeRingBuffer)(StageWithHistoryId stageWithHistoryId, size_t slot, uint8_t* dest, size_t destSize); /** @brief Given a buffer that has the serialized version of a cache written * using the serialize function, this function will override all the data * in the ringbuffer at the requested slot with the data encoded in the * buffer. This function will only succeed if the StageWithHistory that * is passed in was created from the same UsdStage (opened at the same root layer) * that was used to create the original serialized cache. * * * @stageWithHistoryId[in] The stage to write the data to * @slot[in] The index in the ring buffer to pull to * @input[in] Pointer to buffer of data containing serialized cache * @inputSize[in] Size of data in the buffer * @simFrameNumber[in] The frame of the simulation to set the ring buffer entry to * @simFrameTime[in] The simFrame time to set the ring buffer to * * @return True if buffer was successfully de-serialized * * @TODO: whould we care that it came from the same version of the USD file? */ bool (CARB_ABI* deserializeIntoRingBuffer)(StageWithHistoryId stageWithHistoryId, size_t slot, const uint8_t* input, const size_t inputSize, size_t simFrameNumber, carb::flatcache::RationalTime simFrameTime); /** @brief Replicate the ring buffers from the master to the workers when running * multiple processes. Data is serialized into buffers allocated and broadcast * by Realm, followed by deserialization into the remote ring buffers. This * function is synchronous, i.e., the remote FlatCaches have finished updating * when this function returns. */ void (CARB_ABI* replicateRingBuffers)(); }; struct Platform; struct IPlatform { CARB_PLUGIN_INTERFACE("carb::flatcache::IPlatform", 0, 1); const Platform& (CARB_ABI* get)(const PlatformId& platformId); Platform& (CARB_ABI* getMutable)(const PlatformId& platformId); void (CARB_ABI* reset)(const PlatformId& platformId); void (CARB_ABI* resetAll)(); }; } // namespace flatcache } // namespace carb
41,868
C
40.169125
164
0.630386
omniverse-code/kit/fabric/include/carb/flatcache/GetArrayGPU.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "PathToAttributesMap.h" #include <carb/profiler/Profile.h> namespace carb { namespace flatcache { const uint64_t kProfilerMask = 1; // If this is an array-of-arrays: // array.cpuData - array of CPU pointers on CPU // gpuPointerArray->cpuData() - array of GPU pointers on CPU inline void PathToAttributesMap::enableGpuRead(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* gpuPointerArray) { CARB_PROFILE_ZONE(kProfilerMask, "enableGpuRead"); using omni::gpucompute::MemcpyKind; log("begin enableGpuRead\n"); bool& cpuValid = array.cpuValid; bool& gpuValid = array.gpuValid; bool& gpuAllocedWithCuda = array.gpuAllocedWithCuda; uint8_t* cpuArray = array.cpuData(); uint8_t*& gpuArray = array.gpuArray; if (gpuValid) { // Nothing to do } else if (cpuValid) { std::lock_guard<MirroredArray::AttributeMutex> hostDeviceLock(array.attributeMutex); const TypeC type = array.type; const Typeinfo &typeInfo = getTypeInfo(type); if (typeInfo.isArray) { const size_t elemCount = array.count; uint8_t** cpuPointers = reinterpret_cast<uint8_t**>(cpuArray); uint8_t** gpuPointers = reinterpret_cast<uint8_t**>(gpuPointerArray->cpuData()); for (size_t elem = 0; elem != elemCount; elem++) { const size_t desiredCapacity = elemToArraySize[elem]; const size_t cpuCapacity = reinterpret_cast<size_t*>(elemToArrayCpuCapacity->cpuData())[elem]; size_t& gpuCapacity = reinterpret_cast<size_t*>(elemToArrayGpuCapacity->cpuData())[elem]; if(gpuCapacity != desiredCapacity) { destructiveResizeIfNecessaryGPU(*gpuPointerArray, elem, gpuCapacity, desiredCapacity, typeInfo.arrayElemSize, platform.gpuCuda, platform.gpuCudaCtx); } const size_t copyByteCount = std::min(desiredCapacity, cpuCapacity) * typeInfo.arrayElemSize; if (copyByteCount > 0) { void* cpuPointer = cpuPointers[elem]; void* gpuPointer = gpuPointers[elem]; CARB_ASSERT(cpuPointer); CARB_ASSERT(gpuPointer); platform.gpuCuda->memcpyAsync( *platform.gpuCudaCtx, gpuPointer, cpuPointer, copyByteCount, MemcpyKind::hostToDevice); } } gpuPointerArray->cpuValid = true; } else { // Copy the outer array from CPU to GPU size_t byteCount = array.size(); allocGpuMemIfNecessary(array, byteCount, typeInfo.size, platform.gpuCuda, platform.gpuCudaCtx); log("array values: to GPU\n"); uint8_t* cpuArray = array.cpuData(); carb::profiler::ZoneId zoneId = CARB_PROFILE_BEGIN(kProfilerMask, "outer array values"); platform.gpuCuda->memcpyAsync(*platform.gpuCudaCtx, gpuArray, cpuArray, byteCount, MemcpyKind::hostToDevice); CARB_PROFILE_END(kProfilerMask, zoneId); } // New state cpuValid = true; gpuValid = true; gpuAllocedWithCuda = true; } } inline void PathToAttributesMap::enableGpuWrite(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* arrayGpuDataArray) { CARB_PROFILE_ZONE(kProfilerMask, "enableGpuWrite"); using omni::gpucompute::MemcpyKind; bool& usdValid = array.usdValid; bool& cpuValid = array.cpuValid; bool& gpuValid = array.gpuValid; bool& gpuAllocedWithCuda = array.gpuAllocedWithCuda; const TypeC type = array.type; const Typeinfo &typeInfo = getTypeInfo(type); std::lock_guard<MirroredArray::AttributeMutex> hostDeviceLock(array.attributeMutex); if (!typeInfo.isArray && !gpuValid) { size_t byteCount = array.size(); allocGpuMemIfNecessary(array, byteCount, typeInfo.size, platform.gpuCuda, platform.gpuCudaCtx); } else if (typeInfo.isArray) { // Array-valued elements are lazily allocated, meaning they are only // resized when write access is requested. // Write access has been requested, so resize if necessary size_t elemCount = array.count; for (size_t elem = 0; elem != elemCount; elem++) { size_t& gpuCapacity = reinterpret_cast<size_t*>(elemToArrayGpuCapacity->cpuData())[elem]; size_t desiredElemCount = elemToArraySize[elem]; resizeIfNecessaryGPU( *arrayGpuDataArray, elem, gpuCapacity, desiredElemCount, typeInfo.arrayElemSize, platform.gpuCuda, platform.gpuCudaCtx); } // Upload of allocated pointers to GPU happens outside this function } // New state usdValid = false; cpuValid = false; gpuValid = true; gpuAllocedWithCuda = true; if (elemToArrayCpuCapacity) elemToArrayCpuCapacity->usdValid = false; if (elemToArrayGpuCapacity) elemToArrayGpuCapacity->usdValid = false; if (arrayGpuDataArray) arrayGpuDataArray->usdValid = false; } inline ConstSpanC PathToAttributesMap::getArraySpanRdGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArraySpanRdGpuC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return { nullptr, 0, 0 }; // We don't set dirty indices here because this method gives read-only access return getArraySpanC(bucketId, attrName, CudaReadConfig(), suffix).array; } inline const void* PathToAttributesMap::getArrayRdGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayRdGpuC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; // We don't set dirty indices here because this method gives read-only access return getArraySpanC(bucketId, attrName, CudaReadConfig(), suffix).array.ptr; } inline SpanC PathToAttributesMap::getArrayGpuC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayGpuC", apiLogEnabled, attrName); ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CudaReadWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array; } inline ConstSpanC PathToAttributesMap::getArrayRdGpuC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayRdGpuC", apiLogEnabled, attrName); const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CudaReadConfig(), suffix); // We don't set dirty indices here because this method gives read-only access return arrayAndDirtyIndices.array; } inline SpanC PathToAttributesMap::getArrayWrGpuC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayWrC", apiLogEnabled, attrName); ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CudaWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array; } inline SpanC PathToAttributesMap::getArraySpanWrGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArraySpanWrGpuC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return { nullptr, 0, 0 }; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, CudaWriteConfig(), suffix); setArrayDirty(array); return array.array; } inline void* PathToAttributesMap::getArrayWrGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayWrGpuC", apiLogEnabled, attrName); // Get write-only GPU access BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, CudaWriteConfig(), suffix); setArrayDirty(array); return array.array.ptr; } inline SpanC PathToAttributesMap::getArraySpanGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArraySpanGpuC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return { nullptr, 0, 0 }; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, CudaReadWriteConfig(), suffix); setArrayDirty(array); return array.array; } inline void* PathToAttributesMap::getArrayGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayGpuC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, CudaReadWriteConfig(), suffix); setArrayDirty(array); return array.array.ptr; } inline SpanC PathToAttributesMap::getAttributeGpuC(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind, NameSuffix suffix) { APILOGGER("getAttributeGpuC", apiLogEnabled, path, attrName); bool present; // Whether this path has a bucket BucketId bucketId; // Pointer to the bucket if it does size_t element; // Index corresponding to path in this bucket's arrays std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, CudaReadWriteConfig().withPtrToPtrKind(ptrToPtrKind), suffix); setArrayElementDirty(array, element); return getArrayElementPtr(array.array, element); } inline ConstSpanC PathToAttributesMap::getAttributeRdGpuC(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind, NameSuffix suffix) { APILOGGER("getAttributeRdGpuC", apiLogEnabled, path, attrName); bool present; BucketId bucketId; size_t element; std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; ConstSpanC array = getArraySpanC(bucketId, attrName, CudaReadConfig().withPtrToPtrKind(ptrToPtrKind), suffix).array; // We don't set dirty indices here because this method gives read-only access return getArrayElementPtr(array, element); } inline SpanC PathToAttributesMap::getAttributeWrGpuC(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind, NameSuffix suffix) { APILOGGER("getAttributeWrGpuC", apiLogEnabled, path, attrName); // Writing an element is a RMW on the whole array, so use getArrayGpu instead of getArrayGpuWr bool present; BucketId bucketId; size_t element; std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, CudaReadWriteConfig().withPtrToPtrKind(ptrToPtrKind), suffix); setArrayElementDirty(array, element); return getArrayElementPtr(array.array, element); } // Typed accessors template <typename T> inline const T* PathToAttributesMap::getArrayRdGpu(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayRdGpu", apiLogEnabled, attrName); // TODO: check that T is the correct type return reinterpret_cast<const T*>(getArrayRdGpuC(bucket, attrName)); } template <typename T> inline T* PathToAttributesMap::getArrayWrGpu(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayWrGpu", apiLogEnabled, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getArrayWrGpuC(bucket, attrName)); } template <typename T> inline T* PathToAttributesMap::getArrayGpu(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayGpu", apiLogEnabled, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getArrayGpuC(bucket, attrName)); } template <typename T> inline T* PathToAttributesMap::getAttributeGpu(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind) { APILOGGER("getAttributeGpu", apiLogEnabled, path, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getAttributeGpuC(path, attrName, ptrToPtrKind).ptr); } template <typename T> inline const T* PathToAttributesMap::getAttributeRdGpu(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind) { APILOGGER("getAttributeRdGpu", apiLogEnabled, path, attrName); // TODO: check that T is the correct type return reinterpret_cast<const T*>(getAttributeRdGpuC(path, attrName, ptrToPtrKind).ptr); } template <typename T> inline T* PathToAttributesMap::getAttributeWrGpu(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind) { APILOGGER("getAttributeWrGpu", apiLogEnabled, path, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getAttributeWrGpuC(path, attrName, ptrToPtrKind).ptr); } } }
14,162
C
37.909341
169
0.69856
omniverse-code/kit/fabric/include/carb/flatcache/AttrNameAndType.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/flatcache/IToken.h> #include <carb/flatcache/IPath.h> #include <carb/flatcache/Type.h> namespace carb { namespace flatcache { // Basic types // Types and methods ending in C are intended to be used with C-ABI interfaces. // PathToAttributesMap allows metadata to be attached to attributes. // The metadata that exist currently are for (flatcache) internal use only. // Abstractly it holds an array for each attribute, where element 0 // (NameSuffix::none) is the value itself, and other elements are the metadata. // It is called NameSuffix because conceptually each metadatum adds a // new attribute with a name suffix specifying the type of metadata. // For example, suppose you have an attribute "points" that has an attached // elemCount. Conceptually you have two attributes "points" and // "points_elemCount". enum class NameSuffix { none = 0, // Index NameSuffix::value is the index of the data itself // The following metadata is present on USD attributes that connect to others connection // The target(prim, attribute) of the connection }; struct Connection { PathC path; TokenC attrName; }; // AttrNameAndType specifies the name and type of an attribute. When the user // searches for buckets of prims they use this type to specify which attributes // the prims must have. Also the user can query the name and type of an // attribute at a given path, and the output has this type. // // This version of the struct contains the type in flatcache format only. // The original, AttrNameAndType, additionally contains the type in USD format, // but that version will be deprecated. struct AttrNameAndType { Type type; Token name; NameSuffix suffix; AttrNameAndType() = default; AttrNameAndType(Type type, Token name, NameSuffix suffix = NameSuffix::none) : type(type), name(name), suffix(suffix) { } // Note that in the name comparisons below TokenC masks off USD's lifetime bit. // For example, tokens created from the same string are considered equal even // if one was created with finite lifetime and the other infinite lifetime. bool operator<(const AttrNameAndType& rhs) const { if (TypeC(type) < TypeC(rhs.type)) return true; if (TypeC(rhs.type) < TypeC(type)) return false; if (TokenC(name) < TokenC(rhs.name)) return true; if (TokenC(rhs.name) < TokenC(name)) return false; return suffix < rhs.suffix; } bool operator==(const AttrNameAndType& other) const { return type == other.type && name == other.name && suffix == other.suffix; } }; static_assert(std::is_standard_layout<AttrNameAndType>::value, "AttrNameAndType must be standard layout as it is used in C-ABI interfaces"); // NOTE: This type alias provides source level compatibility. Usage of the original AttrNameAndType structure has // been replaced with what was previously called AttrNameAndType_v2 and the _v2 suffix dropped. This alias allows code // which still refers to AttrNameAndType_v2 to compile. using AttrNameAndType_v2 = AttrNameAndType; } } namespace std { template <> struct hash<carb::flatcache::AttrNameAndType> { // Use the same hash_combine as boost template <class T> static inline void hash_combine(std::size_t& seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } std::size_t operator()(const carb::flatcache::AttrNameAndType& key) const { size_t hash = std::hash<carb::flatcache::Type>{}(key.type); hash_combine(hash, std::hash<carb::flatcache::Token>{}(key.name)); hash_combine(hash, uint32_t(key.suffix)); return hash; } }; }
4,247
C
32.984
118
0.705204
omniverse-code/kit/fabric/include/carb/flatcache/Platform.h
#pragma once #include <carb/flatcache/Allocator.h> namespace omni { namespace gpucompute { struct GpuCompute; struct Context; } // namespace gpucompute } // namespace omni namespace carb { namespace flatcache { struct Platform { Allocator allocator; omni::gpucompute::GpuCompute* gpuCuda = nullptr; omni::gpucompute::Context* gpuCudaCtx = nullptr; // The gpuD3dVk interface is used only if you access GPU arrays using D3D or Vulkan. // If you're only using CPU or CUDA GPU arrays then you don't set it. omni::gpucompute::GpuCompute* gpuD3dVk = nullptr; omni::gpucompute::Context* gpuD3dVkCtx = nullptr; Platform() = default; Platform(const Platform& other) = delete; Platform& operator=(const Platform& other) = delete; Platform(Platform&& other) = default; Platform& operator=(Platform&& other) = default; inline void reset() { gpuD3dVk = nullptr; gpuD3dVkCtx = nullptr; gpuCuda = nullptr; gpuCudaCtx = nullptr; allocator.~Allocator(); new (&allocator) Allocator(); } // mirror of IPlatform functions static void get(const PlatformId& id); static void getMutable(const PlatformId& id); static void reset(const PlatformId& id); static void resetAll(); }; } // namespace flatcache } // namespace carb
1,343
C
21.032787
88
0.676843
omniverse-code/kit/fabric/include/carb/flatcache/Type.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 <sstream> #include <string> namespace carb { namespace flatcache { // TypeC are integer keys that identify types, like float3, int[] etc. // There isn't a USD type that can be cast to TypeC, // please use carb::flatcache::usdTypeToTypeC(). struct TypeC { uint32_t type; constexpr bool operator<(const TypeC& other) const { return type < other.type; } constexpr bool operator==(const TypeC& other) const { return type == other.type; } constexpr bool operator!=(const TypeC& other) const { return type != other.type; } }; static_assert(std::is_standard_layout<TypeC>::value, "Struct must be standard layout as it is used in C-ABI interfaces"); static constexpr TypeC kUnknownType{ 0 }; enum class BaseDataType : uint8_t { eUnknown = 0, eBool, eUChar, eInt, eUInt, eInt64, eUInt64, eHalf, eFloat, eDouble, eToken, // RELATIONSHIP is stored as a 64-bit integer internally, but shouldn't be // treated as an integer type by nodes. eRelationship, // For internal use only eAsset, ePrim, eConnection, // eTags are attributes that have a name but no type or value // They are used for named tags, including USD applied schemas eTag }; inline std::ostream& operator<<(std::ostream& s, const BaseDataType& type) { static const std::string names[] = { "unknown", "bool", "uchar", "int", "uint", "int64", "uint64", "half", "float", "double", "token", "rel", "asset", "prim", "connection", "tag" }; if (type <= BaseDataType::eTag) { return s << names[uint8_t(type)]; } return s; } // These correspond with USD attribute "roles", with the exception of eString. // For example that a vector3f or vector3d (VECTOR) would be transformed // differently from a point3f or point3d (POSITION). enum class AttributeRole : uint8_t { eNone = 0, eVector, eNormal, ePosition, eColor, eTexCoord, eQuaternion, eTransform, eFrame, eTimeCode, // eText is not a USD role. If a uchar[] attribute has role eText then // the corresponding USD attribute will have type "string", and be human // readable in USDA. If it doesn't, then it will have type "uchar[]" in USD // and appear as an array of numbers in USDA. eText, // eAppliedSchema is not a USD role, eTags with this role are USD applied schema. eAppliedSchema, // ePrimTypeName is not a USD role, eTags with this role are USD prim types. ePrimTypeName, // eExecution is not a USD role, uint attributes with this role are used for control flow in Action Graphs. eExecution, eMatrix, // eObjectId is not a USD role, uint64 attributes with this role are used for Python object identification. eObjectId, // eBundle is not a USD role, ePrim and eRelationship attributes with this role identify OmniGraph bundles eBundle, // ePath is not a USD role, it refers to strings that are reinterpreted as SdfPaths. The attribute type must // be a uchar[] with a USD type "string". ePath, // eInstancedAttribute is used as a role on tag types in place of attribute types on instanced prims. eInstancedAttribute, // eAncestorPrimTypeName is not a USD role, eTags with this role are ancestor types of a USD prim type. eAncestorPrimTypeName, // Special marker for roles that are not yet determined eUnknown, }; inline std::ostream& operator<<(std::ostream& s, const AttributeRole& type) { static const std::string ognRoleNames[] = { "none", "vector", "normal", "point", "color", "texcoord", "quat", "transform", "frame", "timecode", "text", "appliedSchema", "primTypeName", "execution", "matrix", "objectId", "bundle", "path", "instancedAttribute", "ancestorPrimTypeName", "unknown" }; if (type <= AttributeRole::eUnknown) { return s << ognRoleNames[uint8_t(type)]; } return s; } // Role names as used by USD, which are slightly different from the internal names used inline std::string usdRoleName(const AttributeRole& type) { static const std::string usdRoleNames[] = { "none", "vector", "normal", "position", "color", "texCoord", "quaternion", "transform", "frame", "timecode", "text", "appliedSchema", "primTypeName", "execution", "matrix", "objectId", "bundle", "path", "instancedAttribute", "ancestorPrimTypeName", "unknown" }; if (type <= AttributeRole::eUnknown) { return usdRoleNames[uint8_t(type)]; } return usdRoleNames[uint8_t(AttributeRole::eUnknown)]; } struct Type { BaseDataType baseType; // 1 byte // 1 for raw base types; 2 for vector2f, int2, etc; 3 for point3d, normal3f, etc; // 4 for quatf, color4d, float4, matrix2f etc; 9 for matrix3f, etc; 16 for matrix4d, etc. uint8_t componentCount; // 1 byte // 0 for a single value // 1 for an array // 2 for an array of arrays (not yet supported) uint8_t arrayDepth; // 1 byte AttributeRole role; // 1 byte constexpr Type(BaseDataType baseType, uint8_t componentCount = 1, uint8_t arrayDepth = 0, AttributeRole role = AttributeRole::eNone) : baseType(baseType), componentCount(componentCount), arrayDepth(arrayDepth), role(role) { } constexpr Type() : Type(BaseDataType::eUnknown) { } // Matches little endian interpretation of the four bytes constexpr explicit Type(const TypeC& t) : baseType(BaseDataType(t.type & 0xff)), componentCount((t.type >> 8) & 0xff), arrayDepth((t.type >> 16) & 0xff), role(AttributeRole((t.type >> 24) & 0xff)) { } constexpr explicit operator TypeC() const { uint32_t type = uint8_t(role) << 24 | arrayDepth << 16 | componentCount << 8 | uint8_t(baseType); return TypeC{ type }; } constexpr bool operator==(const Type& rhs) const { return compatibleRawData(rhs) && role == rhs.role; } constexpr bool operator!=(const Type& rhs) const { return !((*this) == rhs); } constexpr bool operator<(const Type& rhs) const { return TypeC(*this) < TypeC(rhs); } /** * Role-insensitive equality check */ constexpr bool compatibleRawData(const Type& otherType) const { return baseType == otherType.baseType && componentCount == otherType.componentCount && arrayDepth == otherType.arrayDepth; } /** * Check to see if this is one of the matrix types */ constexpr bool isMatrixType() const { return (role == AttributeRole::eMatrix) || (role == AttributeRole::eFrame) || (role == AttributeRole::eTransform); } /** * Returns the dimensions of the type, componentCount for most types and square root of that for matrix types */ constexpr uint8_t dimension() const { if (isMatrixType()) { return componentCount == 4 ? 2 : (componentCount == 9 ? 3 : (componentCount == 16 ? 4 : componentCount)); } return componentCount; } std::string getTypeName() const { std::ostringstream typeName; typeName << baseType; if (componentCount > 1) typeName << uint32_t(componentCount); if (arrayDepth == 1) typeName << "[]"; else if (arrayDepth == 2) typeName << "[][]"; // Some roles are hidden from USD if ((role != AttributeRole::eNone) && (role != AttributeRole::eObjectId) && (role != AttributeRole::eBundle) && (role != AttributeRole::ePath) ) { typeName << " (" << usdRoleName(role) << ")"; } return typeName.str(); } // ====================================================================== /** * OGN formats the type names slightly differently. * - the tuples are internal "float[3]" instead of "float3" * - the roles replace the actual name "colord[3]" instead of "double3 (color)" */ std::string getOgnTypeName() const { std::ostringstream typeName; if (role == AttributeRole::eText) { typeName << "string"; return typeName.str(); } if (role == AttributeRole::ePath) { typeName << "path"; return typeName.str(); } if (role != AttributeRole::eNone) { typeName << role; // For roles with explicit types, add that to the role name if ((role != AttributeRole::eTimeCode) && (role != AttributeRole::eTransform) && (role != AttributeRole::eFrame) && (role != AttributeRole::eObjectId) && (role != AttributeRole::eBundle) && (role != AttributeRole::eExecution)) { switch (baseType) { case BaseDataType::eHalf: typeName << "h"; break; case BaseDataType::eFloat: typeName << "f"; break; case BaseDataType::eDouble: typeName << "d"; break; default: typeName << baseType; break; } } } else { typeName << baseType; } if (componentCount > 1) { typeName << "[" << uint32_t(dimension()) << "]"; } if (arrayDepth == 1) typeName << "[]"; else if (arrayDepth == 2) typeName << "[][]"; return typeName.str(); } }; inline std::ostream& operator<<(std::ostream& s, const Type& type) { s << type.getTypeName(); return s; } } } namespace std { template <> struct hash<carb::flatcache::Type> { std::size_t operator()(const carb::flatcache::Type& key) const { return carb::flatcache::TypeC(key).type; } }; template <> struct hash<carb::flatcache::TypeC> { std::size_t operator()(const carb::flatcache::TypeC& key) const { return key.type; } }; }
11,365
C
30.484764
139
0.560493
omniverse-code/kit/fabric/include/carb/flatcache/GetArrayD3dGpu.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Defines.h> #include <carb/graphics/Graphics.h> #include <omni/gpucompute/GpuCompute.h> using namespace carb::graphics; using std::unique_ptr; namespace carb { namespace flatcache { // If this is an array-of-arrays: // array.cpuData - array of CPU pointers on CPU // gpuPointerArray->cpuData() - array of GPU pointers on CPU inline void PathToAttributesMap::enableD3dGpuRead(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* gpuPointerArray) { using omni::gpucompute::MemcpyKind; bool& cpuValid = array.cpuValid; bool& gpuValid = array.gpuValid; bool& gpuAllocedWithCuda = array.gpuAllocedWithCuda; uint8_t* cpuArray = array.cpuData(); uint8_t*& gpuArray = array.gpuArray; if (gpuValid) { // Nothing to do } else if (!gpuValid && cpuValid) { const TypeC type = array.type; const Typeinfo &typeInfo = getTypeInfo(type); std::lock_guard<MirroredArray::AttributeMutex> hostDeviceLock(array.attributeMutex); // If each element is an array, then they could be of different sizes // So alloc and memcpy each one if (typeInfo.isArray) { size_t elemCount = array.count; uint8_t** elemToArrayCpuData = (uint8_t**)cpuArray; uint8_t** elemToArrayGpuData = (uint8_t**)gpuPointerArray->cpuData(); for (size_t elem = 0; elem != elemCount; elem++) { // Make sure that the dest (GPU) buffer is large enough const uint8_t* const& cpuData = elemToArrayCpuData[elem]; // src size_t& destCapacity = reinterpret_cast<size_t*>(elemToArrayGpuCapacity->cpuData())[elem]; size_t desiredElemCount = elemToArraySize[elem]; destructiveResizeIfNecessaryGPU( *gpuPointerArray, elem, destCapacity, desiredElemCount, typeInfo.arrayElemSize, platform.gpuD3dVk, platform.gpuD3dVkCtx); // Copy from CPU to GPU if (desiredElemCount != 0 && cpuData) { uint8_t*& gpuData = elemToArrayGpuData[elem]; // dest size_t copyByteCount = desiredElemCount * typeInfo.arrayElemSize; platform.gpuD3dVk->memcpy(*platform.gpuD3dVkCtx, gpuData, cpuData, copyByteCount, MemcpyKind::hostToDevice); } else if (desiredElemCount != 0 && !cpuData) { printf("Warning: GPU read access requested, CPU is valid but not allocated\n"); } } // We don't need to copy the outer array to GPU here. // In D3dVk, the outer array is currently a CPU array of descriptors that we copy to // a kernel calls descriptor set at dispatch time } else { // Copy the outer array from CPU to GPU size_t byteCount = array.size(); allocGpuMemIfNecessary(array, byteCount, typeInfo.size, platform.gpuD3dVk, platform.gpuD3dVkCtx); uint8_t* cpuArray = array.cpuData(); platform.gpuD3dVk->memcpy(*platform.gpuD3dVkCtx, gpuArray, cpuArray, byteCount, MemcpyKind::hostToDevice); } // New state cpuValid = true; gpuValid = true; gpuAllocedWithCuda = false; } } inline void PathToAttributesMap::enableD3dGpuWrite(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* arrayGpuDataArray) { log("begin enableGpuWrite\n"); bool& usdValid = array.usdValid; bool& cpuValid = array.cpuValid; bool& gpuValid = array.gpuValid; bool& gpuAllocedWithCuda = array.gpuAllocedWithCuda; const TypeC type = array.type; const Typeinfo &typeInfo = getTypeInfo(type); std::lock_guard<MirroredArray::AttributeMutex> hostDeviceLock(array.attributeMutex); if (!gpuValid) { size_t byteCount = array.size(); allocGpuMemIfNecessary(array, byteCount, typeInfo.size, platform.gpuD3dVk, platform.gpuD3dVkCtx); // Array-valued elements are lazily allocated, meaning they are only // resized when write access is requested. // Write access has been requested, so resize if necessary if (typeInfo.isArray) { size_t elemCount = array.count; for (size_t elem = 0; elem != elemCount; elem++) { size_t& gpuCapacity = reinterpret_cast<size_t*>(elemToArrayGpuCapacity->cpuData())[elem]; size_t desiredElemCount = elemToArraySize[elem]; resizeIfNecessaryGPU( *arrayGpuDataArray, elem, gpuCapacity, desiredElemCount, typeInfo.arrayElemSize, platform.gpuD3dVk, platform.gpuD3dVkCtx); } // Upload of allocated pointers to GPU happens outside this function } } // New state usdValid = false; cpuValid = false; gpuValid = true; gpuAllocedWithCuda = false; log("end enableGpuWrite\n\n"); } inline const void* PathToAttributesMap::getArrayRdD3d(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; // We don't set dirty indices here because this method gives read-only access return getArraySpanC(bucketId, attrName, D3dVkReadConfig(), suffix).array.ptr; } inline void* PathToAttributesMap::getArrayWrD3d(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, D3dVkReadWriteConfig(), suffix); setArrayDirty(array); return array.array.ptr; } inline void* PathToAttributesMap::getArrayD3d(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; ArrayAndDirtyIndices array = getArraySpanC(bucketId, attrName, D3dVkReadWriteConfig(), suffix); setArrayDirty(array); return array.array.ptr; } #if 0 // If array of values, return the Buffer* that was returned by malloc // If array of arrays, return array of Buffer* for each element array inline std::pair<void**, size_t> PathToAttributesMap::getArrayD3d(const Bucket& bucket, const TokenC& attrName) { std::pair<void**, size_t> retval = { nullptr, 0 }; BucketImpl& bucketImpl = buckets[bucket]; auto iter = bucketImpl.arrays.find({ pxr::TfType(), TypeC(), attrName }); bool found = (iter != bucketImpl.arrays.end()); if (found) { bool isTag = (typeToInfo[iter->first.type].size == 0); if (!isTag) { pxr::TfType type = iter->first.type; size_t elemSize = typeToInfo[type].size; size_t arrayElemSize = typeToInfo[type].arrayElemSize; // Read enable must come before write enable enableD3dGpuRead(iter->second, elemSize, arrayElemSize); enableD3dGpuWrite(iter->second, elemSize, arrayElemSize); retval.first = iter->second.d3dArrays.data(); retval.second = iter->second.d3dArrays.size(); } else if (isTag) { // If is a tag, then array.data() will be zero, so set special value // to distinguish from tag absent case retval.first = (void**)-1; } } return retval; } #endif inline omni::gpucompute::GpuPointer PathToAttributesMap::getAttributeD3d(const PathC& path, const TokenC& attrName) { bool present; // Whether this path has a bucket BucketId bucketId; // Pointer to the bucket if it does size_t element; // Index corresponding to path in this bucket's arrays std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; // TODO: Get rid of double hash lookup below (getArraySpanC + explicit call) ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, D3dVkReadWriteConfig()); setArrayElementDirty(arrayAndDirtyIndices, element); void* array = arrayAndDirtyIndices.array.ptr; if (array != nullptr) { // Get elemSize const BucketImpl* bucketImplPtr = buckets.find(bucketId); if (!bucketImplPtr) return { nullptr, 0, 0 }; const AttrName name{ attrName, NameSuffix::none }; const MirroredArray *valuesArray; if (!bucketImplPtr->scalarAttributeArrays.find(name, &valuesArray)) { const ArrayAttributeArray *arrayAttributeArray; if (bucketImplPtr->arrayAttributeArrays.find(name, &arrayAttributeArray)) { valuesArray = &arrayAttributeArray->values; } else { return { nullptr, 0, 0 }; } } assert(valuesArray); const Typeinfo &typeinfo = getTypeInfo(valuesArray->type); const bool isArrayOfArray = typeinfo.isArray; const size_t elemSize = typeinfo.size; if (!isArrayOfArray) { return { array, element * elemSize, elemSize }; } else if (isArrayOfArray) { // For arrays of arrays we return the Buffer* of the inner array uint8_t* const* elemToArrayData = (uint8_t* const*)array; return { elemToArrayData[element], 0, 0 }; } } return { nullptr, 0, 0 }; } } }
10,667
C
37.652174
142
0.626043
omniverse-code/kit/fabric/include/carb/flatcache/PathToAttributesMap.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Defines.h> #include <carb/flatcache/AttrNameAndType.h> #include <carb/flatcache/IdTypes.h> #include <carb/flatcache/ApiLogger.h> #include <carb/flatcache/HashMap.h> #include <carb/flatcache/IFlatcache.h> #include <carb/flatcache/IPath.h> #include <carb/flatcache/IToken.h> #include <carb/flatcache/Ordered_Set.h> #include <carb/flatcache/Platform.h> #include <carb/flatcache/PrimChanges.h> #include <carb/flatcache/Type.h> #include <carb/logging/Log.h> #include <carb/profiler/Profile.h> #include <carb/thread/Mutex.h> #include <omni/gpucompute/GpuCompute.h> #include <fstream> // The following is needed to include USD headers #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" # pragma GCC diagnostic ignored "-Wunused-local-typedefs" # pragma GCC diagnostic ignored "-Wunused-function" // This suppresses deprecated header warnings, which is impossible with pragmas. // Alternative is to specify -Wno-deprecated build option, but that disables other useful warnings too. # ifdef __DEPRECATED # define OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS # undef __DEPRECATED # endif #endif #include <pxr/base/tf/type.h> #include <pxr/usd/usd/timeCode.h> // PathToAttributesMap doesn't depend on USD for tokens or paths // However, it's useful to be able to see the USD text representation of tokens and // paths when debugging. Set ENABLE_USD_DEBUGGING to 1 to enable that. #if defined(_DEBUG) # define ENABLE_USD_DEBUGGING 1 #else # define ENABLE_USD_DEBUGGING 0 #endif // TODO: Move this to some shared macro header if needed elsewhere #if defined(_DEBUG) #define VALIDATE_TRUE(X) CARB_ASSERT(X) #else #define VALIDATE_TRUE(X) X #endif #define PTAM_SIZE_TYPE size_t #define PTAM_SIZE_TYPEC (flatcache::TypeC(carb::flatcache::Type(carb::flatcache::BaseDataType::eUInt64))) static_assert(sizeof(PTAM_SIZE_TYPE) == sizeof(uint64_t), "Unexpected sizeof size_t"); #define PTAM_POINTER_TYPE void* #define PTAM_POINTER_TYPEC (flatcache::TypeC(carb::flatcache::Type(carb::flatcache::BaseDataType::eUInt64))) static_assert(sizeof(PTAM_POINTER_TYPE) == sizeof(uint64_t), "Unexpected sizeof void*"); // When we switch to CUDA async CPU<->GPU copies, we'll need to use pinned CPU // memory for performance. However, the allocations themselves will be much // slower. If you want to see how much slower, set USE_PINNED_MEMORY to 1. // When we do switch, we should probably do a single allocation and sub // allocate it ourselves. That way we'd only call cudaHostAlloc once. #define USE_PINNED_MEMORY 0 // Set this to one to enable CARB profile zones for large bucket copies #define PROFILE_LARGE_BUCKET_COPIES 0 // We plan to move TfToken and AssetPath construction to IToken. // Until we do we have to depend on token.h, a USD header #include "FlatCacheUSD.h" #include <pxr/usd/sdf/pathTable.h> // 104 only - do not port this to 105+ // Enums are in their own file since they have no external dependencies #include "Enums.h" #include <pxr/base/tf/token.h> #include <pxr/usd/sdf/path.h> #include <algorithm> #include <iostream> #include <iterator> #include <map> #include <queue> #include <set> #include <unordered_map> #include <utility> using pxr::UsdTimeCode; using Hierarchy = pxr::SdfPathTable<int>; // 104 only - do not port this to 105+ namespace carb { namespace flatcache { struct AttrName { TokenC name; NameSuffix suffix; bool operator<(const AttrName& other) const = delete; bool operator==(const AttrName& other) const = delete; }; // Use the same hash_combine as boost template <class T> static inline size_t hash_combine(std::size_t seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } } } namespace carb { namespace flatcache { inline std::string toString(NameSuffix suffix) { if (suffix == NameSuffix::connection) return "_connection"; else if (suffix == NameSuffix::none) return ""; return ""; } inline std::ostream& operator<<(std::ostream& s, const NameSuffix& nameSuffix) { s << toString(nameSuffix); return s; } // FlatCache buckets UsdPrims according to their type and the UsdAttributes // they have. For example, all the UsdGeomMeshes can go in one bucket, all the // UsdSkelAnimations in another. The user can then quickly get a contiguous // array of all the meshes, without having to traverse the whole stage. // // The name of a bucket is its set of attribute names (Tokens). // As in the USD API, these tokens are the names used in USDA files, not C++ // type names like UsdGeomMesh. // // Example (using C++11 initializer lists to create the sets): // Bucket meshes = { Token("Mesh") }; // Bucket skelAnimations = { Token("SkelAnimation") }; // // For efficiency, set is an ordered c++ array, not std::set using Bucket = set<AttrNameAndType>; struct BucketAndId { const Bucket bucket; const BucketId bucketId; }; // Buckets store attribute values in contiguous arrays, and in C++ array // indices are size_t using ArrayIndex = size_t; const ArrayIndex kInvalidArrayIndex = 0xffff'ffff'ffff'ffff; // Invariants: // I0: setOfChangedIndices = [0..N), if allIndicesChanged // = changedIndices, otherwise // I1: If setOfChangedIndices==[0..N) then allIndicesChanged=true and changedIndices = {} // where N is defined by the caller // // In particular this means that changedIndices can't have size N // because if all indices were changed, then changedIndices = {}, by I1 struct ChangedIndicesImpl { bool allIndicesChanged = true; flatcache::set<ArrayIndex> changedIndices; ChangedIndicesImpl(size_t N) { if (N == 0) allIndicesChanged = true; else allIndicesChanged = false; } // Create the singleton set {index} ChangedIndicesImpl(ArrayIndex index, size_t N) { if (index == 0 && N == 1) { // Maintain invariant I0 allIndicesChanged = true; } else { // Maintain invariant I0 changedIndices = { index }; allIndicesChanged = false; } } void dirtyAll() { // Maintain invariant I1 allIndicesChanged = true; changedIndices.clear(); } void insert(size_t index, size_t N) { CARB_ASSERT(index < N); // If all indices already changed, then inserting an index has no // effect if (allIndicesChanged) return; changedIndices.insert(index); // Maintain invariant I1 if (changedIndices.size() == N) { dirtyAll(); } } void decrementN(size_t newN) { if (allIndicesChanged) return; changedIndices.erase(newN); if (changedIndices.size() == newN) allIndicesChanged = true; } void erase(size_t index, size_t N) { CARB_ASSERT(index < N); if (allIndicesChanged) { allIndicesChanged = false; // Make a sorted list of integers [0..N) \ index changedIndices.v.resize(N - 1); size_t dest = 0; for (size_t i = 0; i != index; i++) { changedIndices.v[dest++] = i; } for (size_t i = index + 1; i != N; i++) { changedIndices.v[dest++] = i; } return; } changedIndices.erase(index); } bool contains(size_t index) { if (allIndicesChanged) return true; return changedIndices.contains(index); } }; struct ArrayAndDirtyIndices { SpanC array; // We use SpanC instead of gsl::span<const uint8_t> to allow casting to array of correct type std::vector<ChangedIndicesImpl*> changedIndicesForEachListener; // This is empty if change tracking is not enabled for this attribute }; // Bucket vectors and their attribute arrays are public, so users can iterate // over them directly using for loops. // For users that prefer opaque iterators, we provide View. struct View; // FlatCache doesn't need all metadata in UsdAttribute, just the attribute's // type, size in bytes, whether it is an array, and if it is an array, the // size of each elements in bytes struct Typeinfo { size_t size; bool isArray; size_t arrayElemSize; }; // FlatCache stores a map from attribute names (Tokens) to their type and // size. using TypeToInfo = HashMap<TypeC, Typeinfo, std::hash<TypeC>, std::equal_to<TypeC>, AllocFunctor, FreeFunctor>; // By default, an attribute's value is not in the cache, and flags == eNone // Once the user reads a value, ePresent is true // Once the user writes a value, eDirty is true enum class Flags { eNone = 0, ePresent = 1, eDirty = 2 }; // Operators for combining Flags constexpr enum Flags operator|(const enum Flags a, const enum Flags b) { return (enum Flags)(uint32_t(a) | uint32_t(b)); } constexpr enum Flags operator&(const enum Flags a, const enum Flags b) { return (enum Flags)(uint32_t(a) & uint32_t(b)); } struct BucketChangesImpl { // Which attributes changed gsl::span<const AttrNameAndType> changedAttributes; // For each attribute, which prims changed? std::vector<ConstChangedIndicesC> changedIndices; gsl::span<const Path> pathArray; // Which indices contain newly added prims? gsl::span<const size_t> addedIndices; }; struct PrimBucketListImpl { flatcache::set<BucketId> buckets; std::vector<BucketChangesImpl> changes; void clear() { buckets.clear(); changes.clear(); } }; using SerializationCache = HashMap<uint64_t, std::string>; using DeserializationCache = HashMap<std::string, pxr::SdfPath>; // Now we've defined the basic types, we can define the type of FlatCache. // // Abstractly, FlatCache maps each Path to the UsdAttributes of the UsdPrim // at that path. So the type of FlatCache is "PathToAttributesMap". struct PathToAttributesMap { struct MirroredArray { private: std::vector<uint8_t> cpuArray; public: Platform& platform; TypeC type; Typeinfo typeinfo; uint8_t* gpuArray; size_t gpuCapacity; // Amount of memory allocated at gpuArray in bytes std::vector<void*> d3dArrays; // Actually vector of Buffer* size_t count; bool usdValid; bool cpuValid; bool gpuValid; bool gpuAllocedWithCuda; using AttributeMutex = carb::thread::mutex; AttributeMutex attributeMutex; MirroredArray(Platform& platform_, const TypeC &type, const Typeinfo& typeinfo) noexcept; ~MirroredArray(); MirroredArray(const MirroredArray& other) = delete; MirroredArray& operator=(const MirroredArray& other) noexcept; MirroredArray(MirroredArray&& other) noexcept; MirroredArray& operator=(MirroredArray&& other) noexcept; friend void swap(MirroredArray& a, MirroredArray& b) noexcept; inline bool isArrayOfArray() const { CARB_ASSERT((typeinfo.arrayElemSize != 0) == typeinfo.isArray); return typeinfo.isArray; } inline MirroredArray* getValuesArray() { return this; } void resize(size_t byteCount) { // CPU // At the moment, CPU always resizes, but eventually it will only // resize if it is allocated and valid // This will ensure that GPU temp data is never allocated on CPU cpuArray.resize(byteCount); // Don't need to resize GPU here, because it is deferred until next // copy to/from GPU mem } // GPU resize that preserves existing contents // This is used by addPath and addAttributes void resizeGpu(omni::gpucompute::GpuCompute* computeAPI, omni::gpucompute::Context* computeCtx, size_t byteCount, size_t elemSize) { if (!computeAPI || !computeCtx) return; bool capacitySufficient = (byteCount <= gpuCapacity); if (!capacitySufficient) { void* oldGpuArray = gpuArray; size_t oldByteCount = gpuCapacity; gpuArray = reinterpret_cast<uint8_t*>(computeAPI->mallocAsync(*computeCtx, byteCount, elemSize)); gpuCapacity = byteCount; if (oldGpuArray) { using omni::gpucompute::MemcpyKind; computeAPI->memcpyAsync(*computeCtx, gpuArray, oldGpuArray, oldByteCount, MemcpyKind::deviceToDevice); computeAPI->freeAsync(*computeCtx, oldGpuArray); } } } size_t size() const { return cpuArray.size(); } uint8_t* cpuData() { return cpuArray.data(); } const uint8_t* cpuData() const { return cpuArray.data(); } void clear() { cpuArray.clear(); } }; using ScalarAttributeArray = MirroredArray; struct ArrayAttributeArray { enum class MirroredArrays : uint8_t { Values, ElemCounts, CpuElemCounts, GpuElemCounts, GpuPtrs, Count }; ArrayAttributeArray(Platform& platform_, const TypeC& type, const Typeinfo &typeinfo) noexcept; ~ArrayAttributeArray(); ArrayAttributeArray(const ArrayAttributeArray& other) = delete; ArrayAttributeArray& operator=(const ArrayAttributeArray& other) noexcept; ArrayAttributeArray(ArrayAttributeArray&& other) noexcept; ArrayAttributeArray& operator=(ArrayAttributeArray&& other) noexcept; friend void swap(ArrayAttributeArray& a, ArrayAttributeArray& b) noexcept; inline MirroredArray* getValuesArray() { return &values; } MirroredArray values; MirroredArray elemCounts; MirroredArray cpuElemCounts; MirroredArray gpuElemCounts; MirroredArray gpuPtrs; }; // DO NOT generalize this static_assert using globally named defines for magic numbers. // We intentionally sprinkle static_assert on hardcoded sizes around this file to increase friction when changing // the struct definition. Any change to ArrayAttributeArray requires evaluating multiple locations that rely on // keeping in sync with the struct. Having each of these be hardcoded comparions forces future authors to // individually evaluate each dependent site for correctness. If the comparison is generalized, future authors could // simply adjust the global definition without examining every dependent routine, which might lead to errors. static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); struct Changes { // changedAttributes and changesIndices together implement an ordered // map, from attribute to changed indices. // changedAttributes is a flatcache::set, which is a sorted std::vector. // // To lookup an element of the map, find the index, i, of the key in // changedAttributes, then read the value from changedIndices[i] // // changedAttributes and changedIndices must have the same size. // // TODO: make a general ordered_map class based on flatcache::set flatcache::set<AttrNameAndType> changedAttributes; std::vector<ChangedIndicesImpl> changedIndices; // // New elements are stored in a set // flatcache::set<ArrayIndex> addedIndices; void setDirty(const AttrNameAndType& nameAndType, size_t index, size_t maxIndex) { auto& keys = changedAttributes.v; auto& values = changedIndices; auto insertIter = lower_bound(keys.begin(), keys.end(), nameAndType); ptrdiff_t insertIndex = insertIter - keys.begin(); bool found = (insertIter != keys.end() && !(nameAndType < *insertIter)); if (found) { values[insertIndex].insert(index, maxIndex); } else { keys.insert(insertIter, nameAndType); values.insert(values.begin() + insertIndex, ChangedIndicesImpl(index, maxIndex)); } } void dirtyAll(const AttrNameAndType& nameAndType, size_t maxIndex) { auto& keys = changedAttributes.v; auto& values = changedIndices; auto insertIter = lower_bound(keys.begin(), keys.end(), nameAndType); ptrdiff_t insertIndex = insertIter - keys.begin(); bool found = (insertIter != keys.end() && !(nameAndType < *insertIter)); if (found) { values[insertIndex].dirtyAll(); } else { keys.insert(insertIter, nameAndType); ChangedIndicesImpl changedIndices(maxIndex); changedIndices.dirtyAll(); values.insert(values.begin() + insertIndex, changedIndices); } } void addNewPrim(size_t index) { addedIndices.insert(index); } void removePrim(size_t index) { // // we just clean the index from the set // addedIndices.erase(index); } size_t getNewPrimCount() { return addedIndices.size(); } }; // FlatCache buckets UsdPrims according to type and attributes, and // BucketImpl stores the attribute values of a bucket's prims in // structure-of-arrays (SOA) format. // BucketImpl maps each attribute name (TokenC) to a MirroredArray, a // contiguous byte array (vector<uint8_t>) and a bitfield encoding the // validate/dirtiness of each mirror. // Abstractly, flatcache data is addressed like a multidimensional array // buckets[bucket][attributeName][path]. // FlatCache uses byte arrays instead of typed arrays, because USD files, // scripts, and plugins can define custom types, so no dll or exe knows the // complete set of types at the time of its compilation. // BucketImpl also contains elemToPath to map each SOA element to the // Path it came from. struct BucketImpl { struct Hasher { size_t operator()(const AttrName& key) const { return hash_combine(hash(key.name), uint32_t(key.suffix)); } }; struct KeyEqual { bool operator()(const AttrName& a, const AttrName& b) const { return (a.name == b.name) && (a.suffix == b.suffix); } }; using ScalarAttributeArrays = HashMap<AttrName, ScalarAttributeArray, Hasher, KeyEqual, AllocFunctor, FreeFunctor>; using ArrayAttributeArrays = HashMap<AttrName, ArrayAttributeArray, Hasher, KeyEqual, AllocFunctor, FreeFunctor>; Platform& platform; ScalarAttributeArrays scalarAttributeArrays; ArrayAttributeArrays arrayAttributeArrays; std::vector<pxr::SdfPath> elemToPath; // listenerIdToChanges entries are lazily created when the user changes // an attribute, or when an attribute moves between buckets HashMap<ListenerId, Changes, ListenerIdHasher, std::equal_to<ListenerId>, AllocFunctor, FreeFunctor> listenerIdToChanges; template<typename CallbackT> void forEachValueArray(CallbackT callback); BucketImpl(Platform &platform_) : platform(platform_) , scalarAttributeArrays(0, Hasher(), KeyEqual(), AllocFunctor{ &platform.allocator }, FreeFunctor{ &platform.allocator }) , arrayAttributeArrays(0, Hasher(), KeyEqual(), AllocFunctor{ &platform.allocator }, FreeFunctor{ &platform.allocator }) , elemToPath() , listenerIdToChanges(0, ListenerIdHasher(), std::equal_to<ListenerId>(), AllocFunctor{ &platform.allocator }, FreeFunctor{ &platform.allocator }) { } ~BucketImpl() { #if PROFILE_LARGE_BUCKET_COPIES size_t count = elemToPath.size(); carb::profiler::ZoneId zoneId = carb::profiler::kUnknownZoneId; if (1000 <= count) zoneId = CARB_PROFILE_BEGIN(1, "Destroy Bucket %zu", count); arrays.clear(); elemToPath.clear(); if (1000 <= count) CARB_PROFILE_END(1, zoneId); #endif // #if PROFILE_LARGE_BUCKET_COPIES } BucketImpl(const BucketImpl&) = delete; inline BucketImpl& operator=(const BucketImpl& other) noexcept { #if PROFILE_LARGE_BUCKET_COPIES size_t count = other.elemToPath.size(); carb::profiler::ZoneId zoneId = carb::profiler::kUnknownZoneId; if (1000 <= count) zoneId = CARB_PROFILE_BEGIN(1, "Copy Bucket %zu", count); #endif // #if PROFILE_LARGE_BUCKET_COPIES scalarAttributeArrays.clear(); scalarAttributeArrays.reserve(other.scalarAttributeArrays.size()); other.scalarAttributeArrays.forEach([this](const AttrName& name, const ScalarAttributeArray &otherArray) { // construct new array with the current BucketImpl platform, but mimicing type of otherArray ScalarAttributeArray *array; scalarAttributeArrays.allocateEntry(name, &array); new (array) ScalarAttributeArray(platform, otherArray.type, otherArray.typeinfo); *array = otherArray; }); arrayAttributeArrays.clear(); arrayAttributeArrays.reserve(other.arrayAttributeArrays.size()); other.arrayAttributeArrays.forEach([this](const AttrName& name, const ArrayAttributeArray &otherArray) { // construct new array with the current BucketImpl platform, but mimicing type of otherArray ArrayAttributeArray *array; arrayAttributeArrays.allocateEntry(name, &array); new (array) ArrayAttributeArray(platform, otherArray.values.type, otherArray.values.typeinfo); *array = otherArray; }); elemToPath = other.elemToPath; listenerIdToChanges.clear(); listenerIdToChanges.reserve(other.listenerIdToChanges.size()); other.listenerIdToChanges.forEach([this](const ListenerId& listener, const Changes &otherChanges) { Changes* changes; VALIDATE_TRUE(listenerIdToChanges.allocateEntry(listener, &changes)); static_assert(std::is_copy_constructible<Changes>::value, "Expected listenerIdToChanges values to be copy-constructible"); new (changes) Changes(otherChanges); }); bucket = other.bucket; #if PROFILE_LARGE_BUCKET_COPIES if (1000 <= count) CARB_PROFILE_END(1, zoneId); #endif // #if PROFILE_LARGE_BUCKET_COPIES return *this; } BucketImpl(BucketImpl&& other) noexcept = delete; inline BucketImpl& operator=(BucketImpl&& other) noexcept { // this->platform = std::move(b.platform); // intentionally not move-assigning platform (we can't anyways, it's a ref) this->scalarAttributeArrays = std::move(other.scalarAttributeArrays); this->arrayAttributeArrays = std::move(other.arrayAttributeArrays); this->elemToPath = std::move(other.elemToPath); this->listenerIdToChanges = std::move(other.listenerIdToChanges); this->bucket = std::move(other.bucket); return *this; } const Bucket& GetBucket() const { return bucket; } // // TODO: In the future we should support universal ref + // move assignments, unforuntately Bucket doesn't follow // the rule of 5 so that is unavailable to us currently. // void SetBucket(const Bucket& _bucket) { bucket = _bucket; } private: // // bucketImpl knows the Bucket it represents // Bucket bucket; }; /** * @struct BucketIdToImpl * * @brief Convenience data structure for quick bucket lookups * * @details We want to avoid the cost of hashmap lookups when possible * due to the large number of times that elements are looked * up via a single element lookup. This class creates a static vector * to track buckets. It also will keep the array densely packed * as possible, while not incurring the cost of moves * * @notes 1) NOT threadsafe * * @todo possibly store the last and first valid so one can avoid un-needed * iteration * @todo provide an iterator * @todo make deleting buckets move lastFreeSlot back where approriate so that * it is always meaningful as "end()" */ struct BucketIdToImpl { // A reasonable first size for the number of buckets // If one changed this number, they would have to update // the constants in the unit tests "Check Bucket Growth" static const int max_buckets_init = 1024; /** * @brief Initialize storage to the minimum size * We rely on C++ behavior that default initalizes the * std::vector bool to false for valid tracking * */ BucketIdToImpl(Platform& platform) : platform(platform) , buckets(max_buckets_init) , lastEmptySlot{ 0 } { } ~BucketIdToImpl() { clear(); } /** * @brief mimic emplace function for stl objects * * @details This allows us to do move of buckets after they have been * created into the storage. We choose for backwards compatibility * with other APS to return a pair. It takes care of the correct place * to store the bucket for you to keep the storage as dense as possible. * This claims the next bucket, and will move out of * @param bucketImpl a new bucket to be added to the Storage, empty after function call * due to move. * * @return <BucketId, BucketImpl&> the pair representing the Id for lookup of the bucket * and a reference to the data since it was moved from param * */ std::pair<BucketId, BucketImpl&> emplace(BucketImpl* bucketImpl) { CARB_ASSERT(bucketImpl); BucketId bucketId = ClaimNextOpenBucket(); if (buckets[size_t(bucketId)]) { platform.allocator.delete_(buckets[size_t(bucketId)]); } buckets[size_t(bucketId)] = std::move(bucketImpl); return std::pair<BucketId, BucketImpl&>(bucketId, *buckets[(size_t)bucketId]); } /** * @brief Erase the specified bucket * * @details This actually forces deletion of the object that is to be deleted it adds the * id to the list of free buckets so that it will be recycled before more are * added to the end * * @param id : The id of the bucket to be deleted */ void erase(BucketId id) { if (size_t(id) < buckets.size() && buckets[size_t(id)]) { // Ignoring optimization of if last slot is empty freeSlots.push(id); platform.allocator.delete_(buckets[size_t(id)]); buckets[size_t(id)] = nullptr; } } // Find the bucket at the requested slot, if no bucket exists // then we return /** * @brief Find the bucket if it exists * * @param id : The id of the bucket to be found * * @return If the bucket exists a pointer is return, otherwise a null pointer is returned */ BucketImpl* find(BucketId id) { if (size_t(id)< buckets.size()) return buckets[size_t(id)]; return nullptr; } /** * @brief Find the bucket if it exists (const) * * @param id : The id of the bucket to be found * * @return If the bucket exists a cosnt pointer is return, otherwise a null pointer is returned */ const BucketImpl* find(BucketId slot) const { if (size_t(slot) < buckets.size()) return buckets[size_t(slot)]; return nullptr; } /** * @brief Clear all the buckets * * @details This will force deletion of all the nodes and make the storage appear empty * */ void clear() { for (uint64_t i = 0; i < size_t(lastEmptySlot); ++i) { if (buckets[i]) { platform.allocator.delete_(buckets[i]); buckets[i] = nullptr; } } // no clear in std::queue so we swap with a new one std::queue<BucketId>().swap(freeSlots); lastEmptySlot.id = 0; } /** * @brief get the possible end of the storage * * @details This will return the last possible id for a bucket, however * should be combined with valid to be carefule * * @return The last "allocated bucket" but could not be valid */ size_t end() const { return size_t(lastEmptySlot); } /** * @brief Support copy assignment. * * @note In order for this to be a valid copy it must be followed up * by a call to PathToAttributesMap::BucketImplCopyArrays to * correctly copy array-of-array data. * * @return Copy constructed buckets, without array-of-arrays set up */ BucketIdToImpl& operator=(const BucketIdToImpl& other) { // Array of free slots this->freeSlots = other.freeSlots; // Track the last empty slot this->lastEmptySlot = other.lastEmptySlot; // // A bucketImpl is a struct that mainly contains a map // to arrays which are of the data type MirroredArray. // A MirroredArray has two states // (1) It contains an array of data // (2) It contains an array of arrays. // In the case of (2) the array itself doesn't have enough // information to make a copy of the array of arrays, so the // copy constructor is overloaded and the structure around the // array of arrays is loaded, but the actual copying of that data is // pushed off to be done by the function BucketImplCopyArrays // which is a member of PathToAttributesMap which is the only place // that currently has enough information to make the copy // this->buckets.resize(other.buckets.size()); for (size_t i = 0; i < this->buckets.size(); ++i) { if (other.buckets[i]) { if (!this->buckets[i]) { this->buckets[i] = platform.allocator.new_<BucketImpl>(platform); } *this->buckets[i] = *other.buckets[i]; } else if (this->buckets[i]) { platform.allocator.delete_(this->buckets[i]); this->buckets[i] = nullptr; } } return *this; } /** * @brief Resize the internals * * @details Note that resize will only grow, calling with a smaller size is a no-op * */ void resize(size_t newSize) { if (newSize > buckets.size()) { buckets.resize(newSize); } } /** * @brief Claim a bucket by index, this means that the pointer will be * returned regardless of valid, and that it will mark as valid * and update internals where needed. In the case where an index is * requested that is past the allocated then more memory is allocated * * @note This should be used sparingly, generally it is intended to be used * in the case where we are re-constructing one flat cache from another, * if things are done out of order it could be expensize, also it is assumed * all external mappings are maintained by the claimer * * @param id : The id of the bucket to be claimed * * @return A reference to the bucketImpl that was claimed */ BucketImpl& claim(BucketId id) { // grow if needed if (size_t(id)>= buckets.size()) { resize(size_t(id)+ 1); } // if the bucket is already valid we can just return access to it if (!buckets[size_t(id)]) { // otherwise we need to update accordingly while (lastEmptySlot <= id) { if (!buckets[size_t(lastEmptySlot)]) { freeSlots.push(lastEmptySlot); } ++lastEmptySlot; } buckets[size_t(id)] = platform.allocator.new_<BucketImpl>(platform); } CARB_ASSERT(buckets[size_t(id)]); return *buckets[size_t(id)]; } template<typename CallbackT> void forEachValidBucket(CallbackT callback) const; private: /** * @brief Get the next open bucket * * @note May invalidate references to existing buckets * */ BucketId ClaimNextOpenBucket() { BucketId slot = lastEmptySlot; if (freeSlots.size() != 0) { slot = freeSlots.front(); freeSlots.pop(); } else { ++lastEmptySlot; if (size_t(lastEmptySlot) == buckets.size()) { std::vector<BucketImpl*> newVector; newVector.resize(buckets.size() * 2); // // A bucketImpl is a struct that mainly contains a map // to arrays which are of the data type MirroredArray. // A MirroredArray has two states // (1) It contains an array of data // (2) It contains an array of arrays. // In the case of (2) the array itself doesn't have enough // information to make a copy of the array of arrays, so the // copy constructor is overloaded and the structure around the // array of arrays is loaded, but the actual copying of that data is // pushed off to be done by the function BucketImplCopyArrays // which is a member of PathToAttributesMap which is the only place // that currently has enough information to make the copy // // Since we cannot guarantee that someone will know to call // the copyArrays function we enforce that data must be moved here. // for (size_t i = 0; i < buckets.size(); ++i) { newVector[i] = std::move(buckets[i]); } std::swap(newVector, buckets); } } CARB_ASSERT(!buckets[size_t(slot)]); buckets[size_t(slot)] = platform.allocator.new_<BucketImpl>(platform); return slot; } Platform& platform; // array of bucket impls std::vector<BucketImpl*> buckets; // Array of free slots std::queue<BucketId> freeSlots; // Track the last empty slot BucketId lastEmptySlot; }; // Internally we convert Paths to uint64_t path ids using asInt(). // PathId is the domain of pathToBucketElem, defined below. using PathId = PathC; Platform& platform; // Concretely, FlatCache is the following three maps: // 1) Each path maps to a bucket, and an SOA index within that bucket. // This level of indirection allows the user to delete prims and/or // attributes without creating holes in the SOAs. Whenever the user // deletes a prim, the cache moves the last SOA element to the deleted // element, and updates the path to element map of the moved SOA element. // 2) Buckets (sets of attribute names) map to BucketImpls, defined above. // This allows the user to quickly get e.g. arrays of all the meshes, // or all the meshes that have rigid body attributes. // 3) pxr::TfType names map to TypeInfos, containing attribute type and size in bytes. HashMap<PathId, std::pair<BucketId, ArrayIndex>, std::hash<PathId>, std::equal_to<PathId>, AllocFunctor, FreeFunctor> pathToBucketElem; BucketIdToImpl buckets; std::map<Bucket, BucketId> attrNameSetToBucketId; // Each listener has its own attrNamesToLog and enableChangeTracking struct ChangeTrackerConfig { set<TokenC> attrNamesToLog; bool changeTrackingEnabled = true; }; HashMap<ListenerId, ChangeTrackerConfig, ListenerIdHasher, std::equal_to<ListenerId>, AllocFunctor, FreeFunctor> listenerIdToChangeTrackerConfig; TypeToInfo typeToInfo; UsdStageId usdStageId; bool minimalPopulationDone = false; // 104 only - do not port this forward to 105+ Hierarchy stageHierarchy; // 104 only - do not port this forward to 105+ mutable bool apiLogEnabled = false; // The rest of PathToAttributesMap is methods size_t size(); void clear(); void printMirroredArray(const char* const label, const ScalarAttributeArray &array, const size_t* const arrayElemCount) const; void print() const; // Void* multiple attribute interface void getArraysRdC(const void** attrsOut, const Bucket& bucket, const TokenC* attrNames, size_t attrCount); void getAttributesRdC(const void** attrsOut, const PathC* paths, const TokenC* attrNames, size_t attrCount); void getAttributesRdGpuC(const void** attrsOut, const PathC* paths, const TokenC* attrNames, size_t attrCount, PtrToPtrKind ptrToPtrKind); void getArraysWrC(void** attrsOut, const Bucket& bucket, const TokenC* attrNames, size_t attrCount); void getAttributesWrC(void** attrsOut, const PathC& path, const TokenC* attrNames, size_t attrCount); void getAttributesWrGpuC(void** attrsOut, const PathC& path, const TokenC* attrNames, size_t attrCount, PtrToPtrKind ptrToPtrKind); // Span interface SpanC getArraySpanC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); ConstSpanC getArraySpanRdC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getArraySpanWrC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); // Void* interface void addAttributeC( const PathC& path, const TokenC& attrName, TypeC type, const void* value = nullptr); void addArrayAttributeC( const PathC& path, const TokenC& attrName, TypeC type, const void* value, const size_t arrayElemCount); void addAttributesToPrim( const PathC& path, const std::vector<TokenC>& attrNames, const std::vector<TypeC>& typeCs); void addAttributeC(const PathC& path, const TokenC& attrName, NameSuffix suffix, TypeC type, const void* value = nullptr); void addArrayAttributeC(const PathC& path, const TokenC& attrName, NameSuffix suffix, TypeC type, const void* value, const size_t arrayElemCount); void* getArrayC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getAttributeC(const PathC& path, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); const void* getArrayRdC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); ConstSpanC getAttributeRdC(const PathC& path, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); void* getArrayWrC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getAttributeWrC(const PathC& path, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getOrCreateAttributeWrC(const PathC& path, const TokenC& attrName, TypeC type); // Type safe interface template <typename T> void addAttribute(const PathC& path, const TokenC& attrName, TypeC type, const T& value); template <typename T> void addSubAttribute(const PathC& path, const TokenC& attrName, NameSuffix suffix, TypeC type, const T& value); template <typename T> T* getArray(const Bucket& bucket, const TokenC& attrName); template <typename T> T* getAttribute(const PathC& path, const TokenC& attrName); template <typename T> const T* getArrayRd(const Bucket& bucket, const TokenC& attrName); template <typename T> const T* getArrayRd(BucketId bucketId, const TokenC& attrName); template <typename T> const T* getAttributeRd(const PathC& path, const TokenC& attrName); template <typename T> T* getArrayWr(const Bucket& bucket, const TokenC& attrName); template <typename T> T* getAttributeWr(const PathC& path, const TokenC& attrName); template <typename T> T* getAttributeWr(const PathC& path, const TokenC& attrName, NameSuffix suffix); void removeAttribute(const PathC& path, const TokenC& attrName); void removeSubAttribute(const PathC& path, const TokenC& attrName, NameSuffix suffix); /** @brief Destroy all attributes with matching names from prim at given path * * @path[in] Path to the prim holding the attribute * @attrNames[in] Attribute name array * */ void removeAttributesFromPath(const PathC& path, const std::vector<TokenC>& attrNames); ValidMirrors getAttributeValidBits( const PathC& path, const TokenC& attrName, ArrayAttributeArray::MirroredArrays subArray = ArrayAttributeArray::MirroredArrays::Values) const; // Accessors for element count of array attributes size_t* getArrayAttributeSize(const PathC& path, const TokenC& attrName); const size_t* getArrayAttributeSizeRd(const PathC& path, const TokenC& attrName); size_t* getArrayAttributeSizeWr(const PathC& path, const TokenC& attrName); size_t* getArrayAttributeSizes(const Bucket& bucket, const TokenC& attrName); const size_t* getArrayAttributeSizesRd(const Bucket& bucket, const TokenC& attrName); size_t* getArrayAttributeSizesWr(const Bucket& bucket, const TokenC& attrName); SpanC setArrayAttributeSizeAndGet(PathC path, const TokenC& attrName, size_t newSize); SpanC setArrayAttributeSizeAndGet(BucketId bucketId, size_t elementIndex, const TokenC& attrName, size_t newSize); // GPU can currently read, but not write, size of arrays // This is because writing causes array to resize, and that's not currently supported on GPU const size_t* getArrayAttributeSizeRdGpu(const PathC& path, const TokenC& attrName); const size_t* getArrayAttributeSizesRdGpu(const Bucket& bucket, const TokenC& attrName); // Void* CUDA GPU interface SpanC getAttributeGpuC(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind = PtrToPtrKind::eNotApplicable, NameSuffix suffix = NameSuffix::none); ConstSpanC getAttributeRdGpuC(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind = PtrToPtrKind::eNotApplicable, NameSuffix suffix = NameSuffix::none); SpanC getAttributeWrGpuC(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind = PtrToPtrKind::eNotApplicable, NameSuffix suffix = NameSuffix::none); void* getArrayGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); const void* getArrayRdGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); void* getArrayWrGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); // Span CUDA GPU interface SpanC getArraySpanGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); ConstSpanC getArraySpanRdGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getArraySpanWrGpuC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); // Type safe CUDA GPU interface template <typename T> T* getAttributeGpu(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind = PtrToPtrKind::eNotApplicable); template <typename T> const T* getAttributeRdGpu(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind = PtrToPtrKind::eNotApplicable); template <typename T> T* getAttributeWrGpu(const PathC& path, const TokenC& attrName, PtrToPtrKind ptrToPtrKind = PtrToPtrKind::eNotApplicable); template <typename T> T* getArrayGpu(const Bucket& bucket, const TokenC& attrName); template <typename T> const T* getArrayRdGpu(const Bucket& bucket, const TokenC& attrName); template <typename T> T* getArrayWrGpu(const Bucket& bucket, const TokenC& attrName); // D3D GPU interface omni::gpucompute::GpuPointer getAttributeD3d(const PathC& path, const TokenC& attrName); void* getArrayD3d(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); const void* getArrayRdD3d(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); void* getArrayWrD3d(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); // PathC methods void addPath(const PathC& path, const Bucket& bucket = {}); void renamePath(const PathC& oldPath, const PathC& newPath); set<AttrNameAndType> getTypes(const PathC& path) const; size_t getAttributeCount(const PathC& path) const; TypeC getType(const PathC& path, const TokenC& attrName) const; void removePath(const PathC& path); size_t count(const PathC& path) const; size_t count(const PathC& path, const TokenC& attrName) const; // Type methods void addType(TypeC type, Typeinfo typeInfo); Typeinfo getTypeInfo(TypeC type) const; // Bucket methods BucketId addBucket(const Bucket& bucket); void addAttributeC( const Bucket& bucket, const TokenC& attrName, TypeC type, const void* value = nullptr); void addArrayAttributeC(const Bucket& bucket, const TokenC& attrName, TypeC type, const void* value, const size_t arrayElemCount); template <typename T> void addAttribute(const Bucket& bucket, const TokenC& attrName, TypeC type, const T& value); void removeAttributeC(const Bucket& bucket, const TokenC& attrName, TypeC type); void printBucket(const Bucket& bucket) const; void printBucketName(const Bucket& bucketTypes, BucketId bucketId) const; void printBucketNames() const; void printBucketNamesAndTypes() const; flatcache::set<BucketId> findBuckets(const set<AttrNameAndType>& all, const set<AttrNameAndType>& any = {}, const set<AttrNameAndType>& none = {}) const; View getView(const set<AttrNameAndType>& inc, const set<AttrNameAndType>& exc = {}); size_t getElementCount(const Bucket& bucket) const; const PathC* getPathArray(const Bucket& bucket) const; TypeC getType(const Bucket& bucket, const TokenC& attrName) const; /** @brief Destroy all attributes with matching names from a given Bucket - array version of removeAttributeC * * @bucket[in] Bucket to remove attributes from * @attrNames[in] Attribute name array * */ void removeAttributesFromBucket(const Bucket& bucket, const std::vector<TokenC>& attrNames); // BucketId methods size_t getElementCount(BucketId bucketId) const; SpanC getArrayC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); ConstSpanC getArrayRdC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getArrayWrC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getOrCreateArrayWrC( BucketId bucketId, const TokenC& attrName, TypeC type, NameSuffix suffix = NameSuffix::none); SpanC getArrayGpuC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); ConstSpanC getArrayRdGpuC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); SpanC getArrayWrGpuC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix = NameSuffix::none); BucketId getBucketId(const PathC& path) const; ArrayPointersAndSizesC getArrayAttributeArrayWithSizes(BucketId bucketId, const TokenC& attrName); ConstArrayPointersAndSizesC getArrayAttributeArrayWithSizesRd(BucketId bucketId, const TokenC& attrName); ArrayPointersAndSizesC getArrayAttributeArrayWithSizesWr(BucketId bucketId, const TokenC& attrName); SpanSizeC getArrayAttributeSizes(BucketId bucketId, const TokenC& attrName); ConstSpanSizeC getArrayAttributeSizesRd(BucketId bucketId, const TokenC& attrName); ConstSpanSizeC getArrayAttributeSizesRdGpu(BucketId bucketId, const TokenC& attrName); SpanSizeC getArrayAttributeSizesWr(BucketId bucketId, const TokenC& attrName); ConstPathCSpan getPathArray(BucketId bucketId) const; Bucket getNamesAndTypes(BucketId bucketId) const; // std::vector<Bucket> methods std::vector<size_t> getElementCounts(const std::vector<Bucket>& buckets) const; template <typename T> std::vector<const T*> getArraysRd(const std::vector<Bucket>& buckets, const TokenC& attrName); template <typename T> std::vector<T*> getArraysWr(const std::vector<Bucket>& buckets, const TokenC& attrName); template <typename T> std::vector<T*> getArrays(const std::vector<Bucket>& buckets, const TokenC& attrName); // BucketImpl methods size_t getElementCount(const BucketImpl& bucketImpl) const; // Allow default construction PathToAttributesMap(const PlatformId& platformId = PlatformId::Global); // Disallow copying PathToAttributesMap(const PathToAttributesMap&) = delete; // Allow copy assignment. This is used by StageWithHistory PathToAttributesMap& operator=(const PathToAttributesMap&); // Allow move construction and assignment PathToAttributesMap(PathToAttributesMap&& other) noexcept = default; PathToAttributesMap& operator=(PathToAttributesMap&& other) noexcept = default; ~PathToAttributesMap(); // Methods that are currently used in flatcache.cpp // TODO: Make private struct ArrayOfArrayInfo { // For each array, the element count requested by the user size_t* arraySizeArray; // For each array, the element count allocated on the CPU MirroredArray* arrayCpuCapacityArray; // For each array, the element count allocated on the GPU MirroredArray* arrayGpuCapacityArray; // For each array, the GPU data MirroredArray* arrayGpuPtrArray; }; struct ConstArrayOfArrayInfo { // For each array, the element count requested by the user const MirroredArray * arraySizeArray; // For each array, the element count allocated on the CPU const MirroredArray* arrayCpuCapacityArray; // For each array, the element count allocated on the GPU const MirroredArray* arrayGpuCapacityArray; // For each array, the GPU data const MirroredArray* arrayGpuPtrArray; }; // enableCpuWrite() is used in flatcache.cpp, so needs to be public // TODO: move that code from there to here void enableCpuWrite(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* elemToArrayGpuData); // getArrayOfArrayInfo() is used in flatcache.cpp, so needs to be public // TODO: move that code from there to here ArrayOfArrayInfo getArrayOfArrayInfo(Typeinfo typeInfo, BucketImpl& bucketImpl, TokenC attrName); ArrayOfArrayInfo getArrayOfArrayInfo(ArrayAttributeArray &arrayAttributeArray); ConstArrayOfArrayInfo getArrayOfArrayInfo(Typeinfo typeInfo, const BucketImpl& bucketImpl, TokenC attrName) const; ConstArrayOfArrayInfo getArrayOfArrayInfo(const ArrayAttributeArray &arrayAttributeArray) const; void bucketImplCopyScalarAttributeArray(ScalarAttributeArray &dest, const ScalarAttributeArray &src); void bucketImplCopyArrayAttributeArray(BucketImpl& destBucketImpl, const AttrName& destName, ArrayAttributeArray &dest, const ArrayAttributeArray &src); void bucketImplCopyArrays(BucketImpl& destBucketImpl, BucketId destBucketId, const BucketImpl& srcBucketImpl, BucketId srcBucketId, const carb::flatcache::set<AttrNameAndType>& attrFilter = {}); // Serialization struct Serializer { uint8_t *p; uint8_t *buf; uint8_t *end; uint64_t bytesWritten; // increments even if attempts are made to write past end bool overflowed; void init(uint8_t *const _buf, uint8_t *const end); bool writeBytes(const uint8_t *const src, uint64_t size); bool writeString(const char* const s, const size_t len); bool writeString(const std::string &s); template<typename T> bool write(const T &t); }; struct Deserializer { const uint8_t *p; const uint8_t *buf; const uint8_t *end; uint64_t bytesRead; // increments even if attempts are made to read past end bool overflowed; void init(const uint8_t *const _buf, const uint8_t *const end); bool readBytes(uint8_t *const dst, uint64_t size); bool readString(std::string &s); template<typename T> bool read(T &t); }; uint64_t serializeScalarAttributeArray(BucketImpl& srcBucketImpl, const BucketId& srcBucketId, const AttrName& srcName, ScalarAttributeArray& srcScalarAttributeArray, Serializer &out); bool deserializeScalarAttributeArray(BucketImpl& destBucketImpl, const BucketId& destBucketId, Deserializer &in); uint64_t serializeArrayAttributeArray(BucketImpl& srcBucketImpl, const BucketId& srcBucketId, const AttrName& srcName, ArrayAttributeArray& srcArrayAttributeArray, Serializer &out); bool deserializeArrayAttributeArray(BucketImpl& destBucketImpl, const BucketId& destBucketId, Deserializer &in); PrimBucketListImpl getChanges(ListenerId listener); void popChanges(ListenerId listener); private: // Device is used by getArrayC enum class Device { eCPU = 0, eCudaGPU = 1, eD3dVkGPU = 2 }; static inline constexpr ArrayOfArrayInfo ScalarArrayOfArrayInfo() { return ArrayOfArrayInfo{ nullptr, nullptr, nullptr, nullptr }; } // TODO: Now that EnableReadFn and EnableWriteFn can have the same type, should they just be one alias? using EnableReadFn = void (PathToAttributesMap::*)(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuData); using EnableWriteFn = void (PathToAttributesMap::*)(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuData); struct IOConfig { EnableReadFn enableRead; EnableWriteFn enableWrite; EnableReadFn enableRdPtrForWrite; Device device; PtrToPtrKind ptrToPtrKind; inline IOConfig& withEnableRead(EnableReadFn _enableRead) { enableRead = _enableRead; return *this; } inline IOConfig& withEnableWrite(EnableWriteFn _enableWrite) { enableWrite = _enableWrite; return *this; } inline IOConfig& withEnableRdPtrForWrite(EnableReadFn _enableRdPtrForWrite) { enableRdPtrForWrite = _enableRdPtrForWrite; return *this; } inline IOConfig& withDevice(Device _device) { device = _device; return *this; } inline IOConfig& withPtrToPtrKind(PtrToPtrKind _ptrToPtrKind) { ptrToPtrKind = _ptrToPtrKind; return *this; } }; void serializeMirroredArrayMetadata(const AttrName& srcName, MirroredArray &srcValuesArray, Serializer &out); template<typename ArraysT, typename ArraysMapT> void deserializeMirroredArrayMetadata(Platform& platform, ArraysMapT& arraysMap, AttrName &destName, Typeinfo *&typeInfo, ArraysT *&destArray, Deserializer &in); BucketImpl& addAttributeInternal(BucketImpl& prevBucketImpl, const Bucket& bucket, const TokenC& attrName, const TypeC ctype, const void* value, const Typeinfo& typeinfo, const size_t arrayElemCount); void fillAttributeInternal(BucketImpl& bucketImpl, const AttrName& name, const size_t startIndex, const size_t endIndex, const void* value, const Typeinfo& typeinfo, const size_t arrayElemCount, MirroredArray *const valuesArray, ArrayAttributeArray *const arrayAttributeArray); void addAttributeInternal(const PathC& path, const TokenC& attrNameC, const NameSuffix nameSuffix, const TypeC ctype, const void* value, const Typeinfo& typeinfo, const size_t arrayElemCount); bool findArrayAttributeArrayForPath(const PathC& path, const TokenC& attrName, size_t& outElementIndex, BucketImpl*& outBucketImpl, ArrayAttributeArray*& outArrayAttributeArray); bool findArrayAttributeArrayForBucketId(const BucketId bucketId, const TokenC& attrName, BucketImpl*& outBucketImpl, ArrayAttributeArray*& outArrayAttributeArray); void allocElement(ScalarAttributeArray &scalar); void allocElement(ArrayAttributeArray &vector); size_t allocElement(BucketImpl& bucketImpl); void allocElementForMove(BucketImpl& srcBucketImpl, const ArrayOfArrayInfo &srcAoaInfo, const AttrName& name, MirroredArray &destArray, MirroredArray *const srcArray); size_t allocElementForMove(BucketImpl& destBucketImpl, BucketImpl& srcBucketImpl, const PathC& path); void addElementToTrackers(size_t elemIndex, BucketImpl& bucketImpl); void makeSrcValidIfDestValid(MirroredArray& srcArray, BucketImpl& srcBucketImpl, const ArrayOfArrayInfo& srcAoaInfo, const MirroredArray& destArray, const AttrName& name); void moveElementBetweenBuckets(const PathC& path, BucketId destBucketId, BucketId srcBucketId, const Bucket& destBucket); void moveElementScalarData(ScalarAttributeArray &destArray, const size_t destElemIndex, const ScalarAttributeArray &srcArray, const size_t srcElemIndex); void moveElementArrayData(ArrayAttributeArray &destArray, const size_t destElemIndex, const ArrayAttributeArray &srcArray, const size_t srcElemIndex); void moveElement(BucketImpl& destBucket, size_t destElemIndex, BucketImpl& srcBucket, size_t srcElemIndex); void destroyElement(BucketId bucketId, size_t elemIndex, bool destroyDataPointedTo); ArrayAndDirtyIndices getArraySpanC(BucketId bucketId, TokenC attrName, const IOConfig &io, NameSuffix suffix = NameSuffix::none); ArrayAndDirtyIndices getArraySpanC(MirroredArray& array, const AttrName& name, const ArrayOfArrayInfo& aoa, BucketImpl& bucketImpl, const IOConfig &io); void enableCpuReadImpl(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* elemToArrayGpuData, bool printWarnings = true); void enableCpuRead(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* elemToArrayGpuData); void enableCpuReadIfValid(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* elemToArrayGpuData); void enableGpuRead(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* elemToArrayGpuData); void enableGpuWrite(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* elemToArrayGpuData); void enableD3dGpuRead(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* gpuPointerArray); void enableD3dGpuWrite(MirroredArray& array, const size_t* elemToArraySize, MirroredArray* elemToArrayCpuCapacity, MirroredArray* elemToArrayGpuCapacity, MirroredArray* elemToArrayGpuData); static inline constexpr IOConfig CpuReadConfig() { return IOConfig{ &PathToAttributesMap::enableCpuRead, // enableRead nullptr, // enableWrite nullptr, // enableRdPtrForWrite Device::eCPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig CpuWriteConfig() { return IOConfig{ nullptr, // enableRead &PathToAttributesMap::enableCpuWrite, // enableWrite &PathToAttributesMap::enableCpuRead, // enableRdPtrForWrite Device::eCPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig CpuReadWriteConfig() { return IOConfig{ &PathToAttributesMap::enableCpuRead, // enableRead &PathToAttributesMap::enableCpuWrite, // enableWrite &PathToAttributesMap::enableCpuRead, // enableRdPtrForWrite Device::eCPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; // TODO: This probably needs to go away, it only exists to turn off "printWarnings" static inline constexpr IOConfig CpuReadIfValidWriteConfig() { return IOConfig{ &PathToAttributesMap::enableCpuReadIfValid, // enableRead &PathToAttributesMap::enableCpuWrite, // enableWrite &PathToAttributesMap::enableCpuRead, // enableRdPtrForWrite Device::eCPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig CudaReadConfig() { return IOConfig{ &PathToAttributesMap::enableGpuRead, // enableRead nullptr, // enableWrite nullptr, // enableRdPtrForWrite Device::eCudaGPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig CudaWriteConfig() { return IOConfig{ nullptr, // enableRead &PathToAttributesMap::enableGpuWrite, // enableWrite &PathToAttributesMap::enableGpuRead, // enableRdPtrForWrite Device::eCudaGPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig CudaReadWriteConfig() { return IOConfig{ &PathToAttributesMap::enableGpuRead, // enableRead &PathToAttributesMap::enableGpuWrite, // enableWrite &PathToAttributesMap::enableGpuRead, // enableRdPtrForWrite Device::eCudaGPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig D3dVkReadConfig() { return IOConfig{ &PathToAttributesMap::enableD3dGpuRead, // enableRead nullptr, // enableWrite nullptr, // enableRdPtrForWrite Device::eD3dVkGPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig D3dVkWriteConfig() { return IOConfig{ nullptr, // enableRead &PathToAttributesMap::enableD3dGpuWrite, // enableWrite &PathToAttributesMap::enableD3dGpuRead, // enableRdPtrForWrite Device::eD3dVkGPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; static inline constexpr IOConfig D3dVkReadWriteConfig() { return IOConfig{ &PathToAttributesMap::enableD3dGpuRead, // enableRead &PathToAttributesMap::enableD3dGpuWrite, // enableWrite &PathToAttributesMap::enableD3dGpuRead, // enableRdPtrForWrite Device::eD3dVkGPU, // device PtrToPtrKind::eNotApplicable // ptrToPtrKind }; }; std::tuple<bool, BucketId, size_t> getPresentAndBucketAndElement(const PathC& path) const; SpanC getArrayElementPtr(SpanC array, size_t bucketElement) const; ConstSpanC getArrayElementPtr(ConstSpanC array, size_t bucketElement) const; void destructiveResizeIfNecessary(uint8_t*& cpuData, size_t& capacity, size_t desiredElemCount, size_t elemByteCount); void destructiveResizeIfNecessaryGPU(MirroredArray& gpuPointerArray, size_t elem, size_t& capacity, size_t desiredElemCount, size_t elemByteCount, omni::gpucompute::GpuCompute* computeAPI, omni::gpucompute::Context* computeCtx); void resizeIfNecessary(uint8_t*& cpuData, size_t& capacity, size_t desiredElemCount, size_t elemByteCount, TypeC type); void resizeIfNecessaryGPU(MirroredArray& gpuPointerArray, size_t elem, size_t& capacity, size_t desiredElemCount, size_t elemByteCount, omni::gpucompute::GpuCompute* computeAPI, omni::gpucompute::Context* computeCtx); void allocGpuMemIfNecessary(PathToAttributesMap::MirroredArray& array, size_t byteCount, size_t elemSize, omni::gpucompute::GpuCompute* computeAPI, omni::gpucompute::Context* computeCtx); std::pair<BucketId, BucketImpl&> findOrCreateBucket(const Bucket& bucket); void eraseBucket(const Bucket& bucket); BucketId findBucketId(const Bucket& bucket); std::tuple<BucketId, ArrayIndex> getBucketAndArrayIndex(const PathC& path) const; std::tuple<BucketId, ArrayIndex> addAttributeGetBucketAndArrayIndex( const PathC& path, const TokenC& attrNameC, NameSuffix nameSuffix, TypeC type); void addAttributesToBucket( const PathC& path, const std::vector<TokenC>& attrNames, const std::vector<TypeC>& typeCs); void setArrayDirty(ArrayAndDirtyIndices& arrayAndDirtyIndices); void setArrayElementDirty(ArrayAndDirtyIndices& arrayAndDirtyIndices, size_t elemIndex); BucketImpl& addAttributeC(BucketImpl& bucketImpl, const Bucket& bucket, const TokenC& attrName, TypeC ctype, const void* value = nullptr); BucketImpl& addArrayAttributeC(BucketImpl& bucketImpl, const Bucket& bucket, const TokenC& attrName, TypeC ctype, const void* value, const size_t arrayElemCount); void checkInvariants(); /** * @brief Internal debug function * * @details This loops over all the array attributes checking that the * invariants hold true. Currently it just enforces * (I1) If the size and cpu size match that the cpu array pointer isn't null * * * @return none */ bool __validateArrayInvariants() const; }; // PathToAttributesMap doesn't depend on USD for tokens or paths // However, it's useful to be able to see the USD text representation of tokens and // paths when debugging. Set ENABLE_USD_DEBUGGING to 1 to enable that. // Then use toTfToken() to convert TokenC to pxr::TfToken inline const pxr::TfToken& toTfToken(const TokenC& token) { return reinterpret_cast<const pxr::TfToken&>(token); } inline const pxr::SdfPath& toSdfPath(const PathC& path) { return reinterpret_cast<const pxr::SdfPath&>(path); } // Query result struct View { PathToAttributesMap* path2attrsMap; std::vector<Bucket> buckets; std::vector<size_t> bucketElemCounts; }; using BucketImpl = PathToAttributesMap::BucketImpl; // The rest of this file is methods // Returns the number of Paths known to the cache inline size_t PathToAttributesMap::size() { return pathToBucketElem.size(); } // Delete all data in the cache, meaning all the buckets and the map // from paths to buckets. inline void PathToAttributesMap::clear() { buckets.clear(); pathToBucketElem.clear(); attrNameSetToBucketId.clear(); } template<typename CallbackT> inline void PathToAttributesMap::BucketIdToImpl::forEachValidBucket(CallbackT callback) const { BucketId id{ 0 }; for (size_t i = 0; i < buckets.size(); ++i, ++id) { if (buckets[i]) { callback(id, *buckets[i]); } } } inline void PathToAttributesMap::printMirroredArray(const char* const label, const ScalarAttributeArray &array, const size_t* const arrayElemCount) const { auto printValue = [](const uint8_t *const data, const size_t size) { if (!data) { printf("<nullptr>"); } else { if (size <= sizeof(uint8_t)) { printf("u8=%u, d8=%d, c=%c", *data, *(const int8_t*)data, *(const char*)data); } else if (size <= sizeof(uint16_t)) { printf("u16=%u, d16=%d", *(const uint16_t*)data, *(const int16_t*)data); } else if (size <= sizeof(uint32_t)) { printf("u32=%u, d32=%d, float=%f", *(const uint32_t*)data, *(const int32_t*)data, *(const float*)data); } else if (size <= sizeof(uint64_t)) { printf("u64=%" PRIu64 ", d64=%" PRId64 ", double=%f, ptr=0x%p", *(const uint64_t*)data, *(const int64_t*)data, *(const double*)data, *(void**)data); } else { printf("\n"); for (size_t i = 0; i < size; i += 16) { printf(" %06zx: ", i); for (size_t j = 0; j < 16; ++j) { if (i + j < size) { printf("%02x ", data[i + j]); } else { printf(" "); } } printf(" "); for (size_t j = 0; j < 16; j++) { if (i + j < size) { printf("%c", isprint(data[i + j]) ? data[i + j] : '.'); } } printf("\n"); } } } }; printf(" %s (type %d)[count %zu]:\n", label, array.type.type, array.count); const Typeinfo &typeinfo = array.typeinfo; const size_t elemSize = typeinfo.size; printf(" cpuValid=%d 0x%p\n", array.cpuValid, array.cpuData()); if (array.cpuValid) { for (size_t elem = 0; elem < array.count; ++elem) { printf(" [%5zu]: ", elem); const uint8_t *const elemData = array.cpuData() + elem * elemSize; printf("0x%p ", elemData); if (arrayElemCount) { CARB_ASSERT(typeinfo.isArray); const uint8_t* const base = *((const uint8_t **)elemData); printf(" => 0x%p", base); for (size_t i = 0; i < arrayElemCount[elem]; ++i) { printf("\n [%5zu]: ", i); const uint8_t* const arrayData = base ? base + i * typeinfo.arrayElemSize : nullptr; printValue(arrayData, typeinfo.arrayElemSize); } } else { printValue(elemData, elemSize); } printf("\n"); } } printf(" gpuValid=%d 0x%p\n", array.gpuValid, array.gpuArray); printf(" usdValid=%d\n", array.usdValid); } // Print the cache, specifically the Paths and the UsdAttributes they map to // (but not the values of the attributes currently) inline void PathToAttributesMap::print() const { auto va = [](auto ...params) -> const char* { static char tmp[1024]; #ifdef _WIN32 _snprintf_s(tmp, sizeof(tmp), params...); #else snprintf(tmp, sizeof(tmp), params...); #endif return (const char*)&tmp; }; std::cout << "(== PathToAttributesMap::print() begin ==)\n"; buckets.forEachValidBucket([this, va](const BucketId bucketId, const BucketImpl& bucketImpl) { printf("bucket [%zu]:\n", size_t(bucketId)); if (!bucketImpl.elemToPath.size()) { printf(" <no elements>\n"); } else { for (size_t elem = 0; elem < bucketImpl.elemToPath.size(); ++elem) { printf(" elem [%5zu]: \"%s\"\n", elem, bucketImpl.elemToPath[elem].GetText()); } } if (bucketImpl.scalarAttributeArrays.empty() && bucketImpl.arrayAttributeArrays.empty()) { printf(" <no attributes>\n"); } else { bucketImpl.scalarAttributeArrays.forEach([this, &va](const AttrName& name, const ScalarAttributeArray &array) { printMirroredArray(va("%s \"%s\"", "sattr", toTfToken(name.name).GetText()), array, nullptr); }); bucketImpl.arrayAttributeArrays.forEach([this, &va](const AttrName& name, const ArrayAttributeArray &array) { printMirroredArray(va("%s \"%s\" %s", "vattr", toTfToken(name.name).GetText(), "values"), array.values, (const size_t*)array.cpuElemCounts.cpuData()); printMirroredArray(va("%s \"%s\" %s", "vattr", toTfToken(name.name).GetText(), "elemCounts"), array.elemCounts, nullptr); printMirroredArray(va("%s \"%s\" %s", "vattr", toTfToken(name.name).GetText(), "cpuElemCounts"), array.cpuElemCounts, nullptr); printMirroredArray(va("%s \"%s\" %s", "vattr", toTfToken(name.name).GetText(), "gpuElemCounts"), array.gpuElemCounts, nullptr); printMirroredArray(va("%s \"%s\" %s", "vattr", toTfToken(name.name).GetText(), "gpuPtrs"), array.gpuPtrs, nullptr); }); } }); std::cout << "(== PathToAttributesMap::print() end ==)\n\n"; } #define ENABLE_LOG 0 inline void log(const char* format, ...) { #if ENABLE_LOG va_list args; va_start(args, format); vprintf(format, args); va_end(args); #endif } inline void PathToAttributesMap::addType(TypeC type, Typeinfo typeInfo) { Typeinfo *v; typeToInfo.allocateEntry(type, &v); *v = typeInfo; } inline Typeinfo PathToAttributesMap::getTypeInfo(TypeC type) const { const Typeinfo* typeinfo; if (typeToInfo.find(type, &typeinfo)) { return *typeinfo; } else { return Typeinfo(); } } inline BucketId PathToAttributesMap::addBucket(const Bucket& bucket) { auto iter = attrNameSetToBucketId.find(bucket); bool found = (iter != attrNameSetToBucketId.end()); if (!found) { // Create bucket auto bucketIdAndImpl = buckets.emplace(platform.allocator.new_<BucketImpl>(platform)); auto bucketAndId = attrNameSetToBucketId.emplace(bucket, bucketIdAndImpl.first); const Bucket& addedBucket = bucketAndId.first->first; BucketImpl& bucketImpl = bucketIdAndImpl.second; bucketImpl.SetBucket(bucket); // Make array for each type for (const AttrNameAndType& b : addedBucket) { const Type attrType = b.type; const Token& attrName = b.name; const NameSuffix& suffix = b.suffix; const TypeC attrTypeC = TypeC(attrType); const Typeinfo* typeinfo; if (typeToInfo.find(attrTypeC, &typeinfo)) { AttrName name{ attrName, suffix }; if (typeinfo->isArray) { ArrayAttributeArray* ptr; bucketImpl.arrayAttributeArrays.allocateEntry(std::move(name), &ptr); new (ptr) ArrayAttributeArray(platform, attrTypeC, *typeinfo); } else { ScalarAttributeArray* ptr; bucketImpl.scalarAttributeArrays.allocateEntry(std::move(name), &ptr); new (ptr) ScalarAttributeArray(platform, attrTypeC, *typeinfo); } } else { std::cout << "Error: Typeinfo for " << attrType << " not found. Please add it using addType()." << std::endl; } } return bucketIdAndImpl.first; } else { return iter->second; } } // Multiple attribute methods inline void PathToAttributesMap::getAttributesRdC(const void** attrsOut, const PathC* paths, const TokenC* attrNames, size_t attrCount) { // TODO: make optimized version instead of calling getAttributeRdC for (size_t i = 0; i != attrCount; i++) { attrsOut[i] = getAttributeRdC(paths[i], attrNames[i]).ptr; } } inline void PathToAttributesMap::getAttributesRdGpuC(const void** attrsOut, const PathC* paths, const TokenC* attrNames, size_t attrCount, PtrToPtrKind ptrToPtrKind) { // TODO: make optimized version instead of calling getAttributeRdGpuC for (size_t i = 0; i != attrCount; i++) { attrsOut[i] = getAttributeRdGpuC(paths[i], attrNames[i], ptrToPtrKind).ptr; } } inline void PathToAttributesMap::getArraysRdC(const void** attrsOut, const Bucket& bucket, const TokenC* attrNames, size_t attrCount) { // TODO: make optimized version instead of calling getArrayRdC for (size_t i = 0; i != attrCount; i++) { attrsOut[i] = getArrayRdC(bucket, attrNames[i]); } } inline void PathToAttributesMap::getAttributesWrC(void** attrsOut, const PathC& path, const TokenC* attrNames, size_t attrCount) { // TODO: make optimized version instead of calling getAttributeWrC for (size_t i = 0; i != attrCount; i++) { attrsOut[i] = getAttributeWrC(path, attrNames[i]).ptr; } } inline void PathToAttributesMap::getAttributesWrGpuC(void** attrsOut, const PathC& path, const TokenC* attrNames, size_t attrCount, PtrToPtrKind ptrToPtrKind) { // TODO: make optimized version instead of calling getAttributeWrGpuC for (size_t i = 0; i != attrCount; i++) { attrsOut[i] = getAttributeWrGpuC(path, attrNames[i], ptrToPtrKind).ptr; } } inline void PathToAttributesMap::getArraysWrC(void** attrsOut, const Bucket& bucket, const TokenC* attrNames, size_t attrCount) { // TODO: make optimized version instead of calling getArrayWrC for (size_t i = 0; i != attrCount; i++) { attrsOut[i] = getArrayWrC(bucket, attrNames[i]); } } // Algorithm: // Check whether bucket already has a bucketId // If it does: // Check whether bucketId has a bucketImpl // If it does: // return (bucketId, bucketImpl) // Else: // Print error message // return (bucketId, empty bucketImpl) // Else: // Allocate a bucketId // attrNameSetToBucketId += (bucket->bucketId) // buckets += (bucketId->empty bucketImpl) // inline std::pair<BucketId, BucketImpl&> PathToAttributesMap::findOrCreateBucket(const Bucket& bucket) { auto iter = attrNameSetToBucketId.find(bucket); bool foundBucketAndId = (iter != attrNameSetToBucketId.end()); BucketId bucketId; if (foundBucketAndId) { bucketId = iter->second; auto implPtr = buckets.find(bucketId); if (implPtr) { return { bucketId, *implPtr }; } else { // This is an error, but make an impl so that we can return gracefully CARB_LOG_ERROR("BucketId->impl not found"); // Allocate an impl and id->impl mapping and then set the // attrNameSetToBucketId to the slot of the new impl auto idAndImpl = buckets.emplace(platform.allocator.new_<BucketImpl>(platform)); iter->second = idAndImpl.first; idAndImpl.second.SetBucket(bucket); return idAndImpl; } } // Allocate an impl and place in vector auto idAndImpl = buckets.emplace(platform.allocator.new_<BucketImpl>(platform)); // Store bucket->Id mapping attrNameSetToBucketId.emplace(bucket, idAndImpl.first); idAndImpl.second.SetBucket(bucket); return idAndImpl; } inline void PathToAttributesMap::eraseBucket(const Bucket& bucket) { auto iter = attrNameSetToBucketId.find(bucket); bool foundBucketAndId = (iter != attrNameSetToBucketId.end()); BucketId bucketId; if (foundBucketAndId) { bucketId = iter->second; auto implPtr = buckets.find(bucketId); if (implPtr) { buckets.erase(bucketId); } else { CARB_LOG_ERROR("BucketId->impl not found"); } attrNameSetToBucketId.erase(bucket); } else { // Nothing to do } } // Add an attribute to all elements of a bucket // Note that this might cause a merge with an existing bucket // // Here are the maps we have to update: // pathToBucketElem :: path -> (bucketId, arrayIndex) // buckets :: bucketId -> bucketImpl // attrNameSetToBucketId :: bucket-> bucketId // inline BucketImpl& PathToAttributesMap::addAttributeC(BucketImpl& bucketImpl, const Bucket& bucket, const TokenC& attrName, TypeC ctype, const void* value) { // TODO: should we warn on missing type? const Typeinfo& typeinfo = getTypeInfo(ctype); if (typeinfo.isArray && value) { CARB_LOG_ERROR("addAttributeC: Attempted to add array-value attribute with default values. Use addArrayAttribute instead."); return bucketImpl; } return addAttributeInternal(bucketImpl, bucket, attrName, ctype, value, typeinfo, 0); } inline BucketImpl& PathToAttributesMap::addArrayAttributeC(BucketImpl& bucketImpl, const Bucket& bucket, const TokenC& attrName, TypeC ctype, const void* value, const size_t arrayElemCount) { CARB_ASSERT(!arrayElemCount || value); // TODO: should we warn on missing type? const Typeinfo& typeinfo = getTypeInfo(ctype); return addAttributeInternal(bucketImpl, bucket, attrName, ctype, value, typeinfo, arrayElemCount); } // Add an attribute to all elements of a bucket inline void PathToAttributesMap::addAttributeC( const Bucket& bucket, const TokenC& attrName, TypeC ctype, const void* value) { const auto iter = attrNameSetToBucketId.find(bucket); if (iter != attrNameSetToBucketId.end()) { const BucketId bucketId = iter->second; BucketImpl *const implPtr = buckets.find(bucketId); if (implPtr) { // TODO: should we warn on missing type? const Typeinfo& typeinfo = getTypeInfo(ctype); if (typeinfo.isArray && value) { CARB_LOG_ERROR("addAttributeC: Attempted to add array-value attribute with default values. Use addArrayAttribute instead."); return; } addAttributeInternal(*implPtr, bucket, attrName, ctype, value, typeinfo, 0); } } } inline void PathToAttributesMap::addArrayAttributeC(const Bucket& bucket, const TokenC& attrName, TypeC ctype, const void* value, const size_t arrayElemCount) { CARB_ASSERT(!arrayElemCount || value); const auto iter = attrNameSetToBucketId.find(bucket); if (iter != attrNameSetToBucketId.end()) { const BucketId bucketId = iter->second; BucketImpl *const implPtr = buckets.find(bucketId); if (implPtr) { // TODO: should we warn on missing type? const Typeinfo& typeinfo = getTypeInfo(ctype); addAttributeInternal(*implPtr, bucket, attrName, ctype, value, typeinfo, arrayElemCount); } } } template <typename T> void PathToAttributesMap::addAttribute( const Bucket& bucket, const TokenC& attrName, TypeC type, const T& value) { APILOGGER("addAttribute", apiLogEnabled, attrName); // TODO: check that type is compatible return addAttributeC(bucket, attrName, type, &value); } inline size_t PathToAttributesMap::getElementCount(const BucketImpl& bucketImpl) const { return bucketImpl.elemToPath.size(); } inline size_t PathToAttributesMap::getElementCount(BucketId bucketId) const { const auto implPtr = buckets.find(bucketId); if (implPtr) { return implPtr->elemToPath.size(); } return 0; } inline size_t PathToAttributesMap::getElementCount(const Bucket& bucket) const { const auto iter = attrNameSetToBucketId.find(bucket); if (iter != attrNameSetToBucketId.end()) { BucketId bucketId = iter->second; return getElementCount(bucketId); } return 0; } inline PathToAttributesMap::ArrayOfArrayInfo PathToAttributesMap::getArrayOfArrayInfo(Typeinfo typeInfo, BucketImpl& bucketImpl, TokenC attrName) { if (typeInfo.isArray) { ArrayAttributeArray *array; if (bucketImpl.arrayAttributeArrays.find(AttrName{ attrName, NameSuffix::none }, &array)) { return getArrayOfArrayInfo(*array); } } return { nullptr, nullptr, nullptr, nullptr }; } inline PathToAttributesMap::ArrayOfArrayInfo PathToAttributesMap::getArrayOfArrayInfo(ArrayAttributeArray &arrayAttributeArray) { MirroredArray *const arraySizeArray = &arrayAttributeArray.elemCounts; MirroredArray *const arrayCpuCapacityArray = &arrayAttributeArray.cpuElemCounts; MirroredArray *const arrayGpuCapacityArray = &arrayAttributeArray.gpuElemCounts; MirroredArray *const arrayGpuPtrArray = &arrayAttributeArray.gpuPtrs; return { (size_t*)arraySizeArray->cpuData(), arrayCpuCapacityArray, arrayGpuCapacityArray, arrayGpuPtrArray }; } inline PathToAttributesMap::ConstArrayOfArrayInfo PathToAttributesMap::getArrayOfArrayInfo(Typeinfo typeInfo, const BucketImpl& bucketImpl, TokenC attrName) const { if (typeInfo.isArray) { const ArrayAttributeArray *array; if (bucketImpl.arrayAttributeArrays.find(AttrName{ attrName, NameSuffix::none }, &array)) { return getArrayOfArrayInfo(*array); } } return { nullptr, nullptr, nullptr, nullptr }; } inline PathToAttributesMap::ConstArrayOfArrayInfo PathToAttributesMap::getArrayOfArrayInfo(const ArrayAttributeArray &arrayAttributeArray) const { const MirroredArray *const arraySizeArray = &arrayAttributeArray.elemCounts; const MirroredArray *const arrayCpuCapacityArray = &arrayAttributeArray.cpuElemCounts; const MirroredArray *const arrayGpuCapacityArray = &arrayAttributeArray.gpuElemCounts; const MirroredArray *const arrayGpuPtrArray = &arrayAttributeArray.gpuPtrs; return { arraySizeArray, arrayCpuCapacityArray, arrayGpuCapacityArray, arrayGpuPtrArray }; } inline std::vector<size_t> PathToAttributesMap::getElementCounts(const std::vector<Bucket>& buckets) const { size_t bucketCount = buckets.size(); std::vector<size_t> retval(bucketCount); for (size_t i = 0; i != bucketCount; i++) { retval[i] = getElementCount(buckets[i]); } return retval; } inline void PathToAttributesMap::addElementToTrackers(size_t elemIndex, BucketImpl& bucketImpl) { // Update change trackers // We allocate them lazily, so we have to iterate over listenerIdToChangeTrackerConfig // then allocate bucketImpl.listenerIdToChanges if necessary listenerIdToChangeTrackerConfig.forEach([this, &bucketImpl, &elemIndex](ListenerId& listenerId, ChangeTrackerConfig& config) { if (config.changeTrackingEnabled) { // Allocate changes if necessary Changes* changes; if (bucketImpl.listenerIdToChanges.allocateEntry(listenerId, &changes)) { new (changes) Changes(); } changes->addNewPrim(elemIndex); } }); } inline void PathToAttributesMap::allocElement(ScalarAttributeArray &scalar) { const size_t allocSize = scalar.typeinfo.size; const size_t newSize = scalar.size() + allocSize; scalar.resize(newSize); // Only resize GPU mirror if it was previously allocated if (scalar.gpuCapacity != 0) { scalar.resizeGpu(platform.gpuCuda, platform.gpuCudaCtx, newSize, allocSize); } scalar.count++; } inline void PathToAttributesMap::allocElement(ArrayAttributeArray &arrayAttributeArray) { static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); allocElement(arrayAttributeArray.values); allocElement(arrayAttributeArray.elemCounts); allocElement(arrayAttributeArray.cpuElemCounts); allocElement(arrayAttributeArray.gpuElemCounts); allocElement(arrayAttributeArray.gpuPtrs); // For array-valued attributes, initialize CPU and GPU element counts static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); reinterpret_cast<size_t*>(arrayAttributeArray.elemCounts.cpuData())[arrayAttributeArray.elemCounts.count-1] = 0; arrayAttributeArray.elemCounts.cpuValid = true; reinterpret_cast<size_t*>(arrayAttributeArray.cpuElemCounts.cpuData())[arrayAttributeArray.cpuElemCounts.count - 1] = 0; arrayAttributeArray.cpuElemCounts.cpuValid = true; reinterpret_cast<size_t*>(arrayAttributeArray.gpuElemCounts.cpuData())[arrayAttributeArray.gpuElemCounts.count - 1] = 0; arrayAttributeArray.gpuElemCounts.cpuValid = true; } inline size_t PathToAttributesMap::allocElement(BucketImpl& bucketImpl) { // I moved this here to support old-style ArrayBase::resize // TODO: Now that ArrayBase is gone, check whether we can move it back const size_t element = bucketImpl.elemToPath.size(); bucketImpl.elemToPath.emplace_back(); // Allocate an empty path, it gets set later bucketImpl.scalarAttributeArrays.forEach([this, &bucketImpl](const AttrName& name, ScalarAttributeArray &array) { allocElement(array); CARB_UNUSED(bucketImpl); CARB_ASSERT(array.count == bucketImpl.elemToPath.size()); }); bucketImpl.arrayAttributeArrays.forEach([this, &bucketImpl](const AttrName& name, ArrayAttributeArray &array) { allocElement(array); CARB_UNUSED(bucketImpl); CARB_ASSERT(array.values.count == bucketImpl.elemToPath.size()); CARB_ASSERT(array.elemCounts.count == bucketImpl.elemToPath.size()); CARB_ASSERT(array.cpuElemCounts.count == bucketImpl.elemToPath.size()); CARB_ASSERT(array.gpuElemCounts.count == bucketImpl.elemToPath.size()); CARB_ASSERT(array.gpuPtrs.count == bucketImpl.elemToPath.size()); }); addElementToTrackers(element, bucketImpl); return element; } // CPU and GPU valid bits are per SoA array, not per-prim per-attribute. // Suppose we have a prim with attr whose GPU mirror is not valid, and we want // to add it to a bucket that has a valid GPU mirror of that attribute. What // should we set the bucket array's gpuValid to after the add? // // Option 1: set bucket's gpuValid to false. // If cpuValid were true for the bucket, then this would be inefficient but // correct. But, if cpuValid were false, then we'd have to copy all the bucket's // data from GPU to CPU to avoid invalidating the only valid copy of the data. // That would be very inefficient for a bucket with a lot of prims, or an // array of array-valued attributes. // // Option 2: set bucket's gpuValid to true. // For the bucket plus our new element to be gpuValid, we need to make the new // element gpuValid by copying it from CPU to GPU. // // We've chosen Option 2 as it is the most efficient and makeSrcValidIfDestValid // implements it. // The explanation above was for GPU mirrors, but it applies equally to CPU. // // We are changing the srcArray mirrors to match destArray, so // counterintuitively destArray is const and srcArray is not. inline void PathToAttributesMap::makeSrcValidIfDestValid(MirroredArray& srcArray, BucketImpl& srcBucketImpl, const ArrayOfArrayInfo& srcAoaInfo, const MirroredArray& destArray, const AttrName& name) { bool srcCpuValid = srcArray.cpuValid; bool srcGpuValid = srcArray.gpuValid; bool destCpuValid = destArray.cpuValid; bool destGpuValid = destArray.gpuValid; if (srcCpuValid && !srcGpuValid && destGpuValid) { // Possible states: // srcCpu srcGpu destCpu destGpu // 1 0 0 1 // 1 0 1 1 // With a valid CPU source, this will copy data to the GPU to make it valid // We don't set dirty indices here because this method gives read-only access getArraySpanC(srcArray, name, srcAoaInfo, srcBucketImpl, CudaReadConfig()); // srcCpu srcGpu destCpu destGpu // 1 1 0 1 // 1 1 1 1 } else if (!srcCpuValid && !srcGpuValid && !destCpuValid && destGpuValid) { // srcCpu srcGpu destCpu destGpu // 0 0 0 1 // Without a valid CPU source, just allocate memory so it can be "valid" even if not initialized getArraySpanC(srcArray, name, srcAoaInfo, srcBucketImpl, CudaWriteConfig()); // srcCpu srcGpu destCpu destGpu // 0 1 0 1 } else if (!srcCpuValid && srcGpuValid && destCpuValid) { // srcCpu srcGpu destCpu destGpu // 0 1 1 0 // 0 1 1 1 // With a valid GPU source, this will copy data back to the CPU to make it valid // We don't set dirty indices here because this method gives read-only access getArraySpanC(srcArray, name, srcAoaInfo, srcBucketImpl, CpuReadConfig()); // srcCpu srcGpu destCpu destGpu // 1 1 1 0 // 1 1 1 1 } else if (!srcCpuValid && !srcGpuValid && destCpuValid && !destGpuValid) { // srcCpu srcGpu destCpu destGpu // 0 0 1 0 // Without a valid GPU source, just allocate memory so it can be "valid" even if not initialized getArraySpanC(srcArray, name, srcAoaInfo, srcBucketImpl, CpuWriteConfig()); // srcCpu srcGpu destCpu destGpu // 1 0 1 0 } else if (!srcCpuValid && !srcGpuValid && destCpuValid && destGpuValid) { // srcCpu srcGpu destCpu destGpu // 0 0 1 1 // Without a valid GPU source, just allocate memory so it can be "valid" even if not initialized getArraySpanC(srcArray, name, srcAoaInfo, srcBucketImpl, CudaWriteConfig()); // srcCpu srcGpu destCpu destGpu // 0 1 1 1 // This one clears gpuValid, because we assume that the user is going to write to it // But, we're not passing the allocated pointer to the user so... getArraySpanC(srcArray, name, srcAoaInfo, srcBucketImpl, CpuWriteConfig()); // srcCpu srcGpu destCpu destGpu // 1 0 1 1 // ..we can safely set gpuValid to true srcArray.gpuValid = true; // srcCpu srcGpu destCpu destGpu // 1 1 1 1 } } inline void PathToAttributesMap::allocElementForMove(BucketImpl& srcBucketImpl, const ArrayOfArrayInfo &srcAoaInfo, const AttrName& name, MirroredArray &destArray, MirroredArray *const srcArray) { bool srcGpuAlloced = false; if (srcArray) { makeSrcValidIfDestValid(*srcArray, srcBucketImpl, srcAoaInfo, destArray, name); srcGpuAlloced = (srcArray->gpuCapacity != 0); } if (srcArray) { if (destArray.type != srcArray->type) { if (destArray.typeinfo.size != srcArray->typeinfo.size) { CARB_LOG_ERROR_ONCE("PathToAttributesMap (%p) contains attributes with duplicate name \"%s\" with different types and different per-element sizes (%zu vs %zu). Data will almost certainly become corrupted during request to move elements between buckets!", this, toTfToken(name.name).GetString().c_str(), destArray.typeinfo.size, srcArray->typeinfo.size); } else { CARB_LOG_WARN_ONCE("PathToAttributesMap (%p) contains attributes with duplicate name \"%s\" with different types but same per-element size. Data may become corrupted during request to move elements between buckets!", this, toTfToken(name.name).GetString().c_str()); } } } const size_t allocSize = destArray.typeinfo.size; const size_t newSize = destArray.size() + allocSize; destArray.resize(newSize); const bool destGpuAlloced = (destArray.gpuCapacity != 0); if (srcGpuAlloced || destGpuAlloced) { destArray.resizeGpu(platform.gpuCuda, platform.gpuCudaCtx, destArray.size(), destArray.typeinfo.size); } destArray.count++; } // When moving elements between buckets we want to only allocate GPU storage if // the source had a valid GPU mirror. inline size_t PathToAttributesMap::allocElementForMove(BucketImpl& destBucketImpl, BucketImpl& srcBucketImpl, const PathC& path) { const size_t element = destBucketImpl.elemToPath.size(); destBucketImpl.elemToPath.emplace_back(); // Allocate an empty path, it gets set later // Only allocate dest GPU mirror if src has GPU mirror destBucketImpl.scalarAttributeArrays.forEach([this, &srcBucketImpl](const AttrName& name, ScalarAttributeArray &array) { ScalarAttributeArray *srcArray = srcBucketImpl.scalarAttributeArrays.find(name, &srcArray) ? srcArray : nullptr; const ArrayOfArrayInfo aoa = ScalarArrayOfArrayInfo(); allocElementForMove(srcBucketImpl, aoa, name, array, srcArray); }); destBucketImpl.arrayAttributeArrays.forEach([this, &srcBucketImpl](const AttrName& name, ArrayAttributeArray &array) { ArrayAttributeArray *srcArray = srcBucketImpl.arrayAttributeArrays.find(name, &srcArray) ? srcArray : nullptr; static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); const ArrayOfArrayInfo aoa = srcArray ? getArrayOfArrayInfo(*srcArray) : ScalarArrayOfArrayInfo(); allocElementForMove(srcBucketImpl, aoa, name, array.values, srcArray ? &srcArray->values : nullptr); allocElementForMove(srcBucketImpl, aoa, name, array.elemCounts, srcArray ? &srcArray->elemCounts : nullptr); allocElementForMove(srcBucketImpl, aoa, name, array.cpuElemCounts, srcArray ? &srcArray->cpuElemCounts : nullptr); allocElementForMove(srcBucketImpl, aoa, name, array.gpuElemCounts, srcArray ? &srcArray->gpuElemCounts : nullptr); allocElementForMove(srcBucketImpl, aoa, name, array.gpuPtrs, srcArray ? &srcArray->gpuPtrs : nullptr); // For array-valued attributes, initialize CPU and GPU element counts static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); reinterpret_cast<size_t*>(array.elemCounts.cpuData())[array.elemCounts.count - 1] = 0; array.elemCounts.cpuValid = true; reinterpret_cast<size_t*>(array.cpuElemCounts.cpuData())[array.cpuElemCounts.count - 1] = 0; array.cpuElemCounts.cpuValid = true; reinterpret_cast<size_t*>(array.gpuElemCounts.cpuData())[array.gpuElemCounts.count - 1] = 0; array.gpuElemCounts.cpuValid = true; }); addElementToTrackers(element, destBucketImpl); return element; } // Array resize that does not preserve previous data inline void PathToAttributesMap::destructiveResizeIfNecessary(uint8_t*& cpuData, size_t& capacity, size_t desiredElemCount, size_t elemByteCount) { // Resize iff (capacity < desiredElemCount) if (capacity != desiredElemCount) { size_t byteCount = desiredElemCount * elemByteCount; if (!USE_PINNED_MEMORY || !platform.gpuCuda) { free(cpuData); cpuData = reinterpret_cast<uint8_t*>(malloc(byteCount)); } else if (platform.gpuCuda) { // Use page-locked memory CPU for CUDA platform.gpuCuda->freeHost(*platform.gpuCudaCtx, cpuData); platform.gpuCuda->hostAlloc(*platform.gpuCudaCtx, (void**)&cpuData, byteCount); } capacity = desiredElemCount; } } // Flatcache only stores POD types, with the following exceptions: // eToken (pxr::TfToken) // eAsset (std::array<pxr::TfToken, 2>) // // The following code constructs an array of objects of one of these types, // filling memory[newCpuData + oldByteCount .. newCpuData + newByteCount) // It is called when enlarging arrays of such types template <typename T> void constructInPlace(uint8_t* newCpuData, size_t oldByteCount, size_t newByteCount) { T* begin = reinterpret_cast<T*>(newCpuData + oldByteCount); T* end = reinterpret_cast<T*>(newCpuData + newByteCount); for (T* current = begin; current != end; current++) { new (current) T; } } // We plan to move TfToken and AssetPath construction to IToken. // Until we do we have to declare this here and depend on USD headers. struct AssetPath { pxr::TfToken assetPath; pxr::TfToken resolvedPath; }; inline bool PathToAttributesMap::__validateArrayInvariants() const { bool encounteredFailure = false; // loop over the buckets BucketId id{ 0 }; for (unsigned int i = 0; i < this->buckets.end(); ++i, ++id) { const auto bucketImplPtr = buckets.find(id); if (!bucketImplPtr) continue; const auto& bucketImpl = *bucketImplPtr; if (bucketImpl.elemToPath.size() == 0) continue; //loop over all the arrays bucketImpl.arrayAttributeArrays.forEach([&encounteredFailure](const AttrName& name, const ArrayAttributeArray& local_array) { const Typeinfo& typeInfo = local_array.values.typeinfo; const size_t elemSize = typeInfo.size; // only care about actual data if (name.suffix != NameSuffix::none) return; // look up array info const MirroredArray* arraySizeArray = &local_array.elemCounts; const MirroredArray* arrayCpuCapacityArray = &local_array.cpuElemCounts; // skip tags and not arrays if (elemSize != 0) { //number of elements const size_t elemCount = local_array.values.count; // pointers to data const uint8_t* const* elemToArrayCpuData = reinterpret_cast<const uint8_t* const*>(local_array.values.cpuData()); for (size_t elem = 0; elem != elemCount; elem++) { // get the actual pointer const uint8_t* cpuData = elemToArrayCpuData[elem]; // look up the cpu capacity const size_t& cpuCapacity = reinterpret_cast<const size_t*>(arraySizeArray->cpuData())[elem]; const size_t& desiredElemCount = reinterpret_cast<const size_t*>(arrayCpuCapacityArray->cpuData())[elem]; if (cpuCapacity == desiredElemCount) { // we should have valid data if (cpuCapacity != 0 && !cpuData) { std::cout << "Invalid array name = " << toTfToken(name.name).GetString() << std::endl; encounteredFailure = true; } } } } }); } return encounteredFailure; } // Array resize that preserves previous data inline void PathToAttributesMap::resizeIfNecessary( uint8_t*& cpuData, size_t& capacity, size_t desiredElemCount, size_t elemByteCount, TypeC typeC) { // TODO: reduce number of reallocations by allocating capacity larger than size // and not always reallocating when desiredElemCount<capacity if (capacity < desiredElemCount) { size_t oldByteCount = capacity * elemByteCount; size_t newByteCount = desiredElemCount * elemByteCount; uint8_t* newCpuData = nullptr; if (!USE_PINNED_MEMORY || !platform.gpuCuda) { newCpuData = reinterpret_cast<uint8_t*>(malloc(newByteCount)); } else if (platform.gpuCuda) { platform.gpuCuda->hostAlloc(*platform.gpuCudaCtx, reinterpret_cast<void**>(&newCpuData), newByteCount); } if (cpuData) { size_t copyByteCount = std::min(oldByteCount, newByteCount); memcpy(newCpuData, cpuData, copyByteCount); if (!USE_PINNED_MEMORY || !platform.gpuCuda) { free(cpuData); } else if (platform.gpuCuda) { platform.gpuCuda->freeHost(*platform.gpuCudaCtx, cpuData); } } // If type has a constructor, construct any new elements if (oldByteCount < newByteCount) { Type type(typeC); const uint8_t kScalar = 1; const uint8_t kArray = 1; if (type == Type(BaseDataType::eToken, kScalar, kArray)) { constructInPlace<pxr::TfToken>(newCpuData, oldByteCount, newByteCount); } else if (type == Type(BaseDataType::eAsset, kScalar, kArray)) { constructInPlace<flatcache::AssetPath>(newCpuData, oldByteCount, newByteCount); } else if (type == Type(BaseDataType::eConnection, kScalar, kArray)) { constructInPlace<flatcache::Connection>(newCpuData, oldByteCount, newByteCount); } } cpuData = newCpuData; capacity = desiredElemCount; } } inline void PathToAttributesMap::enableCpuReadImpl(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* gpuArrayDataArray, bool printWarnings) { using omni::gpucompute::MemcpyKind; bool& usdValid = array.usdValid; bool& cpuValid = array.cpuValid; bool& gpuValid = array.gpuValid; bool& usingCuda = array.gpuAllocedWithCuda; uint8_t* cpuArray = array.cpuData(); uint8_t*& gpuArray = array.gpuArray; // If CPU copy is valid, nothing to do // If GPU copy is valid, copy to CPU // If USD copy is valid, copy to CPU if (cpuValid) { // Nothing to do } else if (!cpuValid && gpuValid) { size_t byteCount = array.size(); // Select which API to use omni::gpucompute::GpuCompute* computeAPI = nullptr; omni::gpucompute::Context* computeCtx = nullptr; if (usingCuda) { computeAPI = platform.gpuCuda; computeCtx = platform.gpuCudaCtx; } else if (!usingCuda) { computeAPI = platform.gpuD3dVk; computeCtx = platform.gpuD3dVkCtx; } const Typeinfo &typeinfo = array.typeinfo; std::lock_guard<MirroredArray::AttributeMutex> hostDeviceLock(array.attributeMutex); if (typeinfo.isArray) { size_t elemCount = array.count; uint8_t** elemToArrayCpuData = reinterpret_cast<uint8_t**>(cpuArray); uint8_t** elemToArrayGpuData = reinterpret_cast<uint8_t**>(gpuArrayDataArray->cpuData()); for (size_t elem = 0; elem != elemCount; elem++) { // Make sure that the dest (CPU) buffer is large enough uint8_t*& cpuData = elemToArrayCpuData[elem]; // dest const uint8_t* const& gpuData = elemToArrayGpuData[elem]; // src size_t& destCapacity = reinterpret_cast<size_t*>(elemToArrayCpuCapacity->cpuData())[elem]; size_t desiredElemCount = elemToArraySize[elem]; destructiveResizeIfNecessary(cpuData, destCapacity, desiredElemCount, typeinfo.arrayElemSize); // Copy from GPU to CPU size_t copyByteCount = desiredElemCount * typeinfo.arrayElemSize; if(gpuData) computeAPI->memcpy(*computeCtx, cpuData, gpuData, copyByteCount, MemcpyKind::deviceToHost); } // Don't copy the outer array to CPU, because GPU is not allowed to change outer array } else { log("array values: from GPU\n"); computeAPI->memcpy(*computeCtx, cpuArray, gpuArray, byteCount, MemcpyKind::deviceToHost); } cpuValid = true; } else if (!cpuValid && usdValid) { // printf("TODO: read data lazily from USD\n"); } else { if (printWarnings) CARB_LOG_WARN("No source has valid data array=%p usdValid=%i cpuValid=%i gpuValid=%i gpuAllocedWithCuda=%i", &array, array.usdValid, array.cpuValid, array.gpuValid, array.gpuAllocedWithCuda); } } inline void PathToAttributesMap::enableCpuReadIfValid(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* gpuArrayDataArray) { enableCpuReadImpl(array, elemToArraySize, elemToArrayCpuCapacity, elemToArrayGpuCapacity, gpuArrayDataArray, false); } inline void PathToAttributesMap::enableCpuRead(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* gpuArrayDataArray) { enableCpuReadImpl(array, elemToArraySize, elemToArrayCpuCapacity, elemToArrayGpuCapacity, gpuArrayDataArray, true); } inline void PathToAttributesMap::enableCpuWrite(PathToAttributesMap::MirroredArray& array, const size_t* elemToArraySize, PathToAttributesMap::MirroredArray* elemToArrayCpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuCapacity, PathToAttributesMap::MirroredArray* elemToArrayGpuData) { using omni::gpucompute::MemcpyKind; bool& usdValid = array.usdValid; bool& cpuValid = array.cpuValid; bool& gpuValid = array.gpuValid; const Typeinfo &typeinfo = array.typeinfo; // Array-valued elements are lazily allocated, meaning they are only // resized when write access is requested. // Write access has been requested, so resize if necessary std::lock_guard<MirroredArray::AttributeMutex> hostDeviceLock(array.attributeMutex); if (typeinfo.isArray) { size_t elemCount = array.count; uint8_t** elemToArrayCpuData = reinterpret_cast<uint8_t**>(array.cpuData()); CARB_ASSERT(elemToArrayCpuCapacity->cpuValid); for (size_t elem = 0; elem != elemCount; elem++) { uint8_t*& cpuData = elemToArrayCpuData[elem]; size_t& cpuCapacity = reinterpret_cast<size_t*>(elemToArrayCpuCapacity->cpuData())[elem]; size_t desiredElemCount = elemToArraySize[elem]; resizeIfNecessary(cpuData, cpuCapacity, desiredElemCount, typeinfo.arrayElemSize, array.type); } } // New state usdValid = false; cpuValid = true; gpuValid = false; } inline ArrayAndDirtyIndices PathToAttributesMap::getArraySpanC(MirroredArray& array, const AttrName& name, const ArrayOfArrayInfo& aoa, BucketImpl& bucketImpl, const IOConfig& io) { const size_t elemCount = bucketImpl.elemToPath.size(); const Typeinfo& typeinfo = array.typeinfo; const size_t elemSize = typeinfo.size; log("begin getArrayC\n"); bool isTag = (elemSize == 0); if (isTag) { // If is a tag, then array.data() will be zero, so set special value // to distinguish from tag absent case return { SpanC{ (uint8_t*)-1, elemCount, 0 }, {} }; } // Read enable must come before write enable if (io.enableRead) { (this->*io.enableRead)(array, aoa.arraySizeArray, aoa.arrayCpuCapacityArray, aoa.arrayGpuCapacityArray, aoa.arrayGpuPtrArray); // If requesting GPU access to array-of-array, additionally // enable array of GPU pointers for GPU read if (typeinfo.isArray && io.device == Device::eCudaGPU) { (this->*io.enableRead)(*aoa.arrayGpuPtrArray, nullptr, nullptr, nullptr, nullptr); } } if (io.enableWrite) { (this->*io.enableWrite)(array, aoa.arraySizeArray, aoa.arrayCpuCapacityArray, aoa.arrayGpuCapacityArray, aoa.arrayGpuPtrArray); // If requesting GPU access to array-of-array, additionally // enable array of GPU pointers for GPU _read_ // This is necessary because the pointers may have been // reallocated on CPU, and the GPU needs to _read_ these new // pointers if (typeinfo.isArray && io.device == Device::eCudaGPU) { (this->*io.enableRdPtrForWrite)(*aoa.arrayGpuPtrArray, nullptr, nullptr, nullptr, nullptr); } } // If CPU pointer requested // return CPU pointer // If GPU pointer requested and not array of array // return GPU pointer // If GPU pointer requested and array of array // return GPU pointer to GPU pointer array uint8_t* retPtr = nullptr; if (io.device == Device::eCPU) { retPtr = array.cpuData(); } else if (io.device == Device::eCudaGPU && !typeinfo.isArray) { retPtr = array.gpuArray; } else if (io.device == Device::eCudaGPU && typeinfo.isArray && io.ptrToPtrKind == PtrToPtrKind::eGpuPtrToGpuPtr) { retPtr = aoa.arrayGpuPtrArray->gpuArray; } else if (io.device == Device::eCudaGPU && typeinfo.isArray && io.ptrToPtrKind == PtrToPtrKind::eCpuPtrToGpuPtr) { retPtr = aoa.arrayGpuPtrArray->cpuData(); } else if (io.device == Device::eD3dVkGPU && !typeinfo.isArray) { retPtr = array.gpuArray; } else if (io.device == Device::eD3dVkGPU && typeinfo.isArray) { retPtr = aoa.arrayGpuPtrArray->cpuData(); } // If enabling write, // for each enabled listener listening to this attribute // if changedIndices exists // add to vector // else // create changedIndices and add to vector // return vector // else // return empty vector std::vector<ChangedIndicesImpl*> changedIndicesForEachListener; changedIndicesForEachListener.reserve(listenerIdToChangeTrackerConfig.size()); if (io.enableWrite) { // optimization because the cost to create attrNameAndType is non-trivial, // but they are loop invariant so we should try to only do it once. bool costlyInvariantsInitialized = false; AttrNameAndType *const attrNameAndType = (AttrNameAndType*)alloca(sizeof(AttrNameAndType)); // stack-allocate here for scope, but lazily-initialize below listenerIdToChangeTrackerConfig.forEach([this, &bucketImpl, &costlyInvariantsInitialized, &name, &attrNameAndType, &array, &elemCount, &changedIndicesForEachListener](ListenerId& listenerId, ChangeTrackerConfig& config) { // Create listener if it doesn't exist in bucket Changes* changes; if (bucketImpl.listenerIdToChanges.allocateEntry(listenerId, &changes)) { new (changes) Changes(); } if (config.changeTrackingEnabled && config.attrNamesToLog.contains(name.name)) { if (!costlyInvariantsInitialized) { new (attrNameAndType) AttrNameAndType(Type(array.type), name.name, name.suffix); costlyInvariantsInitialized = true; } auto iter = changes->changedAttributes.find(*attrNameAndType); bool foundChangedIndices = (iter != changes->changedAttributes.end()); if (!foundChangedIndices) { // TODO: move this into a new ordered_map class auto& keys = changes->changedAttributes.v; auto& values = changes->changedIndices; auto insertIter = lower_bound(keys.begin(), keys.end(), *attrNameAndType); ptrdiff_t insertIndex = insertIter - keys.begin(); keys.insert(insertIter, *attrNameAndType); values.insert(values.begin() + insertIndex, ChangedIndicesImpl(elemCount)); changedIndicesForEachListener.push_back(&values[insertIndex]); } else { ptrdiff_t attrIndex = iter - changes->changedAttributes.begin(); changedIndicesForEachListener.push_back(&changes->changedIndices[attrIndex]); } } }); } return { SpanC{ retPtr, elemCount, typeinfo.size }, changedIndicesForEachListener }; } inline ArrayAndDirtyIndices PathToAttributesMap::getArraySpanC(BucketId bucketId, TokenC attrName, const IOConfig &io, NameSuffix suffix) { BucketImpl *const bucketImpl = buckets.find(bucketId); if (!bucketImpl) { return { SpanC{ nullptr, 0, 0 }, {} }; } const AttrName name{ attrName, suffix }; { ScalarAttributeArray *array; if (bucketImpl->scalarAttributeArrays.find(name, &array)) { const ArrayOfArrayInfo aoa = ScalarArrayOfArrayInfo(); return getArraySpanC(*array, name, aoa, *bucketImpl, io); } } { ArrayAttributeArray *array; if (bucketImpl->arrayAttributeArrays.find(name, &array)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*array); return getArraySpanC(array->values, name, aoa, *bucketImpl, io); } } return { SpanC{ nullptr, 0, 0 }, {} }; } template <typename T> inline const T* PathToAttributesMap::getArrayRd(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayRd", apiLogEnabled, attrName); // TODO: check that T is the correct type return reinterpret_cast<const T*>(getArrayRdC(bucket, attrName, NameSuffix::none)); } template <typename T> inline const T* PathToAttributesMap::getArrayRd(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayRd", apiLogEnabled, attrName); // TODO: check that T is the correct type return reinterpret_cast<const T*>(getArrayRdC(bucketId, attrName, NameSuffix::none).ptr); } template <typename T> inline T* PathToAttributesMap::getArrayWr(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayWr", apiLogEnabled, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getArrayWrC(bucket, attrName, NameSuffix::none)); } template <typename T> inline T* PathToAttributesMap::getArray(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArray", apiLogEnabled, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getArrayC(bucket, attrName, NameSuffix::none)); } template <typename T> inline std::vector<const T*> PathToAttributesMap::getArraysRd(const std::vector<Bucket>& buckets, const TokenC& attrName) { size_t bucketCount = buckets.size(); std::vector<const T*> retval(bucketCount); for (size_t i = 0; i != bucketCount; i++) { retval[i] = getArrayRd<T>(buckets[i], attrName); } return retval; } template <typename T> inline std::vector<T*> PathToAttributesMap::getArraysWr(const std::vector<Bucket>& buckets, const TokenC& attrName) { size_t bucketCount = buckets.size(); std::vector<const T*> retval(bucketCount); for (size_t i = 0; i != bucketCount; i++) { retval[i] = getArrayWr<T>(buckets[i], attrName); } return retval; } template <typename T> inline std::vector<T*> PathToAttributesMap::getArrays(const std::vector<Bucket>& buckets, const TokenC& attrName) { size_t bucketCount = buckets.size(); std::vector<T*> retval(bucketCount); for (size_t i = 0; i != bucketCount; i++) { retval[i] = getArray<T>(buckets[i], attrName); } return retval; } inline BucketId PathToAttributesMap::findBucketId(const Bucket& bucket) { auto iter = attrNameSetToBucketId.find(bucket); bool found = iter != attrNameSetToBucketId.end(); if (!found) return { kInvalidBucketId }; return iter->second; } inline ConstSpanC PathToAttributesMap::getArraySpanRdC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArraySpanRdC", apiLogEnabled, attrName); // Get read-only CPU access BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return { nullptr, 0, 0 }; const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuReadConfig(), suffix); // We don't set dirty indices here because this method gives read-only access return arrayAndDirtyIndices.array; } inline const void* PathToAttributesMap::getArrayRdC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayRdC", apiLogEnabled, attrName); // Get read-only CPU access BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuReadConfig(), suffix); // We don't set dirty indices here because this method gives read-only access return arrayAndDirtyIndices.array.ptr; } inline ConstSpanC PathToAttributesMap::getArrayRdC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayRdC", apiLogEnabled, attrName); // Get read-only CPU access const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuReadConfig(), suffix); // We don't set dirty indices here because this method gives read-only access return arrayAndDirtyIndices.array; } inline SpanC PathToAttributesMap::getArraySpanWrC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArraySpanWrC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return { nullptr, 0, 0 }; ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array; } inline void* PathToAttributesMap::getArrayWrC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayWrC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array.ptr; } inline SpanC PathToAttributesMap::getArrayWrC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayWrC", apiLogEnabled, attrName); ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array; } inline SpanC PathToAttributesMap::getOrCreateArrayWrC( BucketId bucketId, const TokenC& attrName, TypeC type, NameSuffix suffix) { APILOGGER("getOrCreateArrayWrC", apiLogEnabled, attrName); auto bucketImpl = buckets.find(bucketId); if (!bucketImpl) { return SpanC{ nullptr, 0, 0 }; } const AttrName name{ attrName, suffix }; ArrayOfArrayInfo aoa; MirroredArray* array = nullptr; const Typeinfo& typeinfo = getTypeInfo(type); if (typeinfo.isArray) { ArrayAttributeArray *arrayAttributeArray; if (!bucketImpl->arrayAttributeArrays.find(name, &arrayAttributeArray)) { Bucket bucket = getNamesAndTypes(bucketId); bucketImpl = &addAttributeC(*bucketImpl, bucket, attrName, type); const bool found = bucketImpl->arrayAttributeArrays.find({ attrName, NameSuffix::none }, &arrayAttributeArray); CARB_ASSERT(found); CARB_UNUSED(found); array = &arrayAttributeArray->values; aoa = getArrayOfArrayInfo(*arrayAttributeArray); } else { array = &arrayAttributeArray->values; aoa = getArrayOfArrayInfo(*arrayAttributeArray); } } else { ScalarAttributeArray *scalarAttributeArray; if (!bucketImpl->scalarAttributeArrays.find(name, &scalarAttributeArray)) { Bucket bucket = getNamesAndTypes(bucketId); bucketImpl = &addAttributeC(*bucketImpl, bucket, attrName, type); const bool found = bucketImpl->scalarAttributeArrays.find({ attrName, NameSuffix::none }, &scalarAttributeArray); CARB_ASSERT(found); CARB_UNUSED(found); array = scalarAttributeArray; aoa = ScalarArrayOfArrayInfo(); } else { array = scalarAttributeArray; aoa = ScalarArrayOfArrayInfo(); } } CARB_ASSERT(type == array->type); ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(*array, name, aoa, *bucketImpl, CpuWriteConfig()); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array; } inline SpanC PathToAttributesMap::getArraySpanC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArraySpanC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return { nullptr, 0, 0 }; ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuReadWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array; } inline void* PathToAttributesMap::getArrayC(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayC", apiLogEnabled, attrName); BucketId bucketId = findBucketId(bucket); if (bucketId == kInvalidBucketId) return nullptr; ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuReadWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array.ptr; } inline void PathToAttributesMap::setArrayDirty(ArrayAndDirtyIndices& array) { for (ChangedIndicesImpl* listener : array.changedIndicesForEachListener) { listener->dirtyAll(); } } inline void PathToAttributesMap::setArrayElementDirty(ArrayAndDirtyIndices& array, size_t elemIndex) { for (ChangedIndicesImpl* listener : array.changedIndicesForEachListener) { listener->insert(elemIndex, array.array.elementCount); } } inline SpanC PathToAttributesMap::getArrayC(BucketId bucketId, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getArrayC", apiLogEnabled, attrName); ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(bucketId, attrName, CpuReadWriteConfig(), suffix); setArrayDirty(arrayAndDirtyIndices); return arrayAndDirtyIndices.array; } inline const PathC* PathToAttributesMap::getPathArray(const Bucket& bucket) const { auto iter = attrNameSetToBucketId.find(bucket); bool found = (iter != attrNameSetToBucketId.end()); if (found) { BucketId bucketId = iter->second; const auto implPtr = buckets.find(bucketId); if (implPtr) { return reinterpret_cast<const PathC*>(implPtr->elemToPath.data()); } else { CARB_LOG_WARN_ONCE("Found in attrNameSetToBucketId, but didn't find BucketId %zu in buckets\n", size_t(bucketId)); } } CARB_LOG_ERROR("getPathArray: Bucket not found"); printBucket(bucket); std::cout << "\n"; CARB_LOG_INFO("Bucket list:"); printBucketNamesAndTypes(); return nullptr; } inline ConstPathCSpan PathToAttributesMap::getPathArray(BucketId bucketId) const { const auto implPtr = buckets.find(bucketId); if (implPtr) { const BucketImpl& bucketImpl = *implPtr; return { reinterpret_cast<const Path*>(bucketImpl.elemToPath.data()), bucketImpl.elemToPath.size() }; } else { CARB_LOG_WARN_ONCE("Found in attrNameSetToBucketId, but didn't find BucketId %zu in buckets\n", size_t(bucketId)); } return { nullptr, 0 }; } inline Bucket PathToAttributesMap::getNamesAndTypes(BucketId bucketId) const { auto implPtr = buckets.find(bucketId); if (implPtr) { const BucketImpl& bucketImpl = *implPtr; size_t maxCount = bucketImpl.scalarAttributeArrays.size(); set<flatcache::AttrNameAndType> bucket; bucket.reserve(maxCount); bucketImpl.scalarAttributeArrays.forEach([&bucket](const AttrName& name, const ScalarAttributeArray& array) { const TypeC& type = array.type; if (name.suffix == NameSuffix::none || name.suffix == NameSuffix::connection) { AttrNameAndType attrNameAndType; attrNameAndType.type = carb::flatcache::Type(type); attrNameAndType.name = name.name; attrNameAndType.suffix = name.suffix; bucket.insert(attrNameAndType); } }); bucketImpl.arrayAttributeArrays.forEach([&bucket](const AttrName& name, const ArrayAttributeArray& array) { const TypeC& type = array.values.type; if (name.suffix == NameSuffix::none || name.suffix == NameSuffix::connection) { AttrNameAndType attrNameAndType; attrNameAndType.type = Type(type); attrNameAndType.name = name.name; attrNameAndType.suffix = name.suffix; bucket.insert(attrNameAndType); } }); return bucket; } else { CARB_LOG_ERROR_ONCE("getNamesAndTypes, bucketId %zu not found\n", size_t(bucketId)); return set<AttrNameAndType>(); } } inline void PathToAttributesMap::checkInvariants() { for (auto& bucketAndId : attrNameSetToBucketId) { const Bucket& correctBucket = bucketAndId.first; BucketId bucketId = bucketAndId.second; Bucket candidateBucket = getNamesAndTypes(bucketId); if (candidateBucket.size() != correctBucket.size()) { CARB_BREAK_POINT(); } for (size_t i = 0; i != candidateBucket.size(); i++) { const AttrNameAndType& candidateNameAndType = candidateBucket.v[i]; const AttrNameAndType& correctNameAndType = correctBucket.v[i]; if (!(candidateNameAndType == correctNameAndType)) { std::stringstream ss; ss << "Candidate: " << Type(candidateNameAndType.type) << " " << Token(candidateNameAndType.name).getText() << toString(candidateNameAndType.suffix) << " " << " Correct: " << Type(correctNameAndType.type) << " " << Token(correctNameAndType.name).getText() << toString(correctNameAndType.suffix) << " " << "\n"; CARB_LOG_ERROR("%s", ss.str().c_str()); CARB_BREAK_POINT(); } } } } inline std::pair<bool, std::vector<AttrNameAndType>::const_iterator> findAttrNameAndType(const Bucket& bucket, const TokenC& attrName) { #if 0 // Do O(log n) search of bucket for attrName, ignoring type auto cmp = [](const AttrNameAndType& a, AttrNameAndTime b) { return a.name < b; }; auto i = lower_bound(bucket.begin(), bucket.end(), attrName, cmp); // There can be multiple elements with same attrName, so check them all while (i != bucket.end() && i->name == attrName && i->suffix != NameSuffix::none) i++; // At this point i is either at the end, or at the end of the elements with attrName, or pointing to an element with // suffix==none // If didn't get to the end, and didn't get to the end of the elements with attrName, then must be pointing to // attrName with suffix==none bool found = (i != bucket.end() && i->name == attrName); return found ? (i->tfType) : (pxr::TfType()); #else // Until we fix the order of the fields in the tuple to make equal attrNames contiguous, do a linear search auto i = bucket.begin(); while (i != bucket.end() && !(i->name == attrName && i->suffix == NameSuffix::none)) i++; bool found = (i != bucket.end()); return make_pair(found, i); #endif } inline TypeC PathToAttributesMap::getType(const Bucket& bucket, const TokenC& attrName) const { APILOGGER("getType", apiLogEnabled, attrName); std::vector<AttrNameAndType>::const_iterator pAttrNameAndType; bool found; std::tie(found, pAttrNameAndType) = findAttrNameAndType(bucket, attrName); return found ? TypeC(pAttrNameAndType->type) : TypeC(); } inline void PathToAttributesMap::addPath(const PathC& path, const Bucket& destBucket) { std::pair<BucketId, ArrayIndex> *pathAndBucketElem; if (pathToBucketElem.allocateEntry(path, &pathAndBucketElem)) { auto bucketIdAndImpl = findOrCreateBucket(destBucket); BucketId bucketId = bucketIdAndImpl.first; BucketImpl& bucketImpl = bucketIdAndImpl.second; bucketImpl.SetBucket(destBucket); size_t endElement = allocElement(bucketImpl); *pathAndBucketElem = std::make_pair(bucketId, endElement); bucketImpl.elemToPath[endElement] = { toSdfPath(path) }; } else { auto iter = attrNameSetToBucketId.find(destBucket); bool destBucketExists = (iter != attrNameSetToBucketId.end()); BucketId destBucketId = destBucketExists ? iter->second : kInvalidBucketId; BucketId currentBucketId = pathAndBucketElem->first; bool destBucketSpecified = (destBucket.size() != 0); if (!destBucketSpecified || (destBucketExists && destBucketId == currentBucketId)) { // If the dest bucket is not specified, or if already in the right // bucket, then leave path in current bucket return; } else if (destBucketSpecified && (destBucketId != currentBucketId)) { moveElementBetweenBuckets(path, destBucketId, currentBucketId, destBucket); } } } // renames a path in a bucket inline void PathToAttributesMap::renamePath(const PathC& oldPath, const PathC& newPath) { // TODO: should this early exit if oldPath == newPath? std::pair<BucketId, ArrayIndex> *oldPathAndBucketElem; if (pathToBucketElem.find(oldPath, &oldPathAndBucketElem)) { BucketImpl* bucketImplPtr = buckets.find(oldPathAndBucketElem->first); bucketImplPtr->elemToPath[oldPathAndBucketElem->second] = toSdfPath(newPath); std::pair<BucketId, ArrayIndex> *newPathAndBucketElem; pathToBucketElem.allocateEntry(newPath, &newPathAndBucketElem); *newPathAndBucketElem = std::move(*oldPathAndBucketElem); pathToBucketElem.freeEntry(oldPath); } else { CARB_LOG_WARN_ONCE("PathToAttributesMap::renamePath(%s,%s) - cannot find bucket to rename\n", Path(oldPath).getText(), Path(newPath).getText()); return; } } // present - Whether this path has a bucket // bucket - Pointer to bucket if it does // element - Index corresponding to path in this bucket's arrays inline std::tuple<bool, BucketId, size_t> PathToAttributesMap::getPresentAndBucketAndElement(const PathC& path) const { const std::pair<BucketId, ArrayIndex>* bucketElem; if (!pathToBucketElem.find(path, &bucketElem)) { return { false, kInvalidBucketId, 0 }; } return { true, bucketElem->first, bucketElem->second }; } inline BucketId PathToAttributesMap::getBucketId(const PathC& path) const { std::tuple<bool, flatcache::BucketId, size_t> presentAndBucketAndElement = getPresentAndBucketAndElement(path); bool present = std::get<0>(presentAndBucketAndElement); if (!present) return flatcache::kInvalidBucketId; return std::get<1>(presentAndBucketAndElement); } inline SpanC PathToAttributesMap::getArrayElementPtr(SpanC array, size_t bucketElement) const { if (array.ptr == nullptr) return { nullptr, 0, 0 }; size_t elemSize = array.elementSize; return { array.ptr + bucketElement * elemSize, 1, elemSize }; } inline ConstSpanC PathToAttributesMap::getArrayElementPtr(ConstSpanC array, size_t bucketElement) const { if (array.ptr == nullptr) return { nullptr, 0, 0 }; size_t elemSize = array.elementSize; return { array.ptr + bucketElement * elemSize, 1, elemSize }; } inline SpanC PathToAttributesMap::getAttributeC(const PathC& path, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getAttributeC", apiLogEnabled, attrName); bool present; // Whether this path has a bucket BucketId bucketId; // Pointer to the bucket if it does size_t element; // Index corresponding to path in this bucket's arrays std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(bucketId, attrName, CpuReadWriteConfig(), suffix); setArrayElementDirty(arrayAndchangedIndices, element); SpanC array = arrayAndchangedIndices.array; return getArrayElementPtr(array, element); } inline ConstSpanC PathToAttributesMap::getAttributeRdC(const PathC& path, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getAttributeRdC", apiLogEnabled, attrName); bool present; BucketId bucketId; size_t element; std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; const ConstSpanC array = getArraySpanC(bucketId, attrName, CpuReadConfig(), suffix).array; // We don't set dirty indices here because this method gives read-only access return getArrayElementPtr(array, element); } inline SpanC PathToAttributesMap::getAttributeWrC(const PathC& path, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getAttributeWrC", apiLogEnabled, path, attrName); bool present; BucketId bucketId; size_t element; std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; // Writing an element is a RMW on the whole array, so get read/write CPU access ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(bucketId, attrName, CpuReadIfValidWriteConfig(), suffix); setArrayElementDirty(arrayAndchangedIndices, element); SpanC array = arrayAndchangedIndices.array; return getArrayElementPtr(array, element); } inline SpanC PathToAttributesMap::setArrayAttributeSizeAndGet(PathC path, const TokenC& attrName, size_t newSize) { bool present; // Whether this path has a bucket BucketId bucketId; // Pointer to the bucket if it does size_t elementIndex; // Index corresponding to path in this bucket's arrays std::tie(present, bucketId, elementIndex) = getPresentAndBucketAndElement(path); if (!present) return { nullptr, 0, 0 }; return setArrayAttributeSizeAndGet(bucketId, elementIndex, attrName, newSize); } inline SpanC PathToAttributesMap::setArrayAttributeSizeAndGet( BucketId bucketId, size_t elementIndex, const TokenC& attrName, size_t newSize) { APILOGGER("setArrayAttributeSizeAndGet", apiLogEnabled, attrName); // TODO: remove double hash lookup here ArrayAndDirtyIndices sizeArray; { BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); sizeArray = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadWriteConfig()); } else { sizeArray = { 0 }; } } if (sizeArray.array.elementCount <= elementIndex) return { nullptr, 0, 0 }; // Set the size size_t* sizePtr = reinterpret_cast<size_t*>(getArrayElementPtr(sizeArray.array, elementIndex).ptr); if (!sizePtr) return { nullptr, 0, 0 }; *sizePtr = newSize; // TODO: does this need to be moved higher next to getArraySpanC above? setArrayElementDirty(sizeArray, elementIndex); // Get the new array-valued element ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(bucketId, attrName, CpuReadWriteConfig(), NameSuffix::none); setArrayElementDirty(arrayAndchangedIndices, elementIndex); SpanC array = arrayAndchangedIndices.array; uint8_t** arrayData = reinterpret_cast<uint8_t**>(getArrayElementPtr(array, elementIndex).ptr); if (!arrayData) return { nullptr, 0, 0 }; return { *arrayData, newSize, 0 }; } template <typename T> T* PathToAttributesMap::getAttribute(const PathC& path, const TokenC& attrName) { APILOGGER("getAttribute", apiLogEnabled, path, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getAttributeC(path, attrName, NameSuffix::none).ptr); } template <typename T> const T* PathToAttributesMap::getAttributeRd(const PathC& path, const TokenC& attrName) { APILOGGER("getAttributeRd", apiLogEnabled, path, attrName); // TODO: check that T is the correct type return reinterpret_cast<const T*>(getAttributeRdC(path, attrName, NameSuffix::none).ptr); } template <typename T> T* PathToAttributesMap::getAttributeWr(const PathC& path, const TokenC& attrName) { APILOGGER("getAttributeWr", apiLogEnabled, path, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getAttributeWrC(path, attrName, NameSuffix::none).ptr); } template <typename T> T* PathToAttributesMap::getAttributeWr(const PathC& path, const TokenC& attrName, NameSuffix suffix) { APILOGGER("getAttributeWr", apiLogEnabled, path, attrName); // TODO: check that T is the correct type return reinterpret_cast<T*>(getAttributeWrC(path, attrName, suffix).ptr); } inline ValidMirrors PathToAttributesMap::getAttributeValidBits(const PathC& path, const TokenC& attrName, ArrayAttributeArray::MirroredArrays subArray) const { APILOGGER("getAttributeValidBits", apiLogEnabled, path, attrName); bool present; // Whether this path has a bucket BucketId bucketId; // Pointer to the bucket if it does size_t element; // Index corresponding to path in this bucket's arrays std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) return ValidMirrors::eNone; const BucketImpl* bucketImplPtr = buckets.find(bucketId); if (!bucketImplPtr) return ValidMirrors::eNone; const MirroredArray *array = nullptr; const ScalarAttributeArray *scalarAttributeArray; const AttrName name{ attrName, NameSuffix::none }; if (bucketImplPtr->scalarAttributeArrays.find(name, &scalarAttributeArray)) { array = scalarAttributeArray; } else { const ArrayAttributeArray *arrayAttributeArray; if (bucketImplPtr->arrayAttributeArrays.find(name, &arrayAttributeArray)) { // This if statement is only needed because we ported OM-70434 fix from 105 to 104.2 // In 105, these mirrored arrays are stored in an array, indexed by subarray if (subArray == ArrayAttributeArray::MirroredArrays::Values) { array = &arrayAttributeArray->values; } else if (subArray == ArrayAttributeArray::MirroredArrays::ElemCounts) { array = &arrayAttributeArray->elemCounts; } else if (subArray == ArrayAttributeArray::MirroredArrays::CpuElemCounts) { array = &arrayAttributeArray->cpuElemCounts; } else if (subArray == ArrayAttributeArray::MirroredArrays::GpuElemCounts) { array = &arrayAttributeArray->gpuElemCounts; } else if (subArray == ArrayAttributeArray::MirroredArrays::GpuPtrs) { array = &arrayAttributeArray->gpuPtrs; } } else { return ValidMirrors::eNone; } } const size_t elemSize = array->typeinfo.size; const bool isTag = (elemSize == 0); if (isTag) return ValidMirrors::eNone; ValidMirrors retval = ValidMirrors::eNone; if (array->cpuValid) retval = retval | ValidMirrors::eCPU; if (array->gpuValid && array->gpuAllocedWithCuda) retval = retval | ValidMirrors::eCudaGPU; if (array->gpuValid && !array->gpuAllocedWithCuda) retval = retval | ValidMirrors::eGfxGPU; return retval; } inline bool PathToAttributesMap::findArrayAttributeArrayForPath(const PathC& path, const TokenC& attrName, size_t& outElementIndex, BucketImpl*& outBucketImpl, ArrayAttributeArray*& outArrayAttributeArray) { BucketId bucketId; bool found; std::tie(found, bucketId, outElementIndex) = getPresentAndBucketAndElement(path); if (found) { outBucketImpl = buckets.find(bucketId); if (outBucketImpl) { ArrayAttributeArray* array; if (outBucketImpl->arrayAttributeArrays.find({ attrName, NameSuffix::none }, &array)) { outArrayAttributeArray = array; return true; } } } CARB_LOG_WARN_ONCE("Warning: %s not found\n", toTfToken(attrName).GetText()); return false; } inline bool PathToAttributesMap::findArrayAttributeArrayForBucketId(const BucketId bucketId, const TokenC& attrName, BucketImpl*& outBucketImpl, ArrayAttributeArray*& outArrayAttributeArray) { if (bucketId != kInvalidBucketId) { outBucketImpl = buckets.find(bucketId); if (outBucketImpl) { ArrayAttributeArray* array; if (outBucketImpl->arrayAttributeArrays.find({ attrName, NameSuffix::none }, &array)) { outArrayAttributeArray = array; return true; } } } CARB_LOG_WARN_ONCE("Warning: %s not found\n", toTfToken(attrName).GetText()); return false; } inline size_t* PathToAttributesMap::getArrayAttributeSize(const PathC& path, const TokenC& attrName) { APILOGGER("getArrayAttributeSize", apiLogEnabled, path, attrName); size_t element; BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForPath(path, attrName, element, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadWriteConfig()); setArrayElementDirty(arrayAndchangedIndices, element); const SpanC array = arrayAndchangedIndices.array; return reinterpret_cast< size_t*>(getArrayElementPtr(array, element).ptr); } return nullptr; } inline const size_t* PathToAttributesMap::getArrayAttributeSizeRd(const PathC& path, const TokenC& attrName) { APILOGGER("getArrayAttributeSizeRd", apiLogEnabled, path, attrName); size_t element; BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForPath(path, attrName, element, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); const ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadConfig()); const ConstSpanC array = arrayAndchangedIndices.array; return reinterpret_cast<const size_t*>(getArrayElementPtr(array, element).ptr); } return nullptr; } inline size_t* PathToAttributesMap::getArrayAttributeSizeWr(const PathC& path, const TokenC& attrName) { APILOGGER("getArrayAttributeSizeWr", apiLogEnabled, path, attrName); size_t element; BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForPath(path, attrName, element, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadIfValidWriteConfig()); setArrayElementDirty(arrayAndchangedIndices, element); const SpanC array = arrayAndchangedIndices.array; return reinterpret_cast<size_t*>(getArrayElementPtr(array, element).ptr); } return nullptr; } inline const size_t* PathToAttributesMap::getArrayAttributeSizeRdGpu(const PathC& path, const TokenC& attrName) { APILOGGER("getArrayAttributeSizeRdGpu", apiLogEnabled, path, attrName); size_t element; BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForPath(path, attrName, element, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); const ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->gpuElemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CudaReadConfig()); const ConstSpanC array = arrayAndchangedIndices.array; return reinterpret_cast<const size_t*>(getArrayElementPtr(array, element).ptr); } return nullptr; } inline const size_t* PathToAttributesMap::getArrayAttributeSizesRdGpu(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayAttributeSizesRdGpu", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; const BucketId bucketId = findBucketId(bucket); if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); const ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->gpuElemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CudaReadConfig()); const ConstSpanC array = arrayAndchangedIndices.array; return reinterpret_cast<const size_t*>(array.ptr); } return nullptr; } inline ConstSpanSizeC PathToAttributesMap::getArrayAttributeSizesRdGpu(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayAttributeSizesRdGpu", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); const ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->gpuElemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CudaReadConfig()); const ConstSpanC array = arrayAndchangedIndices.array; return { reinterpret_cast<const size_t*>(array.ptr), array.elementCount }; } return { nullptr, 0 }; } inline size_t* PathToAttributesMap::getArrayAttributeSizes(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayAttributeSizes", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; const BucketId bucketId = findBucketId(bucket); if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadWriteConfig()); setArrayDirty(arrayAndchangedIndices); const SpanC array = arrayAndchangedIndices.array; return reinterpret_cast<size_t*>(array.ptr); } return nullptr; } inline SpanSizeC PathToAttributesMap::getArrayAttributeSizes(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayAttributeSizes", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadWriteConfig()); setArrayDirty(arrayAndchangedIndices); const SpanC array = arrayAndchangedIndices.array; CARB_ASSERT(array.elementSize == sizeof(size_t)); return { reinterpret_cast<size_t*>(array.ptr), array.elementCount }; } return { 0, 0 }; } inline ConstSpanSizeC PathToAttributesMap::getArrayAttributeSizesRd(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayAttributeSizesRd", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadConfig()); const ConstSpanC array = arrayAndchangedIndices.array; CARB_ASSERT(array.elementSize == sizeof(size_t)); return { reinterpret_cast<const size_t*>(array.ptr), array.elementCount }; } return { 0, 0 }; } inline SpanSizeC PathToAttributesMap::getArrayAttributeSizesWr(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayAttributeSizesWr", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuWriteConfig()); setArrayDirty(arrayAndchangedIndices); const SpanC array = arrayAndchangedIndices.array; CARB_ASSERT(array.elementSize == sizeof(size_t)); return { reinterpret_cast<size_t*>(array.ptr), array.elementCount }; } return { 0, 0 }; } inline ArrayPointersAndSizesC PathToAttributesMap::getArrayAttributeArrayWithSizes(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayAttributeArrayWithSizes", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); SpanC spanOfPointers; { ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->values, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadWriteConfig()); setArrayDirty(arrayAndDirtyIndices); spanOfPointers = arrayAndDirtyIndices.array; } ConstSpanC spanOfSizes; { const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadConfig()); spanOfSizes = arrayAndDirtyIndices.array; } CARB_ASSERT(spanOfPointers.elementSize == sizeof(uint8_t*)); CARB_ASSERT(spanOfSizes.elementSize == sizeof(size_t)); CARB_ASSERT(spanOfPointers.elementCount == spanOfSizes.elementCount); return { reinterpret_cast<uint8_t* const*>(spanOfPointers.ptr), reinterpret_cast<const size_t*>(spanOfSizes.ptr), spanOfPointers.elementCount }; } return ArrayPointersAndSizesC{ 0, 0, 0 }; } inline ConstArrayPointersAndSizesC PathToAttributesMap::getArrayAttributeArrayWithSizesRd(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayAttributeArrayWithSizesRd", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ConstSpanC spanOfPointers; { const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->values, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadConfig()); spanOfPointers = arrayAndDirtyIndices.array; } ConstSpanC spanOfSizes; { const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadConfig()); spanOfSizes = arrayAndDirtyIndices.array; } CARB_ASSERT(spanOfPointers.elementSize == sizeof(uint8_t*)); CARB_ASSERT(spanOfSizes.elementSize == sizeof(size_t)); CARB_ASSERT(spanOfPointers.elementCount == spanOfSizes.elementCount); return { reinterpret_cast<uint8_t* const*>(spanOfPointers.ptr), reinterpret_cast<const size_t*>(spanOfSizes.ptr), spanOfPointers.elementCount }; } return ConstArrayPointersAndSizesC{ 0, 0, 0 }; } inline ArrayPointersAndSizesC PathToAttributesMap::getArrayAttributeArrayWithSizesWr(BucketId bucketId, const TokenC& attrName) { APILOGGER("getArrayAttributeArrayWithSizesWr", apiLogEnabled, attrName); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); SpanC spanOfPointers; { ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->values, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadWriteConfig()); setArrayDirty(arrayAndDirtyIndices); spanOfPointers = arrayAndDirtyIndices.array; } ConstSpanC spanOfSizes; { const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadConfig()); spanOfSizes = arrayAndDirtyIndices.array; } CARB_ASSERT(spanOfPointers.elementSize == sizeof(uint8_t*)); CARB_ASSERT(spanOfSizes.elementSize == sizeof(size_t)); CARB_ASSERT(spanOfPointers.elementCount == spanOfSizes.elementCount); return { reinterpret_cast<uint8_t* const*>(spanOfPointers.ptr), reinterpret_cast<const size_t*>(spanOfSizes.ptr), spanOfPointers.elementCount }; } return ArrayPointersAndSizesC{ 0, 0, 0 }; } inline const size_t* PathToAttributesMap::getArrayAttributeSizesRd(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayAttributeSizesRd", apiLogEnabled, attrName); const BucketId bucketId = findBucketId(bucket); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); const ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuReadConfig()); return reinterpret_cast<const size_t*>(arrayAndDirtyIndices.array.ptr); } return nullptr; } inline size_t* PathToAttributesMap::getArrayAttributeSizesWr(const Bucket& bucket, const TokenC& attrName) { APILOGGER("getArrayAttributeSizesWr", apiLogEnabled, attrName); const BucketId bucketId = findBucketId(bucket); BucketImpl* bucketImpl; ArrayAttributeArray *arrayAttributeArray; if (findArrayAttributeArrayForBucketId(bucketId, attrName, bucketImpl, arrayAttributeArray)) { const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->elemCounts, AttrName{ attrName, NameSuffix::none }, aoa, *bucketImpl, CpuWriteConfig()); setArrayDirty(arrayAndDirtyIndices); return reinterpret_cast<size_t*>(arrayAndDirtyIndices.array.ptr); } return nullptr; } // Intersect set<AttrNameAndType> and set<AttrNameAndType> comparing type, // name and suffix, and ignoring tfType inline void set_intersection2(set<AttrNameAndType>::const_iterator first1, set<AttrNameAndType>::const_iterator last1, set<AttrNameAndType>::const_iterator first2, set<AttrNameAndType>::const_iterator last2, std::back_insert_iterator<std::vector<AttrNameAndType>> d_first) { // Note that in the name comparisons below TokenC masks off USD's lifetime bit. // For example, tokens created from the same string are considered equal even // if one was created with finite lifetime and the other infinite lifetime. auto comp1 = [](const AttrNameAndType& a, const AttrNameAndType& b) { if (TypeC(a.type) < TypeC(b.type)) return true; if (TypeC(b.type) < TypeC(a.type)) return false; if (TokenC(a.name) < TokenC(b.name)) return true; if (TokenC(b.name) < TokenC(a.name)) return false; return a.suffix < b.suffix; }; auto comp2 = [](const AttrNameAndType& a, const AttrNameAndType& b) { if (TypeC(a.type) < TypeC(b.type)) return true; if (TypeC(b.type) < TypeC(a.type)) return false; if (TokenC(a.name) < TokenC(b.name)) return true; if (TokenC(b.name) < TokenC(a.name)) return false; return a.suffix < b.suffix; }; while (first1 != last1 && first2 != last2) { if (comp1(*first1, *first2)) { ++first1; } else { if (!comp2(*first2, *first1)) { *d_first++ = *first1++; } ++first2; } } } inline flatcache::set<BucketId> PathToAttributesMap::findBuckets(const set<AttrNameAndType>& all, const set<AttrNameAndType>& any, const set<AttrNameAndType>& none) const { flatcache::set<BucketId> retval; retval.reserve(256); // TODO: Do this in a less brute-force way for (auto& bucketAndId : attrNameSetToBucketId) { const Bucket& bucketTypes = bucketAndId.first; BucketId bucketId = bucketAndId.second; bool bucketEmpty = getElementCount(bucketId) == 0; if (bucketEmpty) continue; std::vector<AttrNameAndType> allTypesPresent; std::vector<AttrNameAndType> anyTypesPresent; std::vector<AttrNameAndType> noneTypesPresent; set_intersection2( all.begin(), all.end(), bucketTypes.begin(), bucketTypes.end(), std::back_inserter(allTypesPresent)); set_intersection2( any.begin(), any.end(), bucketTypes.begin(), bucketTypes.end(), std::back_inserter(anyTypesPresent)); set_intersection2( none.begin(), none.end(), bucketTypes.begin(), bucketTypes.end(), std::back_inserter(noneTypesPresent)); bool allOfAllTypesPresent = (allTypesPresent.size() == all.size()); bool oneOfAnyTypesPresent = (any.size() == 0) || (anyTypesPresent.size() != 0); bool noneOfNoneTypesPresent = (noneTypesPresent.size() == 0); if (allOfAllTypesPresent && oneOfAnyTypesPresent && noneOfNoneTypesPresent) { retval.v.push_back(bucketId); } } // Sort the vector to make it a flatcache::set std::sort(retval.begin(), retval.end()); return retval; } inline std::tuple<BucketId, ArrayIndex> PathToAttributesMap::getBucketAndArrayIndex(const PathC& path) const { const std::pair<BucketId, ArrayIndex>* bucketAndElem; if (pathToBucketElem.find(path, &bucketAndElem)) { const BucketId& bucketId = bucketAndElem->first; const ArrayIndex& arrayIndex = bucketAndElem->second; return { bucketId, arrayIndex }; } else { // Commenting out the error in 104.2 as there is no hasPrim API in 104.2 yet // and FabricSD needs to check for existence of a prim without causing an error to be logged // CARB_LOG_ERROR_ONCE("getBucketAndArrayIndex called on non-existent path '%s'\n", Path(path).getText()); return { kInvalidBucketId, kInvalidArrayIndex }; } } inline Bucket PathToAttributesMap::getTypes(const PathC& path) const { const std::pair<BucketId, ArrayIndex>* bucketAndElem; if (pathToBucketElem.find(path, &bucketAndElem)) { const BucketImpl* bucketImpl = buckets.find(bucketAndElem->first); if (bucketImpl) { return bucketImpl->GetBucket(); } } CARB_LOG_WARN_ONCE("getTypes called on non-existent path %s\n", Path(path).getText()); return Bucket(); } inline size_t PathToAttributesMap::getAttributeCount(const PathC& path) const { const std::pair<BucketId, ArrayIndex>* bucketAndElem; if (pathToBucketElem.find(path, &bucketAndElem)) { const BucketImpl* bucketImpl = buckets.find(bucketAndElem->first); if (bucketImpl) { return bucketImpl->GetBucket().size(); } } CARB_LOG_ERROR_ONCE("getAttributeCount called on non-existent path %s\n", Path(path).getText()); return 0; } inline TypeC PathToAttributesMap::getType(const PathC& path, const TokenC& attrName) const { APILOGGER("getType", apiLogEnabled, path, attrName); const std::pair<BucketId, ArrayIndex>* bucketAndElem; if (!pathToBucketElem.find(path, &bucketAndElem)) { CARB_LOG_WARN_ONCE("getTfType called on non-existent path %s\n", Path(path).getText()); return kUnknownType; } const BucketId &bucketId = bucketAndElem->first; const BucketImpl* bucketImplPtr = buckets.find(bucketId); if (!bucketImplPtr) { CARB_LOG_WARN_ONCE( "getTfType called on non-existent bucket pathAndBucketElem is broken %s\n", Path(path).getText()); return kUnknownType; } const AttrName name{ attrName, NameSuffix::none }; const ScalarAttributeArray *scalarAttributeArray; if (bucketImplPtr->scalarAttributeArrays.find(name, &scalarAttributeArray)) { return scalarAttributeArray->type; } else { const ArrayAttributeArray *arrayAttributeArray; if (bucketImplPtr->arrayAttributeArrays.find(name, &arrayAttributeArray)) { return arrayAttributeArray->values.type; } } CARB_LOG_WARN_ONCE("getType called on non-existent attribute %s %s\n", Path(path).getText(), Token(attrName).getText()); return kUnknownType; } // Return 1 if attribute is present at path, 0 otherwise inline size_t PathToAttributesMap::count(const PathC& path, const TokenC& attrName) const { bool present; // Whether this path has a bucket BucketId bucketId; // Pointer to the bucket if it does size_t element; // Index corresponding to path in this bucket's arrays std::tie(present, bucketId, element) = getPresentAndBucketAndElement(path); if (!present) { return 0; } const BucketImpl* bucketImplPtr = buckets.find(bucketId); if (!bucketImplPtr) return 0; const AttrName name{ attrName, NameSuffix::none }; const ScalarAttributeArray *scalarAttributeArray; if (bucketImplPtr->scalarAttributeArrays.find(name, &scalarAttributeArray)) { return 1; } else { const ArrayAttributeArray *arrayAttributeArray; if (bucketImplPtr->arrayAttributeArrays.find(name, &arrayAttributeArray)) { return 1; } } return 0; } inline void PathToAttributesMap::moveElementScalarData(ScalarAttributeArray &destArray, const size_t destElemIndex, const ScalarAttributeArray &srcArray, const size_t srcElemIndex) { if (srcArray.type != destArray.type) { return; } const Typeinfo& typeinfo = srcArray.typeinfo; const size_t size = typeinfo.size; const bool isArray = typeinfo.isArray; // Ideally usdValid would be driven by the change tracker // however I can't use that until we have a way to tie into that // Ideally there would be a subsscriber for "copying back to USD" // and that could be parsed to see if an element in invalid. At this point // we just have to do it per-attribute since that is as fine-grained as we // have data right now. This happens in moveElement to avoid having to repeat // logic about matching attriubte arrays that the function already does if (!srcArray.usdValid) { destArray.usdValid = srcArray.usdValid; } // // In the case where this is the first element in the new bucket // then the validity of the data needs to be moved from the old // bucket. // if (destElemIndex == 0) { destArray.cpuValid = srcArray.cpuValid; destArray.gpuValid = srcArray.gpuValid; } if (destArray.cpuValid && !srcArray.cpuValid) { // This should not happen because of makeSrcValidIfDestValid CARB_LOG_ERROR_ONCE("Invalid state while moving element: srcArray.cpuValid=%i destArray.cpuValid=%i", srcArray.cpuValid, destArray.cpuValid); assert(false); } if (destArray.gpuValid && !srcArray.gpuValid) { // This should not happen because of makeSrcValidIfDestValid CARB_LOG_ERROR_ONCE("Invalid state while moving element: srcArray.gpuValid=%i destArray.gpuValid=%i", srcArray.gpuValid, destArray.gpuValid); assert(false); } // // As noted above the validity of the src was already matched to the destinations needs // in the case, where for example the src has valid but the dest doesn't that is ok // but we do still move data, because in the case of array-of-array you get to at least // avoid another malloc. // if (srcArray.cpuValid || isArray) { uint8_t* destArrayData = destArray.cpuData(); uint8_t* destPtr = destArrayData + destElemIndex * size; const uint8_t* srcArrayData = srcArray.cpuData(); const uint8_t* srcPtr = srcArrayData + srcElemIndex * size; memcpy(destPtr, srcPtr, size); } if (srcArray.gpuValid) { if (isArray) { if (srcArray.gpuCapacity) { destArray.resizeGpu(platform.gpuCuda, platform.gpuCudaCtx, srcArray.gpuCapacity, typeinfo.size); platform.gpuCuda->memcpyAsync(*platform.gpuCudaCtx, destArray.gpuArray, srcArray.gpuArray, srcArray.gpuCapacity, omni::gpucompute::MemcpyKind::deviceToDevice); } } else { uint8_t* destArrayData = destArray.gpuArray; uint8_t* destPtr = destArrayData + destElemIndex * size; const uint8_t* srcArrayData = srcArray.gpuArray; const uint8_t* srcPtr = srcArrayData + srcElemIndex * size; platform.gpuCuda->memcpyAsync(*platform.gpuCudaCtx, destPtr, srcPtr, size, omni::gpucompute::MemcpyKind::deviceToDevice); } destArray.gpuAllocedWithCuda = true; } } inline void PathToAttributesMap::moveElementArrayData(ArrayAttributeArray &destArray, const size_t destElemIndex, const ArrayAttributeArray &srcArray, const size_t srcElemIndex) { static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); moveElementScalarData(destArray.values, destElemIndex, srcArray.values, srcElemIndex); moveElementScalarData(destArray.elemCounts, destElemIndex, srcArray.elemCounts, srcElemIndex); moveElementScalarData(destArray.cpuElemCounts, destElemIndex, srcArray.cpuElemCounts, srcElemIndex); moveElementScalarData(destArray.gpuElemCounts, destElemIndex, srcArray.gpuElemCounts, srcElemIndex); moveElementScalarData(destArray.gpuPtrs, destElemIndex, srcArray.gpuPtrs, srcElemIndex); } inline void PathToAttributesMap::moveElement(BucketImpl& destBucket, size_t destElemIndex, BucketImpl& srcBucket, size_t srcElemIndex) { srcBucket.scalarAttributeArrays.forEach([this, &destBucket, &destElemIndex, &srcElemIndex](const AttrName& name, const ScalarAttributeArray& srcArray) { // If bucket move is due to removal then one destTupleIndex will be // invalid. So we check for invalid here ScalarAttributeArray *destArray; if (destBucket.scalarAttributeArrays.find(name, &destArray)) { moveElementScalarData(*destArray, destElemIndex, srcArray, srcElemIndex); } }); srcBucket.arrayAttributeArrays.forEach([this, &destBucket, &destElemIndex, &srcElemIndex](const AttrName& name, const ArrayAttributeArray& srcArray) { // If bucket move is due to removal then one destTupleIndex will be // invalid. So we check for invalid here ArrayAttributeArray *destArray; if (destBucket.arrayAttributeArrays.find(name, &destArray)) { moveElementArrayData(*destArray, destElemIndex, srcArray, srcElemIndex); } }); destBucket.elemToPath[destElemIndex] = std::move(srcBucket.elemToPath[srcElemIndex]); } inline void PathToAttributesMap::destroyElement(BucketId bucketId, size_t elemIndex, bool destroyDataPointedTo) { BucketImpl* srcBucketImplPtr = buckets.find(bucketId); if (!srcBucketImplPtr) return; // nothing to delete BucketImpl& srcBucketImpl = *srcBucketImplPtr; size_t elemCount = PathToAttributesMap::getElementCount(srcBucketImpl); if (elemCount == 0) return; // nothing to delete if (destroyDataPointedTo) { // Destruct element about to be overwritten srcBucketImpl.arrayAttributeArrays.forEach([this, &elemIndex](const AttrName& name, ArrayAttributeArray& array) { // If a CPU array has been allocated, delete it uint8_t** arrayCpuPtrArray = reinterpret_cast<uint8_t**>(array.values.cpuData()); uint8_t*& cpuPtrToDelete = arrayCpuPtrArray[elemIndex]; if (cpuPtrToDelete) { if (!USE_PINNED_MEMORY || !platform.gpuCuda) { free(cpuPtrToDelete); } else if (platform.gpuCuda) { platform.gpuCuda->freeHost(*platform.gpuCudaCtx, cpuPtrToDelete); } cpuPtrToDelete = nullptr; } // If a GPU array has been allocated, delete it uint8_t** arrayGpuPtrArray = reinterpret_cast<uint8_t**>(array.gpuPtrs.cpuData()); uint8_t*& gpuPtrToDelete = arrayGpuPtrArray[elemIndex]; if (gpuPtrToDelete) { platform.gpuCuda->free(*platform.gpuCudaCtx, gpuPtrToDelete); gpuPtrToDelete = nullptr; } size_t* arrayCpuCapacityArray = reinterpret_cast<size_t*>(array.cpuElemCounts.cpuData()); arrayCpuCapacityArray[elemIndex] = 0; size_t* arrayGpuCapacityArray = reinterpret_cast<size_t*>(array.gpuElemCounts.cpuData()); arrayGpuCapacityArray[elemIndex] = 0; size_t* arraySizeArray = reinterpret_cast<size_t*>(array.elemCounts.cpuData()); arraySizeArray[elemIndex] = 0; }); } // Copy last element to element to be deleted PathC movedElemPath; size_t lastElemIndex = elemCount - 1; bool deletingLastElement = (elemIndex == lastElemIndex); // If bucket has more than one element, move last element to deleted element if (!deletingLastElement) { moveElement(srcBucketImpl, elemIndex, srcBucketImpl, lastElemIndex); movedElemPath = asInt(srcBucketImpl.elemToPath[elemIndex]); // For all attributes, dirty[elemIndex] := dirty[lastElemIndex] srcBucketImpl.listenerIdToChanges.forEach([&elemIndex, &lastElemIndex, &elemCount](const ListenerId& listenerId, Changes& changes) { size_t trackedAttrCount = changes.changedAttributes.size(); for (size_t i = 0; i != trackedAttrCount; i++) { ChangedIndicesImpl& changedIndices = changes.changedIndices[i]; if (changedIndices.contains(lastElemIndex) && !changedIndices.contains(elemIndex)) { changedIndices.insert(elemIndex, elemCount - 1); } else if (!changedIndices.contains(lastElemIndex) && changedIndices.contains(elemIndex)) { changedIndices.erase(elemIndex, elemCount - 1); } } }); } // Remove last element from change tracker srcBucketImpl.listenerIdToChanges.forEach([&elemCount](const ListenerId& listenerId, Changes& changes) { size_t trackedAttrCount = changes.changedAttributes.size(); for (size_t i = 0; i != trackedAttrCount; i++) { ChangedIndicesImpl& changedIndices = changes.changedIndices[i]; changedIndices.decrementN(elemCount - 1); } }); { const auto removeLastElementFromMirroredArray = [this](MirroredArray& array) { if (array.count > 0) { const size_t newSize = array.size() - array.typeinfo.size; array.count--; array.resize(newSize); } if (array.gpuCapacity != 0) { array.resizeGpu(platform.gpuCuda, platform.gpuCudaCtx, array.size(), array.typeinfo.size); } }; // Reduce element count srcBucketImpl.scalarAttributeArrays.forEach([this, &removeLastElementFromMirroredArray](const AttrName& name, ScalarAttributeArray& array) { removeLastElementFromMirroredArray(array); }); srcBucketImpl.arrayAttributeArrays.forEach([this, &removeLastElementFromMirroredArray](const AttrName& name, ArrayAttributeArray& array) { removeLastElementFromMirroredArray(array.values); removeLastElementFromMirroredArray(array.elemCounts); removeLastElementFromMirroredArray(array.cpuElemCounts); removeLastElementFromMirroredArray(array.gpuElemCounts); removeLastElementFromMirroredArray(array.gpuPtrs); }); } srcBucketImpl.elemToPath.pop_back(); // If bucket has more than one element, remap path that pointed to last element if (!deletingLastElement) { std::pair<BucketId, ArrayIndex>* movedBucketAndElemIndex; if (pathToBucketElem.find(movedElemPath, &movedBucketAndElemIndex)) { movedBucketAndElemIndex->second = elemIndex; } else { CARB_LOG_ERROR_ONCE("destroyElement attempted to re-index missing path %s\n", Path(movedElemPath).getText()); } } // Update change trackers // We allocate them lazily, so we have to iterate over listenerIdToChangeTrackerConfig // then allocate bucketImpl.listenerIdToChanges if necessary auto bucketImpl = buckets.find(bucketId); if (bucketImpl) { listenerIdToChangeTrackerConfig.forEach([this, &bucketImpl, &elemIndex, &lastElemIndex, &deletingLastElement](ListenerId& listenerId, ChangeTrackerConfig& config) { if (config.changeTrackingEnabled) { // Allocate changes if necessary Changes* changes; if (bucketImpl->listenerIdToChanges.allocateEntry(listenerId, &changes)) { new (changes) Changes(); } // // Since we may be moving within a bucket we need to inform the change tracker // if (!deletingLastElement) { if (changes->addedIndices.contains(lastElemIndex)) { // only need to track that it moved if we already // cared about it changes->addNewPrim(elemIndex); } changes->removePrim(lastElemIndex); } else { changes->removePrim(elemIndex); } } }); } } inline void PathToAttributesMap::moveElementBetweenBuckets(const PathC& path, BucketId destBucketId, BucketId srcBucketId, const Bucket& destBucket) { if (destBucketId == srcBucketId) return; // Get source BucketImpl BucketImpl* srcPtr = buckets.find(srcBucketId); if (!srcPtr) { CARB_LOG_ERROR("moveElementBetweenBuckets failed to move path \"%s\" to from bucketId %zu to bucketId %zu, could not find source bucket\n", Path(path).getText(), size_t(srcBucketId), size_t(destBucketId)); return; } // Get bucket and elem index std::pair<BucketId, ArrayIndex>* srcBucketAndElemIndex; if (!pathToBucketElem.find(path, &srcBucketAndElemIndex)) { CARB_LOG_ERROR_ONCE("moveElementBetweenBuckets failed to move path \"%s\" to from bucketId %zu to bucketId %zu, could not find path\n", Path(path).getText(), size_t(srcBucketId), size_t(destBucketId)); return; } // Get dest BucketImpl BucketImpl* destPtr = buckets.find(destBucketId); if (!destPtr) { CARB_LOG_ERROR("moveElementBetweenBuckets failed to move path \"%s\" to from bucketId %zu to bucketId %zu, could not find destination bucket\n", Path(path).getText(), size_t(srcBucketId), size_t(destBucketId)); return; } size_t destElemIndex = PathToAttributesMap::getElementCount(*destPtr); // Allocate element in new bucket allocElementForMove(*destPtr, *srcPtr, path); // Copy values from src to dest // // Ideally usdValid would be driven by the change tracker // however I can't use that until we have a way to tie into that // Ideally there would be a subsscriber for "copying back to USD" // and that could be parsed to see if an element in invalid. At this point // we just have to do it per-attribute since that is as fine-grained as we // have data right now. This happens in moveElement to avoid having to repeat // logic about matching attriubte arrays that the function already does moveElement(*destPtr, destElemIndex, *srcPtr, srcBucketAndElemIndex->second); // Delete element in old bucket // Don't destroy data pointed to, because we want dest element to point to it const bool destroyDataPointedTo = false; destroyElement(srcBucketId, srcBucketAndElemIndex->second, destroyDataPointedTo); // Map path to new bucket *srcBucketAndElemIndex = std::make_pair(destBucketId, destElemIndex); // Convert destBucket to a set<AttrNameAndType> set<AttrNameAndType> destBucket_v2; destBucket_v2.v.resize(destBucket.size()); for (size_t i = 0; i != destBucket.size(); i++) { destBucket_v2.v[i] = AttrNameAndType(Type(destBucket.v[i].type), Token(destBucket.v[i].name), destBucket.v[i].suffix); } // Copy dirty bits to new bucket srcPtr->listenerIdToChanges.forEach([&destPtr, &destBucket_v2, &destElemIndex](const ListenerId &listener, const Changes& srcChanges) { // Create if listenerId doesn't exist on dest bucket Changes* destChanges; if (destPtr->listenerIdToChanges.allocateEntry(listener, &destChanges)) { new (destChanges) Changes(); } size_t changedAttrCount = srcChanges.changedAttributes.size(); size_t destNewElemCount = destPtr->elemToPath.size(); for (size_t i = 0; i != changedAttrCount; i++) { const AttrNameAndType& nameAndType = srcChanges.changedAttributes.v[i]; // TODO: we could optimize this by taking advantage of destBucket_v2 // and changeAttributes being sorted. This would allow us to iterate // through both at the same time, and avoid doing n O(log n) lookups. if (destBucket_v2.contains(nameAndType)) { destChanges->setDirty(nameAndType, destElemIndex, destNewElemCount); } } }); } inline void PathToAttributesMap::addAttributeC( const PathC& path, const TokenC& attrName, TypeC type, const void* value) { addAttributeC(path, attrName, NameSuffix::none, type, value); } inline void PathToAttributesMap::addArrayAttributeC( const PathC& path, const TokenC& attrName, TypeC type, const void* value, const size_t arrayElemCount) { addArrayAttributeC(path, attrName, NameSuffix::none, type, value, arrayElemCount); } /** * @brief adds attributes to a primitive * * @details As opposed to addAttributeC this function allows the user to add multiple attributes to * a primitive at the same time and only does re-bucketing once after adding all of them. * This should be faster than adding them one-by-one and re-bucketing after each of them. * @param path - primitive path * @param attrNames - vector of the attribute names as tokens * @param tfTypes - vector of dynamic runtime types of the attributes * @param typeCs - vector of identifiers for types * * */ inline void PathToAttributesMap::addAttributesToPrim(const PathC& path, const std::vector<TokenC>& attrNames, const std::vector<TypeC>& typeCs) { CARB_ASSERT(attrNames.size() == typeCs.size()); addAttributesToBucket(path, attrNames, typeCs); } // Find bucketId the path is currently in // Find the bucket from the bucketId inline void PathToAttributesMap::addAttributesToBucket(const PathC& path, const std::vector<TokenC>& attrNames, const std::vector<TypeC>& typeCs) { NameSuffix suffix = NameSuffix::none; BucketId srcBucketId; ArrayIndex srcElemIndex; std::tie(srcBucketId, srcElemIndex) = getBucketAndArrayIndex(path); bool pathIsInFlatcache = (srcBucketId != kInvalidBucketId); if (!pathIsInFlatcache) { addPath(path); std::tie(srcBucketId, srcElemIndex) = getBucketAndArrayIndex(path); } // Get dest bucket // Dest bucket types = union(source bucket types, new type) std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; VALIDATE_TRUE(pathToBucketElem.find(path, &bucketAndElemIndex)); BucketImpl *const bucketImplPtr = buckets.find(bucketAndElemIndex->first); CARB_ASSERT(bucketImplPtr); Bucket destBucket = bucketImplPtr->GetBucket(); for (uint32_t c = 0; c < attrNames.size(); ++c) { Token attrName(attrNames[c]); AttrNameAndType nameAndType(Type(typeCs[c]), attrName, NameSuffix::none); // Early out if attribute already present if (destBucket.find(nameAndType) != destBucket.end()) continue; // When adding a new attribute that shadows the name of an existing // attribute, but with a new type, then we choose to drop the old attribute // on the floor. // Unfortunatly since we are searching on name since we will not know the type // we have to scan the list of attributes. for (const AttrNameAndType& bucketNameAndType : destBucket) { if (bucketNameAndType.name == attrNames[c] && bucketNameAndType.suffix == suffix && TypeC(bucketNameAndType.type) != typeCs[c]) { // we can stop here since this enforces uniquness of attribute names // todo: check that USD already enforces this destBucket.erase(bucketNameAndType); break; } } destBucket.insert(nameAndType); } BucketId destBucketId = addBucket(destBucket); if (srcBucketId != destBucketId) { moveElementBetweenBuckets(path, destBucketId, srcBucketId, destBucket); } } // Find bucketId the path is currently in // Find the bucket from the bucketId inline std::tuple<BucketId, ArrayIndex> PathToAttributesMap::addAttributeGetBucketAndArrayIndex( const PathC& path, const TokenC& attrNameC, NameSuffix nameSuffix, TypeC type) { BucketId srcBucketId; ArrayIndex srcElemIndex; std::tie(srcBucketId, srcElemIndex) = getBucketAndArrayIndex(path); bool pathIsInFlatcache = (srcBucketId != kInvalidBucketId); if (!pathIsInFlatcache) { addPath(path); std::tie(srcBucketId, srcElemIndex) = getBucketAndArrayIndex(path); } // Get dest bucket // Dest bucket types = union(source bucket types, new type) std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; VALIDATE_TRUE(pathToBucketElem.find(path, &bucketAndElemIndex)); BucketImpl *const bucketImplPtr = buckets.find(bucketAndElemIndex->first); CARB_ASSERT(bucketImplPtr); Bucket destBucket = bucketImplPtr->GetBucket(); Token attrName(attrNameC); AttrNameAndType nameAndType(Type(type), attrName, nameSuffix); // Early out if attribute already present if (destBucket.find(nameAndType) != destBucket.end()) return { srcBucketId, srcElemIndex }; // When adding a new attribute that shadows the name of an existing // attribute, but with a new type, then we choose to drop the old attribute // on the floor. // Unfortunatly since we are searching on name since we will not know the type // we have to scan the list of attributes. for (const AttrNameAndType& bucketNameAndType : destBucket) { if (bucketNameAndType.name == attrNameC && bucketNameAndType.suffix == nameSuffix && TypeC(bucketNameAndType.type) != type) { // we can stop here since this enforces uniquness of attribute names // todo: check that USD already enforces this destBucket.erase(bucketNameAndType); break; } } destBucket.insert(nameAndType); BucketId destBucketId = addBucket(destBucket); size_t destElemIndex; if (srcBucketId != destBucketId) { destElemIndex = getElementCount(destBucket); moveElementBetweenBuckets(path, destBucketId, srcBucketId, destBucket); } else { destElemIndex = srcElemIndex; } return { destBucketId, destElemIndex }; } inline void PathToAttributesMap::addAttributeC( const PathC& path, const TokenC& attrNameC, NameSuffix nameSuffix, TypeC type, const void* value) { const Typeinfo& typeinfo = getTypeInfo(type); if (typeinfo.isArray && value) { CARB_LOG_ERROR("addAttributeC: Attempted to add array-value attribute with default values. Use addArrayAttribute instead."); return; } addAttributeInternal(path, attrNameC, nameSuffix, type, value, typeinfo, 0); } inline void PathToAttributesMap::addArrayAttributeC(const PathC& path, const TokenC& attrName, NameSuffix suffix, TypeC type, const void* value, const size_t arrayElemCount) { const Typeinfo& typeinfo = getTypeInfo(type); addAttributeInternal(path, attrName, suffix, type, value, typeinfo, arrayElemCount); } inline SpanC PathToAttributesMap::getOrCreateAttributeWrC(const PathC& path, const TokenC& attrName, TypeC type) { APILOGGER("getOrCreateAttributeWrC", apiLogEnabled, path, attrName); BucketId bucketId; ArrayIndex elemIndex; std::tie(bucketId, elemIndex) = addAttributeGetBucketAndArrayIndex(path, attrName, NameSuffix::none, type); ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(bucketId, attrName, CpuReadWriteConfig(), NameSuffix::none); setArrayElementDirty(arrayAndchangedIndices, elemIndex); SpanC array = arrayAndchangedIndices.array; return getArrayElementPtr(array, elemIndex); } template <typename T> void PathToAttributesMap::addAttribute( const PathC& path, const TokenC& attrName, TypeC type, const T& value) { APILOGGER("addAttribute", apiLogEnabled, path, attrName); // TODO: check that type is compatible return addAttributeC(path, attrName, type, &value); } template <typename T> void PathToAttributesMap::addSubAttribute( const PathC& path, const TokenC& attrName, NameSuffix suffix, TypeC type, const T& value) { APILOGGER("addSubAttribute", apiLogEnabled, path, attrName); // TODO: check that type is compatible return addAttributeC(path, attrName, suffix, type, &value); } // Return a new bucket with all sub-attributes of a single attribute removed inline Bucket removeAllSubAttributesFromBucket(const Bucket& bucket, const TokenC& attrName) { Bucket newBucket; // TODO: implement set::delete for (auto nameAndType : bucket) { // Don't compare suffix and type to delete all suffix variants of name if (nameAndType.name != attrName) { newBucket.insert(nameAndType); } } return newBucket; } // Return a new bucket with all sub-attributes of all named attributes removed inline Bucket removeAllSubAttributesFromBucket(const Bucket& bucket, const std::vector<TokenC>& attrNames) { Bucket newBucket; for (auto nameAndType : bucket) { if (std::find_if(attrNames.begin(), attrNames.end(), [&](auto attrName) { return nameAndType.name == attrName; }) == attrNames.end()) { newBucket.insert(nameAndType); } } return newBucket; } inline Bucket removeSubAttributeFromBucket(const Bucket& bucket, const TokenC& attrName, NameSuffix suffix) { Bucket newBucket; // TODO: implement set::delete for (auto nameAndType : bucket) { // Don't compare suffix and type to delete all suffix variants of name if (!(nameAndType.name == attrName && nameAndType.suffix == suffix)) { newBucket.insert(nameAndType); } } return newBucket; } // Remove an attribute and all its subattributes (suffixes). inline void PathToAttributesMap::removeAttribute(const PathC& path, const TokenC& attrName) { APILOGGER("removeAttribute", apiLogEnabled, path, attrName); BucketId srcBucketId; ArrayIndex srcElemIndex; std::tie(srcBucketId, srcElemIndex) = getBucketAndArrayIndex(path); if (srcBucketId == kInvalidBucketId) return; // srcBucketId != kInvalidBucketId guarantees find will succeed std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; VALIDATE_TRUE(pathToBucketElem.find(path, &bucketAndElemIndex)); BucketImpl *const bucketImplPtr = buckets.find(bucketAndElemIndex->first); CARB_ASSERT(bucketImplPtr); const Bucket& srcTypes = bucketImplPtr->GetBucket(); const Bucket destBucket = removeAllSubAttributesFromBucket(srcTypes, attrName); const BucketId destBucketId = addBucket(destBucket); moveElementBetweenBuckets(path, destBucketId, srcBucketId, destBucket); } inline void PathToAttributesMap::removeAttributesFromPath(const PathC& path, const std::vector<TokenC>& attrNames) { BucketId srcBucketId; ArrayIndex srcElemIndex; std::tie(srcBucketId, srcElemIndex) = getBucketAndArrayIndex(path); if (srcBucketId == kInvalidBucketId) return; // srcBucketId != kInvalidBucketId guarantees find will succeed std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; VALIDATE_TRUE(pathToBucketElem.find(path, &bucketAndElemIndex)); BucketImpl *const bucketImplPtr = buckets.find(bucketAndElemIndex->first); CARB_ASSERT(bucketImplPtr); const Bucket& bucket = bucketImplPtr->GetBucket(); const Bucket destBucket = removeAllSubAttributesFromBucket(bucket, attrNames); const BucketId destBucketId = addBucket(destBucket); if (srcBucketId != destBucketId) { moveElementBetweenBuckets(path, destBucketId, srcBucketId, destBucket); } } inline void PathToAttributesMap::removeAttributesFromBucket(const Bucket& bucket, const std::vector<TokenC>& attrNames) { // first we need to find the actual bucketImpl that we will be // deleting attributes from auto iter = attrNameSetToBucketId.find(bucket); bool found = (iter != attrNameSetToBucketId.end()); if (!found) return; BucketId bucketId = iter->second; BucketImpl* bucketImplPtr = buckets.find(bucketId); if (!bucketImplPtr) return; // Buckets are found based on a set of the attributes, so we build // the new set based on the attribute names Bucket newBucket = removeAllSubAttributesFromBucket(bucket, attrNames); std::pair<BucketId, BucketImpl&> newBucketIdAndImpl = findOrCreateBucket(newBucket); BucketImpl& newBucketImpl = newBucketIdAndImpl.second; const size_t origSize = newBucketImpl.elemToPath.size(); if (origSize == 0) { // In the case where it is a new bucket we prefer just deleting the no longer needed arrays. newBucketImpl = *bucketImplPtr; newBucketImpl.SetBucket(std::move(newBucket)); // loop finding and deleting attribute arrays for (auto attrName : attrNames) { newBucketImpl.scalarAttributeArrays.forEach([this, &attrName, &newBucketImpl](const AttrName& name, ScalarAttributeArray& array) { if (name.name == attrName) { newBucketImpl.scalarAttributeArrays.freeEntry(name); } }); newBucketImpl.arrayAttributeArrays.forEach([this, &attrName, &newBucketImpl](const AttrName& name, ArrayAttributeArray& array) { if (name.name == attrName) { newBucketImpl.arrayAttributeArrays.freeEntry(name); } }); } } else { // TODO : there should be a faster way to do this but more to discuss here later for (const auto path : bucketImplPtr->elemToPath) { moveElementBetweenBuckets( asInt(path), newBucketIdAndImpl.first, bucketId, newBucket); } } // // need to update the pathToBucketElem for all the items that just "moved" buckets // TODO: make this work with moving buckets for (size_t i = origSize; i < newBucketImpl.elemToPath.size(); ++i) { std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; pathToBucketElem.allocateEntry(asInt(newBucketImpl.elemToPath[i]), &bucketAndElemIndex); *bucketAndElemIndex = std::make_pair(newBucketIdAndImpl.first, i); } buckets.erase(bucketId); attrNameSetToBucketId.erase(bucket); } // Remove a particular (name,suffix) pair, for example the connection of an attribute inline void PathToAttributesMap::removeSubAttribute(const PathC& path, const TokenC& attrName, NameSuffix suffix) { APILOGGER("removeSubAttribute", apiLogEnabled, path, attrName); BucketId srcBucketId; ArrayIndex srcElemIndex; std::tie(srcBucketId, srcElemIndex) = getBucketAndArrayIndex(path); if (srcBucketId == kInvalidBucketId) return; // srcBucketId != kInvalidBucketId guarantees find will succeed std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; VALIDATE_TRUE(pathToBucketElem.find(path, &bucketAndElemIndex)); BucketImpl *const bucketImplPtr = buckets.find(bucketAndElemIndex->first); CARB_ASSERT(bucketImplPtr); const Bucket& srcTypes = bucketImplPtr->GetBucket(); bool pathFound = (srcBucketId != kInvalidBucketId); if (!pathFound) { CARB_LOG_ERROR_ONCE("removeSubAttribute called on non-existent path %s \n", Path(path).getText()); return; } const Bucket destBucket = removeSubAttributeFromBucket(srcTypes, attrName, suffix); const BucketId destBucketId = addBucket(destBucket); moveElementBetweenBuckets(path, destBucketId, srcBucketId, destBucket); } // Removes an attribute (and all its subattributes) for all paths in a bucket inline void PathToAttributesMap::removeAttributeC(const Bucket& bucket, const TokenC& attrName, TypeC type) { APILOGGER("removeAttributeC", apiLogEnabled, attrName); // first we need to find the actual bucketImpl that we will be // deleting attributes from auto iter = attrNameSetToBucketId.find(bucket); bool found = (iter != attrNameSetToBucketId.end()); if (!found) return; BucketId bucketId = iter->second; BucketImpl* bucketImplPtr = buckets.find(bucketId); if (!bucketImplPtr) return; // Buckets are found based on a set of the attributes, so we build // the new set based on the attribute names Bucket newBucket = removeAllSubAttributesFromBucket(bucket, attrName); BucketId newBucketId = findBucketId(newBucket); if (newBucketId == kInvalidBucketId) { // In the case where it is a new bucket we prefer just deleting the no longer needed arrays. // This means that nothing needs to be updated as all the prims are in the same place bucketImplPtr->SetBucket(std::move(newBucket)); if (getTypeInfo(type).isArray) { bucketImplPtr->arrayAttributeArrays.forEach([this, &attrName, bucketImplPtr](const AttrName& name, ArrayAttributeArray& array) { if (name.name == attrName) { bucketImplPtr->arrayAttributeArrays.freeEntry(name); } }); } else { bucketImplPtr->scalarAttributeArrays.forEach([this, &attrName, bucketImplPtr](const AttrName& name, ScalarAttributeArray& array) { if (name.name == attrName) { bucketImplPtr->scalarAttributeArrays.freeEntry(name); } }); } attrNameSetToBucketId[newBucket] = bucketId; attrNameSetToBucketId.erase(bucket); } else { std::pair<BucketId, BucketImpl&> newBucketIdAndImpl = findOrCreateBucket(newBucket); BucketImpl& newBucketImpl = newBucketIdAndImpl.second; const size_t origSize = newBucketImpl.elemToPath.size(); // TODO : there should be a faster way to do this but more to discuss here later // currently this pulls from the front, this ensures that elements stay in the same // "order" when moving buckets -> but this means moving stuff around in elemToPath // Doing this in "bulk" will make all of this better. while(bucketImplPtr->elemToPath.size()) { moveElementBetweenBuckets( asInt(bucketImplPtr->elemToPath.front()), newBucketIdAndImpl.first, bucketId, newBucket); } // // need to update the pathToBucketElem for all the items that just "moved" buckets // TODO: make this work with moving buckets for (size_t i = origSize; i < newBucketImpl.elemToPath.size(); ++i) { std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; pathToBucketElem.allocateEntry(asInt(newBucketImpl.elemToPath[i]), &bucketAndElemIndex); *bucketAndElemIndex = std::make_pair(newBucketIdAndImpl.first, i); } } } inline void PathToAttributesMap::removePath(const PathC& path) { std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; if (!pathToBucketElem.find(path, &bucketAndElemIndex)) { CARB_LOG_ERROR_ONCE("removePath called on non-existent path %s \n", Path(path).getText()); return; } const BucketId &bucketId = bucketAndElemIndex->first; const size_t &elemIndex = bucketAndElemIndex->second; const bool destroyDataPointedTo = true; destroyElement(bucketId, elemIndex, destroyDataPointedTo); pathToBucketElem.freeEntry(path); } inline size_t PathToAttributesMap::count(const PathC& path) const { const std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; if (pathToBucketElem.find(path, &bucketAndElemIndex)) { return 1; } else { return 0; } } struct ViewIterator { size_t bucketIndex = 0; size_t elementIndex = 0; std::vector<size_t>::const_iterator bucketElemCount; ViewIterator& operator++() { elementIndex++; if (elementIndex == *bucketElemCount) { bucketIndex++; bucketElemCount++; elementIndex = 0; } return *this; } bool operator!=(const ViewIterator& rhs) const { return bucketIndex != rhs.bucketIndex || elementIndex != rhs.elementIndex; } ViewIterator& operator*() { return *this; } }; // Array resize that does not preserve previous data inline void PathToAttributesMap::destructiveResizeIfNecessaryGPU(MirroredArray& gpuPointerArray, size_t elem, size_t& capacity, size_t desiredElemCount, size_t elemByteCount, omni::gpucompute::GpuCompute* computeAPI, omni::gpucompute::Context* computeCtx) { uint8_t** elemToArrayGpuData = reinterpret_cast<uint8_t**>(gpuPointerArray.cpuData()); uint8_t*& gpuData = elemToArrayGpuData[elem]; // Resize iff (capacity < desiredElemCount) if (capacity != desiredElemCount || gpuData == nullptr) { size_t byteCount = desiredElemCount * elemByteCount; if (gpuData) { platform.gpuCuda->freeAsync(*platform.gpuCudaCtx, gpuData); } gpuData = reinterpret_cast<uint8_t*>(computeAPI->mallocAsync(*computeCtx, byteCount, elemByteCount)); // We've written to gpuData on the CPU so we have to invalidate any GPU mirror of it gpuPointerArray.gpuValid = false; gpuPointerArray.cpuValid = true; capacity = desiredElemCount; } } // Array resize that preserves previous data inline void PathToAttributesMap::resizeIfNecessaryGPU(MirroredArray& gpuPointerArray, size_t elem, size_t& capacity, size_t desiredElemCount, size_t elemByteCount, omni::gpucompute::GpuCompute* computeAPI, omni::gpucompute::Context* computeCtx) { // TODO: reduce number of reallocations by allocating capacity larger than size // and not always reallocating when desiredElemCount<capacity // if gpuCapacity is 0 that means the array was recently copied and needs to be reallocated if(computeAPI && (capacity != desiredElemCount || gpuPointerArray.gpuCapacity == 0)) { size_t oldByteCount = capacity * elemByteCount; size_t newByteCount = desiredElemCount * elemByteCount; uint8_t** elemToArrayGpuData = reinterpret_cast<uint8_t**>(gpuPointerArray.cpuData()); uint8_t*& gpuData = elemToArrayGpuData[elem]; uint8_t* newGpuData = reinterpret_cast<uint8_t*>(computeAPI->mallocAsync(*computeCtx, newByteCount, elemByteCount)); if (gpuData) { using omni::gpucompute::MemcpyKind; size_t copyByteCount = std::min(oldByteCount, newByteCount); computeAPI->memcpy(*computeCtx, newGpuData, gpuData, copyByteCount, MemcpyKind::deviceToDevice); // Note that this free has to be async even though the previous // memcpy is sync. The reason is that deviceToDevice memcpys // are always async, even if you call the sync version of cudaMemcpy. // So if you do "sync" memcpy and then sync free, the free can // execute on the CPU before the copy executes on the GPU. // See https://nvidia-omniverse.atlassian.net/browse/OM-46051 computeAPI->freeAsync(*computeCtx, gpuData); } gpuData = newGpuData; // We've written to gpuData on the CPU so we have to invalidate any GPU mirror of it gpuPointerArray.gpuValid = false; gpuPointerArray.cpuValid = true; capacity = desiredElemCount; } } // This function is called when we are just about to do a transfer to GPU, to // make sure that GPU array is large enough. // It is called only when !gpuValid, so we don't have to preserve any existing // GPU array. // // Algorithm: // If capacity is sufficient, do nothing // If not, free any existing allocation, then allocate inline void PathToAttributesMap::allocGpuMemIfNecessary(PathToAttributesMap::MirroredArray& array, size_t byteCount, size_t elemSize, omni::gpucompute::GpuCompute* computeAPI, omni::gpucompute::Context* computeCtx) { bool capacitySufficient = (byteCount <= array.gpuCapacity); if (!capacitySufficient) { if (array.gpuArray) { computeAPI->freeAsync(*computeCtx, array.gpuArray); } array.gpuArray = reinterpret_cast<uint8_t*>(computeAPI->mallocAsync(*computeCtx, byteCount, elemSize)); array.gpuCapacity = byteCount; } } inline PrimBucketListImpl PathToAttributesMap::getChanges(ListenerId listenerId) { PrimBucketListImpl changesOut; // For now, iterate over all buckets // We'll probably want the user to specify a subset of buckets for change logging changesOut.buckets.reserve(buckets.end()); changesOut.changes.reserve(buckets.end()); BucketId id{ 0 }; for (unsigned int i = 0; i < buckets.end(); ++i, ++id) { BucketImpl* bucketPtr = buckets.find(id); if (!bucketPtr) continue; BucketImpl& bucketImpl = *bucketPtr; BucketId bucketId = id; Changes* changesIn; if (!bucketImpl.listenerIdToChanges.find(listenerId, &changesIn)) { continue; } size_t changedAttrCount = changesIn->changedAttributes.size(); size_t primCount = bucketImpl.elemToPath.size(); bool attributesChanged = (changedAttrCount != 0 && primCount != 0); bool primsAdded = (changesIn->getNewPrimCount() != 0); if (attributesChanged || primsAdded) { changesOut.buckets.v.push_back(bucketId); changesOut.changes.push_back(BucketChangesImpl()); BucketChangesImpl& bucketChanges = changesOut.changes.back(); // Write changed attributes bucketChanges.changedAttributes = changesIn->changedAttributes; bucketChanges.changedIndices.resize(changedAttrCount); for (size_t j = 0; j != changedAttrCount; j++) { bucketChanges.changedIndices[j] = { changesIn->changedIndices[j].allIndicesChanged, { changesIn->changedIndices[j].changedIndices.data(), changesIn->changedIndices[j].changedIndices.size() } }; } bucketChanges.pathArray = { reinterpret_cast<const Path*>(bucketImpl.elemToPath.data()), bucketImpl.elemToPath.size() }; // Write added prims bucketChanges.addedIndices = { changesIn->addedIndices.data(), changesIn->addedIndices.size() }; } } return changesOut; } inline void PathToAttributesMap::popChanges(ListenerId listenerId) { BucketId id{ 0 }; for (unsigned int i = 0; i < buckets.end(); ++i, ++id) { BucketImpl* bucketPtr = buckets.find(id); if (bucketPtr) { // Create listenerId if it doesn't exist Changes* changes; if (bucketPtr->listenerIdToChanges.allocateEntry(listenerId, &changes)) { new (changes) Changes; } changes->changedAttributes.clear(); changes->changedIndices.clear(); changes->addedIndices.clear(); } } } inline PathToAttributesMap::MirroredArray::MirroredArray(Platform& platform_, const TypeC &type, const Typeinfo& typeinfo) noexcept : cpuArray() , platform(platform_) , type(type) , typeinfo(typeinfo) , gpuArray(nullptr) , gpuCapacity(0) , d3dArrays() , count(0) , usdValid(true) , cpuValid(false) , gpuValid(false) , gpuAllocedWithCuda(false) , attributeMutex() { } inline PathToAttributesMap::MirroredArray::~MirroredArray() { // clean up any non-array gpu data if (gpuArray) { if (gpuAllocedWithCuda) { platform.gpuCuda->freeAsync(*platform.gpuCudaCtx, gpuArray); } else { // @TODO Fix crash during D3dVk free! N.B. that this backend is incomplete and not in active use // gpuD3dVk->freeAsync(*gpuD3dVkCtx, gpuArray); } gpuArray = nullptr; } gpuValid = false; } inline PathToAttributesMap::MirroredArray& PathToAttributesMap::MirroredArray::operator=(const MirroredArray& other) noexcept { if (!other.isArrayOfArray()) { cpuArray = other.cpuArray; } else { // Here we set all pointers in dest array to nullptr // The allocation and data copy happens in PathToAttributesMap's operator= cpuArray.resize(other.size()); uint8_t** destPtrs = reinterpret_cast<uint8_t**>(cpuData()); for (size_t elemIndex = 0; elemIndex != other.count; elemIndex++) { destPtrs[elemIndex] = nullptr; } } // platform = other.platform; // intentionally not copy-assigning platform type = other.type; typeinfo = other.typeinfo; usdValid = other.usdValid; cpuValid = other.cpuValid; count = other.count; // GPU data needs to be copied explicitly using the gpu compute API gpuArray = nullptr; gpuCapacity = 0; gpuValid = false; gpuAllocedWithCuda = false; if (other.gpuValid) { // Also need to empty the cpuArray as it is a cpu pointer to now-invalid GPU data uint8_t** destPtrs = reinterpret_cast<uint8_t**>(cpuData()); for (size_t elemIndex = 0; elemIndex != other.count; elemIndex++) { destPtrs[elemIndex] = nullptr; } } return *this; } inline PathToAttributesMap::MirroredArray::MirroredArray(MirroredArray&& other) noexcept : cpuArray(std::move(other.cpuArray)), platform(other.platform), type(other.type), typeinfo(other.typeinfo), gpuArray(other.gpuArray), gpuCapacity(other.gpuCapacity), d3dArrays(std::move(other.d3dArrays)), count(other.count), usdValid(other.usdValid), cpuValid(other.cpuValid), gpuValid(other.gpuValid), gpuAllocedWithCuda(other.gpuAllocedWithCuda), attributeMutex() // intentionally not move constructing the mutex { other.gpuArray = nullptr; } inline PathToAttributesMap::MirroredArray& PathToAttributesMap::MirroredArray::operator=(MirroredArray&& other) noexcept { MirroredArray tmp(std::move(other)); swap(*this, tmp); return *this; } inline void swap(PathToAttributesMap::MirroredArray& a, PathToAttributesMap::MirroredArray& b) noexcept { using std::swap; swap(a.cpuArray, b.cpuArray); swap(a.type, b.type); swap(a.typeinfo, b.typeinfo); swap(a.gpuArray, b.gpuArray); swap(a.gpuCapacity, b.gpuCapacity); swap(a.d3dArrays, b.d3dArrays); swap(a.count, b.count); swap(a.usdValid, b.usdValid); swap(a.cpuValid, b.cpuValid); swap(a.gpuValid, b.gpuValid); swap(a.gpuAllocedWithCuda, b.gpuAllocedWithCuda); // swap(a.attributeMutex, b.attributeMutex); // intentionally NOT swapping attribute mutex because it is not move-constructable } inline PathToAttributesMap::ArrayAttributeArray::ArrayAttributeArray(Platform& platform_, const TypeC& type, const Typeinfo& typeinfo) noexcept : values(platform_, type, typeinfo) , elemCounts(platform_, PTAM_SIZE_TYPEC, Typeinfo{sizeof(PTAM_SIZE_TYPE), false, 0}) , cpuElemCounts(platform_, PTAM_SIZE_TYPEC, Typeinfo{ sizeof(PTAM_SIZE_TYPE), false, 0 }) , gpuElemCounts(platform_, PTAM_SIZE_TYPEC, Typeinfo{ sizeof(PTAM_SIZE_TYPE), false, 0 }) , gpuPtrs(platform_, PTAM_POINTER_TYPEC, Typeinfo{ sizeof(PTAM_POINTER_TYPE), false, 0 }) { static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); } inline PathToAttributesMap::ArrayAttributeArray::~ArrayAttributeArray() { Platform& platform = values.platform; CARB_ASSERT(&platform == &elemCounts.platform); CARB_ASSERT(&platform == &cpuElemCounts.platform); CARB_ASSERT(&platform == &gpuElemCounts.platform); CARB_ASSERT(&platform == &gpuPtrs.platform); if (values.count) { uint8_t** elemToCpuPtr = reinterpret_cast<uint8_t**>(values.cpuData()); for (size_t elemIndex = 0; elemIndex != values.count; elemIndex++) { // If a CPU array has been allocated, free it uint8_t*& cpuPtrToDelete = elemToCpuPtr[elemIndex]; if (cpuPtrToDelete) { if (!USE_PINNED_MEMORY || !platform.gpuCuda) { free(cpuPtrToDelete); } else if (platform.gpuCuda) { platform.gpuCuda->freeHost(*platform.gpuCudaCtx, cpuPtrToDelete); } cpuPtrToDelete = nullptr; values.cpuValid = false; } } } if (gpuPtrs.count) { // CPU array of GPU pointers uint8_t** elemToGpuPtr = reinterpret_cast<uint8_t**>(gpuPtrs.cpuData()); for (size_t elemIndex = 0; elemIndex != gpuPtrs.count; elemIndex++) { // If a GPU array has been allocated, free it uint8_t*& gpuPtrToDelete = elemToGpuPtr[elemIndex]; if (gpuPtrToDelete) { CARB_ASSERT(platform.gpuCuda); CARB_ASSERT(platform.gpuCudaCtx); platform.gpuCuda->freeAsync(*platform.gpuCudaCtx, gpuPtrToDelete); gpuPtrToDelete = nullptr; } } } } inline PathToAttributesMap::ArrayAttributeArray& PathToAttributesMap::ArrayAttributeArray::operator=(const ArrayAttributeArray& other) noexcept { static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); values = other.values; elemCounts = other.elemCounts; cpuElemCounts = other.cpuElemCounts; gpuElemCounts = other.gpuElemCounts; gpuPtrs = other.gpuPtrs; return *this; } inline PathToAttributesMap::ArrayAttributeArray::ArrayAttributeArray(ArrayAttributeArray&& other) noexcept : values(std::move(other.values)) , elemCounts(std::move(other.elemCounts)) , cpuElemCounts(std::move(other.cpuElemCounts)) , gpuElemCounts(std::move(other.gpuElemCounts)) , gpuPtrs(std::move(other.gpuPtrs)) { static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); other.values.count = 0; other.elemCounts.count = 0; other.cpuElemCounts.count = 0; other.gpuElemCounts.count = 0; other.gpuPtrs.count = 0; } inline PathToAttributesMap::ArrayAttributeArray& PathToAttributesMap::ArrayAttributeArray::operator=(ArrayAttributeArray&& other) noexcept { ArrayAttributeArray tmp(std::move(other)); swap(*this, tmp); return *this; } inline void swap(PathToAttributesMap::ArrayAttributeArray& a, PathToAttributesMap::ArrayAttributeArray& b) noexcept { using std::swap; swap(a.values, b.values); swap(a.elemCounts, b.elemCounts); swap(a.cpuElemCounts, b.cpuElemCounts); swap(a.gpuElemCounts, b.gpuElemCounts); swap(a.gpuPtrs, b.gpuPtrs); } inline void PathToAttributesMap::printBucket(const Bucket& bucket) const { bool multiLine = (1 < bucket.size()); printf("{"); if (multiLine) printf("\n"); for (const auto& b : bucket) { TokenC attrName = b.name; NameSuffix suffix = b.suffix; Type type(b.type); if (multiLine) printf(" "); Token attrNameToken(attrName); std::cout << "TypeC(" << type << ") " << attrNameToken.getText() << suffix; if (multiLine) printf("\n"); } printf("} "); // Print arrays in bucket auto iter = attrNameSetToBucketId.find(bucket); bool found = (iter != attrNameSetToBucketId.end()); if (!found) return; BucketId bucketId = iter->second; auto bucketImplPtr = buckets.find(bucketId); if (bucketImplPtr) { const BucketImpl& bucketImpl = *bucketImplPtr; bucketImpl.scalarAttributeArrays.forEach([&multiLine](const AttrName& name, const ScalarAttributeArray& array) { #if ENABLE_USD_DEBUGGING std::cout << toTfToken(name.name).GetText() << " " << toString(name.suffix) << " "; #else std::cout << name.name.token << " "; #endif std::cout << array.size() << "bytes "; if (multiLine) std::cout << "\n"; }); bucketImpl.arrayAttributeArrays.forEach([&multiLine](const AttrName& name, const ArrayAttributeArray& array) { #if ENABLE_USD_DEBUGGING std::cout << toTfToken(name.name).GetText() << " " << toString(name.suffix) << " "; #else std::cout << name.name.token << " "; #endif std::cout << array.values.size() << "bytes "; if (multiLine) std::cout << "\n"; }); } } inline void PathToAttributesMap::printBucketName(const Bucket& bucketTypes, BucketId bucketId) const { const BucketImpl* bucketImplPtr = buckets.find(bucketId); if (!bucketImplPtr) return; const BucketImpl& bucketImpl = *bucketImplPtr; std::cout << "Id: " << size_t(bucketId) << " "; size_t bucketPrimCount = bucketImpl.elemToPath.size(); std::cout << "PrimCount: " << bucketPrimCount << " "; // Find USD prim type for (auto attrNameAndType : bucketTypes) { Type type(attrNameAndType.type); if (type.role == AttributeRole::ePrimTypeName) { Token nameToken(attrNameAndType.name); std::cout << "PrimType: " << nameToken.getText() << " "; } } std::cout << "AttributeNames: "; for (auto attrNameAndType : bucketTypes) { Token nameToken(attrNameAndType.name); std::cout << nameToken.getText() << toString(attrNameAndType.suffix) << " "; } std::cout << "\n"; } inline void PathToAttributesMap::printBucketNames() const { std::cout << "Buckets:\n"; for (auto& bucketIdAndBucket : attrNameSetToBucketId) { const Bucket& bucketTypes = bucketIdAndBucket.first; BucketId bucketId = bucketIdAndBucket.second; std::cout << " "; printBucketName(bucketTypes, bucketId); } } inline void PathToAttributesMap::printBucketNamesAndTypes() const { std::cout << "Buckets:\n"; for (auto& bucketIdAndBucket : attrNameSetToBucketId) { std::cout << " "; const Bucket& bucketTypes = bucketIdAndBucket.first; for (AttrNameAndType attrNameAndType : bucketTypes) { Type type(attrNameAndType.type); Token nameToken(attrNameAndType.name); std::cout << "(" << type << " " << nameToken.getText() << " " << attrNameAndType.suffix << " " << "TypeC(" << attrNameAndType.type << ") "; } std::cout << "\n"; } } inline void PathToAttributesMap::bucketImplCopyScalarAttributeArray(ScalarAttributeArray &dest, const ScalarAttributeArray &src) { CARB_ASSERT(dest.type == src.type); if (src.gpuValid) { dest.resizeGpu(platform.gpuCuda, platform.gpuCudaCtx, src.size(), dest.typeinfo.size); platform.gpuCuda->memcpyAsync(*platform.gpuCudaCtx, dest.gpuArray, src.gpuArray, src.gpuCapacity, omni::gpucompute::MemcpyKind::deviceToDevice); dest.gpuValid = true; dest.gpuCapacity = src.gpuCapacity; dest.gpuAllocedWithCuda = src.gpuAllocedWithCuda; } } inline void PathToAttributesMap::bucketImplCopyArrayAttributeArray(BucketImpl& destBucketImpl, const AttrName& destName, ArrayAttributeArray &dest, const ArrayAttributeArray &src) { CARB_ASSERT(dest.values.type == src.values.type); const Typeinfo &typeInfo = dest.values.typeinfo; const size_t arrayElemSize = typeInfo.arrayElemSize; MirroredArray *const destSizeArray = &dest.elemCounts; MirroredArray *const destCpuCapacityArray = &dest.cpuElemCounts; const ArrayOfArrayInfo destAOA = getArrayOfArrayInfo(dest); // TODO: Figure out how to remove this fixup step in a more "clean" way // Need to set capacity to zero, because capacity will // have been erroneously copied from source in // MirroredArray copy constructor ArrayAndDirtyIndices arrayAndchangedIndices = getArraySpanC(*destCpuCapacityArray, destName, destAOA, destBucketImpl, CpuWriteConfig()); setArrayDirty(arrayAndchangedIndices); SpanC destCapacitySpan = arrayAndchangedIndices.array; size_t* destCapacities = reinterpret_cast<size_t*>(destCapacitySpan.ptr); for (size_t elemIndex = 0; elemIndex != destCapacitySpan.elementCount; elemIndex++) { destCapacities[elemIndex] = 0; } // getArrayWrC to allocate data for arrays ArrayAndDirtyIndices destSpan = getArraySpanC(dest.values, destName, destAOA, destBucketImpl, CpuWriteConfig()); setArrayDirty(destSpan); const size_t* elemCounts = reinterpret_cast<const size_t*>(destSizeArray->cpuData()); if (src.values.cpuValid) { // TODO: Isn't this redundant with the call to getArraySpanC above with cpu write access? enableCpuWrite(dest.values, elemCounts, destCpuCapacityArray, nullptr, nullptr); uint8_t** destPtrs = reinterpret_cast<uint8_t**>(destSpan.array.ptr); uint8_t* const* srcPtrs = reinterpret_cast<uint8_t* const*>(src.values.cpuData()); for (size_t elemIndex = 0; elemIndex != destSpan.array.elementCount; elemIndex++) { uint8_t* destPtr = destPtrs[elemIndex]; const uint8_t* srcPtr = srcPtrs[elemIndex]; size_t sizeBytes = elemCounts[elemIndex] * arrayElemSize; memcpy(destPtr, srcPtr, sizeBytes); } } else { dest.values.cpuValid = false; } if (src.values.gpuValid) { MirroredArray *const destGpuElemCountArray = &dest.gpuElemCounts; MirroredArray *const destGpuPtrArray = &dest.gpuPtrs; enableGpuWrite(dest.values, elemCounts, destCpuCapacityArray, destGpuElemCountArray, destGpuPtrArray); const MirroredArray *const srcGpuPtrArray = &src.gpuPtrs; // Select which API to use omni::gpucompute::GpuCompute* computeAPI = nullptr; omni::gpucompute::Context* computeCtx = nullptr; if (src.values.gpuAllocedWithCuda) { computeAPI = platform.gpuCuda; computeCtx = platform.gpuCudaCtx; } if (computeAPI) { uint8_t** destPtrs = reinterpret_cast<uint8_t**>(destGpuPtrArray->cpuData()); uint8_t* const* srcPtrs = reinterpret_cast<uint8_t* const*>(srcGpuPtrArray->cpuData()); for (size_t elemIndex = 0; elemIndex != destSpan.array.elementCount; elemIndex++) { uint8_t* destPtr = destPtrs[elemIndex]; const uint8_t* srcPtr = srcPtrs[elemIndex]; size_t sizeBytes = elemCounts[elemIndex] * arrayElemSize; computeAPI->memcpyAsync(*computeCtx, destPtr, srcPtr, sizeBytes, omni::gpucompute::MemcpyKind::deviceToDevice); } destGpuPtrArray->gpuAllocedWithCuda = src.values.gpuAllocedWithCuda; } } } inline void PathToAttributesMap::bucketImplCopyArrays(BucketImpl& destBucketImpl, BucketId destBucketId, const BucketImpl& srcBucketImpl, BucketId srcBucketId, const carb::flatcache::set<AttrNameAndType_v2>& attrFilter) { destBucketImpl.scalarAttributeArrays.forEach([this, &srcBucketImpl, &attrFilter](const AttrName& destName, ScalarAttributeArray& dest) { AttrNameAndType_v2 destNameV2( carb::flatcache::Type(dest.type), destName.name, destName.suffix); const bool attrIsInFilter = attrFilter.size() == 0 || (attrFilter.find(destNameV2) != attrFilter.end()); if (attrIsInFilter && destName.suffix == NameSuffix::none) { const ScalarAttributeArray* src; VALIDATE_TRUE(srcBucketImpl.scalarAttributeArrays.find(destName, &src)); CARB_ASSERT(src); bucketImplCopyScalarAttributeArray(dest, *src); } }); destBucketImpl.arrayAttributeArrays.forEach([this, &destBucketImpl, &srcBucketImpl, &attrFilter](const AttrName& destName, ArrayAttributeArray& dest) { AttrNameAndType_v2 destNameV2( carb::flatcache::Type(dest.values.type), destName.name, destName.suffix); const bool attrIsInFilter = attrFilter.size() == 0 || (attrFilter.find(destNameV2) != attrFilter.end()); if (attrIsInFilter && destName.suffix == NameSuffix::none) { const ArrayAttributeArray* src; VALIDATE_TRUE(srcBucketImpl.arrayAttributeArrays.find(destName, &src)); CARB_ASSERT(src); bucketImplCopyArrayAttributeArray(destBucketImpl, destName, dest, *src); } }); } template<typename CallbackT> void inline PathToAttributesMap::BucketImpl::forEachValueArray(CallbackT callback) { scalarAttributeArrays.forEach([&callback](const AttrName& name, ScalarAttributeArray& array) { callback(name, array); }); arrayAttributeArrays.forEach([&callback](const AttrName& name, ArrayAttributeArray& array) { callback(name, array.values); static_assert(sizeof(PathToAttributesMap::ArrayAttributeArray) == 5 * sizeof(PathToAttributesMap::MirroredArray), "ArrayAttributeArray has unexpected size"); // Intentionally skips these // callback(name, array.elemCounts); // callback(name, array.cpuElemCounts); // callback(name, array.gpuElemCounts); // callback(name, array.gpuPtrs); }); } inline void PathToAttributesMap::Serializer::init(uint8_t *const _buf, uint8_t *const _end) { p = buf = _buf; end = _end; bytesWritten = 0; overflowed = false; } inline bool PathToAttributesMap::Serializer::writeBytes(const uint8_t *const src, uint64_t size) { CARB_ASSERT(src); bytesWritten += size; if (p != nullptr && p + size <= end) { memcpy(p, src, size); p += size; return true; } overflowed = true; return false; } inline bool PathToAttributesMap::Serializer::writeString(const char* const s, const size_t len) { bool OK = true; if (!write<size_t>(len)) { OK = false; } if (!writeBytes(reinterpret_cast<const uint8_t*>(s), len)) { OK = false; } return OK; } inline bool PathToAttributesMap::Serializer::writeString(const std::string &s) { bool OK = true; if (!write<size_t>(s.length())) { OK = false; } if (!writeBytes(reinterpret_cast<const uint8_t*>(s.data()), s.length())) { OK = false; } return OK; } template<typename T> bool PathToAttributesMap::Serializer::write(const T &t) { static_assert(std::is_pod<T>::value, "T must be POD"); return writeBytes(reinterpret_cast<const uint8_t*>(&t), sizeof(T)); } inline void PathToAttributesMap::Deserializer::init(const uint8_t *const _buf, const uint8_t *const _end) { p = buf = _buf; end = _end; bytesRead = 0; overflowed = false; } inline bool PathToAttributesMap::Deserializer::readBytes(uint8_t *const dst, uint64_t size) { CARB_ASSERT(dst); bytesRead += size; if (p + size <= end) { memcpy(dst, p, size); p += size; return true; } overflowed = true; return false; }; inline bool PathToAttributesMap::Deserializer::readString(std::string &s) { size_t len; read<size_t>(len); s.resize(len); return readBytes(reinterpret_cast<uint8_t*>(&s[0]), len); } template<typename T> bool PathToAttributesMap::Deserializer::read(T &t) { static_assert(std::is_pod<T>::value, "T must be POD"); return readBytes(reinterpret_cast<uint8_t*>(&t), sizeof(T)); } inline void PathToAttributesMap::serializeMirroredArrayMetadata(const AttrName& srcName, MirroredArray &srcValuesArray, Serializer &out) { out.writeString(toTfToken(srcName.name).GetString()); out.write<NameSuffix>(srcName.suffix); // TfToken are actually pointers, so we need to serialize the encoded TypeC out.write<TypeC>(srcValuesArray.type); out.write<bool>(srcValuesArray.cpuValid); out.write<bool>(srcValuesArray.usdValid); out.write<size_t>(srcValuesArray.count); } pxr::TfType typeCtoTfType(TypeC typeC); template<typename ArraysT, typename ArraysMapT> inline void PathToAttributesMap::deserializeMirroredArrayMetadata(Platform& platform, ArraysMapT& arraysMap, AttrName &destName, Typeinfo *&typeInfo, ArraysT *&destArray, Deserializer &in) { std::string nameStr; in.readString(nameStr); in.read<NameSuffix>(destName.suffix); destName.name = asInt(pxr::TfToken(nameStr)); TypeC destType; { in.read<TypeC>(destType); } // typeToInfo is deserialized before all mirrored arrays, so the type must exist. VALIDATE_TRUE(typeToInfo.find(destType, &typeInfo)); if (!arraysMap.allocateEntry(destName, &destArray)) { CARB_LOG_ERROR("Failed to insert dest mirrored array"); return; } CARB_ASSERT(destArray); new (destArray) ArraysT(platform, destType, *typeInfo); MirroredArray *const destValuesArray = destArray->getValuesArray(); destValuesArray->type = destType; in.read<bool>(destValuesArray->cpuValid); in.read<bool>(destValuesArray->usdValid); in.read<size_t>(destValuesArray->count); destValuesArray->resize(destValuesArray->count * typeInfo->size); } inline uint64_t PathToAttributesMap::serializeScalarAttributeArray(BucketImpl& srcBucketImpl, const BucketId& srcBucketId, const AttrName& srcName, ScalarAttributeArray& srcScalarAttributeArray, Serializer &out) { const size_t bytesBegin = out.bytesWritten; MirroredArray &srcValuesArray = srcScalarAttributeArray; serializeMirroredArrayMetadata(srcName, srcValuesArray, out); if (srcValuesArray.cpuValid) { const ConstSpanC srcSpan = getArraySpanC(srcValuesArray, srcName, ScalarArrayOfArrayInfo(), srcBucketImpl, CpuReadConfig()).array; CARB_ASSERT(srcSpan.elementCount == srcValuesArray.count); const uint8_t* srcPtr = reinterpret_cast<const uint8_t*>(srcSpan.ptr); const Typeinfo &typeInfo = srcValuesArray.typeinfo; CARB_ASSERT(!typeInfo.isArray); out.writeBytes(srcPtr, srcSpan.elementCount * typeInfo.size); } return out.bytesWritten - bytesBegin; } inline bool PathToAttributesMap::deserializeScalarAttributeArray(BucketImpl& destBucketImpl, const BucketId& destBucketId, Deserializer &in) { AttrName destName; Typeinfo *typeInfo; ScalarAttributeArray *destArray; deserializeMirroredArrayMetadata(destBucketImpl.platform, destBucketImpl.scalarAttributeArrays, destName, typeInfo, destArray, in); CARB_ASSERT(typeInfo); CARB_ASSERT(destArray); CARB_ASSERT(!typeInfo->isArray); if (destArray->cpuValid) { uint8_t* destPtr = reinterpret_cast<uint8_t*>(destArray->cpuData()); in.readBytes(destPtr, destArray->count * typeInfo->size); } return true; } inline uint64_t PathToAttributesMap::serializeArrayAttributeArray(BucketImpl& srcBucketImpl, const BucketId& srcBucketId, const AttrName& srcName, ArrayAttributeArray& srcArrayAttributeArray, Serializer &out) { const size_t bytesBegin = out.bytesWritten; MirroredArray &srcValuesArray = srcArrayAttributeArray.values; serializeMirroredArrayMetadata(srcName, srcValuesArray, out); // write scalar metadata auto writeScalarArrayOfArrayMetadata = [this](BucketImpl& srcBucketImpl, const BucketId& srcBucketId, const AttrName& srcName, ScalarAttributeArray& srcScalarAttributeArray, Serializer &out) { // similar to serializeScalarAttributeArray, but we can skip some metadata because it should be inferrable out.write<bool>(srcScalarAttributeArray.cpuValid); out.write<bool>(srcScalarAttributeArray.usdValid); out.write<size_t>(srcScalarAttributeArray.count); if (srcScalarAttributeArray.cpuValid) { const ConstSpanC srcSpan = getArraySpanC(srcScalarAttributeArray, srcName, ScalarArrayOfArrayInfo(), srcBucketImpl, CpuReadConfig()).array; CARB_ASSERT(srcSpan.elementCount == srcScalarAttributeArray.count); const uint8_t* srcPtr = reinterpret_cast<const uint8_t*>(srcSpan.ptr); const Typeinfo &typeInfo = srcScalarAttributeArray.typeinfo; CARB_ASSERT(!typeInfo.isArray); out.writeBytes(srcPtr, srcSpan.elementCount * typeInfo.size); } }; static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); writeScalarArrayOfArrayMetadata(srcBucketImpl, srcBucketId, srcName, srcArrayAttributeArray.elemCounts, out); writeScalarArrayOfArrayMetadata(srcBucketImpl, srcBucketId, srcName, srcArrayAttributeArray.cpuElemCounts, out); // TODO: Can we omit these? writeScalarArrayOfArrayMetadata(srcBucketImpl, srcBucketId, srcName, srcArrayAttributeArray.gpuElemCounts, out); writeScalarArrayOfArrayMetadata(srcBucketImpl, srcBucketId, srcName, srcArrayAttributeArray.gpuPtrs, out); // write array-of-array values if (srcValuesArray.cpuValid) { const ArrayOfArrayInfo destAOA = getArrayOfArrayInfo(srcArrayAttributeArray); const ConstSpanC srcSpan = getArraySpanC(srcValuesArray, srcName, destAOA, srcBucketImpl, CpuReadConfig()).array; CARB_ASSERT(srcSpan.elementCount == srcValuesArray.count); // TODO: Should this be cpuElemCounts instead of elemCounts? The requested capacity may not have been applied yet.. const size_t* elemCounts = reinterpret_cast<const size_t*>(srcArrayAttributeArray.elemCounts.cpuData()); const Typeinfo &typeInfo = srcValuesArray.typeinfo; CARB_ASSERT(typeInfo.isArray); uint8_t* const* srcPtrs = reinterpret_cast<uint8_t* const*>(srcSpan.ptr); for (size_t elemIndex = 0; elemIndex != srcSpan.elementCount; elemIndex++) { const uint8_t* srcPtr = srcPtrs[elemIndex]; const size_t elemCount = elemCounts[elemIndex]; out.writeBytes(srcPtr, elemCount * typeInfo.arrayElemSize); } } return out.bytesWritten - bytesBegin; } inline bool PathToAttributesMap::deserializeArrayAttributeArray(BucketImpl& destBucketImpl, const BucketId& destBucketId, Deserializer &in) { AttrName destName; Typeinfo *typeInfo; ArrayAttributeArray *destArray; deserializeMirroredArrayMetadata(destBucketImpl.platform, destBucketImpl.arrayAttributeArrays, destName, typeInfo, destArray, in); CARB_ASSERT(typeInfo); CARB_ASSERT(destArray); CARB_ASSERT(typeInfo->isArray); // write scalar metadata auto readScalarArrayOfArrayMetadata = [this](BucketImpl& destBucketImpl, const BucketId& destBucketId, const AttrName& destName, ScalarAttributeArray& destScalarAttributeArray, Deserializer &in) { // similar to deserializeScalarAttributeArray, but we can skip some metadata because it should be inferrable in.read<bool>(destScalarAttributeArray.cpuValid); in.read<bool>(destScalarAttributeArray.usdValid); in.read<size_t>(destScalarAttributeArray.count); const Typeinfo &typeInfo = destScalarAttributeArray.typeinfo; destScalarAttributeArray.resize(typeInfo.size * destScalarAttributeArray.count); if (destScalarAttributeArray.cpuValid) { CARB_ASSERT(destScalarAttributeArray.size() == (getTypeInfo(destScalarAttributeArray.type).size * destScalarAttributeArray.count)); uint8_t *const destPtr = reinterpret_cast<uint8_t*>(destScalarAttributeArray.cpuData()); CARB_ASSERT(!typeInfo.isArray); in.readBytes(destPtr, destScalarAttributeArray.count * typeInfo.size); } }; static_assert(sizeof(ArrayAttributeArray) == 5 * sizeof(MirroredArray), "ArrayAttributeArray has unexpected size"); readScalarArrayOfArrayMetadata(destBucketImpl, destBucketId, destName, destArray->elemCounts, in); readScalarArrayOfArrayMetadata(destBucketImpl, destBucketId, destName, destArray->cpuElemCounts, in); // TODO: Can we omit these? readScalarArrayOfArrayMetadata(destBucketImpl, destBucketId, destName, destArray->gpuElemCounts, in); readScalarArrayOfArrayMetadata(destBucketImpl, destBucketId, destName, destArray->gpuPtrs, in); // read array-of-array values MirroredArray& destValuesArray = destArray->values; if (destValuesArray.cpuValid) { // Need to set capacity to zero, because capacity will // have been erroneously copied from source const ArrayOfArrayInfo destAOA = getArrayOfArrayInfo(*destArray); const SpanC destCapacitySpan = getArraySpanC(destArray->cpuElemCounts, destName, destAOA, destBucketImpl, CpuReadWriteConfig()).array; size_t *const destCapacities = reinterpret_cast<size_t*>(destCapacitySpan.ptr); for (size_t elemIndex = 0; elemIndex != destCapacitySpan.elementCount; elemIndex++) { destCapacities[elemIndex] = 0; } const size_t* elemCounts = reinterpret_cast<const size_t*>(destArray->elemCounts.cpuData()); // getArrayWrC to allocate data for arrays const SpanC destSpan = getArraySpanC(destValuesArray, destName, destAOA, destBucketImpl, CpuReadWriteConfig()).array; uint8_t** destPtrs = reinterpret_cast<uint8_t**>(destSpan.ptr); for (size_t elemIndex = 0; elemIndex != destValuesArray.count; elemIndex++) { uint8_t* destPtr = destPtrs[elemIndex]; size_t elemCount = elemCounts[elemIndex]; in.readBytes(destPtr, elemCount * typeInfo->arrayElemSize); } destValuesArray.cpuValid = true; } return true; } inline BucketImpl& PathToAttributesMap::addAttributeInternal(BucketImpl& prevBucketImpl, const Bucket& prevBucket, const TokenC& attrName, const TypeC type, const void* value, const Typeinfo& typeinfo, const size_t arrayElemCount) { APILOGGER("addAttributeInternal", apiLogEnabled, attrName); // newBucket := oldBucket Union { attrName } // findOrCreate (bucketId, bucketImpl) for newBucket, which updates // attrNameSetToBucketId and buckets Bucket nextBucket = prevBucket; nextBucket.insert({ carb::flatcache::Type(type), attrName, NameSuffix::none }); // Early out if attribute already in bucket const bool attributeAlreadyInBucket = (nextBucket.size() == prevBucket.size()); if (attributeAlreadyInBucket) return prevBucketImpl; const std::pair<BucketId, BucketImpl&> nextBucketIdAndImpl = findOrCreateBucket(nextBucket); const BucketId nextBucketId = nextBucketIdAndImpl.first; BucketImpl& nextBucketImpl = nextBucketIdAndImpl.second; const size_t nextBucketOriginalSize = nextBucketImpl.elemToPath.size(); if (nextBucketOriginalSize == 0) { // Move arrays etc. from original bucket nextBucketImpl = std::move(prevBucketImpl); nextBucketImpl.SetBucket(std::move(nextBucket)); // Below are codified assumptions about the side-effects of attempted move-assigning of a BucketImpl. // We assume that move-assigning prevBucketImpl like above will clear it as well. This is important because // prevBucketImpl may still reside as a valid bucket in the PathToAttributesMap::buckets map. // // These asserts live outside of the move-assignment operator definition because, technically, the compiler is // allowed to elect to use a copy-assignment if it needs to. // // TODO: Would this be better expressed as an explicit "clear" of prevBucketImpl? Why wasn't that the original // behavior? CARB_ASSERT(prevBucketImpl.scalarAttributeArrays.empty()); CARB_ASSERT(prevBucketImpl.arrayAttributeArrays.empty()); CARB_ASSERT(prevBucketImpl.elemToPath.empty()); CARB_ASSERT(prevBucketImpl.listenerIdToChanges.empty()); } else { // TODO : there should be a faster way to do this but more to discuss here later auto prevBucketMapIter = attrNameSetToBucketId.find(prevBucket); const BucketId prevBucketId = (prevBucketMapIter != attrNameSetToBucketId.end()) ? prevBucketMapIter->second : kInvalidBucketId; for (const auto path : prevBucketImpl.elemToPath) { moveElementBetweenBuckets(asInt(path), nextBucketId, prevBucketId, nextBucket); } } const size_t nextBucketNewSize = nextBucketImpl.elemToPath.size(); CARB_ASSERT(nextBucketNewSize >= nextBucketOriginalSize); CARB_ASSERT(getTypeInfo(type).size == typeinfo.size); CARB_ASSERT(getTypeInfo(type).isArray == typeinfo.isArray); CARB_ASSERT(getTypeInfo(type).arrayElemSize == typeinfo.arrayElemSize); // Add an array for the new attribute const AttrName name{ attrName, NameSuffix::none }; ArrayAttributeArray *arrayAttributeArray; MirroredArray* valuesArray; if (typeinfo.isArray) { const bool inserted = nextBucketImpl.arrayAttributeArrays.allocateEntry(std::move(name), &arrayAttributeArray); valuesArray = &arrayAttributeArray->values; if (inserted) { new (arrayAttributeArray) ArrayAttributeArray(nextBucketImpl.platform, type, typeinfo); while (valuesArray->count < nextBucketNewSize) { allocElement(*arrayAttributeArray); } } } else { const bool inserted = nextBucketImpl.scalarAttributeArrays.allocateEntry(std::move(name), &valuesArray); arrayAttributeArray = nullptr; if (inserted) { new (valuesArray) ScalarAttributeArray(nextBucketImpl.platform, type, typeinfo); while (valuesArray->count < nextBucketNewSize) { allocElement(*valuesArray); } } arrayAttributeArray = nullptr; } CARB_ASSERT(valuesArray); CARB_ASSERT(!typeinfo.isArray || arrayAttributeArray); CARB_ASSERT(!typeinfo.isArray || getTypeInfo(valuesArray->type).isArray); #if CARB_ASSERT_ENABLED const size_t elemCount = getElementCount(nextBucketImpl.GetBucket()); CARB_ASSERT(valuesArray->count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->cpuElemCounts.count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->elemCounts.count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->gpuElemCounts.count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->gpuPtrs.count == elemCount); #endif // #if CARB_ASSERT_ENABLED // fixup elem/path maps for (pxr::SdfPath& path : nextBucketImpl.elemToPath) { std::pair<BucketId, ArrayIndex>* bucketAndElemIndex; if (pathToBucketElem.find(asInt(path), &bucketAndElemIndex)) { bucketAndElemIndex->first = nextBucketId; } } // If default value specified, copy it to every element if (value) { fillAttributeInternal(nextBucketImpl, name, nextBucketOriginalSize, nextBucketNewSize, value, typeinfo, arrayElemCount, valuesArray, arrayAttributeArray); } return nextBucketImpl; } inline void PathToAttributesMap::fillAttributeInternal(BucketImpl& bucketImpl, const AttrName& name, const size_t startIndex, const size_t endIndex, const void* value, const Typeinfo& typeinfo, const size_t arrayElemCount, MirroredArray *const valuesArray, ArrayAttributeArray *const arrayAttributeArray) { CARB_ASSERT(valuesArray); CARB_ASSERT(value); CARB_ASSERT(!typeinfo.isArray || arrayAttributeArray); CARB_ASSERT(startIndex < valuesArray->count); CARB_ASSERT(endIndex <= valuesArray->count); if (typeinfo.isArray) { CARB_ASSERT(arrayAttributeArray); const ArrayOfArrayInfo aoa = getArrayOfArrayInfo(*arrayAttributeArray); // Fill array sizes { ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(arrayAttributeArray->elemCounts, name, aoa, bucketImpl, CpuWriteConfig()); CARB_ASSERT(startIndex < arrayAndDirtyIndices.array.elementCount); CARB_ASSERT(endIndex <= arrayAndDirtyIndices.array.elementCount); for (size_t i = startIndex; i < endIndex; ++i) { reinterpret_cast<size_t*>(arrayAndDirtyIndices.array.ptr)[i] = arrayElemCount; setArrayElementDirty(arrayAndDirtyIndices, i); } } // Fill array values { ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(*valuesArray, name, aoa, bucketImpl, CpuWriteConfig()); CARB_ASSERT(startIndex < arrayAndDirtyIndices.array.elementCount); CARB_ASSERT(endIndex <= arrayAndDirtyIndices.array.elementCount); for (size_t i = startIndex; i < endIndex; ++i) { uint8_t** dest = reinterpret_cast<uint8_t**>(arrayAndDirtyIndices.array.ptr) + arrayAndDirtyIndices.array.elementSize * i; CARB_ASSERT(*dest); memcpy(*dest, value, arrayElemCount * typeinfo.arrayElemSize); // assumes coherent and packed array value provided setArrayElementDirty(arrayAndDirtyIndices, i); } } } else { const ArrayOfArrayInfo aoa = ScalarArrayOfArrayInfo(); ArrayAndDirtyIndices arrayAndDirtyIndices = getArraySpanC(*valuesArray, name, aoa, bucketImpl, CpuWriteConfig()); CARB_ASSERT(startIndex < arrayAndDirtyIndices.array.elementCount); CARB_ASSERT(endIndex <= arrayAndDirtyIndices.array.elementCount); for (size_t i = startIndex; i < endIndex; ++i) { uint8_t* dest = arrayAndDirtyIndices.array.ptr + arrayAndDirtyIndices.array.elementSize * i; memcpy(dest, value, typeinfo.size); setArrayElementDirty(arrayAndDirtyIndices, i); } } } inline void PathToAttributesMap::addAttributeInternal(const PathC& path, const TokenC& attrNameC, const NameSuffix nameSuffix, const TypeC ctype, const void* value, const Typeinfo& typeinfo, const size_t arrayElemCount) { APILOGGER("addAttributeInternal", apiLogEnabled, path, attrNameC); BucketId bucketId; ArrayIndex elemIndex; std::tie(bucketId, elemIndex) = addAttributeGetBucketAndArrayIndex(path, attrNameC, nameSuffix, ctype); BucketImpl *const bucketImpl = buckets.find(bucketId); CARB_ASSERT(bucketImpl); ArrayAttributeArray *arrayAttributeArray; MirroredArray* valuesArray; const AttrName attrName{ attrNameC, nameSuffix }; if (typeinfo.isArray) { bucketImpl->arrayAttributeArrays.find(attrName, &arrayAttributeArray); CARB_ASSERT(arrayAttributeArray); valuesArray = &arrayAttributeArray->values; } else { bucketImpl->scalarAttributeArrays.find(attrName, &valuesArray); arrayAttributeArray = nullptr; } CARB_ASSERT(valuesArray); CARB_ASSERT(!typeinfo.isArray || arrayAttributeArray); if (value) { fillAttributeInternal(*bucketImpl, attrName, elemIndex, elemIndex + 1, value, typeinfo, arrayElemCount, valuesArray, arrayAttributeArray); } #if CARB_ASSERT_ENABLED const size_t elemCount = bucketImpl->elemToPath.size(); CARB_ASSERT(valuesArray->count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->cpuElemCounts.count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->elemCounts.count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->gpuElemCounts.count == elemCount); CARB_ASSERT(!arrayAttributeArray || arrayAttributeArray->gpuPtrs.count == elemCount); #endif // #if CARB_ASSERT_ENABLED } inline PathToAttributesMap::PathToAttributesMap(const PlatformId& platformId) : platform(carb::getCachedInterface<carb::flatcache::IPlatform>()->getMutable(platformId)) , pathToBucketElem(0, std::hash<PathId>(), std::equal_to<PathId>(), AllocFunctor{ &platform.allocator }, FreeFunctor{ &platform.allocator }) , buckets(platform) , attrNameSetToBucketId() , listenerIdToChangeTrackerConfig(0, ListenerIdHasher(), std::equal_to<ListenerId>(), AllocFunctor{ &platform.allocator }, FreeFunctor{ &platform.allocator }) , typeToInfo(0, std::hash<TypeC>(), std::equal_to<TypeC>(), AllocFunctor{ &platform.allocator }, FreeFunctor{ &platform.allocator }) , usdStageId() , minimalPopulationDone(false) { // required types for arrays of arrays Typeinfo* typeinfo; typeToInfo.allocateEntry(PTAM_SIZE_TYPEC, &typeinfo); *typeinfo = Typeinfo{ sizeof(PTAM_SIZE_TYPE), false, 0 }; typeToInfo.allocateEntry(PTAM_POINTER_TYPEC, &typeinfo); *typeinfo = Typeinfo{ sizeof(PTAM_POINTER_TYPE), false, 0 }; } inline PathToAttributesMap& PathToAttributesMap::operator=(const flatcache::PathToAttributesMap& other) { carb::profiler::ZoneId zoneId = CARB_PROFILE_BEGIN(1, "Clear buckets"); buckets.clear(); CARB_PROFILE_END(1, zoneId); zoneId = CARB_PROFILE_BEGIN(1, "Copy pathToBucketElem"); pathToBucketElem.clear(); pathToBucketElem.reserve(other.pathToBucketElem.size()); other.pathToBucketElem.forEach([this](const PathId& key, const std::pair<BucketId, ArrayIndex> &otherValue) { std::pair<BucketId, ArrayIndex>* value; VALIDATE_TRUE(pathToBucketElem.allocateEntry(key, &value)); static_assert(std::is_copy_constructible<std::pair<BucketId, ArrayIndex>>::value, "Expected pathToBucketElem values to be copy-constructible"); new (value) std::pair<BucketId, ArrayIndex>(otherValue); }); CARB_PROFILE_END(1, zoneId); zoneId = CARB_PROFILE_BEGIN(1, "Copy scalar attributes"); buckets = other.buckets; CARB_PROFILE_END(1, zoneId); attrNameSetToBucketId = other.attrNameSetToBucketId; typeToInfo = other.typeToInfo; usdStageId = other.usdStageId; minimalPopulationDone = other.minimalPopulationDone; stageHierarchy = other.stageHierarchy; zoneId = CARB_PROFILE_BEGIN(1, "Copy array attributes"); { BucketId id{ 0 }; for (size_t i = 0; i < buckets.end(); ++i, ++id) { auto bucketPtr = buckets.find(id); if (bucketPtr) { const BucketImpl& srcBucketImpl = *(other.buckets.find(id)); BucketImpl& destBucketImpl = *bucketPtr; // Copy any array-valued attributes bucketImplCopyArrays(destBucketImpl, id, srcBucketImpl, id); } } } CARB_PROFILE_END(1, zoneId); return *this; } inline PathToAttributesMap::~PathToAttributesMap() { } } } #include <carb/flatcache/GetArrayGPU.h> // Enable the warnings we disabled when we included USD headers #if defined(__GNUC__) # pragma GCC diagnostic pop # ifdef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS # define __DEPRECATED # undef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS # endif #endif
267,444
C
38.574578
369
0.645073
omniverse-code/kit/fabric/include/carb/flatcache/HashMap.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <cstdint> #include <cstdlib> #include <carb/Defines.h> #include <carb/flatcache/Defines.h> #include <carb/flatcache/Intrinsics.h> namespace carb { namespace flatcache { struct HashMapDefaultAlloc { inline void* operator()(const size_t bytes) { return std::malloc(bytes); } }; struct HashMapDefaultFree { inline void operator()(void *const ptr) { std::free(ptr); } }; // A hashmap implemented with the following decisions: // // * Memory is allocated in a single contiguous buffer so that find operations make linear cache line fetches as much // as possible. This intends to make more easily predictable memory access patterns, and thus, easier hardware-level // prefetch decisions. Similarly, whole-map iteration benefits from the same cache-friendly access patterns. // // * Find operations intentionally are coded without range checks on the main loop. This is a tradeoff of speed for // less error-detection in release builds. To help mitigate this, debug builds do track probe counts to validate // we don't exceed the possible length of the hashmap. // // * No opinion codified on thread synchronization. It can be used safely if done carefully, but this is not a // guarantee of the implementation. // // * No iterators provided. If some batch operation must occur, use the forEach() function provided, which should // suffice. The forEach() method should provide similar performance without the added risk of callers being able to // arbitrarily cache iterators outside the control of the HashMap, its routines, or even its lifetime. // // * Deletes copy-constructor and copy-assignment for non-standard-layout mappings. This forces callers to implement // these routines explicitly, favoring the clarity of reading intent in explicit implementation over ambiguity over // compiler selection. Mappings that have standard-layout default to use a memcpy to copy data as fast as possible. // // * Implements allocateEntry() method, rather than insert()/emplace() methods mimicing std::unordered_map API. This // does the minimum steps necessary to reserve address space for a key-value mapping, and provides the caller with // the reserved buffer memory address for them to do their own construction, assignment, or initialization routines. // This favors slightly more explicit coding patterns at the caller to force clarity of intent. In particular, // it make more obvious the choice of the caller between construction vs assignment, and copy vs move semantics. It // also offers greater flexibility without sacrificing performance. // // * ~HashMap() and clear() operate different depending on if KeyT and ValueT are known to be // std::is_trivially_destructible. If they are, the fastest option is chosen: to deallocate the memory without // iteration or explicitly destruction per-entry. Otherwise, the implementation iterates to non-trivially destruct // each object in-place. template<typename KeyT, typename ValueT, typename HashT = std::hash<KeyT>, typename KeyEqualsT = std::equal_to<KeyT>, typename AllocT = HashMapDefaultAlloc, typename FreeT = HashMapDefaultFree> struct HashMap { // I didn't experiment with this exhaustively, could be tuned better, probably static constexpr size_t LOAD_FACTOR_NUMERATOR = 3ull; static constexpr size_t LOAD_FACTOR_DENOMENATOR = 4ull; static constexpr size_t MIN_INIT_CAPACITY = 4ull; static_assert((MIN_INIT_CAPACITY & (MIN_INIT_CAPACITY - 1ull)) == 0, "MIN_INIT_CAPACITY must be a power of two!"); static constexpr bool KEY_IS_TRIVIALLY_DESTRUCTIBLE = std::is_trivially_destructible<KeyT>::value; static constexpr bool VALUE_IS_TRIVIALLY_DESTRUCTIBLE = std::is_trivially_destructible<ValueT>::value; enum EntryState : uint8_t { HASH_MAP_ENTRY_STATE_FREE, HASH_MAP_ENTRY_STATE_OCCUPIED, HASH_MAP_ENTRY_STATE_DELETED, }; struct EntryT { EntryState state; KeyT key; ValueT value; }; static constexpr size_t allocationSize( const size_t capacity ); static constexpr size_t loadThreshold( const size_t capacity ); static constexpr size_t inverseLoadThreshold( const size_t capacity ); static constexpr size_t capacityAdjustedForLoadThreshold( const size_t capacity ); HashMap( const size_t capacity = 0, const HashT &hasher = HashT(), const KeyEqualsT &keyEquals = KeyEqualsT(), const AllocT &alloc_ = AllocT(), const FreeT &free_ = FreeT() ); ~HashMap(); HashMap(const HashMap& other); HashMap& operator=(const HashMap& other); HashMap(HashMap&& other) noexcept; HashMap& operator=(HashMap&& other) noexcept; inline friend void swap(HashMap& a, HashMap& b) noexcept { using std::swap; swap(a.m_hasher, b.m_hasher); swap(a.m_keyEquals, b.m_keyEquals); swap(a.m_alloc, b.m_alloc); swap(a.m_free, b.m_free); swap(a.m_size, b.m_size); swap(a.m_capacity, b.m_capacity); swap(a.m_loadThreshold, b.m_loadThreshold); swap(a.m_mask, b.m_mask); swap(a.m_entries, b.m_entries); } void clear(); const void* data() const; bool empty() const; size_t size() const; size_t capacty() const; void reserve(const size_t capacity); bool find( const KeyT& key, ValueT** outValue ); bool find( const KeyT& key, const ValueT** outValue ) const; bool exists( const KeyT& key ) const; bool allocateEntry( KeyT&& key, ValueT** outValue ); bool allocateEntry( const KeyT& key, ValueT** outValue ); // Intended to be safe to call during forEach() as it does not invalidate iteration. bool freeEntry( const KeyT& key ); void freeEntryByKeyAddress( const KeyT *const key ); void freeEntryByValueAddress( const ValueT *const value ); template<typename CallbackT> inline void forEach( CallbackT callback ); template<typename CallbackT> inline void forEach( CallbackT callback ) const; size_t totalCollisionLength() const; private: size_t hashInternal( const KeyT& key ) const; void resizeIfNecessary(); void resize( const size_t nextCapacity ); void freeEntryInternal( EntryT *const entry ); bool findFirstAvailable( const KeyT& key, EntryT** outEntry ); bool findExisting( const KeyT& key, EntryT** outEntry ); bool findExisting( const KeyT& key, const EntryT** outEntry ) const; HashT m_hasher; KeyEqualsT m_keyEquals; AllocT m_alloc; FreeT m_free; size_t m_size; size_t m_capacity; size_t m_loadThreshold; size_t m_mask; EntryT* m_entries; }; template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline constexpr size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::allocationSize( const size_t capacity ) { return capacity * sizeof( EntryT ); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline constexpr size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::loadThreshold( const size_t capacity ) { return (capacity * LOAD_FACTOR_NUMERATOR / LOAD_FACTOR_DENOMENATOR); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline constexpr size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::inverseLoadThreshold( const size_t capacity ) { return (capacity * LOAD_FACTOR_DENOMENATOR / LOAD_FACTOR_NUMERATOR); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline constexpr size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::capacityAdjustedForLoadThreshold( const size_t capacity ) { // reserves capacity to the nearest power of two that satisfies the load threshhold for the requested capacity size_t adjustedCapacity; if (capacity && capacity >= loadThreshold(MIN_INIT_CAPACITY)) { // +1 because we want capacity < loadThreshold(adjustedCapacity), not capacity <= loadThreshold(adjustedCapacity) adjustedCapacity = 1ull << ( 64u - clz64( inverseLoadThreshold( capacity + 1 ) - 1ull ) ); } else { adjustedCapacity = MIN_INIT_CAPACITY; } CARB_ASSERT(capacity < loadThreshold(adjustedCapacity)); CARB_ASSERT((adjustedCapacity & (adjustedCapacity - 1ull)) == 0); return adjustedCapacity; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::HashMap(const size_t capacity, const HashT &hasher, const KeyEqualsT &keyEquals, const AllocT &alloc_, const FreeT &free_) { m_hasher = hasher; m_keyEquals = keyEquals; m_alloc = alloc_; m_free = free_; m_size = 0; if (capacity) { const size_t adjustedCapacity = capacityAdjustedForLoadThreshold(capacity); const size_t bufSize = allocationSize(adjustedCapacity); m_capacity = adjustedCapacity; m_loadThreshold = loadThreshold(adjustedCapacity); m_mask = adjustedCapacity - 1ull; m_entries = (EntryT*)m_alloc(bufSize); memset(m_entries, 0, bufSize); } else { m_capacity = 0; m_loadThreshold = 0; m_mask = 0; m_entries = nullptr; } } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::~HashMap() { if ( m_entries ) { if (!KEY_IS_TRIVIALLY_DESTRUCTIBLE || !VALUE_IS_TRIVIALLY_DESTRUCTIBLE) { size_t index = 0; size_t visited = 0; for ( ; index < m_capacity && visited < m_size; ++index) { EntryT *const entry = &m_entries[index]; if ( entry->state == HASH_MAP_ENTRY_STATE_OCCUPIED ) { if (!KEY_IS_TRIVIALLY_DESTRUCTIBLE) { entry->key.~KeyT(); } if (!VALUE_IS_TRIVIALLY_DESTRUCTIBLE) { entry->value.~ValueT(); } CARB_ASSERT(visited < m_size); ++visited; } } } m_free(m_entries); m_entries = nullptr; } } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::HashMap(const HashMap& other) : m_hasher(other.m_hasher) , m_keyEquals(other.m_keyEquals) , m_alloc(other.m_alloc) , m_free(other.m_free) , m_size(other.m_size) , m_capacity(other.m_capacity) , m_loadThreshold(other.m_loadThreshold) , m_mask(other.m_mask) { static_assert(std::is_trivially_copyable<EntryT>::value, "Copying of HashMap is only supported for key-value mappings that are use standard-layout classes."); const size_t bufSize = allocationSize(m_capacity); m_entries = (EntryT*)m_alloc(bufSize); memcpy(m_entries, other.m_entries, bufSize); CARB_ASSERT(m_entries); CARB_ASSERT(m_capacity); CARB_ASSERT((m_capacity & (m_capacity - 1ull)) == 0); // assert m_capacity is power of two CARB_ASSERT(m_size < m_capacity); CARB_ASSERT(m_size < m_loadThreshold); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>& HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::operator=(const HashMap& other) { HashMap tmp(other); swap(*this, tmp); return *this; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::HashMap(HashMap&& other) noexcept : m_hasher(std::move(other.m_hasher)) , m_keyEquals(std::move(other.m_keyEquals)) , m_alloc(std::move(other.m_alloc)) , m_free(std::move(other.m_free)) , m_size(std::move(other.m_size)) , m_capacity(std::move(other.m_capacity)) , m_loadThreshold(std::move(other.m_loadThreshold)) , m_mask(std::move(other.m_mask)) , m_entries(std::move(other.m_entries)) { other.m_entries = nullptr; other.clear(); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>& HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::operator=(HashMap&& other) noexcept { HashMap tmp(std::move(other)); swap(*this, tmp); return *this; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::clear() { if ( m_entries ) { if (!KEY_IS_TRIVIALLY_DESTRUCTIBLE || !VALUE_IS_TRIVIALLY_DESTRUCTIBLE) { size_t index = 0; size_t visited = 0; for ( ; index < m_capacity && visited < m_size; ++index) { EntryT *const entry = &m_entries[index]; if ( entry->state == HASH_MAP_ENTRY_STATE_OCCUPIED ) { if (!KEY_IS_TRIVIALLY_DESTRUCTIBLE) { entry->key.~KeyT(); } if (!VALUE_IS_TRIVIALLY_DESTRUCTIBLE) { entry->value.~ValueT(); } CARB_ASSERT(visited < m_size); ++visited; } entry->state = HASH_MAP_ENTRY_STATE_FREE; } } else { static_assert(HASH_MAP_ENTRY_STATE_FREE == 0, "memset(0) requires HASH_MAP_ENTRY_STATE_FREE == 0"); memset(m_entries, 0, allocationSize(m_capacity)); } } m_size = 0; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline const void* HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::data() const { return m_entries; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::empty() const { return m_size == 0; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::size() const { return m_size; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::capacty() const { return m_capacity; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::reserve(const size_t capacity) { const size_t adjustedCapacity = capacityAdjustedForLoadThreshold(capacity); if (m_capacity < adjustedCapacity) { resize(adjustedCapacity); } } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::find( const KeyT& key, ValueT** outValue ) { EntryT* existing; if (findExisting( key, &existing) ) { *outValue = &existing->value; return true; } return false; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::find( const KeyT& key, const ValueT** outValue ) const { const EntryT* existing; if (findExisting( key, &existing) ) { *outValue = &existing->value; return true; } return false; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::exists( const KeyT& key ) const { const EntryT* existing; if (findExisting( key, &existing) ) { return true; } return false; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::allocateEntry( KeyT&& key, ValueT** outValue ) { EntryT* availableEntry; resizeIfNecessary(); const bool available = findFirstAvailable(key, &availableEntry); CARB_ASSERT(availableEntry); if (available) { new (&availableEntry->key) KeyT(std::move(key)); CARB_ASSERT(availableEntry->state != HASH_MAP_ENTRY_STATE_OCCUPIED); availableEntry->state = HASH_MAP_ENTRY_STATE_OCCUPIED; *outValue = &availableEntry->value; CARB_ASSERT(m_size < m_capacity); CARB_ASSERT(m_size + 1 > m_size); ++m_size; return true; } *outValue = &availableEntry->value; return false; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::allocateEntry( const KeyT& key, ValueT** outValue ) { EntryT* availableEntry; resizeIfNecessary(); const bool available = findFirstAvailable(key, &availableEntry); CARB_ASSERT(availableEntry); if (available) { new (&availableEntry->key) KeyT(key); CARB_ASSERT(availableEntry->state != HASH_MAP_ENTRY_STATE_OCCUPIED); availableEntry->state = HASH_MAP_ENTRY_STATE_OCCUPIED; *outValue = &availableEntry->value; CARB_ASSERT(m_size < m_capacity); CARB_ASSERT(m_size + 1 > m_size); ++m_size; return true; } *outValue = &availableEntry->value; return false; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::freeEntry( const KeyT& key ) { EntryT* existing; if (findExisting(key, &existing)) { freeEntryInternal(existing); return true; } else { return false; } } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::freeEntryByKeyAddress( const KeyT *const key ) { static_assert(!std::is_polymorphic<EntryT>::value, "Unable to freeEntry by key address!"); constexpr size_t OFFSET = offsetof(EntryT, key); EntryT *const entry = (EntryT*)(((uintptr_t)key) - OFFSET); freeEntryInternal(entry); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::freeEntryByValueAddress(const ValueT *const value) { static_assert(!std::is_polymorphic<EntryT>::value, "Unable to freeEntry by value address!"); constexpr size_t OFFSET = offsetof(EntryT, value); EntryT *const entry = (EntryT*)(((uintptr_t)value) - OFFSET); freeEntryInternal(entry); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::hashInternal( const KeyT& key ) const { size_t hash = m_hasher(key); #define HASHMAP_DEFENSIVE_SALT IN_USE #if USING( HASHMAP_DEFENSIVE_SALT ) // Apply a defensive salt to the user-calculated hash value. It is unsafe to assume user-provided hashes are good. // // Kit historically had a problem where std::hash<PathC> caused terrible distributions inside of space-restricted // hashmaps. This was primarly because the hash values returned had zero entropy in the lower 8 bits. The higher // bits had excellent entropy, though. It is trivial to improve std::hash<PathC> by doing (oldHashValue >> 8). // In other words, tossing the bits with zero entropy. This will produce perfectly unique hash value output for // every PathC input. However, using this directly in a hash map is still not ideal because, while the hash function // has a guarantee on uniqueness, it does not necessarily lend to good distributions in a hash table. Two hash // values that are multiples of each other will naturally colliide in any space-restricted hashmap. // (Which, realistically, is all real hash maps since hardware memory is not infinite.) Applying a little salt on // top of the hash value fixes this distribution problem. // // This also provides general safety against poorly implemented user-provided hash functions that don't generate // unique or well distributed values. // // Known problematic data sets: // - PathC (interned SdfPaths) // - TokenC (interned TfTokens) // // Salt techniques tried: // - H3_XX64 (xxhash): // - good distribution // - too slow // - H3_XX64 (xxhash) with custom seeds: // - no seed performed better than the xxhash default secret // - Custom H3_XX64 implementation specialized for aligned 64-bit keys: // - methematically identical distribution to H3_XX64 // - 2x faster performance than official implementation // - Multiply by a prime // - best distribution so far // - best speed so far (3x faster than custom H3_XX64) // // TODO: A fun intern experiment would be to investigate our various omniverse hash functions for distribution and // speed. And also investigate alternative defensive salting techniques. return hash * 48271ull; #else // #if USING( HASHMAP_DEFENSIVE_SALT ) return hash; #endif // #if USING( HASHMAP_DEFENSIVE_SALT ) #undef HASHMAP_DEFENSIVE_SALT } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::resizeIfNecessary() { if (m_size >= m_loadThreshold) { CARB_ASSERT(!m_capacity || m_capacity * 2 > m_capacity); resize(m_capacity ? m_capacity * 2 : MIN_INIT_CAPACITY); } else if (!m_entries) { const size_t bufSize = allocationSize(m_capacity); m_entries = (EntryT*)m_alloc(bufSize); memset(m_entries, 0, bufSize); } CARB_ASSERT(m_entries); CARB_ASSERT(m_capacity); CARB_ASSERT((m_capacity & (m_capacity - 1)) == 0); CARB_ASSERT(m_size < m_capacity); CARB_ASSERT(m_size < m_loadThreshold); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::resize(const size_t nextCapacity) { CARB_ASSERT(m_size < loadThreshold(nextCapacity)); CARB_ASSERT((nextCapacity & (nextCapacity - 1)) == 0); HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT> tmp(nextCapacity, m_hasher, m_keyEquals, m_alloc, m_free ); size_t index = 0; size_t visited = 0; for ( ; index < m_capacity && visited < m_size; ++index) { EntryT *const entry = &m_entries[index]; if ( entry->state == HASH_MAP_ENTRY_STATE_OCCUPIED ) { ValueT *tmpV; tmp.allocateEntry(std::move(entry->key), &tmpV); new (tmpV) ValueT(std::move(entry->value)); CARB_ASSERT(visited < m_size); ++visited; } } CARB_ASSERT(m_size == tmp.m_size); using std::swap; swap(m_entries, tmp.m_entries); swap(m_size, tmp.m_size); swap(m_capacity, tmp.m_capacity); swap(m_loadThreshold, tmp.m_loadThreshold); swap(m_mask, tmp.m_mask); } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::freeEntryInternal( EntryT *const entry ) { CARB_ASSERT(entry); CARB_ASSERT(entry->state == HASH_MAP_ENTRY_STATE_OCCUPIED); if (!KEY_IS_TRIVIALLY_DESTRUCTIBLE) { entry->key.~KeyT(); } if (!VALUE_IS_TRIVIALLY_DESTRUCTIBLE) { entry->value.~ValueT(); } entry->state = HASH_MAP_ENTRY_STATE_DELETED; CARB_ASSERT(m_size); CARB_ASSERT(m_size - 1 < m_size); --m_size; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> template<typename CallbackT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::forEach( CallbackT callback ) { size_t index = 0; size_t visited = 0; const size_t size_captured = m_size; for ( ; index < m_capacity && visited < size_captured; ++index) { if (m_entries[index].state == HASH_MAP_ENTRY_STATE_OCCUPIED) { callback(m_entries[index].key, m_entries[index].value); CARB_ASSERT(visited < size_captured); ++visited; } } } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> template<typename CallbackT> inline void HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::forEach(CallbackT callback) const { size_t index = 0; size_t visited = 0; const size_t size_captured = m_size; for (; index < m_capacity && visited < size_captured; ++index) { if (m_entries[index].state == HASH_MAP_ENTRY_STATE_OCCUPIED) { callback(m_entries[index].key, m_entries[index].value); CARB_ASSERT(visited < size_captured); ++visited; } } } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline size_t HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::totalCollisionLength() const { size_t len = 0; if ( m_entries ) { size_t index = 0; size_t visited = 0; const size_t size_captured = m_size; for (; index < m_capacity && visited < size_captured; ++index) { const EntryT *const probe = &m_entries[index]; if (probe->state == HASH_MAP_ENTRY_STATE_OCCUPIED) { const EntryT *const natural = &m_entries[hashInternal(probe->key) & m_mask]; len += (size_t)((natural <= probe) ? (probe - natural) : ( ( probe + m_capacity ) - natural) ); CARB_ASSERT(visited < size_captured); ++visited; } } } return len; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::findFirstAvailable( const KeyT& key, EntryT** outEntry ) { EntryT* probe; size_t probeIdx; // This will technically resize opportunistically if the key might already exist, but at least // that edge case will only occur once per resize, and being opportunistic avoids searching first. resizeIfNecessary(); #if USING( ASSERTS ) size_t probes = 0; #endif // #if USING( ASSERTS ) probeIdx = hashInternal(key) & m_mask; CARB_ASSERT(m_size < m_capacity); // otherwise we infinite loop while(1) { CARB_ASSERT( probeIdx < m_capacity ); probe = &m_entries[probeIdx]; if ( probe->state == HASH_MAP_ENTRY_STATE_FREE ) { *outEntry = probe; return true; } else if ( probe->state == HASH_MAP_ENTRY_STATE_OCCUPIED ) { if ( m_keyEquals(probe->key, key) ) { *outEntry = probe; return false; } } else if ( probe->state == HASH_MAP_ENTRY_STATE_DELETED ) { *outEntry = probe; return true; } probeIdx = ( probeIdx + 1 ) & m_mask; #if USING( ASSERTS ) ++probes; CARB_ASSERT(probes < m_capacity); #endif // #if USING( ASSERTS ) } CARB_ASSERT(false && "unreachable code"); return false; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::findExisting( const KeyT& key, EntryT** outEntry ) { if (!m_size) { return false; } EntryT* probe; size_t probeIdx; #if USING( ASSERTS ) size_t probes = 0; #endif // #if USING( ASSERTS ) probeIdx = hashInternal(key) & m_mask; CARB_ASSERT(m_size < m_capacity); // otherwise we infinite loop while(1) { CARB_ASSERT( probeIdx < m_capacity ); probe = &m_entries[probeIdx]; if ( probe->state == HASH_MAP_ENTRY_STATE_FREE ) { return false; } else if ( probe->state == HASH_MAP_ENTRY_STATE_OCCUPIED ) { if ( m_keyEquals(probe->key, key) ) { *outEntry = probe; return true; } } else { // skip CARB_ASSERT( probe->state == HASH_MAP_ENTRY_STATE_DELETED ); } probeIdx = ( probeIdx + 1 ) & m_mask; #if USING( ASSERTS ) ++probes; CARB_ASSERT(probes < m_capacity); #endif // #if USING( ASSERTS ) } CARB_ASSERT(false && "unreachable code"); return false; } template<typename KeyT, typename ValueT, typename HashT, typename KeyEqualsT, typename AllocT, typename FreeT> inline bool HashMap<KeyT, ValueT, HashT, KeyEqualsT, AllocT, FreeT>::findExisting( const KeyT& key, const EntryT** outEntry ) const { return const_cast<HashMap*>(this)->findExisting( key, const_cast< EntryT** >(outEntry) ); } } // namespace flatcache } // namespace carb
31,028
C
35.634002
162
0.655182
omniverse-code/kit/fabric/include/carb/flatcache/Enums.h
// Copyright (c) 2021-2021 NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once namespace carb { namespace flatcache { /** * @enum PtrToPtrKind * * @details When getting an array-valued attribute for GPU access, you can * optionally use this enum to ask for a GPU pointer to the GPU data * pointer (eGpuPtrToGpuPtr), or a CPU pointer to the GPU data * pointer (eCpuPtrToGpuPtr). * The advantage of using eCpuPtrToGpuPtr is that you can dereference * the returned pointer on the CPU, and pass the GPU data pointer as * a CUDA kernel parameter. * The advantage of using eGpuPtrToGpuPtr is that it makes it easier * to extend kernels to operate on arrays of arrays later. Also it * allows us to support allocation and resizing of array-valued * attributes on the GPU in the future. * * PtrToPtrKind is not a parameter of methods returning arrays of * arrays, for example getArrayGPU(). This is because there is no way * to pass a variable length array of GPU pointers to a kernel using * its CPU launch parameters. So GPU arrays of arrays always have to * be passed to kernels as a GPU pointer to an array of GPU pointers. */ enum class PtrToPtrKind { eNotApplicable = 0, eGpuPtrToGpuPtr = 0, // eGpuPtrToGpuPtr == eNotApplicable for backward compatibility eCpuPtrToGpuPtr = 1 }; } // namespace flatcache } // namespace carb
1,865
C
41.40909
88
0.70563
omniverse-code/kit/fabric/include/carb/flatcache/IdTypes.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 <cstdint> #include <stddef.h> namespace carb { namespace flatcache { struct StageInProgressId { uint64_t id; }; struct StageAtTimeIntervalId { uint64_t id; }; struct StageWithHistoryId { uint64_t id; }; struct PrimBucketListId { uint64_t id; }; struct ListenerId { size_t id; bool operator==(ListenerId other) const { return id == other.id; } }; struct ListenerIdHasher { size_t operator()(const ListenerId& key) const { return key.id; } }; enum class PlatformId : uint8_t { Global = 0, // add additional platforms here Count, }; } }
1,081
C
15.149254
77
0.696577
omniverse-code/kit/fabric/include/carb/flatcache/OGUtilsNotForGeneralUser.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Interface.h> namespace carb { namespace flatcache { struct OGUtilsNotForGeneralUser { CARB_PLUGIN_INTERFACE("carb::flatcache::OGUtilsNotForGeneralUser", 0, 2); ////////////////////////////////////////////////////////////////////////// // A simple collection of utility functions for interacting with flatcache ////////////////////////////////////////////////////////////////////////// /** @brief Import attributes from a usd prim, in provided cache, at a given path, * read at a given time * * @cache[in/out] The cache to be populated * @dstPath[in] The path location in the cache to import attributes to * @prim[in] The prim from which to read the attributes in USD * @time[in] The time at which to read the attributes from * @filter[in] A subset of attributes to consider during this import process. * Will import all attributes if left empty * @force[in] Whether to overwrite values, or just add missing ones */ void(CARB_ABI* importPrimAttributesToCacheAtPathAtTime)(struct PathToAttributesMap& cache, const pxr::SdfPath& dstPath, const pxr::UsdPrim& prim, const pxr::UsdTimeCode& time, const std::set<TokenC>& filter, bool force); /** @brief Copy a subset of data from the cache back to USD * * @cache[in/out] The cache to read the data from * @buckets[in] A collection of bucket subsets, from which the data needs to be copied back to USD */ void (CARB_ABI* pushDataToUSD)(struct PathToAttributesMap& cache, struct BucketSubset const& bucket, bool skipMeshPoints); // Prefetch the whole USD stage to the cache // Typically you only call this at stage load time, because the USD notify // handler updates the cache if the stage changes. void(CARB_ABI* usdToCache)(PathToAttributesMap& cache, bool processConnections); }; } }
2,644
C
41.66129
126
0.59947
omniverse-code/kit/fabric/include/omni/gpucompute/D3dContext.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/graphics/Graphics.h> using namespace carb::graphics; namespace omni { namespace gpucompute { // TODO: move out of public API struct ContextD3D { std::unique_ptr<Device, GfxResult (*)(Device*)> device; CommandQueue* commandQueue; // Not unique_ptr because we don't own it std::unique_ptr<CommandAllocator, void (*)(CommandAllocator*)> commandAllocator; std::unique_ptr<CommandList, void (*)(CommandList*)> commandList; std::unique_ptr<Fence, void (*)(Fence*)> fence; ContextD3D(DeviceDesc deviceDesc, carb::graphics::Graphics* graphics) : device(graphics->createDevice(deviceDesc), graphics->destroyDevice), commandQueue(graphics->getCommandQueue(device.get(), CommandQueueType::eRender, 0)), commandAllocator(graphics->createCommandAllocator(commandQueue), graphics->destroyCommandAllocator), commandList(graphics->createCommandList(commandAllocator.get()), graphics->destroyCommandList), fence(graphics->createFence(device.get(), carb::graphics::FenceDesc { kFenceCreateFlagNone, "GPU compute context fence" }), graphics->destroyFence) { } }; } }
1,595
C
39.923076
157
0.743574
omniverse-code/kit/fabric/include/omni/gpucompute/GpuCompute.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/Types.h> #include <map> #include <memory> #include <vector> using namespace carb; namespace carb { namespace graphics { struct Context; struct Graphics; struct Device; struct CommandList; struct CommandQueue; struct Fence; struct Shader; } } namespace omni { namespace gpucompute { enum class MemcpyKind { hostToHost = 0, hostToDevice = 1, deviceToHost = 2, deviceToDevice = 3 }; struct Context; struct Shader; struct Parameter { const char* name; bool isConstantBuffer; }; // API agnostic representation of // static_cast<char*>(buffer) + byteOffset // which points to data of size elemSize struct GpuPointer { void* buffer; size_t byteOffset; size_t elemSize; }; struct CpuBuffer { void* data; size_t count; }; struct Args { // TODO: move CPU backend into its own plugin // GPU std::vector<GpuPointer> gpuBuffers; std::vector<size_t> gpuArgToBufferCount; // CPU std::vector<CpuBuffer> cpuArgs; }; // A CUDA-style interface for D3D, consisting of GPU malloc, free, memcpy and // kernel dispatch struct GpuCompute { CARB_PLUGIN_INTERFACE("omni::gpucompute::GpuCompute", 0, 1) // CPU memory allocation void(CARB_ABI* hostAlloc)(Context& context, void** ptr, size_t byteCount); void(CARB_ABI* freeHost)(Context& context, void* ptr); // GPU memory allocation void*(CARB_ABI* malloc)(Context& context, size_t byteCount, size_t elemSize); void(CARB_ABI* free)(Context& context, void* ptr); // GPU async memory allocation (uses stream 0 for CUDA) void*(CARB_ABI* mallocAsync)(Context& context, size_t byteCount, size_t elemSize); void(CARB_ABI* freeAsync)(Context& context, void* ptr); void(CARB_ABI* memcpy)(Context& context, void* dst, const void* src, size_t byteCount, MemcpyKind kind); void(CARB_ABI* dispatch)(Context& context, Shader& shader, Args& args, carb::Uint3 gridDim); Context&(CARB_ABI* createContext)(); Context&(CARB_ABI* createContextD3dVk)(carb::graphics::Graphics* graphics, carb::graphics::Device* device, carb::graphics::CommandList* commandList, carb::graphics::CommandQueue* commandQueue, carb::graphics::Fence* fence); void(CARB_ABI* destroyContext)(Context& context); uint32_t(CARB_ABI* peekAtLastError)(Context& context); uint32_t(CARB_ABI* getLastError)(Context& context); void(CARB_ABI* memcpyAsync)(Context& context, void* dst, const void* src, size_t byteCount, MemcpyKind kind); }; enum class Target { CPU, GPU }; struct ComputeCompiler { CARB_PLUGIN_INTERFACE("omni::gpucompute::ComputeCompiler", 0, 1) omni::gpucompute::Shader*(CARB_ABI* compile)(carb::graphics::Device* device, Target target, const char* codeString); void(CARB_ABI* getParameters)(Parameter*& parameters, size_t& count, Shader& shader); void(CARB_ABI* destroyShader)(Shader& shader); }; } }
3,512
C
25.022222
120
0.679385
omniverse-code/kit/include/carb/IObject.h
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! //! @brief Implementation of Carbonite objects. #pragma once #include "Interface.h" #include <cstdint> namespace carb { /** * Reference-counted object base. */ class IObject { public: CARB_PLUGIN_INTERFACE("carb::IObject", 1, 0) /** * Destructor. */ virtual ~IObject() = default; /** * Atomically add one to the reference count. * @returns The current reference count after one was added, though this value may change before read if other * threads are also modifying the reference count. The return value is guaranteed to be non-zero. */ virtual size_t addRef() = 0; /** * Atomically subtracts one from the reference count. If the result is zero, carb::deleteHandler() is called for * `this`. * @returns The current reference count after one was subtracted. If zero is returned, carb::deleteHandler() was * called for `this`. */ virtual size_t release() = 0; }; /** * Smart pointer type for ref counting `IObject`. It automatically controls reference count for the underlying * `IObject` pointer. */ template <class T> class ObjectPtr { public: //////////// Ctors/dtor //////////// /** * Policy directing how the smart pointer is initialized from from raw pointer. */ enum class InitPolicy { eBorrow, ///< Increases reference count. eSteal ///< Assign the pointer without increasing the reference count. }; /** * Default Constructor */ ObjectPtr() : m_object(nullptr) { } /** * Nullptr Constructor */ ObjectPtr(std::nullptr_t) : m_object(nullptr) { } /** * Constructor * @param object The raw pointer to an object. If not `nullptr`, it will be "borrowed"; that is, the reference count * will be increased as long as `*this` contains it. */ explicit ObjectPtr(T* object) : m_object(object) { if (m_object) { m_object->addRef(); } } /** * Constructor. * @param object The raw pointer to an object. * @param policy Directive on whether the reference count should be increased or not. */ ObjectPtr(T* object, InitPolicy policy) : m_object(object) { if (policy == InitPolicy::eBorrow && m_object != nullptr) { m_object->addRef(); } } /** * Copy constructor. Always increases the reference count. * @param other The smart pointer from which to copy a reference. */ ObjectPtr(const ObjectPtr<T>& other) : ObjectPtr(other.m_object, InitPolicy::eBorrow) { } /// @copydoc ObjectPtr(const ObjectPtr<T>& other) template <class U> ObjectPtr(const ObjectPtr<U>& other) : ObjectPtr(other.m_object, InitPolicy::eBorrow) { } /** * Move constructor. Steals the reference count from @p other and leaves it empty. * @param other The smart pointer from which to steal a reference. */ ObjectPtr(ObjectPtr<T>&& other) : m_object(other.m_object) { other.m_object = nullptr; } /// @copydoc ObjectPtr(ObjectPtr<T>&& other) template <class U> ObjectPtr(ObjectPtr<U>&& other) : m_object(other.m_object) { other.m_object = nullptr; } /** * Destructor. */ ~ObjectPtr() { _release(); } //////////// Helpers //////////// //////////// Ptr //////////// /** * Converts the smart pointer to a raw pointer. * @returns The raw pointer referenced by the smart pointer. May be `nullptr`. */ T* get() const { return m_object; } /** * Pointer dereference operator. * @returns The raw pointer referenced by the smart pointer. */ T* operator->() const { CARB_ASSERT(m_object); return m_object; } /** * Dereference operator. * @returns A reference to the pointed-at object. */ T& operator*() const { CARB_ASSERT(m_object); return *m_object; } /** * Boolean conversion operator. * @returns `true` if the smart pointer is not empty; `false` if the smart pointer is empty. */ explicit operator bool() const { return get() != nullptr; } //////////// Explicit access //////////// /** * Returns the address of the internal reference. * @returns The address of the internal reference. */ T* const* getAddressOf() const { return &m_object; } /// @copydoc getAddressOf() const T** getAddressOf() { return &m_object; } /** * Helper function to release any current reference and return the address of the internal reference pointer. * @returns The address of the internal reference. */ T** releaseAndGetAddressOf() { _release(); return &m_object; } /** * Resets this smart pointer to `nullptr` and returns the previously reference object @a without releasing the held * reference. * @returns The previously referenced object. */ T* detach() { T* temp = m_object; m_object = nullptr; return temp; } /** * Releases the reference on any held object and instead @a steals the given object. * @param other The object to steal a reference to. */ void attach(T* other) { _release(); m_object = other; } //////////// Assignment operator //////////// /** * Assignment to @a nullptr. Releases any previously held reference. * @returns @a *this */ ObjectPtr& operator=(decltype(nullptr)) { _release(); return *this; } /** * Releases any previously held reference and copies a reference to @p other. * @param other The object to reference. * @returns @a *this */ ObjectPtr& operator=(T* other) { ObjectPtr(other).swap(*this); return *this; } /// @copydoc operator= template <typename U> ObjectPtr& operator=(U* other) { ObjectPtr(other).swap(*this); return *this; } /// @copydoc operator= ObjectPtr& operator=(const ObjectPtr& other) { ObjectPtr(other).swap(*this); return *this; } /// @copydoc operator= template <class U> ObjectPtr& operator=(const ObjectPtr<U>& other) { ObjectPtr(other).swap(*this); return *this; } /** * Releases any previously held reference and steals the reference from @p other. * @param other The reference to steal. Will be swapped with @a *this. * @returns @a *this */ ObjectPtr& operator=(ObjectPtr&& other) { other.swap(*this); return *this; } /// @copydoc operator=(ObjectPtr&& other) template <class U> ObjectPtr& operator=(ObjectPtr<U>&& other) { ObjectPtr(std::move(other)).swap(*this); return *this; } /** * Compares equality of this object and another one of the same type. * * @param[in] other The other object to compare this one to. * @returns `true` if the two objects identify the same underlying object. Returns * `false` otherwise. */ template <class U> bool operator==(const ObjectPtr<U>& other) const { return get() == other.get(); } /** * Compares inequality of this object and another one of the same type. * * @param[in] other The other object to compare this one to. * @returns `true` if the two objects do not identify the same underlying object. Returns * `false` otherwise. */ template <class U> bool operator!=(const ObjectPtr<U>& other) const { return get() != other.get(); } /** * Swaps with another smart pointer. * @param other The smart pointer to swap with. */ void swap(ObjectPtr& other) { std::swap(m_object, other.m_object); } private: void _release() { if (T* old = std::exchange(m_object, nullptr)) { old->release(); } } T* m_object; }; /** * Helper function to create carb::ObjectPtr from a carb::IObject pointer by "stealing" the pointer; that is, without * increasing the reference count. * @param other The raw pointer to steal. * @returns A smart pointer referencing @p other. */ template <class T> inline ObjectPtr<T> stealObject(T* other) { return ObjectPtr<T>(other, ObjectPtr<T>::InitPolicy::eSteal); } /** * Helper function to create carb::ObjectPtr from a carb::IObject pointer by "borrowing" the pointer; that is, by * increasing the reference count. * @param other The raw pointer to reference. * @returns A smart pointer referencing @p other. */ template <class T> inline ObjectPtr<T> borrowObject(T* other) { return ObjectPtr<T>(other, ObjectPtr<T>::InitPolicy::eBorrow); } } // namespace carb
9,445
C
23.663185
120
0.596506
omniverse-code/kit/include/carb/SdkVersion.h
// Copyright (c) 2023-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. // // NOTE: This file is generated by 'make_version.lua' and should not be modified directly. // //! @file //! @brief Defines a macro containing the SDK version this header was built with. #pragma once //! Version string for this SDK build. This string is also returned by carbGetSdkVersion(). //! This value can be passed to @ref CARB_IS_SAME_SDK_VERSION() to verify that the loaded //! version of the Carbonite framework library matches the headers that are in use. #define CARB_SDK_VERSION "158.5+release158.tc9626.54324001"
966
C
49.894734
92
0.773292
omniverse-code/kit/include/carb/PluginInitializers.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 Utilities to ease the creation of Carbonite plugins. #pragma once #include "Defines.h" namespace carb { #ifndef DOXYGEN_BUILD namespace detail { inline bool& initialized() noexcept { static bool init = false; return init; } } // namespace detail #endif struct Framework; namespace logging { void registerLoggingForClient() noexcept; void deregisterLoggingForClient() noexcept; } // namespace logging namespace profiler { void registerProfilerForClient() noexcept; void deregisterProfilerForClient() noexcept; } // namespace profiler namespace assert { void registerAssertForClient() noexcept; void deregisterAssertForClient() noexcept; } // namespace assert namespace l10n { void registerLocalizationForClient() noexcept; void deregisterLocalizationForClient() noexcept; } // namespace l10n /** * Function called automatically at plugin startup to initialize utilities within each plugin. */ inline void pluginInitialize() { if (detail::initialized()) return; carb::detail::initialized() = true; logging::registerLoggingForClient(); profiler::registerProfilerForClient(); assert::registerAssertForClient(); l10n::registerLocalizationForClient(); } /** * Function called automatically at plugin shutdown to de-initialize utilities within each plugin. */ inline void pluginDeinitialize() { if (!detail::initialized()) return; carb::detail::initialized() = false; assert::deregisterAssertForClient(); profiler::deregisterProfilerForClient(); logging::deregisterLoggingForClient(); l10n::deregisterLocalizationForClient(); } } // namespace carb
2,084
C
24.426829
98
0.758157
omniverse-code/kit/include/carb/Defines.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 Carbonite basic defines and helper functions. #pragma once #include <cassert> #include <cinttypes> #include <climits> #include <cstdarg> #include <cstdint> #include <cstdio> #include <cstdlib> #include <csignal> #ifndef CARB_NO_MALLOC_FREE # include <cstring> #else # include <cstddef> // for size_t #endif #include <new> #include <exception> // for std::terminate #include <type_traits> #include <mutex> /** A macro to put into `#else` branches when writing platform-specific code. */ #define CARB_UNSUPPORTED_PLATFORM() static_assert(false, "Unsupported platform!") /** A macro to put into the `#else` branches when writing CPU architecture specific code. */ #define CARB_UNSUPPORTED_ARCHITECTURE() static_assert(false, "Unsupported architecture!") #ifndef CARB_DEBUG # if defined(NDEBUG) || defined(DOXYGEN_BUILD) //! A macro indicating whether the current compilation unit is built in debug mode. Always defined as either 0 or 1. Can //! be overridden by defining before this file is included or by passing on the compiler command line. Defined as `0` //! if `NDEBUG` is defined; `1` otherwise. # define CARB_DEBUG 0 # else # define CARB_DEBUG 1 # endif #endif //! A macro that can be used to indicate classes and members that participate in visualizers, such as \a carb.natvis. //! This is a reminder that these classes, members and types will require visualizer fixup if changes are made. #define CARB_VIZ #ifdef DOXYGEN_BUILD //! A macro defined as `1` if compilation is targeting Windows; `0` otherwise. Exactly one of the `CARB_PLATFORM_*` //! macros will be set to `1`. May be overridden by defining before this file is included or by passing on the compiler //! command line. By default, set to `1` if `_WIN32` is defined. # define CARB_PLATFORM_WINDOWS 0 //! A macro defined as `1` if compilation is targeting Linux; `0` otherwise. Exactly one of the `CARB_PLATFORM_*` //! macros will be set to `1`. May be overridden by defining before this file is included or by passing on the compiler //! command line. By default, set to `1` if `_WIN32` is not defined and `__linux__` is defined. # define CARB_PLATFORM_LINUX 1 //! A macro defined as `1` if compilation is targeting Mac OS; `0` otherwise. Exactly one of the `CARB_PLATFORM_*` //! macros will be set to `1`. May be overridden by defining before this file is included or by passing on the compiler //! command line. By default, set to `1` if `_WIN32` and `__linux__` are not defined and `__APPLE__` is defined. # define CARB_PLATFORM_MACOS 0 //! The name of the current platform as a string. # define CARB_PLATFORM_NAME #elif defined(CARB_PLATFORM_WINDOWS) && defined(CARB_PLATFORM_LINUX) && defined(CARB_PLATFORM_MACOS) # if (!!CARB_PLATFORM_WINDOWS) + (!!CARB_PLATFORM_LINUX) + (!!CARB_PLATFORM_MACOS) != 1 # define CARB_PLATFORM_WINDOWS // show previous definition # define CARB_PLATFORM_LINUX // show previous definition # define CARB_PLATFORM_MACOS // show previous definition # error Exactly one of CARB_PLATFORM_WINDOWS, CARB_PLATFORM_LINUX or CARB_PLATFORM_MACOS must be non-zero. # endif #elif !defined(CARB_PLATFORM_WINDOWS) && !defined(CARB_PLATFORM_LINUX) # ifdef _WIN32 # define CARB_PLATFORM_WINDOWS 1 # define CARB_PLATFORM_LINUX 0 # define CARB_PLATFORM_MACOS 0 # define CARB_PLATFORM_NAME "windows" # elif defined(__linux__) # define CARB_PLATFORM_WINDOWS 0 # define CARB_PLATFORM_LINUX 1 # define CARB_PLATFORM_MACOS 0 # define CARB_PLATFORM_NAME "linux" # elif defined(__APPLE__) # define CARB_PLATFORM_WINDOWS 0 # define CARB_PLATFORM_LINUX 0 # define CARB_PLATFORM_MACOS 1 # define CARB_PLATFORM_NAME "macos" # else CARB_UNSUPPORTED_PLATFORM(); # endif #else # error "Must define all of CARB_PLATFORM_WINDOWS, CARB_PLATFORM_LINUX and CARB_PLATFORM_MACOS or none." #endif #if CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS || defined(DOXYGEN_BUILD) # include <unistd.h> // _POSIX_VERSION comes from unistd.h /** This is set to `_POSIX_VERSION` platforms that are mostly-compliant with POSIX. * This is set to 0 on other platforms (e.g. no GNU extensions). */ # define CARB_POSIX _POSIX_VERSION #else # define CARB_POSIX 0 #endif #ifndef DOXYGEN_SHOULD_SKIP_THIS # if CARB_PLATFORM_WINDOWS # ifndef CARB_NO_MALLOC_FREE # include "malloc.h" # endif # include <intrin.h> # elif CARB_PLATFORM_LINUX # include <alloca.h> # include <signal.h> # define _alloca alloca # endif #endif // Architecture defines #ifdef DOXYGEN_BUILD //! A macro defined as `1` if compilation is targeting the AArch64 platform; `0` otherwise. May not be overridden on the //! command line or by defining before including this file. Set to `1` if `__aarch64__` is defined, `0` if `__x86_64__` //! or `_M_X64` are defined, and left undefined otherwise. # define CARB_AARCH64 0 //! A macro defined as `1` if compilation is targeting the x86-64 platform; `0` otherwise. May not be overridden on the //! command line or by defining before including this file. Set to `0` if `__aarch64__` is defined, `1` if `__x86_64__` //! or `_M_X64` are defined, and left undefined otherwise. # define CARB_X86_64 1 //! The name of the current architecture as a string. # define CARB_ARCH_NAME #elif defined(__aarch64__) # define CARB_AARCH64 1 # define CARB_X86_64 0 #elif defined(__x86_64__) /*GCC*/ || defined(_M_X64) /*MSVC*/ # define CARB_X86_64 1 # define CARB_AARCH64 0 #endif #if CARB_PLATFORM_MACOS # define CARB_ARCH_NAME "universal" #else # if CARB_X86_64 # define CARB_ARCH_NAME "x86_64" # elif CARB_AARCH64 # define CARB_ARCH_NAME "aarch64" # endif #endif #ifndef CARB_PROFILING //! When set to a non-zero value, profiling macros in \a include/carb/profiler/Profile.h will report to the profiler; //! otherwise the profiling macros have no effect. Always set to `1` by default, but may be overridden by defining a //! different value before including this file or by specifying a different value on the compiler command line. # define CARB_PROFILING 1 #endif #ifdef DOXYGEN_BUILD //! A macro defined as `1` if compilation is targeting the Tegra platform. By default set to `1` only if `__aarch64__` //! and `__LINARO_RELEASE__` are defined; `0` otherwise. May be overridden by defining a different value before //! including this file or by specifying a different value on the compiler command line. # define CARB_TEGRA 0 #elif !defined(CARB_TEGRA) # if defined(__aarch64__) && defined(__LINARO_RELEASE__) # define CARB_TEGRA 1 # else # define CARB_TEGRA 0 # endif #endif #ifdef DOXYGEN_BUILD //! A macro defined as `1` if compilation is using Microsoft Visual C++, that is, if `_MSC_VER` is defined. May be //! overridden by defining a different value before including this file or by specifying a different value on the //! compiler command line, however, only one of `CARB_COMPILER_MSC` and `CARB_COMPILER_GNUC` must be set to `1`; the //! other macro(s) must be set to `0`. # define CARB_COMPILER_MSC 0 //! A macro defined as `1` if compilation is using GNU C Compiler (GCC), that is, if `_MSC_VER` is not defined but //! `__GNUC__` is defined. May be overridden by defining a different value before including this file or by specifying a //! different value on the compiler command line, however, only one of `CARB_COMPILER_MSC` and `CARB_COMPILER_GNUC` must //! be set to `1`; the other macro(s) must be set to `0`. # define CARB_COMPILER_GNUC 1 #elif defined(CARB_COMPILER_MSC) && defined(CARB_COMPILER_GNUC) # if (!!CARB_COMPILER_MSC) + (!!CARB_COMPILER_GNUC) != 1 # define CARB_COMPILER_MSC // Show previous definition # define CARB_COMPILER_GNUC // Show previous definition # error Exactly one of CARB_COMPILER_MSC or CARB_COMPILER_GNUC must be non-zero. # endif #elif !defined(CARB_COMPILER_MSC) && !defined(CARB_COMPILER_GNUC) # ifndef CARB_COMPILER_MSC # if defined(_MSC_VER) # define CARB_COMPILER_MSC 1 # define CARB_COMPILER_GNUC 0 # elif defined(__GNUC__) # define CARB_COMPILER_MSC 0 # define CARB_COMPILER_GNUC 1 # else # error "Unsupported compiler." # endif # endif #else # error "Must define CARB_COMPILER_MSC and CARB_COMPILER_GNUC or neither." #endif #ifdef DOXYGEN_BUILD //! A macro defined as `1` if a Clang-infrastructure toolchain is building the current file, that is, if `__clang__` is //! defined; `0` if not. May be overridden by defining a different value before including this file or by specifying a //! different value on the compiler command line. //! @note It is legal to have \ref CARB_COMPILER_MSC and \ref CARB_TOOLCHAIN_CLANG both as `1` simultaneously, which //! represents a Clang-infrastructure toolchain running in Microsoft compatibility mode. # define CARB_TOOLCHAIN_CLANG 0 #elif !defined(CARB_TOOLCHAIN_CLANG) # if defined(__clang__) # define CARB_TOOLCHAIN_CLANG 1 # else # define CARB_TOOLCHAIN_CLANG 0 # endif #endif #ifdef DOXYGEN_BUILD //! A macro defined as `1` if the toolchain is building the current file with `-fsanitize=address`, that is, if //! `__SANITIZE_ADDRESS__` is defined; `0` otherwise. May be overridden by defining a different value before including //! this file or by specifying a different value on the compiler command line. Microsoft Visual Studio supports address //! sanitizer starting with 2019 (v16.9) by specifying `/fsanitize=address` on the compiler command line. //! See https://learn.microsoft.com/en-us/cpp/sanitizers/asan?view=msvc-160 # define CARB_ASAN_ENABLED 0 #elif !defined(CARB_ASAN_ENABLED) # ifdef __SANITIZE_ADDRESS__ # define CARB_ASAN_ENABLED __SANITIZE_ADDRESS__ # else # define CARB_ASAN_ENABLED 0 # endif #endif //! De-parenthesize the contents of \c pack_. `CARB_DEPAREN((x, y))` becomes `x, y`. An unparenthesized pack will cause //! cause a compilation failure; e.g.: `CARB_DEPAREN(foo)` will not work, but `CARB_DEPAREN((foo))` will. #define CARB_DEPAREN(pack_) CARB_IDENTITY pack_ //! Return exactly the arguments. This is useful for expansion of the tokens. #define CARB_IDENTITY(...) __VA_ARGS__ // Compiler specific defines. Exist for all supported compilers but may be a no-op for certain compilers. #ifdef DOXYGEN_BUILD //! Acts as a `char[]` with the current full function signature. # define CARB_PRETTY_FUNCTION "<function signature here>" //! GCC only, defined as `__attribute__((__VA_ARGS__))`; ignored on non-GCC compilers. # define CARB_ATTRIBUTE(...) //! MSVC only, defined as `__declspec(__VA_ARGS__)`; ignored on non-MSVC compilers. # define CARB_DECLSPEC(...) //! MSVC only, defined as `__VA_ARGS__`; ignored on non-MSVC compilers. # define CARB_MSC_ONLY(...) //! Only non-MSVC compilers, defined as `__VA_ARGS__`; ignored on MSVC. # define CARB_NOT_MSC(...) //! GCC only, defined as `gnuc_only_block`; ignored on non-GCC compilers. # define CARB_GNUC_ONLY(...) //! Only non-GCC compilers, defined as `__VA_ARGS__`; ignored on GCC. # define CARB_NOT_GNUC(...) //! Generic pragma, only to be used for pragmas that are the same on all supported compilers. //! @see CARB_PRAGMA_MSC //! @see CARB_PRAGMA_GNUC # define CARB_PRAGMA(...) //! MSVC only, defined as `__pragma(__VA_ARGS__)`; ignored on non-MSVC compilers. # define CARB_PRAGMA_MSC(...) //! GCC only, defined as `_Pragma(__VA_ARGS__)`; ignored on non-GCC compilers. # define CARB_PRAGMA_GNUC(...) //! Macro to work around Exhale tripping over `constexpr` sometimes and reporting things like: //! `Invalid C++ declaration: Expected identifier in nested name, got keyword: static` # define CARB_DOC_CONSTEXPR const //! Indicates whether exceptions are enabled for the current compilation unit. Value depends on parameters passed to the //! compiler. # define CARB_EXCEPTIONS_ENABLED 1 //! Conditionally includes text only when documenting (i.e. when `DOXYGEN_BUILD` is defined). //! @param ... The text to include if documenting # define CARB_DOC_ONLY(...) __VA_ARGS__ //! Declares a value or statement in a way that prevents Doxygen and Sphinx from getting confused //! about matching symbols. There seems to be a bug in Sphinx that prevents at least templated //! symbols from being matched to the ones generated by Doxygen when keywords such as `decltype` //! are used. This is effectively the opposite operation as CARB_DOC_ONLY(). # define CARB_NO_DOC(...) #else # define CARB_DOC_CONSTEXPR constexpr # define CARB_DOC_ONLY(...) # define CARB_NO_DOC(...) __VA_ARGS__ # if CARB_COMPILER_MSC # define CARB_PRETTY_FUNCTION __FUNCSIG__ # define CARB_ATTRIBUTE(...) # define CARB_MSC_ONLY(...) __VA_ARGS__ # define CARB_NOT_MSC(...) # define CARB_GNUC_ONLY(...) # define CARB_NOT_GNUC(...) __VA_ARGS__ # define CARB_PRAGMA(...) __pragma(__VA_ARGS__) # define CARB_DECLSPEC(...) __declspec(__VA_ARGS__) # define CARB_PRAGMA_MSC(...) CARB_PRAGMA(__VA_ARGS__) # define CARB_PRAGMA_GNUC(...) # ifdef __cpp_exceptions # define CARB_EXCEPTIONS_ENABLED 1 # else # define CARB_EXCEPTIONS_ENABLED 0 # endif // Other MSC-specific definitions that must exist outside of the carb namespace extern "C" void _mm_prefetch(char const* _A, int _Sel); // From winnt.h/intrin.h # if defined(__INTELLISENSE__) && _MSC_VER < 1920 // See: https://stackoverflow.com/questions/61485127/including-windows-h-causes-unknown-attributeno-init-all-error # define no_init_all deprecated # endif # elif CARB_COMPILER_GNUC # define CARB_PRETTY_FUNCTION __PRETTY_FUNCTION__ # define CARB_ATTRIBUTE(...) __attribute__((__VA_ARGS__)) # define CARB_DECLSPEC(...) # define CARB_MSC_ONLY(...) # define CARB_NOT_MSC(...) __VA_ARGS__ # define CARB_GNUC_ONLY(...) __VA_ARGS__ # define CARB_NOT_GNUC(...) # define CARB_PRAGMA(...) _Pragma(__VA_ARGS__) # define CARB_PRAGMA_MSC(...) # define CARB_PRAGMA_GNUC(...) CARB_PRAGMA(__VA_ARGS__) # ifdef __EXCEPTIONS # define CARB_EXCEPTIONS_ENABLED 1 # else # define CARB_EXCEPTIONS_ENABLED 0 # endif # else # error Unsupported compiler # endif #endif #if defined(DOXYGEN_BUILD) || defined(OMNI_BIND) //! Turns optimizations off at the function level until a CARB_OPTIMIZE_ON_MSC() call is seen. //! This must be called outside of the body of any function and will remain in effect until //! either a CARB_OPTIMIZE_ON_MSC() call is seen or the end of the translation unit. This //! unfortunately needs to be a separate set of macros versus the one for GCC and Clang due //! to the different style of disabling and enabling optimizations under the MSC compiler. # define CARB_OPTIMIZE_OFF_MSC() //! Restores previous optimizations that were temporarily disable due to an earlier call to //! CARB_OPTIMIZE_OFF_MSC(). This must be called outside the body of any function. If this //! call is not made, the previous optimization state will remain until the end of the current //! translation unit. # define CARB_OPTIMIZE_ON_MSC() //! Disables optimizations for the function that is tagged with this attribute. This only //! affects the single function that it tags. Optimizations will be restored to the previous //! settings for the translation unit outside of the tagged function. # define CARB_NO_OPTIMIZE_GNUC_CLANG() #else # if CARB_COMPILER_MSC # define CARB_OPTIMIZE_OFF_MSC() CARB_PRAGMA_MSC(optimize("", off)) # define CARB_OPTIMIZE_ON_MSC() CARB_PRAGMA_MSC(optimize("", on)) # define CARB_NO_OPTIMIZE_GNUC_CLANG() # elif CARB_TOOLCHAIN_CLANG # define CARB_NO_OPTIMIZE_GNUC_CLANG() CARB_ATTRIBUTE(optnone) # define CARB_OPTIMIZE_OFF_MSC() # define CARB_OPTIMIZE_ON_MSC() # elif CARB_COMPILER_GNUC # define CARB_NO_OPTIMIZE_GNUC_CLANG() CARB_ATTRIBUTE(optimize("-O0")) # define CARB_OPTIMIZE_OFF_MSC() # define CARB_OPTIMIZE_ON_MSC() # else # error Unsupported compiler # endif #endif // MSC-specific warning macros are defined only for MSC // CARB_IGNOREWARNING_MSC_PUSH: MSVC only; pushes the warning state // CARB_IGNOREWARNING_MSC_POP: MSVC only; pops the warning state // CARB_IGNOREWARNING_MSC(w): MSVC only; disables the given warning number (ex: CARB_IGNOREWARNING_MSC(4505)) // CARB_IGNOREWARNING_MSC_WITH_PUSH(w): MSVC only; combines CARB_IGNOREWARNING_MSC_PUSH and CARB_IGNOREWARNING_MSC() #if !defined(DOXYGEN_BUILD) && CARB_COMPILER_MSC # define CARB_IGNOREWARNING_MSC_PUSH __pragma(warning(push)) # define CARB_IGNOREWARNING_MSC_POP __pragma(warning(pop)) # define CARB_IGNOREWARNING_MSC(w) __pragma(warning(disable : w)) # define CARB_IGNOREWARNING_MSC_WITH_PUSH(w) \ CARB_IGNOREWARNING_MSC_PUSH \ CARB_IGNOREWARNING_MSC(w) #else //! For MSVC only, pushes the current compilation warning configuration. Defined as `__pragma(warning(push))` for MSVC //! only; ignored by other compilers. # define CARB_IGNOREWARNING_MSC_PUSH //! For MSVC only, pops the compilation warning configuration previously pushed with \ref CARB_IGNOREWARNING_MSC_PUSH, //! overwriting the current state. Defined as `__pragma(warning(pop))` for MSVC only; ignored by other compilers. # define CARB_IGNOREWARNING_MSC_POP //! For MSVC only, disables a specific compiler warning for the current compilation warning configuration. Defined as //! `__pragma(warning(disable : <w>))` for MSVC only; ignored by other compilers. //! @param w The warning number to disable. # define CARB_IGNOREWARNING_MSC(w) //! Syntactic sugar for \ref CARB_IGNOREWARNING_MSC_PUSH followed by \ref CARB_IGNOREWARNING_MSC. //! @param w The warning number to disable. # define CARB_IGNOREWARNING_MSC_WITH_PUSH(w) #endif // GNUC-specific helper macros are defined for GCC and Clang-infrastructure // CARB_IGNOREWARNING_GNUC_PUSH: GCC only; pushes the warning state // CARB_IGNOREWARNING_GNUC_POP: GCC only; pops the warning state // CARB_IGNOREWARNING_CLANG_PUSH: Clang only; pushes the warning state // CARB_IGNOREWARNING_CLANG_POP: Clang only; pops the warning state // CARB_IGNOREWARNING_GNUC(w): GCC only; disables the given warning (ex: CARB_IGNOREWARNING_GNUC("-Wattributes")) // CARB_IGNOREWARNING_GNUC_WITH_PUSH(w): GCC only; combines CARB_IGNOREWARNING_GNUC_PUSH and CARB_IGNOREWARNING_GNUC() // CARB_IGNOREWARNING_CLANG(w): Clang only; disables the given warning (ex: CARB_IGNOREWARNING_CLANG("-Wattributes")) // CARB_IGNOREWARNING_CLANG_WITH_PUSH(w): Clang only; combines CARB_IGNOREWARNING_CLANG_PUSH and // CARB_IGNOREWARNING_CLANG() #if !defined(DOXYGEN_BUILD) && (CARB_COMPILER_GNUC || CARB_TOOLCHAIN_CLANG) # define CARB_IGNOREWARNING_GNUC_PUSH _Pragma("GCC diagnostic push") # define CARB_IGNOREWARNING_GNUC_POP _Pragma("GCC diagnostic pop") # define INTERNAL_CARB_IGNOREWARNING_GNUC(str) _Pragma(# str) # define CARB_IGNOREWARNING_GNUC(w) INTERNAL_CARB_IGNOREWARNING_GNUC(GCC diagnostic ignored w) # define CARB_IGNOREWARNING_GNUC_WITH_PUSH(w) CARB_IGNOREWARNING_GNUC_PUSH CARB_IGNOREWARNING_GNUC(w) # if CARB_TOOLCHAIN_CLANG # define CARB_IGNOREWARNING_CLANG_PUSH _Pragma("GCC diagnostic push") # define CARB_IGNOREWARNING_CLANG_POP _Pragma("GCC diagnostic pop") # define INTERNAL_CARB_IGNOREWARNING_CLANG(str) _Pragma(# str) # define CARB_IGNOREWARNING_CLANG(w) INTERNAL_CARB_IGNOREWARNING_CLANG(GCC diagnostic ignored w) # define CARB_IGNOREWARNING_CLANG_WITH_PUSH(w) CARB_IGNOREWARNING_CLANG_PUSH CARB_IGNOREWARNING_CLANG(w) # else # define CARB_IGNOREWARNING_CLANG_PUSH # define CARB_IGNOREWARNING_CLANG_POP # define CARB_IGNOREWARNING_CLANG(w) # define CARB_IGNOREWARNING_CLANG_WITH_PUSH(w) # endif #else //! For GCC only, pushes the current compilation warning configuration. Defined as `_Pragma("GCC diagnostic push")` for //! GCC only; ignored by other compilers. # define CARB_IGNOREWARNING_GNUC_PUSH //! For GCC only, pops the compilation warning configuration previously pushed with \ref CARB_IGNOREWARNING_GNUC_PUSH, //! overwriting the current state. Defined as `_Pragma("GCC diagnostic pop")` for GCC only; ignored by other compilers. # define CARB_IGNOREWARNING_GNUC_POP //! For Clang only, pushes the current compilation warning configuration. Defined as `_Pragma("GCC diagnostic push")` //! for Clang only; ignored by other compilers. # define CARB_IGNOREWARNING_CLANG_PUSH //! For Clang only, pops the compilation warning configuration previously pushed with \ref //! CARB_IGNOREWARNING_CLANG_PUSH, overwriting the current state. Defined as `_Pragma("GCC diagnostic pop")` for Clang //! only; ignored by other compilers. # define CARB_IGNOREWARNING_CLANG_POP //! For GCC only, disables a specific compiler warning for the current compilation warning configuration. Defined as //! `_Pragma("GCC diagnostic ignored <warning>")` for GCC only; ignored by other compilers. //! @param w The warning to disable, example: `"-Wattributes"` (note that quotes must be specified) # define CARB_IGNOREWARNING_GNUC(w) //! Syntactic sugar for \ref CARB_IGNOREWARNING_GNUC_PUSH followed by \ref CARB_IGNOREWARNING_GNUC. //! @param w The warning to disable, example: `"-Wattributes"` (note that quotes must be specified) # define CARB_IGNOREWARNING_GNUC_WITH_PUSH(w) //! For Clang only, disables a specific compiler warning for the current compilation warning configuration. Defined as //! `_Pragma("GCC diagnostic ignored <warning>")` for Clang only; ignored by other compilers. //! @param w The warning to disable, example: `"-Wattributes"` (note that quotes must be specified) # define CARB_IGNOREWARNING_CLANG(w) //! Syntactic sugar for \ref CARB_IGNOREWARNING_CLANG_PUSH followed by \ref CARB_IGNOREWARNING_CLANG. //! @param w The warning to disable, example: `"-Wattributes"` (note that quotes must be specified) # define CARB_IGNOREWARNING_CLANG_WITH_PUSH(w) #endif #if defined(__cplusplus) || defined(DOXYGEN_BUILD) //! Defined as `extern "C"` for C++ compilation, that is, when `__cplusplus` is defined; empty define otherwise. # define CARB_EXTERN_C extern "C" #else # define CARB_EXTERN_C #endif //! Grants a function external linkage in a dynamic library or executable. //! //! On MSVC, `extern "C" __declspec(dllexport)`. On GCC/Clang: `extern "C" __attribute__((visibility("default")))`. //! //! This macro is always defined as such. If conditional import/export is desired, use \ref CARB_DYNAMICLINK. #define CARB_EXPORT CARB_EXTERN_C CARB_DECLSPEC(dllexport) CARB_ATTRIBUTE(visibility("default")) //! Imports a function with external linkage from a shared object or DLL. //! //! On all compilers: `extern "C"` //! //! \note on Windows platforms we do not use `__declspec(dllimport)` as it is <a //! href="https://learn.microsoft.com/en-us/cpp/build/importing-into-an-application-using-declspec-dllimport?view=msvc-160">optional</a> //! and can lead to linker warning <a //! href="https://learn.microsoft.com/en-us/cpp/error-messages/tool-errors/linker-tools-warning-lnk4217?view=msvc-160">LNK4217</a>. #define CARB_IMPORT CARB_EXTERN_C // For documentation only #ifdef DOXYGEN_BUILD //! Instructs CARB_DYNAMICLINK to export instead of import //! //! \warning This symbol is not defined anywhere; it is up to the user of \ref CARB_DYNAMICLINK to define this in the //! compilation unit that exports the symbols. **This must be defined before carb/Defines.h is included.** //! //! \see CARB_DYNAMICLINK # define CARB_EXPORTS #endif #if defined(CARB_EXPORTS) || defined(DOXYGEN_BUILD) //! Conditional (import/export) dynamic linking. //! //! If and only if \ref CARB_EXPORTS is defined before including this file, this will match \ref CARB_EXPORT and //! function as granting a function external linkage. If `CARB_EXPORTS` is not defined, this functions as merely //! declaring the function as `extern "C"` so that it can be imported. # define CARB_DYNAMICLINK CARB_EXPORT #else # define CARB_DYNAMICLINK CARB_IMPORT #endif #if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD) //! Defined as `__cdecl` on Windows and an empty define on Linux. Used to explicitly state ABI calling convention for //! API functions. # define CARB_ABI __cdecl #else # define CARB_ABI #endif #if (defined(__cplusplus) && __cplusplus >= 201400L) || defined(DOXYGEN_BUILD) //! Defined as `1` if the current compiler supports C++14; `0` otherwise. C++14 is the minimum required for using //! Carbonite (though building Carbonite requires C++17). # define CARB_HAS_CPP14 1 #else # define CARB_HAS_CPP14 0 #endif #if (defined(__cplusplus) && __cplusplus >= 201700L) || defined(DOXYGEN_BUILD) //! Defined as `1` if the current compiler supports C++17; `0` otherwise. # define CARB_HAS_CPP17 1 #else # define CARB_HAS_CPP17 0 #endif #if (defined(__cplusplus) && __cplusplus >= 202000L) || defined(DOXYGEN_BUILD) //! Defined as `1` if the current compiler supports C++20; `0` otherwise. # define CARB_HAS_CPP20 1 #else # define CARB_HAS_CPP20 0 #endif // [[nodiscard]] #if CARB_HAS_CPP17 || defined(DOXYGEN_BUILD) //! Defined as `[[nodiscard]]` if the current compiler supports C++17. This reverts to \c warn_unused_result attribute //! where it is available and will be empty if it is not. # define CARB_NODISCARD [[nodiscard]] //! Defined as `[[nodiscard]]` if the current compiler supports C++17 and is empty otherwise. This operates similar to //! \c CARB_NODISCARD but is meant to be used on type definitions, as the \c warn_unused_result fallback is not //! supported for types. # define CARB_NODISCARD_TYPE [[nodiscard]] #elif CARB_COMPILER_GNUC # define CARB_NODISCARD __attribute__((warn_unused_result)) # define CARB_NODISCARD_TYPE #else // not supported # define CARB_NODISCARD # define CARB_NODISCARD_TYPE #endif // [[nodiscard(msg)]] #if CARB_HAS_CPP20 || defined(DOXYGEN_BUILD) //! Defined as `[[nodiscard(msg)]]` if the current compiler supports C++20; falls back to \c CARB_NODISCARD without the //! message pre-C++20. # define CARB_NODISCARD_MSG(msg) [[nodiscard(msg)]] //! Defined as `[[nodiscard(msg)]]` if the current compiler supports C++20; falls back to \c CARB_NODISCARD_TYPE without //! the message pre-C++20. # define CARB_NODISCARD_TYPE_MSG(msg) [[nodiscard(msg)]] #else # define CARB_NODISCARD_MSG(msg) CARB_NODISCARD # define CARB_NODISCARD_TYPE_MSG(msg) CARB_NODISCARD_TYPE #endif // [[fallthrough]] #if CARB_HAS_CPP17 || defined(DOXYGEN_BUILD) //! Defined as `[[fallthrough]]` if the current compiler supports C++17; empty otherwise. # define CARB_FALLTHROUGH [[fallthrough]] #elif CARB_COMPILER_GNUC # if __GNUC__ >= 7 # define CARB_FALLTHROUGH __attribute__((fallthrough)) # else // Marker comment # define CARB_FALLTHROUGH /* fall through */ # endif #else // not supported # define CARB_FALLTHROUGH #endif // [[maybe_unused]] #if CARB_HAS_CPP17 && !defined(DOXYGEN_BUILD) # define CARB_MAYBE_UNUSED [[maybe_unused]] # define CARB_CPP17_CONSTEXPR constexpr #elif CARB_COMPILER_GNUC && !defined(DOXYGEN_BUILD) # define CARB_MAYBE_UNUSED __attribute__((unused)) # define CARB_CPP17_CONSTEXPR #else // not supported //! Defined as `[[maybe_unused]]` if the current compiler supports C++17; empty otherwise. # define CARB_MAYBE_UNUSED //! Defined as `constexpr` if the current compiler supports C++17; empty otherwise. # define CARB_CPP17_CONSTEXPR #endif // [[likely]] / [[unlikely]] #if CARB_HAS_CPP20 || defined(DOXYGEN_BUILD) //! Defined as `([[likely]] !!(<expr>))` if the current compiler supports C++20. If the current compiler is GCC, as a //! fallback, `__builtin_expect(!!(<expr>), 1)` will be used. Otherwise, defined as `(!!(<expr>))` //! @param expr The expression to evaluate, optimized with a `true` outcome likely and expected. //! @returns The boolean result of \p expr. # define CARB_LIKELY(expr) ([[likely]] !!(expr)) //! Defined as `([[unlikely]] !!(<expr>))` if the current compiler supports C++20. If the current compiler is GCC, as a //! fallback, `__builtin_expect(!!(<expr>), 0)` will be used. Otherwise, defined as `(!!(<expr>))` //! @param expr The expression to evaluate, optimized with a `false` outcome likely and expected. //! @returns The boolean result of \p expr. # define CARB_UNLIKELY(expr) ([[unlikely]] !!(expr)) #elif CARB_COMPILER_GNUC # define CARB_LIKELY(expr) __builtin_expect(!!(expr), 1) # define CARB_UNLIKELY(expr) __builtin_expect(!!(expr), 0) #else // not supported # define CARB_LIKELY(expr) (!!(expr)) # define CARB_UNLIKELY(expr) (!!(expr)) #endif // [[no_unique_address]] #if CARB_HAS_CPP20 || defined(DOXYGEN_BUILD) //! Defined as `[[no_unique_address]]` if the current compiler supports C++20; empty otherwise. # define CARB_NO_UNIQUE_ADDRESS [[no_unique_address]] #else // not supported # define CARB_NO_UNIQUE_ADDRESS #endif //! Syntactic sugar for `CARB_ATTRIBUTE(visibility("hidden"))`; ignored on compilers other than GCC. #define CARB_HIDDEN CARB_ATTRIBUTE(visibility("hidden")) //! Syntactic sugar for `CARB_DECLSPEC(selectany) CARB_ATTRIBUTE(weak)`, used to enable weak linking. #define CARB_WEAKLINK CARB_DECLSPEC(selectany) CARB_ATTRIBUTE(weak) // constexpr in CPP20, but not before #if CARB_HAS_CPP20 || defined(DOXYGEN_BUILD) //! Defined as `constexpr` if the current compiler supports C++20; empty otherwise. # define CARB_CPP20_CONSTEXPR constexpr #else # define CARB_CPP20_CONSTEXPR #endif // include the IAssert interface here. Note that this cannot be included any earlier because // it requires symbols such as "CARB_ABI". Also note that it cannot be put into the CARB_DEBUG // section below because the mirroring tool picks it up and generates type information for it. // If it is not unconditionally included here, that leads to build errors in release builds. #include "assert/IAssert.h" #ifdef DOXYGEN_BUILD //! On Windows platforms, defined as `__debugbreak()`; on Linux, `raise(SIGTRAP)`. Used to break into the debugger. # define CARB_BREAK_POINT() #elif CARB_POSIX # define CARB_BREAK_POINT() ::raise(SIGTRAP) #elif CARB_PLATFORM_WINDOWS # define CARB_BREAK_POINT() ::__debugbreak() #else CARB_UNSUPPORTED_PLATFORM(); #endif namespace carb { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { // clang-format off #define C(a) (unsigned char)(0x##a) constexpr unsigned char lowerTable[256] = { C(00), C(01), C(02), C(03), C(04), C(05), C(06), C(07), C(08), C(09), C(0A), C(0B), C(0C), C(0D), C(0E), C(0F), C(10), C(11), C(12), C(13), C(14), C(15), C(16), C(17), C(18), C(19), C(1A), C(1B), C(1C), C(1D), C(1E), C(1F), C(20), C(21), C(22), C(23), C(24), C(25), C(26), C(27), C(28), C(29), C(2A), C(2B), C(2C), C(2D), C(2E), C(2F), C(30), C(31), C(32), C(33), C(34), C(35), C(36), C(37), C(38), C(39), C(3A), C(3B), C(3C), C(3D), C(3E), C(3F), C(40), // [0x41, 0x5A] -> [0x61, 0x7A] C(61), C(62), C(63), C(64), C(65), C(66), C(67), C(68), C(69), C(6A), C(6B), C(6C), C(6D), C(6E), C(6F), C(70), C(71), C(72), C(73), C(74), C(75), C(76), C(77), C(78), C(79), C(7A), C(5B), C(5C), C(5D), C(5E), C(5F), C(60), C(61), C(62), C(63), C(64), C(65), C(66), C(67), C(68), C(69), C(6A), C(6B), C(6C), C(6D), C(6E), C(6F), C(70), C(71), C(72), C(73), C(74), C(75), C(76), C(77), C(78), C(79), C(7A), C(7B), C(7C), C(7D), C(7E), C(7F), C(80), C(81), C(82), C(83), C(84), C(85), C(86), C(87), C(88), C(89), C(8A), C(8B), C(8C), C(8D), C(8E), C(8F), C(90), C(91), C(92), C(93), C(94), C(95), C(96), C(97), C(98), C(99), C(9A), C(9B), C(9C), C(9D), C(9E), C(9F), C(A0), C(A1), C(A2), C(A3), C(A4), C(A5), C(A6), C(A7), C(A8), C(A9), C(AA), C(AB), C(AC), C(AD), C(AE), C(AF), C(B0), C(B1), C(B2), C(B3), C(B4), C(B5), C(B6), C(B7), C(B8), C(B9), C(BA), C(BB), C(BC), C(BD), C(BE), C(BF), C(C0), C(C1), C(C2), C(C3), C(C4), C(C5), C(C6), C(C7), C(C8), C(C9), C(CA), C(CB), C(CC), C(CD), C(CE), C(CF), C(D0), C(D1), C(D2), C(D3), C(D4), C(D5), C(D6), C(D7), C(D8), C(D9), C(DA), C(DB), C(DC), C(DD), C(DE), C(DF), C(E0), C(E1), C(E2), C(E3), C(E4), C(E5), C(E6), C(E7), C(E8), C(E9), C(EA), C(EB), C(EC), C(ED), C(EE), C(EF), C(F0), C(F1), C(F2), C(F3), C(F4), C(F5), C(F6), C(F7), C(F8), C(F9), C(FA), C(FB), C(FC), C(FD), C(FE), C(FF), }; constexpr unsigned char upperTable[256] = { C(00), C(01), C(02), C(03), C(04), C(05), C(06), C(07), C(08), C(09), C(0A), C(0B), C(0C), C(0D), C(0E), C(0F), C(10), C(11), C(12), C(13), C(14), C(15), C(16), C(17), C(18), C(19), C(1A), C(1B), C(1C), C(1D), C(1E), C(1F), C(20), C(21), C(22), C(23), C(24), C(25), C(26), C(27), C(28), C(29), C(2A), C(2B), C(2C), C(2D), C(2E), C(2F), C(30), C(31), C(32), C(33), C(34), C(35), C(36), C(37), C(38), C(39), C(3A), C(3B), C(3C), C(3D), C(3E), C(3F), C(40), C(41), C(42), C(43), C(44), C(45), C(46), C(47), C(48), C(49), C(4A), C(4B), C(4C), C(4D), C(4E), C(4F), C(50), C(51), C(52), C(53), C(54), C(55), C(56), C(57), C(58), C(59), C(5A), C(5B), C(5C), C(5D), C(5E), C(5F), C(60), // [0x61, 0x7A] -> [0x41, 0x5A] C(41), C(42), C(43), C(44), C(45), C(46), C(47), C(48), C(49), C(4A), C(4B), C(4C), C(4D), C(4E), C(4F), C(50), C(51), C(52), C(53), C(54), C(55), C(56), C(57), C(58), C(59), C(5A), C(7B), C(7C), C(7D), C(7E), C(7F), C(80), C(81), C(82), C(83), C(84), C(85), C(86), C(87), C(88), C(89), C(8A), C(8B), C(8C), C(8D), C(8E), C(8F), C(90), C(91), C(92), C(93), C(94), C(95), C(96), C(97), C(98), C(99), C(9A), C(9B), C(9C), C(9D), C(9E), C(9F), C(A0), C(A1), C(A2), C(A3), C(A4), C(A5), C(A6), C(A7), C(A8), C(A9), C(AA), C(AB), C(AC), C(AD), C(AE), C(AF), C(B0), C(B1), C(B2), C(B3), C(B4), C(B5), C(B6), C(B7), C(B8), C(B9), C(BA), C(BB), C(BC), C(BD), C(BE), C(BF), C(C0), C(C1), C(C2), C(C3), C(C4), C(C5), C(C6), C(C7), C(C8), C(C9), C(CA), C(CB), C(CC), C(CD), C(CE), C(CF), C(D0), C(D1), C(D2), C(D3), C(D4), C(D5), C(D6), C(D7), C(D8), C(D9), C(DA), C(DB), C(DC), C(DD), C(DE), C(DF), C(E0), C(E1), C(E2), C(E3), C(E4), C(E5), C(E6), C(E7), C(E8), C(E9), C(EA), C(EB), C(EC), C(ED), C(EE), C(EF), C(F0), C(F1), C(F2), C(F3), C(F4), C(F5), C(F6), C(F7), C(F8), C(F9), C(FA), C(FB), C(FC), C(FD), C(FE), C(FF), }; #undef C // clang-format on } // namespace detail #endif /** * Assertion handler helper function. Do not call directly. Used by CARB_CHECK and CARB_ASSERT if the * `IAssert` interface is not available (i.e. the Framework is not instantiated). This function prints an "Assertion * failed" message to `stderr` by default. * * @param condition The condition from an assert in progress. * @param file The source file location from an assert in progress. * @param func The source file function name from an assert in progress. * @param line The source file line from an assert in progress. * @param fmt A `printf`-style format specifier string for the assert in progress. * @param ... Arguments corresponding to format specifiers in \p fmt. * @returns \c true if the software breakpoint should be triggered; \c false if a software breakpoint should be skipped. */ inline bool assertHandlerFallback( const char* condition, const char* file, const char* func, int32_t line, const char* fmt = nullptr, ...) { static std::mutex m; std::lock_guard<std::mutex> g(m); if (fmt != nullptr) { fprintf(stderr, "%s:%s():%" PRId32 ": Assertion (%s) failed: ", file, func, line, condition); va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fputc('\n', stderr); } else fprintf(stderr, "%s:%" PRId32 ":%s(): Assertion (%s) failed.\n", file, line, func, condition); return true; } } // namespace carb #ifdef DOXYGEN_BUILD //! Indicates whether asserts are enabled. May be overridden by defining this before including this file. By default, is //! set to `1` if `CARB_DEBUG` is non-zero. If this is overridden to a non-zero value and `CARB_ASSERT` is not defined, //! `CARB_ASSERT` will receive the default implementation. # define CARB_ASSERT_ENABLED 0 //! Indicates whether runtime checking is enabled. May be overridden by defining this before including this file. By //! default, is set to `1` always. If this is overridden to a non-zero value and `CARB_CHECK` is not defined, //! `CARB_CHECK` will receive the default implementation. # define CARB_CHECK_ENABLED 0 //! Optionally performs an assertion, by default for debug builds only. //! @warning The \p cond should have no side effects! Asserts can be disabled which will cause \p cond to not be //! evaluated. //! @note The \ref CARB_ASSERT_ENABLED define can be used to determine if asserts are enabled, or to cause them to be //! enabled or disabled by defining it before including this file. //! //! The implementation can be overridden on the command line, or by defining to a different implementation before //! including this file. //! //! When \p cond produces a `false` result, the failure is reported to the `g_carbAssert` assertion handler, or if that //! global variable is `nullptr`, calls \ref carb::assertHandlerFallback(). Depending on the result from that function //! call, execution is allowed to continue, or `CARB_BREAK_POINT()` is invoked to notify the debugger. //! @param cond A condition that is evaluated for a boolean result. If the condition produces \c false, the assert //! handler is notified. //! @param ... An optional printf-style format string and variadic parameters. # define CARB_ASSERT(cond, ...) ((void)0) //! Optionally performs a runtime check assertion, by default for both debug and release builds. //! @warning The \p cond should have no side effects! Asserts can be disabled which will cause \p cond to not be //! evaluated. //! @note The \ref CARB_CHECK_ENABLED define can be used to determine if runtime check asserts are enabled, or to cause //! them to be enabled or disabled by defining it before including this file. //! //! The implementation can be overridden on the command line, or by defining to a different implementation before //! including this file. //! //! When \p cond produces a `false` result, the failure is reported to the `g_carbAssert` assertion handler, or if that //! global variable is `nullptr`, calls \ref carb::assertHandlerFallback(). Depending on the result from that function //! call, execution is allowed to continue, or `CARB_BREAK_POINT()` is invoked to notify the debugger. //! @param cond A condition that is evaluated for a boolean result. If the condition produces \c false, the assert //! handler is notified. //! @param ... An optional printf-style format string and variadic parameters. # define CARB_CHECK(cond, ...) ((void)0) //! Terminates the application if a check fails. //! //! The implementation can be overridden on the command line, or by defining to a different implementation before //! including this file. //! //! @warning The application is malformed and undefined behavior occurs if an overriding implementation of //! `CARB_FATAL_UNLESS` allows continuing when \p cond returns false. //! @param cond A condition that is evaluated for a boolean result. If the condition produces \c false, the assert //! handler is notified. If the assert handler returns, `std::terminate()` is called. //! @param fmt An explanation of the failure is required. This is a printf-style format string. //! @param ... printf-style variadic parameters # define CARB_FATAL_UNLESS(cond, fmt, ...) (!(cond) ? (std::terminate(), false) : true) #else /* main assertion test entry point. This is implemented as a single conditional statement to * ensure that the assertion failure breakpoint occurs on the same line of code as the assertion * test itself. CARB_CHECK() exists in release and debug, and CARB_ASSERT() is debug-only. */ // example-begin CARB_IMPL_ASSERT # define CARB_IMPL_ASSERT(cond, ...) \ (CARB_LIKELY(cond) || \ ![&](const char* funcname__, ...) CARB_NOINLINE { \ return g_carbAssert ? \ g_carbAssert->reportFailedAssertion(#cond, __FILE__, funcname__, __LINE__, ##__VA_ARGS__) : \ ::carb::assertHandlerFallback(#cond, __FILE__, funcname__, __LINE__, ##__VA_ARGS__); \ }(CARB_PRETTY_FUNCTION) || \ (CARB_BREAK_POINT(), false)) // example-end CARB_IMPL_ASSERT # ifndef CARB_CHECK # ifndef CARB_CHECK_ENABLED # define CARB_CHECK_ENABLED 1 # endif # if CARB_CHECK_ENABLED # define CARB_CHECK(cond, ...) CARB_IMPL_ASSERT(cond, ##__VA_ARGS__) # else # define CARB_CHECK(cond, ...) ((void)0) # endif # else // CARB_CHECK was already defined # ifndef CARB_CHECK_ENABLED # define CARB_CHECK /* cause an error showing where it was already defined */ # error CARB_CHECK_ENABLED must also be defined if CARB_CHECK is pre-defined! # endif # endif # ifndef CARB_FATAL_UNLESS // example-begin CARB_FATAL_UNLESS # define CARB_FATAL_UNLESS(cond, fmt, ...) \ (CARB_LIKELY(cond) || \ ([&](const char* funcname__, ...) CARB_NOINLINE { \ if (false) \ ::printf(fmt, ##__VA_ARGS__); \ g_carbAssert ? g_carbAssert->reportFailedAssertion(#cond, __FILE__, funcname__, __LINE__, fmt, ##__VA_ARGS__) : \ ::carb::assertHandlerFallback(#cond, __FILE__, funcname__, __LINE__, fmt, ##__VA_ARGS__); \ }(CARB_PRETTY_FUNCTION), std::terminate(), false)) // example-end CARB_FATAL_UNLESS # endif # ifndef CARB_ASSERT # ifndef CARB_ASSERT_ENABLED # if CARB_DEBUG # define CARB_ASSERT_ENABLED 1 # else # define CARB_ASSERT_ENABLED 0 # endif # endif # if CARB_ASSERT_ENABLED # define CARB_ASSERT(cond, ...) CARB_IMPL_ASSERT(cond, ##__VA_ARGS__) # else # define CARB_ASSERT(cond, ...) ((void)0) # endif # else // CARB_ASSERT was already defined # ifndef CARB_ASSERT_ENABLED # define CARB_ASSERT /* cause an error showing where it was already defined */ # error CARB_ASSERT_ENABLED must also be defined if CARB_ASSERT is pre-defined! # endif # endif #endif //! A helper to determine if the size and alignment of two given structures match, causing a static assert if unmatched. //! @param A One type to compare. //! @param B Another type to compare. #define CARB_ASSERT_STRUCTS_MATCH(A, B) \ static_assert( \ sizeof(A) == sizeof(B) && alignof(A) == alignof(B), "Size or alignment mismatch between " #A " and " #B ".") //! A helper to determine if member `A.a` matches the offset and size of `B.b`, causing a static assert if unmatched. //! @param A The struct containing public member \p a. //! @param a A public member of \p A. //! @param B The struct containing public member \p b. //! @param b A public member of \p B. #define CARB_ASSERT_MEMBERS_MATCH(A, a, B, b) \ static_assert(offsetof(A, a) == offsetof(B, b) && sizeof(A::a) == sizeof(B::b), \ "Offset or size mismatch between members " #a " of " #A " and " #b " of " #B ".") //! The maximum value that can be represented by `uint16_t`. #define CARB_UINT16_MAX UINT16_MAX //! The maximum value that can be represented by `uint32_t`. #define CARB_UINT32_MAX UINT32_MAX //! The maximum value that can be represented by `uint64_t`. #define CARB_UINT64_MAX UINT64_MAX //! The maximum value that can be represented by `unsigned long long`. #define CARB_ULLONG_MAX ULLONG_MAX //! The maximum value that can be represented by `unsigned short`. #define CARB_USHRT_MAX USHRT_MAX //! The maximum value that can be represented by `float`. #define CARB_FLOAT_MAX 3.402823466e+38F //! A macro that returns the least of two values. //! @warning This macro will evaluate parameters more than once! Consider using carb_min() or `std::min`. //! @param a The first value. //! @param b The second value. //! @returns The least of \p a or \p b. If the values are equal \p b will be returned. #define CARB_MIN(a, b) (((a) < (b)) ? (a) : (b)) //! A macro the returns the largest of two values. //! @warning This macro will evaluate parameters more than once! Consider using carb_max() or `std::max`. //! @param a The first value. //! @param b The second value. //! @returns The largest of \p a or \p b. If the values are equal \p b will be returned. #define CARB_MAX(a, b) (((a) > (b)) ? (a) : (b)) //! A macro the returns the largest of two values. //! @warning This macro will evaluate parameters more than once! Consider using `std::clamp` or an inline function //! instead. //! @param x The value to clamp. //! @param lo The lowest acceptable value. This will be returned if `x < lo`. //! @param hi The highest acceptable value. This will be returned if `x > hi`. //! @return \p lo if \p x is less than \p lo; \p hi if \p x is greater than \p hi; \p x otherwise. #define CARB_CLAMP(x, lo, hi) (((x) < (lo)) ? (lo) : (((x) > (hi)) ? (hi) : (x))) //! Rounds a given value to the next highest multiple of another given value. //! @warning This macro will evaluate the \p to parameter more than once! Consider using an inline function instead. //! @param value The value to round. //! @param to The multiple to round to. //! @returns \p value rounded up to the next multiple of \p to. #define CARB_ROUNDUP(value, to) ((((value) + (to)-1) / (to)) * (to)) #ifndef DOXYGEN_SHOULD_SKIP_THIS // CARB_JOIN will join together `a` and `b` and also work properly if either parameter is another macro like __LINE__. // This requires two macros since the preprocessor will only recurse macro expansion if # and ## are not present. # define __CARB_JOIN(a, b) a##b #endif //! A macro that joins two parts to create one symbol allowing one or more parameters to be a macro, as if by the `##` //! preprocessor operator. //! Example: `CARB_JOIN(test, __LINE__)` on line 579 produces `test579`. //! @param a The first name to join. //! @param b The second name to join. #define CARB_JOIN(a, b) __CARB_JOIN(a, b) //! A macro that deletes the copy-construct and copy-assign functions for the given classname. //! @param classname The class to delete copy functions for. #define CARB_PREVENT_COPY(classname) \ classname(const classname&) = delete; /**< @private */ \ classname& operator=(const classname&) = delete /**< @private */ //! A macro that deletes the move-construct and move-assign functions for the given classname. //! @param classname The class to delete move functions for. #define CARB_PREVENT_MOVE(classname) \ classname(classname&&) = delete; /**< @private */ \ classname& operator=(classname&&) = delete /**< @private */ //! Syntactic sugar for both \ref CARB_PREVENT_COPY and \ref CARB_PREVENT_MOVE. //! @param classname The class to delete copy and move functions for. #define CARB_PREVENT_COPY_AND_MOVE(classname) \ CARB_PREVENT_COPY(classname); \ CARB_PREVENT_MOVE(classname) #if defined(__COUNTER__) || defined(DOXYGEN_BUILD) //! A helper macro that appends a number to the given name to create a unique name. //! @param str The name to decorate. # define CARB_ANONYMOUS_VAR(str) CARB_JOIN(str, __COUNTER__) #else # define CARB_ANONYMOUS_VAR(str) CARB_JOIN(str, __LINE__) #endif namespace carb { #ifndef DOXYGEN_SHOULD_SKIP_THIS template <typename T, size_t N> constexpr size_t countOf(T const (&)[N]) { return N; } #endif //! Returns the count of an array as a `size_t` at compile time. //! @param a The array to count. //! @returns The number of elements in \p a. #define CARB_COUNTOF(a) carb::countOf(a) #ifndef DOXYGEN_SHOULD_SKIP_THIS template <typename T, uint32_t N> constexpr uint32_t countOf32(T const (&)[N]) { return N; } #endif //! Returns the count of an array as a `uint32_t` at compile time. //! @param a The array to count. //! @returns The number of elements in \p a. #define CARB_COUNTOF32(a) carb::countOf32(a) #ifndef DOXYGEN_SHOULD_SKIP_THIS template <typename T, typename U> constexpr uint32_t offsetOf(U T::*member) { CARB_IGNOREWARNING_GNUC_PUSH # if CARB_TOOLCHAIN_CLANG && __clang_major__ >= 13 // this error is issued on clang 13 CARB_IGNOREWARNING_GNUC_WITH_PUSH("-Wnull-pointer-subtraction") # endif return (uint32_t)((char*)&((T*)nullptr->*member) - (char*)nullptr); CARB_IGNOREWARNING_GNUC_POP } #endif //! Returns the offset of a member of a class at compile time. //! @param a The member of a class. The member must have visibility to the call of `CARB_OFFSETOF`. The class is //! inferred. //! @returns The offset of \p a from its containing class, in bytes, as a `uint32_t`. #define CARB_OFFSETOF(a) carb::offsetOf(&a) #if CARB_COMPILER_MSC || defined(DOXYGEN_BUILD) //! Returns the required alignment of a type. //! @param T The type to determine alignment of. //! @returns The required alignment of \p T, in bytes. # define CARB_ALIGN_OF(T) __alignof(T) #elif CARB_COMPILER_GNUC # define CARB_ALIGN_OF(T) __alignof__(T) #else # error "Align of cannot be determined - compiler not known" #endif // Implement CARB_HARDWARE_PAUSE; a way of idling the pipelines and reducing the penalty // from memory order violations. See // https://software.intel.com/en-us/articles/long-duration-spin-wait-loops-on-hyper-threading-technology-enabled-intel-processors #ifdef DOXYGEN_BUILD //! Instructs the underlying hardware to idle the CPU pipelines and reduce the penalty from memory order violations. # define CARB_HARDWARE_PAUSE() #elif CARB_X86_64 // avoid including immintrin.h # if CARB_COMPILER_MSC # pragma intrinsic(_mm_pause) # define CARB_HARDWARE_PAUSE() _mm_pause() # else # define CARB_HARDWARE_PAUSE() __builtin_ia32_pause() # endif #elif defined(__aarch64__) # define CARB_HARDWARE_PAUSE() __asm__ __volatile__("yield" ::: "memory") #else CARB_UNSUPPORTED_PLATFORM(); #endif #if CARB_COMPILER_MSC || defined(DOXYGEN_BUILD) # pragma intrinsic(_mm_prefetch) //! Instructs the compiler to force inline of the decorated function # define CARB_ALWAYS_INLINE __forceinline //! Attempts to prefetch from memory using a compiler intrinsic. //! @param addr The address to prefetch //! @param write Pass `true` if writing to the address is intended; `false` otherwise. //! @param level The `carb::PrefetchLevel` hint. # define CARB_PREFETCH(addr, write, level) _mm_prefetch(reinterpret_cast<char*>(addr), int(level)) //! A prefetch level hint to pass to \ref CARB_PREFETCH() enum class PrefetchLevel { kHintNonTemporal = 0, //!< prefetch data into non-temporal cache structure and into a location close to the //!< processor, minimizing cache pollution. kHintL1 = 1, //!< prefetch data into all levels of the cache hierarchy. kHintL2 = 2, //!< prefetch data into level 2 cache and higher. kHintL3 = 3, //!< prefetch data into level 3 cache and higher, or an implementation specific choice. }; #elif CARB_COMPILER_GNUC # define CARB_ALWAYS_INLINE CARB_ATTRIBUTE(always_inline) # define CARB_PREFETCH(addr, write, level) __builtin_prefetch((addr), (write), int(level)) enum class PrefetchLevel { kHintNonTemporal = 0, kHintL1 = 3, kHintL2 = 2, kHintL3 = 1, }; #else CARB_UNSUPPORTED_PLATFORM(); #endif //! A macro that declares that a function may not be inlined. #define CARB_NOINLINE CARB_ATTRIBUTE(noinline) CARB_DECLSPEC(noinline) #ifdef DOXYGEN_BUILD //! Declares a function as deprecated. # define CARB_DEPRECATED(msg) //! Declares a file as deprecated. # define CARB_FILE_DEPRECATED //! Declares that a function will not throw any exceptions # define CARB_NOEXCEPT throw() //! Used when declaring opaque types to prevent Doxygen from getting confused about not finding any implementation. # define DOXYGEN_EMPTY_CLASS \ { \ } #else # define CARB_DEPRECATED(msg) CARB_ATTRIBUTE(deprecated(msg)) CARB_DECLSPEC(deprecated(msg)) # ifdef CARB_IGNORE_REMOVEFILE_WARNINGS # define CARB_FILE_DEPRECATED # define CARB_FILE_DEPRECATED_MSG(...) # else # define CARB_FILE_DEPRECATED_MSG(msg) \ CARB_PRAGMA(message("\x1b[33m" __FILE__ ":" CARB_STRINGIFY( \ __LINE__) ": " msg " (#define CARB_IGNORE_REMOVEFILE_WARNINGS to ignore these warnings)\x1b[0m")) \ CARB_PRAGMA(warning_see_message) # define CARB_FILE_DEPRECATED CARB_FILE_DEPRECATED_MSG("This file is no longer needed and will be removed soon") # endif # define CARB_NOEXCEPT noexcept # define DOXYGEN_EMPTY_CLASS #endif #ifndef DOXYGEN_SHOULD_SKIP_THIS template <typename T> constexpr T align(T x, size_t alignment) { return (T)(((size_t)x + alignment - 1) / alignment * alignment); } template <typename T> T* align(T* x, size_t alignment) { return (T*)(((size_t)x + alignment - 1) / alignment * alignment); } #endif //! Aligns a number or pointer to the next multiple of a provided alignment. //! @note The alignment need not be a power-of-two. //! @param x The pointer or value to align //! @param alignment The alignment value in bytes. //! @returns If \p x is already aligned to \p alignment, returns \p x; otherwise returns \p x rounded up to the next //! multiple of \p alignment. #define CARB_ALIGN(x, alignment) carb::align(x, alignment) #ifndef DOXYGEN_SHOULD_SKIP_THIS template <typename T> constexpr T alignedSize(const T& size, uint32_t alignment) { return ((size + alignment - 1) / alignment) * alignment; } #endif //! Aligns a size to the given alignment. //! @note The alignment need not be a power-of-two. //! @param size The size to align. //! @param alignment The alignment value in bytes. //! @returns If \p size is already aligned to \p alignment, returns \p size; otherwise returns \p size rounded up to the //! next multiple of \p alignment. #define CARB_ALIGNED_SIZE(size, alignment) carb::alignedSize(size, alignment) //! Defined as `alignas(T)`. #define CARB_ALIGN_AS(T) alignas(T) #ifndef DOXYGEN_SHOULD_SKIP_THIS template <typename T> constexpr T divideCeil(T size, uint32_t divisor) { static_assert(std::is_integral<T>::value, "Integral required."); return (size + divisor - 1) / divisor; } #endif /** * Divides size by divisor and returns the closest integer greater than or equal to the division result. * For uses such as calculating a number of thread groups that cover all threads in a compute dispatch. * @param size An integer value. * @param divisor The divisor value. * @returns `size / divisor`, rounded up to the nearest whole integer. The type is based on \p size. */ #define CARB_DIVIDE_CEIL(size, divisor) carb::divideCeil(size, divisor) #if (CARB_HAS_CPP17 && defined(__cpp_lib_hardware_interference_size)) || defined(DOXYGEN_BUILD) //! Minimum offset between two objects to avoid false sharing, i.e. cache line size. If C++17 is not supported, falls //! back to the default value of 64 bytes. # define CARB_CACHELINE_SIZE (std::hardware_destructive_interference_size) #else # define CARB_CACHELINE_SIZE (64) #endif //! Defined as `CARB_ALIGN_AS(CARB_CACHELINE_SIZE)`. #define CARB_CACHELINE_ALIGN CARB_ALIGN_AS(CARB_CACHELINE_SIZE) /** This is a wrapper for the platform-specific call to the non-standard but almost universal alloca() function. */ #if CARB_PLATFORM_WINDOWS # define CARB_ALLOCA(size) _alloca(size) #elif CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS # define CARB_ALLOCA(size) alloca(size) #else CARB_UNSUPPORTED_PLATFORM(); #endif //! Attempts to allocate an array of the given type on the stack. //! @warning On Windows, the underlying call to `_alloca()` may throw a SEH stack overflow exception if the stack does //! not have sufficient space to perform the allocation. However, on Linux, there is no error handling for the //! underlying `alloca()` call. The caller is advised to use caution. //! @note The memory allocated is within the stack frame of the current function and is automatically freed when the //! function returns or `longjmp()` or `siglongjmp()` is called. The memory is \a not freed when leaving the scope that //! allocates it, except by the methods mentioned. //! @param T The type of the object(s) to allocate. //! @param number The number of objects to allocate. If `0`, a `nullptr` is returned. //! @returns A properly-aligned pointer that will fit \p number quantity of type \p T on the stack. This memory will be //! freed automatically when the function returns or `longjmp()` or `siglongjmp()` is called. #define CARB_STACK_ALLOC(T, number) \ carb::align<T>(((number) ? (T*)CARB_ALLOCA((number) * sizeof(T) + alignof(T)) : nullptr), alignof(T)) //! Allocates memory from the heap. //! @rst //! .. deprecated:: 126.0 //! Please use `carb::allocate()` instead. //! @endrst //! @warning Memory allocated from this method must be freed within the same module that allocated it. //! @param size The number of bytes to allocate. //! @returns A valid pointer to a memory region of \p size bytes. If an error occurs, `nullptr` is returned. #define CARB_MALLOC(size) std::malloc(size) //! Frees memory previously allocated using CARB_MALLOC(). //! @rst //! .. deprecated:: 126.0 //! Please use `carb::deallocate()` instead. //! @endrst //! @param ptr The pointer previously returned from \c CARB_MALLOC. #define CARB_FREE(ptr) std::free(ptr) #ifndef DOXYGEN_SHOULD_SKIP_THIS # define __CARB_STRINGIFY(x) # x #endif //! Turns a name into a string, resolving macros (i.e. `CARB_STRINGIFY(__LINE__)` on line 815 will produce `"815"`). //! @param x The name to turn into a string. //! @returns \p x as a string. #define CARB_STRINGIFY(x) __CARB_STRINGIFY(x) //! FNV-1a 64-bit hash basis. //! @see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param constexpr uint64_t kFnvBasis = 14695981039346656037ull; //! FNV-1a 64-bit hash prime. //! @see http://www.isthe.com/chongo/tech/comp/fnv/#FNV-param constexpr uint64_t kFnvPrime = 1099511628211ull; //! Compile-time FNV-1a 64-bit hash, use with CARB_HASH_STRING macro //! @param str The string to hash. //! @param n The number of characters in \p str, not including the NUL terminator. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. constexpr uint64_t fnv1aHash(const char* str, std::size_t n, uint64_t hash = kFnvBasis) { return n > 0 ? fnv1aHash(str + 1, n - 1, (hash ^ *str) * kFnvPrime) : hash; } #ifndef DOXYGEN_SHOULD_SKIP_THIS //! Compile-time FNV-1a 64-bit hash for a static string (char array). //! @param array The static string to hash. //! @returns A hash computed from the given parameters. template <std::size_t N> constexpr uint64_t fnv1aHash(const char (&array)[N]) { return fnv1aHash(&array[0], N - 1); } #endif //! Runtime FNV-1a 64-bit string hash //! @param str The C-style (NUL terminated) string to hash. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. inline uint64_t hashString(const char* str, uint64_t hash = kFnvBasis) { while (*str != '\0') { hash ^= static_cast<unsigned char>(*(str++)); hash *= kFnvPrime; } return hash; } //! A fast table-based implementation of std::tolower for ASCII characters only. //! @warning This function does not work on Unicode characters and is not locale-aware; it is ASCII only. //! @param c The character to change to lower case. //! @return The lower-case letter of \p c if \p c is an upper-case letter; \p c otherwise. constexpr unsigned char tolower(unsigned char c) { return detail::lowerTable[c]; }; //! A fast table-based implementation of std::toupper for ASCII characters only. //! @warning This function does not work on Unicode characters and is not locale-aware; it is ASCII only. //! @param c The character to change to upper case. //! @return The upper-case letter of \p c if \p c is a lower-case letter; \p c otherwise. constexpr unsigned char toupper(unsigned char c) { return detail::upperTable[c]; } //! Runtime FNV-1a 64-bit lower-case string hash (as if the string had been converted using \ref tolower()). //! @param str The C-style (NUL terminated) string to hash. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. inline uint64_t hashLowercaseString(const char* str, uint64_t hash = kFnvBasis) { while (*str != '\0') { hash ^= tolower(static_cast<unsigned char>(*(str++))); hash *= kFnvPrime; } return hash; } //! Runtime FNV-1a 64-bit lower-case byte hash (as if the bytes had been converted using \ref tolower()). //! @param buffer The byte buffer to hash. //! @param len The number of bytes in \p buffer. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. inline uint64_t hashLowercaseBuffer(const void* buffer, size_t len, uint64_t hash = kFnvBasis) { const unsigned char* data = static_cast<const unsigned char*>(buffer); const unsigned char* const end = data + len; while (data != end) { hash ^= tolower(*(data++)); hash *= kFnvPrime; } return hash; } //! Runtime FNV-1a 64-bit upper-case string hash (as if the string had been converted using \ref toupper()). //! @param str The C-style (NUL terminated) string to hash. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. inline uint64_t hashUppercaseString(const char* str, uint64_t hash = kFnvBasis) { while (*str != '\0') { hash ^= toupper(static_cast<unsigned char>(*(str++))); hash *= kFnvPrime; } return hash; } //! Runtime FNV-1a 64-bit upper-case byte hash (as if the bytes had been converted using \ref toupper()). //! @param buffer The byte buffer to hash. //! @param len The number of bytes in \p buffer. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. inline uint64_t hashUppercaseBuffer(const void* buffer, size_t len, uint64_t hash = kFnvBasis) { const unsigned char* data = static_cast<const unsigned char*>(buffer); const unsigned char* const end = data + len; while (data != end) { hash ^= toupper(*(data++)); hash *= kFnvPrime; } return hash; } //! Runtime FNV-1a 64-bit byte hash. //! @param buffer The byte buffer to hash. //! @param length The number of bytes in \p buffer. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. inline uint64_t hashBuffer(const void* buffer, size_t length, uint64_t hash = kFnvBasis) { const char* ptr = static_cast<const char*>(buffer); for (size_t i = 0; i < length; ++i) { hash ^= static_cast<unsigned char>(ptr[i]); hash *= kFnvPrime; } return hash; } //! Runtime FNV-1a 64-bit hash of a scalar type. //! @param type An scalar to hash. //! @param hash The previous hash value or starting hash basis. //! @returns A hash computed from the given parameters. template <class T> constexpr uint64_t hashScalar(const T& type, uint64_t hash = kFnvBasis) { static_assert(std::is_scalar<T>::value, "Unsupported type for hashing"); return hashBuffer(reinterpret_cast<const char*>(std::addressof(type)), sizeof(type), hash); } /** * Combines two hashes producing better collision avoidance than XOR. * * @param hash1 The initial hash * @param hash2 The hash to combine with @p hash1 * @returns A combined hash of @p hash1 and @p hash2 */ inline constexpr uint64_t hashCombine(uint64_t hash1, uint64_t hash2) noexcept { constexpr uint64_t kConstant{ 14313749767032793493ull }; constexpr int kRotate = 47; hash2 *= kConstant; hash2 ^= (hash2 >> kRotate); hash2 *= kConstant; hash1 ^= hash2; hash1 *= kConstant; // Add an arbitrary value to prevent 0 hashing to 0 hash1 += 0x42524143; // CARB return hash1; } // The string hash macro is guaranteed to evaluate at compile time. MSVC raises a warning for this, which we disable. #if defined(__CUDACC__) || defined(DOXYGEN_BUILD) //! Computes a literal string hash at compile time. //! @param str The string literal to hash //! @returns A hash computed from the given string literal as if by \ref carb::fnv1aHash(). # define CARB_HASH_STRING(str) std::integral_constant<uint64_t, carb::fnv1aHash(str)>::value #else # define CARB_HASH_STRING(str) \ CARB_IGNOREWARNING_MSC_WITH_PUSH(4307) /* 'operator': integral constant overflow */ \ std::integral_constant<uint64_t, carb::fnv1aHash(str)>::value CARB_IGNOREWARNING_MSC_POP #endif //! Syntactic sugar for `CARB_HASH_STRING(CARB_STRINGIFY(T))`. #define CARB_HASH_TYPE(T) CARB_HASH_STRING(CARB_STRINGIFY(T)) // printf-like functions attributes #if CARB_COMPILER_GNUC || defined(DOXYGEN_BUILD) //! Requests that the compiler validate any variadic arguments as printf-style format specifiers, if supported by the //! compiler. Causes a compilation error if the printf-style format specifier doesn't match the given variadic types. //! @note The current implementation is effective only when `CARB_COMPILER_GNUC` is non-zero. The Windows implementation //! does not work properly for custom printf-like function pointers. It is recommended where possible to use a "fake //! printf" trick to force the compiler to evaluate the arguments: //! ```cpp //! if (0) printf(fmt, arg1, arg2); // Compiler will check but never execute. //! ``` //! @param fmt_ordinal The 1-based function parameter receiving the printf-style format string. //! @param args_ordinal The 1-based function parameter receiving the first variadic argument. # define CARB_PRINTF_FUNCTION(fmt_ordinal, args_ordinal) CARB_ATTRIBUTE(format(printf, fmt_ordinal, args_ordinal)) #elif CARB_COMPILER_MSC // Microsoft suggest to use SAL annotations _Printf_format_string_ and _Printf_format_string_params_ for // printf-like functions. Unfortunately it does not work properly for custom printf-like function pointers. // So, instead of defining marker attribute for format string, we use the "fake printf" trick to force compiler // checks and keep function attribute empty. # define CARB_PRINTF_FUNCTION(fmt_ordinal, args_ordinal) #else # define CARB_PRINTF_FUNCTION(fmt_ordinal, args_ordinal) #endif //! An empty class tag type used with \ref EmptyMemberPair constructors. struct ValueInitFirst { //! Default constructor. constexpr explicit ValueInitFirst() = default; }; //! An empty class tag type used with \ref EmptyMemberPair constructors. struct InitBoth { //! Default constructor. constexpr explicit InitBoth() = default; }; //! Attempts to invoke the Empty Member Optimization by inheriting from the First element if possible, which, if empty //! will eliminate the storage necessary for an empty class; the Second element is always stored as a separate member. //! The First element is inherited from if it is an empty `class`/`struct` and is not declared `final`. //! @tparam First The first element of the pair that the pair will inherit from if empty and not `final`. //! @tparam Second The second element of the pair that will always be a member. template <class First, class Second, bool = std::is_empty<First>::value && !std::is_final<First>::value> class EmptyMemberPair : private First { public: //! Type of the First element using FirstType = First; //! Type of the Second element using SecondType = Second; //! Constructor that default-initializes the `First` member and passes all arguments to the constructor of `Second`. //! @param args arguments passed to the constructor of `second`. template <class... Args2> constexpr explicit EmptyMemberPair(ValueInitFirst, Args2&&... args) : First{}, second{ std::forward<Args2>(args)... } { } //! Constructor that initializes both members. //! @param arg1 the argument that is forwarded to the `First` constructor. //! @param args2 arguments passed to the constructor of `second`. template <class Arg1, class... Args2> constexpr explicit EmptyMemberPair(InitBoth, Arg1&& arg1, Args2&&... args2) : First(std::forward<Arg1>(arg1)), second(std::forward<Args2>(args2)...) { } //! Non-const access to `First`. //! @returns a non-const reference to `First`. constexpr FirstType& first() noexcept { return *this; } //! Const access to `First`. //! @returns a const reference to `First`. constexpr const FirstType& first() const noexcept { return *this; } //! Direct access to the `Second` member. SecondType second; }; #ifndef DOXYGEN_SHOULD_SKIP_THIS template <class First, class Second> class EmptyMemberPair<First, Second, false> { public: using FirstType = First; using SecondType = Second; template <class... Args2> constexpr explicit EmptyMemberPair(ValueInitFirst, Args2&&... args) : m_first(), second(std::forward<Args2>(args)...) { } template <class Arg1, class... Args2> constexpr explicit EmptyMemberPair(InitBoth, Arg1&& arg1, Args2&&... args2) : m_first(std::forward<Arg1>(arg1)), second(std::forward<Args2>(args2)...) { } constexpr FirstType& first() noexcept { return m_first; } constexpr const FirstType& first() const noexcept { return m_first; } private: FirstType m_first; public: SecondType second; }; #endif } // namespace carb /** * Picks the minimum of two values. * * Same as `std::min` but implemented without using the `min` keyword as Windows.h can sometimes `#define` it. * * @param left The first value to compare. * @param right The second value to compare. * @returns \p left if \p left is less than \p right, otherwise \p right, even if the values are equal. */ template <class T> CARB_NODISCARD constexpr const T& carb_min(const T& left, const T& right) noexcept(noexcept(left < right)) { return left < right ? left : right; } /** * Picks the maximum of two values. * * Same as `std::max` but implemented without using the `max` keyword as Windows.h can sometimes `\#define` it. * * @param left The first value to compare. * @param right The second value to compare. * @returns \p right if \p left is less than \p right, otherwise \p left, even if the values are equal. */ template <class T> CARB_NODISCARD constexpr const T& carb_max(const T& left, const T& right) noexcept(noexcept(left < right)) { return left < right ? right : left; } #if CARB_POSIX || defined(DOXYGEN_BUILD) /** * A macro to retry operations if they return -1 and errno is set to EINTR. * @warning The `op` expression is potentially evaluated multiple times. * @param op The operation to retry * @returns The return value of \p op while guaranteeing that `errno` is not `EINTR`. */ # define CARB_RETRY_EINTR(op) \ [&] { \ decltype(op) ret_; \ while ((ret_ = (op)) < 0 && errno == EINTR) \ { \ } \ return ret_; \ }() #endif /** * Portable way to mark unused variables as used. * * This tricks the compiler into thinking that the variables are used, eliminating warnings about unused variables. * * @param args Any variables or arguments that should be marked as unused. */ template <class... Args> void CARB_UNUSED(Args&&... CARB_DOC_ONLY(args)) { } /** A macro to mark functionality that has not been implemented yet. * @remarks This will abort the process with a message. * The macro is [[noreturn]]. */ #define CARB_UNIMPLEMENTED(msg, ...) \ do \ { \ CARB_FATAL_UNLESS(false, (msg), ##__VA_ARGS__); \ std::terminate(); \ } while (0) /** A macro to mark placeholder functions on MacOS while the porting effort is in progress. */ #define CARB_MACOS_UNIMPLEMENTED() CARB_UNIMPLEMENTED("Unimplemented on Mac OS") #if defined(CARB_INCLUDE_PURIFY_NAME) && !defined(DOXYGEN_BUILD) # ifdef __COUNTER__ # define CARB_INCLUDE_PURIFY_TEST(...) \ inline void CARB_JOIN(CARB_INCLUDE_PURIFY_NAME, __COUNTER__)() \ __VA_ARGS__ static_assert(true, "Semicolon required") # else # define CARB_INCLUDE_PURIFY_TEST(...) \ inline void CARB_JOIN(CARB_INCLUDE_PURIFY_NAME, __LINE__)() \ __VA_ARGS__ static_assert(true, "Semicolon required") # endif #else /** * A macro that is used only for public includes to define a function which will instantiate templates. * * The templates are instantiated to make sure that all of the required symbols are available for compilation. * Example usage: * @code{.cpp} * CARB_INCLUDE_PURIFY_TEST({ * carb::Delegate<void()> del; * }); * @endcode * @note The braces must be specified inside the macro parentheses. * @note This function is never executed, merely compiled to test include purification. Unit tests are responsible for * full testing. * @note This macro only produces a function if `CARB_INCLUDE_PURIFY_NAME` is set to a function name. This happens in * Carbonite's premake5.lua file when the include purification projects are generated. */ # define CARB_INCLUDE_PURIFY_TEST(...) #endif
78,032
C
46.726605
136
0.649413
omniverse-code/kit/include/carb/StartupUtils.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 Contains @ref carb::startupFramework() and @ref carb::shutdownFramework(). Consider using @ref //! OMNI_CORE_INIT(), which invokes these methods for you in a safe manner. #pragma once #include "Framework.h" #include "crashreporter/CrashReporterUtils.h" #include "dictionary/DictionaryUtils.h" #include "extras/AppConfig.h" #include "extras/CmdLineParser.h" #include "extras/EnvironmentVariableParser.h" #include "extras/EnvironmentVariableUtils.h" #include "extras/Path.h" #include "extras/VariableSetup.h" #include "filesystem/IFileSystem.h" #include "l10n/L10nUtils.h" #include "logging/Log.h" #include "logging/LoggingSettingsUtils.h" #include "logging/StandardLogger.h" #include "profiler/Profile.h" #include "settings/ISettings.h" #include "tokens/ITokens.h" #include "tokens/TokensUtils.h" #include "../omni/structuredlog/StructuredLogSettingsUtils.h" #include <array> #include <map> #include <string> #include <vector> namespace carb { //! Parameters passed to @ref carb::startupFramework(). struct StartupFrameworkDesc { //! A string containing either one of two things: //! //! * A path to a configuration file. //! //! * A raw string contain the configuration (in either JSON or TOML format based on @p configFormat ). //! //! @ref carb::startupFramework() will first check to see if the string maps to an existing file, and if not, the //! string is treated as a raw configuration string. const char* configString; // Path to a config file or string with configuration data char** argv; //!< Array of command line arguments int argc; //!< Number of command line arguments //! An array of search paths for plugins. //! //! Relative search paths are relative to the executable's directory, not the current working directory. //! //! These search paths will be used when loading the base set of carbonite plugins (such as carb.settings.plugin), //! then this will be set as the default value for the @ref carb::settings::ISettings key `/pluginSearchPaths` (this //! allows the setting to be overridden if you set it in config.toml or pass it on the command line). //! //! Passing an empty array will result in the executable directory being used as the default search path. //! //! This option is needed when the base set of Carbonite plugins are not inside of the executable's directory; //! otherwise, `/pluginSearchPaths` could be set in config.toml or via the command line. //! //! Defaults to `nullptr`. const char* const* initialPluginsSearchPaths; size_t initialPluginsSearchPathCount; //!< Size of array of paths to search for plugins //! Prefix of command line arguments serving as overrides for configuration values. Default is `--/`. const char* cmdLineParamPrefix; //! Prefix of environment variables serving as overrides for configuration values. Default is `OMNI_APPNAME_`. const char* envVarsParamPrefix; const char* configFormat; //!< The selected config format ("toml", "json", etc). Default is "toml". const char* appNameOverride; //!< Override automatic app name search. Defaults to `nullptr`. const char* appPathOverride; //!< Override automatic app path search. Defaults to `nullptr`. bool disableCrashReporter; //!< If `true`, the crash reporter plugin will not be loaded. Defaults to `false`. //! Returns a @ref StartupFrameworkDesc with default values. static StartupFrameworkDesc getDefault() { static constexpr const char* kDefaultCmdLineParamPrefix = "--/"; static constexpr const char* kDefaultEnvVarsParamPrefix = "OMNI_APPNAME_"; static constexpr const char* kDefaultConfigFormat = "toml"; StartupFrameworkDesc result{}; result.cmdLineParamPrefix = kDefaultCmdLineParamPrefix; result.envVarsParamPrefix = kDefaultEnvVarsParamPrefix; result.configFormat = kDefaultConfigFormat; return result; } }; /** * Simple plugin loading function wrapper that loads plugins matching multiple patterns. * * Consider using @ref carb::startupFramework(), which calls this function with user defined paths via config files, the * environment, and the command line. * * @param pluginNamePatterns String that contains plugin names pattern - wildcards are supported. * @param pluginNamePatternCount Number of items in @p pluginNamePatterns. * @param searchPaths Array of paths to look for plugins in. * @param searchPathCount Number of paths in searchPaths array. */ inline void loadPluginsFromPatterns(const char* const* pluginNamePatterns, size_t pluginNamePatternCount, const char* const* searchPaths = nullptr, size_t searchPathCount = 0) { Framework* f = getFramework(); PluginLoadingDesc desc = PluginLoadingDesc::getDefault(); desc.loadedFileWildcards = pluginNamePatterns; desc.loadedFileWildcardCount = pluginNamePatternCount; desc.searchPaths = searchPaths; desc.searchPathCount = searchPathCount; f->loadPlugins(desc); } /** * Simple plugin loading function wrapper that loads plugins matching a single pattern. * * Consider using @ref carb::startupFramework(), which calls this function with user defined paths via config files, the * environment, and the command line. * * @param pluginNamePattern String that contains a plugin pattern - wildcards are supported. * @param searchPaths Array of paths to look for plugins in. * @param searchPathCount Number of paths in searchPaths array. */ inline void loadPluginsFromPattern(const char* pluginNamePattern, const char* const* searchPaths = nullptr, size_t searchPathCount = 0) { const char* plugins[] = { pluginNamePattern }; loadPluginsFromPatterns(plugins, countOf(plugins), searchPaths, searchPathCount); } //! Internal namespace detail { //! Loads plugins based on settings specified in the given @p settings object. //! //! The settings read populated a @ref carb::PluginLoadingDesc. The settings read are: //! //! @rst //! //! /pluginSearchPaths //! Array of paths in which to search for plugins. //! //! /pluginSearchRecursive //! If ``true`` recursively each path in `/pluginSearchPaths`. //! //! /reloadablePlugins //! Array of plugin wildcards that mark plugins as reloadable. //! //! /pluginsLoaded //! Wildcard of plugins to load. //! //! /pluginsExcluded //! Wildcard of plugins that match `/pluginsLoaded` but should not be loaded. //! //! @endrst //! //! Do not use this function directly. Rather, call @ref carb::startupFramework(). inline void loadPluginsFromConfig(settings::ISettings* settings) { if (settings == nullptr) return; Framework* f = getFramework(); // Initialize the plugin loading description to default configuration, // and override parts of it to the config values, if present. PluginLoadingDesc loadingDesc = PluginLoadingDesc::getDefault(); // Check if plugin search paths are present in the config, and override if present const char* kPluginSearchPathsKey = "/pluginSearchPaths"; std::vector<const char*> pluginSearchPaths(settings->getArrayLength(kPluginSearchPathsKey)); if (!pluginSearchPaths.empty()) { settings->getStringBufferArray(kPluginSearchPathsKey, pluginSearchPaths.data(), pluginSearchPaths.size()); loadingDesc.searchPaths = pluginSearchPaths.data(); loadingDesc.searchPathCount = pluginSearchPaths.size(); } const char* kPluginSearchRecursive = "/pluginSearchRecursive"; // Is search recursive? if (settings->isAccessibleAs(carb::dictionary::ItemType::eBool, kPluginSearchRecursive)) { loadingDesc.searchRecursive = settings->getAsBool(kPluginSearchRecursive); } // Check/override reloadable plugins if present const char* kReloadablePluginsKey = "/reloadablePlugins"; std::vector<const char*> reloadablePluginFiles(settings->getArrayLength(kReloadablePluginsKey)); if (!reloadablePluginFiles.empty()) { settings->getStringBufferArray(kReloadablePluginsKey, reloadablePluginFiles.data(), reloadablePluginFiles.size()); loadingDesc.reloadableFileWildcards = reloadablePluginFiles.data(); loadingDesc.reloadableFileWildcardCount = reloadablePluginFiles.size(); } // Check/override plugins to load if present const char* kPluginsLoadedKey = "/pluginsLoaded"; std::vector<const char*> pluginsLoaded; if (settings->getItemType(kPluginsLoadedKey) == dictionary::ItemType::eDictionary) { pluginsLoaded.resize(settings->getArrayLength(kPluginsLoadedKey)); settings->getStringBufferArray(kPluginsLoadedKey, pluginsLoaded.data(), pluginsLoaded.size()); loadingDesc.loadedFileWildcards = pluginsLoaded.size() ? pluginsLoaded.data() : nullptr; loadingDesc.loadedFileWildcardCount = pluginsLoaded.size(); } const char* kPluginsExcludedKey = "/pluginsExcluded"; std::vector<const char*> pluginsExcluded; if (settings->getItemType(kPluginsExcludedKey) == dictionary::ItemType::eDictionary) { pluginsExcluded.resize(settings->getArrayLength(kPluginsExcludedKey)); settings->getStringBufferArray(kPluginsExcludedKey, pluginsExcluded.data(), pluginsExcluded.size()); loadingDesc.excludedFileWildcards = pluginsExcluded.size() ? pluginsExcluded.data() : nullptr; loadingDesc.excludedFileWildcardCount = pluginsExcluded.size(); } // Load plugins based on the resulting desc if (loadingDesc.loadedFileWildcardCount) f->loadPlugins(loadingDesc); } //! Sets @ref carb::Framework's "default" plugins from the given @p settings `/defaultPlugins` key. //! //! In short, this function calls @ref carb::Framework::setDefaultPlugin for each plugin name in `/defaultPlugins`. //! However, since the interface type cannot be specified, plugins listed in `/defaultPlugins` will become the default //! plugin for \a all interfaces they provide. //! //! This function assumes the plugins in `/defaultPlugins` have already been loaded. //! //! The following keys are used from @p settings: //! //! @rst //! /defaultPlugins //! A list of plugin names. These plugins become the default plugins to use when acquire their interfaces. //! @endrst //! //! Do not use this function directly. Rather, call @ref carb::startupFramework(). inline void setDefaultPluginsFromConfig(settings::ISettings* settings) { if (settings == nullptr) return; Framework* f = getFramework(); // Default plugins const char* kDefaultPluginsKey = "/defaultPlugins"; std::vector<const char*> defaultPlugins(settings->getArrayLength(kDefaultPluginsKey)); if (!defaultPlugins.empty()) { settings->getStringBufferArray(kDefaultPluginsKey, defaultPlugins.data(), defaultPlugins.size()); for (const char* pluginName : defaultPlugins) { // Set plugin as default for all interfaces it provides const PluginDesc& pluginDesc = f->getPluginDesc(pluginName); for (size_t i = 0; i < pluginDesc.interfaceCount; i++) { f->setDefaultPluginEx(g_carbClientName, pluginDesc.interfaces[i], pluginName); } } } } #ifndef DOXYGEN_SHOULD_SKIP_THIS // If the dict item is a special raw string then it returns pointer to the buffer past the special raw string marker // In all other cases it returns nullptr inline const char* getRawStringFromItem(carb::dictionary::IDictionary* dictInterface, const carb::dictionary::Item* item) { if (!dictInterface || !item) { return nullptr; } if (dictInterface->getItemType(item) != dictionary::ItemType::eString) { return nullptr; } const char* stringBuffer = dictInterface->getStringBuffer(item); if (!stringBuffer) { return nullptr; } constexpr char kSpecialRawStringMarker[] = "$raw:"; constexpr size_t kMarkerLen = carb::countOf(kSpecialRawStringMarker) - 1; if (std::strncmp(stringBuffer, kSpecialRawStringMarker, kMarkerLen) != 0) { return nullptr; } return stringBuffer + kMarkerLen; } class LoadSettingsHelper { public: struct SupportedConfigInfo { const char* configFormatName; const char* serializerPluginName; const char* configExt; }; LoadSettingsHelper() { Framework* f = getFramework(); m_fs = f->acquireInterface<filesystem::IFileSystem>(); } struct LoadSettingsDesc { std::string appDir; // Application directory std::string appName; // Application name const char* configStringOrPath; // Configuration string that can be null, string containing configuration data // (in selected configFormat) or a path to a config file const extras::ConfigLoadHelper::CmdLineOptionsMap* cmdLineOptionsMap; // Mapping of the command line options const extras::ConfigLoadHelper::PathwiseEnvOverridesMap* pathwiseEnvOverridesMap; // Mapping of path-wise // environment variables that // will be mapped into // corresponding settings const extras::ConfigLoadHelper::EnvVariablesMap* envVariablesMap; // Mapping of common environment variables const char* const* pluginSearchPaths; // Array of directories used by the system to search for plugins size_t pluginSearchPathCount; // Number of elements in the pluginSearchPaths const char* cmdLineConfigPath; // Path to a file containing config override (in selected configFormat), can be // null const char* configFormat; // Selected configuration format that is supported by the system inline static LoadSettingsDesc getDefault() noexcept { LoadSettingsDesc result{}; Framework* f = getFramework(); filesystem::IFileSystem* fs = f->acquireInterface<filesystem::IFileSystem>(); extras::Path execPathStem(extras::getPathStem(fs->getExecutablePath())); // Initialize application path and name to the executable path and name result.appName = execPathStem.getFilename(); result.appDir = execPathStem.getParent(); result.configFormat = "toml"; return result; } inline void overwriteWithNonEmptyParams(const LoadSettingsDesc& other) noexcept { if (!other.appDir.empty()) { appDir = other.appDir; } if (!other.appName.empty()) { appName = other.appName; } if (other.configStringOrPath) { configStringOrPath = other.configStringOrPath; } if (other.cmdLineOptionsMap) { cmdLineOptionsMap = other.cmdLineOptionsMap; } if (other.pathwiseEnvOverridesMap) { pathwiseEnvOverridesMap = other.pathwiseEnvOverridesMap; } if (other.envVariablesMap) { envVariablesMap = other.envVariablesMap; } if (other.pluginSearchPaths) { pluginSearchPaths = other.pluginSearchPaths; pluginSearchPathCount = other.pluginSearchPathCount; } if (other.cmdLineConfigPath) { cmdLineConfigPath = other.cmdLineConfigPath; } if (other.configFormat) { configFormat = other.configFormat; } } }; void loadBaseSettingsPlugins(const char* const* pluginSearchPaths, size_t pluginSearchPathCount) { Framework* f = getFramework(); // clang-format off const char* plugins[] = { "carb.dictionary.plugin", "carb.settings.plugin", "carb.tokens.plugin", m_selectedConfigInfo ? m_selectedConfigInfo->serializerPluginName : "carb.dictionary.serializer-toml.plugin" }; // clang-format on loadPluginsFromPatterns(plugins, countOf(plugins), pluginSearchPaths, pluginSearchPathCount); m_idict = f->tryAcquireInterface<dictionary::IDictionary>(); if (m_idict == nullptr) { CARB_LOG_INFO("Couldn't acquire dictionary::IDictionary interface on startup to load the settings."); return; } m_settings = f->tryAcquireInterface<settings::ISettings>(); if (m_settings == nullptr) { CARB_LOG_INFO("Couldn't acquire settings::ISettings interface on startup to load the settings."); } } class ConfigStageLoader { public: static constexpr const char* kConfigSuffix = ".config"; static constexpr const char* kOverrideSuffix = ".override"; ConfigStageLoader(filesystem::IFileSystem* fs, dictionary::ISerializer* configSerializer, LoadSettingsHelper* helper, const SupportedConfigInfo* selectedConfigInfo, const extras::ConfigLoadHelper::EnvVariablesMap* envVariablesMap) : m_fs(fs), m_configSerializer(configSerializer), m_helper(helper), m_selectedConfigInfo(selectedConfigInfo), m_envVariablesMap(envVariablesMap) { m_possibleConfigPathsStorage.reserve(4); } dictionary::Item* loadAndMergeSharedUserSpaceConfig(const extras::Path& userFolder, dictionary::Item* combinedConfig, std::string* sharedUserSpaceFilepath) { if (!userFolder.isEmpty()) { m_possibleConfigPathsStorage.clear(); m_possibleConfigPathsStorage.emplace_back(userFolder / "omni" + kConfigSuffix + m_selectedConfigInfo->configExt); return tryLoadAnySettingsAndMergeIntoTarget(m_configSerializer, combinedConfig, m_possibleConfigPathsStorage, m_envVariablesMap, sharedUserSpaceFilepath); } return combinedConfig; } dictionary::Item* loadAndMergeAppSpecificUserSpaceConfig(const extras::Path& userFolder, const std::string& appName, dictionary::Item* combinedConfig, std::string* appSpecificUserSpaceFilepath) { if (!userFolder.isEmpty()) { m_possibleConfigPathsStorage.clear(); m_possibleConfigPathsStorage.emplace_back(userFolder / appName + kConfigSuffix + m_selectedConfigInfo->configExt); return tryLoadAnySettingsAndMergeIntoTarget(m_configSerializer, combinedConfig, m_possibleConfigPathsStorage, m_envVariablesMap, appSpecificUserSpaceFilepath); } return combinedConfig; } dictionary::Item* loadAndMergeLocalSpaceConfig(const std::string& appDir, const std::string& appName, dictionary::Item* combinedConfig, std::string* localSpaceConfigFilepath) { const extras::Path cwd(m_fs->getCurrentDirectoryPath()); const extras::Path appDirPath(appDir); const extras::Path exePath(m_fs->getExecutableDirectoryPath()); const std::string appConfig = appName + kConfigSuffix + m_selectedConfigInfo->configExt; m_possibleConfigPathsStorage.clear(); m_possibleConfigPathsStorage.emplace_back(cwd / appConfig); if (!appDir.empty()) { m_possibleConfigPathsStorage.emplace_back(appDirPath / appConfig); } if (appDirPath != exePath) { m_possibleConfigPathsStorage.emplace_back(exePath / appConfig); } return tryLoadAnySettingsAndMergeIntoTarget(m_configSerializer, combinedConfig, m_possibleConfigPathsStorage, m_envVariablesMap, localSpaceConfigFilepath); } dictionary::Item* loadAndMergeSharedUserSpaceConfigOverride(dictionary::Item* combinedConfig, const std::string& sharedUserSpaceFilepath) { if (!sharedUserSpaceFilepath.empty()) { m_possibleConfigPathsStorage.clear(); addPossiblePathOverridesForSearch( extras::getPathStem(sharedUserSpaceFilepath), m_selectedConfigInfo->configExt); return tryLoadAnySettingsAndMergeIntoTarget( m_configSerializer, combinedConfig, m_possibleConfigPathsStorage, m_envVariablesMap, nullptr); } return combinedConfig; } dictionary::Item* loadAndMergeAppSpecificUserSpaceConfigOverride(dictionary::Item* combinedConfig, const std::string& appSpecificUserSpaceFilepath) { if (!appSpecificUserSpaceFilepath.empty()) { m_possibleConfigPathsStorage.clear(); addPossiblePathOverridesForSearch( extras::getPathStem(appSpecificUserSpaceFilepath), m_selectedConfigInfo->configExt); return tryLoadAnySettingsAndMergeIntoTarget( m_configSerializer, combinedConfig, m_possibleConfigPathsStorage, m_envVariablesMap, nullptr); } return combinedConfig; } dictionary::Item* loadAndMergeLocalSpaceConfigOverride(dictionary::Item* combinedConfig, const std::string& localSpaceConfigFilepath) { if (!localSpaceConfigFilepath.empty()) { m_possibleConfigPathsStorage.clear(); addPossiblePathOverridesForSearch( extras::getPathStem(localSpaceConfigFilepath), m_selectedConfigInfo->configExt); return tryLoadAnySettingsAndMergeIntoTarget( m_configSerializer, combinedConfig, m_possibleConfigPathsStorage, m_envVariablesMap, nullptr); } return combinedConfig; } dictionary::Item* loadAndMergeCustomConfig(dictionary::Item* combinedConfig, const char* filepath, dictionary::ISerializer* customSerializer = nullptr) { m_possibleConfigPathsStorage.clear(); m_possibleConfigPathsStorage.emplace_back(filepath); dictionary::ISerializer* configSerializer = customSerializer ? customSerializer : m_configSerializer; return tryLoadAnySettingsAndMergeIntoTarget( configSerializer, combinedConfig, m_possibleConfigPathsStorage, m_envVariablesMap, nullptr); } private: void addPossiblePathOverridesForSearch(const std::string& pathStem, const char* extension) { m_possibleConfigPathsStorage.emplace_back(pathStem + kOverrideSuffix + extension); m_possibleConfigPathsStorage.emplace_back(pathStem + extension + kOverrideSuffix); } dictionary::Item* tryLoadAnySettingsAndMergeIntoTarget(dictionary::ISerializer* configSerializer, dictionary::Item* targetDict, const std::vector<std::string>& possibleConfigPaths, const extras::ConfigLoadHelper::EnvVariablesMap* envVariablesMap, std::string* loadedDictPath) { if (loadedDictPath) { loadedDictPath->clear(); } dictionary::Item* loadedDict = nullptr; for (const auto& curConfigPath : possibleConfigPaths) { const char* dictFilename = curConfigPath.c_str(); if (!m_fs->exists(dictFilename)) { continue; } loadedDict = dictionary::createDictionaryFromFile(configSerializer, dictFilename); if (loadedDict) { if (loadedDictPath) { *loadedDictPath = dictFilename; } CARB_LOG_INFO("Found and loaded settings from: %s", dictFilename); break; } else { CARB_LOG_ERROR("Couldn't load the '%s' config data from file '%s'", m_selectedConfigInfo->configFormatName, dictFilename); break; } } dictionary::IDictionary* dictionaryInterface = m_helper->getDictionaryInterface(); return extras::ConfigLoadHelper::resolveAndMergeNewDictIntoTarget( dictionaryInterface, targetDict, loadedDict, loadedDictPath ? loadedDictPath->c_str() : nullptr, envVariablesMap); } std::vector<std::string> m_possibleConfigPathsStorage; filesystem::IFileSystem* m_fs = nullptr; dictionary::ISerializer* m_configSerializer = nullptr; LoadSettingsHelper* m_helper = nullptr; const SupportedConfigInfo* m_selectedConfigInfo = nullptr; const extras::ConfigLoadHelper::EnvVariablesMap* m_envVariablesMap = nullptr; }; inline dictionary::ISerializer* acquireOrLoadSerializerFromConfigInfo(const LoadSettingsDesc& params, const SupportedConfigInfo* configInfo) { dictionary::ISerializer* configSerializer = getFramework()->tryAcquireInterface<dictionary::ISerializer>(configInfo->serializerPluginName); if (configSerializer) return configSerializer; return loadConfigSerializerPlugin(params.pluginSearchPaths, params.pluginSearchPathCount, configInfo); } inline dictionary::Item* readConfigStages(const LoadSettingsDesc& params, std::string* localSpaceConfigFilepath, std::string* customConfigFilepath, std::string* cmdLineConfigFilepath) { if (!m_configSerializer) { return nullptr; } CARB_LOG_INFO("Using '%s' format for config files.", m_selectedConfigInfo->configFormatName); dictionary::Item* combinedConfig = nullptr; extras::Path userFolder = extras::ConfigLoadHelper::getConfigUserFolder(params.envVariablesMap); std::string sharedUserSpaceFilepath; std::string appSpecificUserSpaceFilepath; ConfigStageLoader configStageLoader(m_fs, m_configSerializer, this, m_selectedConfigInfo, params.envVariablesMap); // Base configs combinedConfig = configStageLoader.loadAndMergeSharedUserSpaceConfig(userFolder, combinedConfig, &sharedUserSpaceFilepath); combinedConfig = configStageLoader.loadAndMergeAppSpecificUserSpaceConfig( userFolder, params.appName, combinedConfig, &appSpecificUserSpaceFilepath); combinedConfig = configStageLoader.loadAndMergeLocalSpaceConfig( params.appDir, params.appName, combinedConfig, localSpaceConfigFilepath); // Overrides combinedConfig = configStageLoader.loadAndMergeSharedUserSpaceConfigOverride(combinedConfig, sharedUserSpaceFilepath); combinedConfig = configStageLoader.loadAndMergeAppSpecificUserSpaceConfigOverride( combinedConfig, appSpecificUserSpaceFilepath); combinedConfig = configStageLoader.loadAndMergeLocalSpaceConfigOverride(combinedConfig, *localSpaceConfigFilepath); tokens::ITokens* tokensInterface = carb::getFramework()->tryAcquireInterface<tokens::ITokens>(); // Loading text configuration override if (params.configStringOrPath) { std::string configPath; if (tokensInterface) { configPath = tokens::resolveString(tokensInterface, params.configStringOrPath); } else { configPath = params.configStringOrPath; } if (m_fs->exists(configPath.c_str())) { std::string configExt = extras::Path(configPath).getExtension(); const SupportedConfigInfo* configInfo = getConfigInfoFromExtension(configExt.c_str()); dictionary::ISerializer* customSerializer = acquireOrLoadSerializerFromConfigInfo(params, configInfo); if (customConfigFilepath) *customConfigFilepath = configPath; combinedConfig = configStageLoader.loadAndMergeCustomConfig(combinedConfig, configPath.c_str(), customSerializer); } else { dictionary::Item* textConfigurationOverride = m_configSerializer->createDictionaryFromStringBuffer(params.configStringOrPath); if (textConfigurationOverride) { CARB_LOG_INFO("Loaded text configuration override"); combinedConfig = extras::ConfigLoadHelper::resolveAndMergeNewDictIntoTarget( m_idict, combinedConfig, textConfigurationOverride, "text configuration override", params.envVariablesMap); } else { CARB_LOG_ERROR("Couldn't process provided config string as a '%s' config file or config data", m_selectedConfigInfo->configFormatName); } } } // Loading custom file configuration override if (params.cmdLineConfigPath) { std::string configPath; if (tokensInterface) { configPath = tokens::resolveString(tokensInterface, params.cmdLineConfigPath); } else { configPath = params.cmdLineConfigPath; } if (m_fs->exists(configPath.c_str())) { std::string configExt = extras::Path(configPath).getExtension(); const SupportedConfigInfo* configInfo = getConfigInfoFromExtension(configExt.c_str()); dictionary::ISerializer* customSerializer = acquireOrLoadSerializerFromConfigInfo(params, configInfo); if (cmdLineConfigFilepath) *cmdLineConfigFilepath = params.cmdLineConfigPath; combinedConfig = configStageLoader.loadAndMergeCustomConfig(combinedConfig, configPath.c_str(), customSerializer); } else { CARB_LOG_ERROR("The config file '%s' provided via command line doesn't exist", params.cmdLineConfigPath); } } combinedConfig = extras::ConfigLoadHelper::applyPathwiseEnvOverrides( m_idict, combinedConfig, params.pathwiseEnvOverridesMap, params.envVariablesMap); combinedConfig = extras::ConfigLoadHelper::applyCmdLineOverrides( m_idict, combinedConfig, params.cmdLineOptionsMap, params.envVariablesMap); return combinedConfig; } const auto& getSupportedConfigTypes() { static const std::array<SupportedConfigInfo, 2> kSupportedConfigTypes = { { { "toml", "carb.dictionary.serializer-toml.plugin", ".toml" }, { "json", "carb.dictionary.serializer-json.plugin", ".json" } } }; return kSupportedConfigTypes; } const SupportedConfigInfo* getConfigInfoFromExtension(const char* configExtension) { const std::string parmsConfigExt = configExtension; for (const auto& curConfigInfo : getSupportedConfigTypes()) { const char* curConfigExtEnd = curConfigInfo.configExt + std::strlen(curConfigInfo.configExt); if (std::equal(curConfigInfo.configExt, curConfigExtEnd, parmsConfigExt.begin(), parmsConfigExt.end(), [](char l, char r) { return std::tolower(l) == std::tolower(r); })) { return &curConfigInfo; } } return nullptr; } const SupportedConfigInfo* getConfigInfoFromFormatName(const char* configFormat) { const std::string parmsConfigFormat = configFormat; for (const auto& curConfigInfo : getSupportedConfigTypes()) { const char* curConfigFormatEnd = curConfigInfo.configFormatName + std::strlen(curConfigInfo.configFormatName); if (std::equal(curConfigInfo.configFormatName, curConfigFormatEnd, parmsConfigFormat.begin(), parmsConfigFormat.end(), [](char l, char r) { return std::tolower(l) == std::tolower(r); })) { return &curConfigInfo; } } return nullptr; } void selectConfigType(const char* configFormat) { m_selectedConfigInfo = getConfigInfoFromFormatName(configFormat); if (!m_selectedConfigInfo) { CARB_LOG_ERROR("Unsupported configuration format: %s. Falling back to %s", configFormat, getSupportedConfigTypes()[0].configFormatName); m_selectedConfigInfo = &getSupportedConfigTypes()[0]; } } static dictionary::ISerializer* loadConfigSerializerPlugin(const char* const* pluginSearchPaths, size_t pluginSearchPathCount, const SupportedConfigInfo* configInfo) { if (!configInfo) { return nullptr; } dictionary::ISerializer* configSerializer = getFramework()->tryAcquireInterface<dictionary::ISerializer>(configInfo->serializerPluginName); if (!configSerializer) { loadPluginsFromPattern(configInfo->serializerPluginName, pluginSearchPaths, pluginSearchPathCount); configSerializer = getFramework()->tryAcquireInterface<dictionary::ISerializer>(configInfo->serializerPluginName); } if (!configSerializer) { CARB_LOG_ERROR("Couldn't acquire ISerializer interface on startup for parsing '%s' settings.", configInfo->configFormatName); } return configSerializer; } void loadSelectedConfigSerializerPlugin(const char* const* pluginSearchPaths, size_t pluginSearchPathCount) { m_configSerializer = loadConfigSerializerPlugin(pluginSearchPaths, pluginSearchPathCount, m_selectedConfigInfo); } void fixRawStrings(dictionary::Item* combinedConfig) { // Fixing the special raw strings auto rawStringsFixer = [&](dictionary::Item* item, uint32_t elementData, void* userData) { CARB_UNUSED(elementData, userData); const char* rawString = getRawStringFromItem(m_idict, item); if (!rawString) { return 0; } // buffering the value to be implementation-safe const std::string value(rawString); m_idict->setString(item, value.c_str()); return 0; }; const auto getChildByIndexMutable = [](dictionary::IDictionary* dict, dictionary::Item* item, size_t index) { return dict->getItemChildByIndexMutable(item, index); }; dictionary::walkDictionary(m_idict, dictionary::WalkerMode::eIncludeRoot, combinedConfig, 0, rawStringsFixer, nullptr, getChildByIndexMutable); } dictionary::IDictionary* getDictionaryInterface() const { return m_idict; } dictionary::ISerializer* getConfigSerializerInterface() const { return m_configSerializer; } settings::ISettings* getSettingsInterface() const { return m_settings; } dictionary::Item* createEmptyDict(const char* name = "<config>") { dictionary::Item* item = m_idict->createItem(nullptr, name, dictionary::ItemType::eDictionary); if (!item) { CARB_LOG_ERROR("Couldn't create empty configuration"); } return item; }; private: filesystem::IFileSystem* m_fs = nullptr; dictionary::IDictionary* m_idict = nullptr; dictionary::ISerializer* m_configSerializer = nullptr; settings::ISettings* m_settings = nullptr; const SupportedConfigInfo* m_selectedConfigInfo = nullptr; }; /** * Helper function to initialize the settings and tokens plugins from different configuration sources */ inline void loadSettings(const LoadSettingsHelper::LoadSettingsDesc& settingsDesc) { Framework* f = getFramework(); // Preparing settings parameters LoadSettingsHelper::LoadSettingsDesc params = LoadSettingsHelper::LoadSettingsDesc::getDefault(); params.overwriteWithNonEmptyParams(settingsDesc); LoadSettingsHelper loadSettingsHelper; loadSettingsHelper.selectConfigType(params.configFormat); loadSettingsHelper.loadBaseSettingsPlugins(params.pluginSearchPaths, params.pluginSearchPathCount); filesystem::IFileSystem* fs = f->acquireInterface<filesystem::IFileSystem>(); tokens::ITokens* tokensInterface = f->tryAcquireInterface<tokens::ITokens>(); // Initializing tokens if (tokensInterface) { const char* kExePathToken = "exe-path"; const char* kExeFilenameToken = "exe-filename"; carb::extras::Path exeFullPath = fs->getExecutablePath(); tokensInterface->setInitialValue(kExePathToken, exeFullPath.getParent().getStringBuffer()); tokensInterface->setInitialValue(kExeFilenameToken, exeFullPath.getFilename().getStringBuffer()); } settings::ISettings* settings = loadSettingsHelper.getSettingsInterface(); std::string localSpaceConfigFilepath; std::string customConfigFilepath; std::string cmdLineConfigFilepath; if (settings) { loadSettingsHelper.loadSelectedConfigSerializerPlugin(params.pluginSearchPaths, params.pluginSearchPathCount); dictionary::Item* combinedConfig = nullptr; combinedConfig = loadSettingsHelper.readConfigStages( params, &localSpaceConfigFilepath, &customConfigFilepath, &cmdLineConfigFilepath); if (!combinedConfig) { dictionary::IDictionary* dictionaryInterface = loadSettingsHelper.getDictionaryInterface(); CARB_LOG_INFO("Using empty configuration for settings as no other sources created it."); combinedConfig = dictionaryInterface->createItem(nullptr, "<settings>", dictionary::ItemType::eDictionary); } if (!combinedConfig) { CARB_LOG_ERROR("Couldn't initialize settings because no configuration were created."); } else { loadSettingsHelper.fixRawStrings(combinedConfig); // Making the settings from the result dictionary settings->initializeFromDictionary(combinedConfig); } } else { CARB_LOG_INFO("Couldn't acquire ISettings interface on startup to load settings."); } // Initializing tokens if (tokensInterface) { const char* kLocalSpaceConfigPathToken = "local-config-path"; const char* kLocalSpaceConfigPathTokenStr = "${local-config-path}"; const char* kCustomConfigPathToken = "custom-config-path"; const char* kCmdLineConfigPathToken = "cli-config-path"; if (!localSpaceConfigFilepath.empty()) { tokensInterface->setInitialValue(kLocalSpaceConfigPathToken, localSpaceConfigFilepath.c_str()); } else { tokensInterface->setInitialValue(kLocalSpaceConfigPathToken, fs->getCurrentDirectoryPath()); } if (!customConfigFilepath.empty()) { tokensInterface->setInitialValue(kCustomConfigPathToken, customConfigFilepath.c_str()); } else { tokensInterface->setInitialValue(kCustomConfigPathToken, kLocalSpaceConfigPathTokenStr); } if (!cmdLineConfigFilepath.empty()) { tokensInterface->setInitialValue(kCmdLineConfigPathToken, cmdLineConfigFilepath.c_str()); } else { tokensInterface->setInitialValue(kCmdLineConfigPathToken, kLocalSpaceConfigPathTokenStr); } } else { CARB_LOG_INFO("Couldn't acquire tokens interface and initialize default tokens."); } } #endif // DOXYGEN_SHOULD_SKIP_THIS } // namespace detail //! Loads the framework configuration based on a slew of input parameters. //! //! First see @ref carb::StartupFrameworkDesc for an idea of the type of data this function accepts. //! //! At a high-level this function: //! //! - Determines application path from CLI args and env vars (see @ref carb::extras::getAppPathAndName()). //! - Sets application path as filesystem root //! - Loads plugins for settings: *carb.settings.plugin*, *carb.dictionary.plugin*, *carb.tokens.plugins* and any //! serializer plugin. //! - Searches for config file, loads it and applies CLI args overrides. //! //! Rather than this function, consider using @ref OMNI_CORE_INIT(), which handles both starting and shutting down the //! framework for you in your application. inline void loadFrameworkConfiguration(const StartupFrameworkDesc& params) { Framework* f = getFramework(); const StartupFrameworkDesc& defaultStartupFrameworkDesc = StartupFrameworkDesc::getDefault(); const char* cmdLineParamPrefix = params.cmdLineParamPrefix; if (!cmdLineParamPrefix) { cmdLineParamPrefix = defaultStartupFrameworkDesc.cmdLineParamPrefix; } const char* envVarsParamPrefix = params.envVarsParamPrefix; if (!envVarsParamPrefix) { envVarsParamPrefix = defaultStartupFrameworkDesc.envVarsParamPrefix; } const char* configFormat = params.configFormat; if (!configFormat) { configFormat = defaultStartupFrameworkDesc.configFormat; } char** const argv = params.argv; const int argc = params.argc; extras::CmdLineParser cmdLineParser(cmdLineParamPrefix); cmdLineParser.parse(argv, argc); const extras::CmdLineParser::Options& args = cmdLineParser.getOptions(); const char* cmdLineConfigPath = nullptr; bool verboseConfiguration = false; int32_t startLogLevel = logging::getLogging()->getLevelThreshold(); if (argv && argc > 0) { auto findOptionIndex = [=](const char* option) { for (int i = 0; i < argc; ++i) { const char* curArg = argv[i]; if (curArg && !strcmp(curArg, option)) { return i; } } return -1; }; auto findOptionValue = [=](const char* option) -> const char* { const int optionIndex = findOptionIndex(option); if (optionIndex == -1) { return nullptr; } if (optionIndex >= argc - 1) { CARB_LOG_ERROR("Argument not present for the '%s' option", option); } return argv[optionIndex + 1]; }; // Parsing verbose configuration option const char* const kVerboseConfigKey = "--verbose-config"; verboseConfiguration = findOptionIndex(kVerboseConfigKey) != -1; if (verboseConfiguration) { logging::getLogging()->setLevelThreshold(logging::kLevelVerbose); } // Parsing cmd line for "--config-path" argument const char* const kConfigPathKey = "--config-path"; cmdLineConfigPath = findOptionValue(kConfigPathKey); if (cmdLineConfigPath) { CARB_LOG_INFO("Using '%s' as the value for '%s'", cmdLineConfigPath, kConfigPathKey); } // Parsing config format from the command line const char* kConfigFormatKey = "--config-format"; const char* const configFormatValue = findOptionValue(kConfigFormatKey); if (configFormatValue) { configFormat = configFormatValue; } } carb::extras::EnvironmentVariableParser envVarsParser(envVarsParamPrefix); envVarsParser.parse(); filesystem::IFileSystem* fs = f->acquireInterface<filesystem::IFileSystem>(); // Prepare application path and name, which will be used to initialize the IFileSystem default root folder, // and also as one of the variants of configuration file name and location. std::string appPath, appName; extras::getAppPathAndName(args, appPath, appName); // If explicitly specified - override this search logic. That means an application doesn't give a control over // app path and/or app name through settings and env vars. if (params.appNameOverride) appName = params.appNameOverride; if (params.appPathOverride) appPath = params.appPathOverride; CARB_LOG_INFO("App path: %s, name: %s", appPath.c_str(), appName.c_str()); // set the application path for the process. This will be one of the locations we search for // the config file by default. fs->setAppDirectoryPath(appPath.c_str()); // Loading settings from config and command line. { detail::LoadSettingsHelper::LoadSettingsDesc loadSettingsParams = detail::LoadSettingsHelper::LoadSettingsDesc::getDefault(); loadSettingsParams.appDir = appPath; loadSettingsParams.appName = appName; loadSettingsParams.configStringOrPath = params.configString; loadSettingsParams.cmdLineOptionsMap = &args; loadSettingsParams.pathwiseEnvOverridesMap = &envVarsParser.getOptions(); loadSettingsParams.envVariablesMap = &envVarsParser.getEnvVariables(); loadSettingsParams.pluginSearchPaths = params.initialPluginsSearchPaths; loadSettingsParams.pluginSearchPathCount = params.initialPluginsSearchPathCount; loadSettingsParams.cmdLineConfigPath = cmdLineConfigPath; loadSettingsParams.configFormat = configFormat; detail::loadSettings(loadSettingsParams); } // restoring the starting log level if (verboseConfiguration) { logging::getLogging()->setLevelThreshold(startLogLevel); } } //! Configures the framework given a slew of input parameters. //! //! First see @ref carb::StartupFrameworkDesc for an idea of the type of data this function accepts. //! //! At a high-level this function: //! //! - Configures logging with config file //! - Loads plugins according to config file with (see \ref detail::loadPluginsFromConfig()) //! - Configures default plugins according to config file (see \ref detail::setDefaultPluginsFromConfig()) //! - Starts the default profiler (if loaded) //! //! Rather than this function, consider using @ref OMNI_CORE_INIT(), which handles both starting and shutting down the //! framework for you in your application. inline void configureFramework(const StartupFrameworkDesc& params) { Framework* f = getFramework(); if (!params.disableCrashReporter) { // Startup the crash reporter loadPluginsFromPattern( "carb.crashreporter-*", params.initialPluginsSearchPaths, params.initialPluginsSearchPathCount); crashreporter::registerCrashReporterForClient(); } auto settings = f->tryAcquireInterface<carb::settings::ISettings>(); // Configure logging plugin and its default logger logging::configureLogging(settings); logging::configureDefaultLogger(settings); omni::structuredlog::configureStructuredLogging(settings); // Uploading leftover dumps asynchronously if (settings != nullptr) { if (!params.disableCrashReporter) { const char* const kStarupDumpsUploadKey = "/app/uploadDumpsOnStartup"; settings->setDefaultBool(kStarupDumpsUploadKey, true); if (settings->getAsBool(kStarupDumpsUploadKey)) { crashreporter::sendAndRemoveLeftOverDumpsAsync(); } } // specify the plugin search paths in settings so that loadPluginsFromConfig() // will have the search paths to look through const char* kPluginSearchPathsKey = "/pluginSearchPaths"; // only set this if nothing else has been manually set settings->setDefaultStringArray( kPluginSearchPathsKey, params.initialPluginsSearchPaths, params.initialPluginsSearchPathCount); } // Load plugins using supplied configuration detail::loadPluginsFromConfig(settings); // Configure default plugins as present in the config detail::setDefaultPluginsFromConfig(settings); #if !CARB_PLATFORM_MACOS // CC-669: avoid registering this on Mac OS since it's unimplemented // Starting up profiling // This way of registering profiler allows to enable/disable profiling in the config file, by // allowing/denying to load profiler plugin. carb::profiler::registerProfilerForClient(); CARB_PROFILE_STARTUP(); #endif carb::l10n::registerLocalizationForClient(); } //! Starts/Configures the framework given a slew of input parameters. //! //! First see @ref carb::StartupFrameworkDesc for an idea of the type of data this function accepts. //! //! At a high-level this function: //! //! - Calls \ref loadFrameworkConfiguration(), which: //! - Determines application path from CLI args and env vars (see @ref carb::extras::getAppPathAndName()). //! - Sets application path as filesystem root //! - Loads plugins for settings: *carb.settings.plugin*, *carb.dictionary.plugin*, *carb.tokens.plugins* and any //! serializer plugin. //! - Searches for config file, loads it and applies CLI args overrides. //! - Calls \ref configureFramework(), which: //! - Configures logging with config file //! - Loads plugins according to config file //! - Configures default plugins according to config file //! - Starts the default profiler (if loaded) //! //! Rather than this function, consider using @ref OMNI_CORE_INIT(), which handles both starting and shutting down the //! framework for you in your application. inline void startupFramework(const StartupFrameworkDesc& params) { loadFrameworkConfiguration(params); configureFramework(params); } //! Tears down the Carbonite framework. //! //! At a high level, this function: //! - Shuts down the profiler system (if running) //! - Calls \ref profiler::deregisterProfilerForClient(), \ref crashreporter::deregisterCrashReporterForClient(), and //! l10n::deregisterLocalizationForClient(). //! //! \note It is not necessary to manually call this function if \ref OMNI_CORE_INIT is used, since that macro will //! ensure that the Framework is released and shut down. inline void shutdownFramework() { CARB_PROFILE_SHUTDOWN(); profiler::deregisterProfilerForClient(); crashreporter::deregisterCrashReporterForClient(); carb::l10n::deregisterLocalizationForClient(); } } // namespace carb
53,299
C
40.349884
128
0.641194
omniverse-code/kit/include/carb/Types.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 Common types used through-out Carbonite. #pragma once #include "Interface.h" #include "Strong.h" #include "../omni/core/OmniAttr.h" #include <cstddef> #include <cstdint> namespace omni { namespace core { OMNI_DECLARE_INTERFACE(ITypeFactory) // forward declaration for entry inPluginFrameworkDesc } namespace log { class ILog; // forward declaration for entry in PluginFrameworkDesc } namespace structuredlog { class IStructuredLog; } } // namespace omni //! The main Carbonite namespace. namespace carb { //! Defines the plugin hot reloading (auto reload) behavior. //! //! @rst //! .. deprecated:: 132.0 //! Hot reloading support has been removed. No replacement will be provided. //! @endrst enum class PluginHotReload { eDisabled, eEnabled }; /** * Defines a descriptor for the plugin implementation, to be provided to the macro CARB_PLUGIN_IMPL. */ struct PluginImplDesc { const char* name; //!< Name of the plugin (e.g. "carb.dictionary.plugin"). Must be globally unique. const char* description; //!< Helpful text describing the plugin. Use for debugging/tools. const char* author; //!< Author (e.g. "NVIDIA"). //! If hot reloading is supported by the plugin. //! @rst //! .. deprecated:: 132.0 //! Hot reloading support has been removed. No replacement will be provided. //! @endrst PluginHotReload hotReload; const char* build; //!< Build version of the plugin. }; CARB_ASSERT_INTEROP_SAFE(PluginImplDesc); //! Defines a struct to be filled by a plugin to provide the framework with all information about it. //! @note This struct has been superseded by PluginRegistryEntry2 but exists for historical and backwards-compatibility. //! In the past, this struct was filled by the macro CARB_PLUGIN_IMPL. struct PluginRegistryEntry { PluginImplDesc implDesc; //!< Textual information about the plugin (name, desc, etc). //! Entry in an array of interfaces implemented by the plugin. struct Interface { InterfaceDesc desc; //!< An interface in the plugin. const void* ptr; //!< Pointer to the interface's `struct`. size_t size; //!< Size of the interface's `struct`. }; Interface* interfaces; //!< Pointer to an array of interfaces implemented by the plugin. size_t interfaceCount; //!< Number of interfaces in the @p interfaces array. }; CARB_ASSERT_INTEROP_SAFE(PluginRegistryEntry); CARB_ASSERT_INTEROP_SAFE(PluginRegistryEntry::Interface); //! Defines a struct to be filled by a plugin to provide the framework with all information about it. //! This struct is automatically created and filled by the macro CARB_PLUGIN_IMPL. struct PluginRegistryEntry2 { size_t sizeofThisStruct; //!< Must reflect `sizeof(PluginRegistryEntry2)`; used as a version for this struct. PluginImplDesc implDesc; //!< Textual information about the plugin (name, desc, etc). //! Entry in an array of interfaces implemented by the plugin. struct Interface2 { size_t sizeofThisStruct; //!< Must reflect `sizeof(Interface2)`; used as a version for this struct. InterfaceDesc desc; //!< An interface in the plugin. size_t size; //!< Required size for the interface (must be the maximum size for all supported versions) size_t align; //!< Required alignment for the interface //! Constructor function for this interface within the plugin (auto-generated by \ref CARB_PLUGIN_IMPL). //! //! Called by the framework to construct the interface. //! @param p The buffer (guaranteed to be at least `size` bytes) to construct the interface into. void(CARB_ABI* Constructor)(void* p); union { //! Destructor function for this interface within the plugin (auto-generated by \ref CARB_PLUGIN_IMPL). //! //! This union member is selected if `VersionedConstructor` is `nullptr`. //! //! Called by the framework to destruct the interface before unloading the plugin. //! @param p The buffer previously passed to \ref Constructor that contains the interface. void(CARB_ABI* Destructor)(void* p); //! Versioned destructor for this interface within the plugin. //! //! This union member is selected if `VersionedConstructor` is not `nullptr`. //! //! This function is typically the user-provided function \ref destroyInterface; if that function is not //! provided no destruction happens. //! @param v The version of the interface, as set in the `v` parameter for \ref VersionedConstructor before //! that function returns. //! @param p The interface buffer that was originally passed to \ref VersionedConstructor. void(CARB_ABI* VersionedDestructor)(Version v, void* p); //!< Destructor with version }; //! Versioned constructor function for this interface within the plugin. //! //! This function is typically \ref fillInterface(carb::Version*, void*). //! @warning This function must not fail when `desc.version` is requested. //! //! @param v When called, the version requested. Before returning, the function should write the version that is //! being constructed into \p p. //! @param p A buffer (guaranteed to be at least `size` bytes) to construct the interface into. //! @retval `true` if the requested version was available and constructed into \p p. //! @retval `false` if the requested version is not available. bool(CARB_ABI* VersionedConstructor)(Version* v, void* p); // Internal note: This struct can be modified via the same rules for PluginRegistryEntry2 below. }; Interface2* interfaces; //!< Pointer to an array of interfaces implemented by the plugin. size_t interfaceCount; //!< Number of interfaces in the @p interfaces array. // Internal note: This struct can be modified without changing the carbonite framework version, provided that new // members are only added to the end of the struct and existing members are not modified. The version can then be // determined by the sizeofThisStruct member. However, if it is modified, please add a new // carb.frameworktest.*.plugin (see ex2initial in premake5.lua for an example). }; CARB_ASSERT_INTEROP_SAFE(PluginRegistryEntry2); CARB_ASSERT_INTEROP_SAFE(PluginRegistryEntry2::Interface2); /** * Defines a struct which contains all key information about a plugin loaded into memory. */ struct PluginDesc { PluginImplDesc impl; //!< Name, description, etc. const InterfaceDesc* interfaces; //!< Array of interfaces implemented by the plugin. size_t interfaceCount; //!< Number of interfaces implemented by the plugin. const InterfaceDesc* dependencies; //!< Array of interfaces on which the plugin depends. size_t dependencyCount; //!< Number of interfaces on which the plugin depends. const char* libPath; //!< File from which the plugin was loaded. }; CARB_ASSERT_INTEROP_SAFE(PluginDesc); //! Lets clients of a plugin know both just before and just after that the plugin is being reloaded. enum class PluginReloadState { eBefore, //!< The plugin is about to be reloaded. eAfter //!< The plugin has been reloaded. }; //! Pass to each plugin's @ref OnPluginRegisterExFn during load. Allows the plugin to grab global Carbonite state such //! as the @ref carb::Framework singleton. struct PluginFrameworkDesc { struct Framework* framework; //!< Owning carb::Framework. Never `nullptr`. omni::core::ITypeFactory* omniTypeFactory; //!< omni::core::ITypeFactory singleton. May be `nullptr`. omni::log::ILog* omniLog; //!< omni::log::ILog singleton. May be `nullptr`. omni::structuredlog::IStructuredLog* omniStructuredLog; //!< omni::structuredlog::IStructuredLog singleton. May be //!< `nullptr`. //! Reserved space for future fields. If a new field is added, subtract 1 from this array. //! //! The fields above must never be removed though newer implementations of carb.dll may decide to populate them with //! nullptr. //! //! When a newer plugin is loaded by an older carb.dll, these fields will be nullptr. It is up to the newer plugin //! (really CARB_PLUGIN_IMPL_WITH_INIT()) to handle this. void* Reserved[28]; }; static_assert(sizeof(PluginFrameworkDesc) == (sizeof(void*) * 32), "sizeof(PluginFrameworkDesc) is unexpected. did you add a new field improperly?"); // contact ncournia for // questions /** * Defines a shared object handle. */ struct CARB_ALIGN_AS(8) SharedHandle { union { void* handlePointer; ///< A user-defined pointer. void* handleWin32; ///< A Windows/NT HANDLE. Defined as void* instead of "HANDLE" to avoid requiring windows.h. int handleFd; ///< A file descriptor (FD), POSIX handle. }; }; //! @defgroup CarbonitePluginExports Functions exported from Carbonite plugins. Use @ref CARB_PLUGIN_IMPL to have //! reasonable default implementations of these function implemented for you in your plugin. //! Required. Returns the plugin's required @ref carb::Framework version. // //! Use @ref CARB_PLUGIN_IMPL to have this function generated for your plugin. //! //! Most users will not have a need to define this function, as it is defined by default via @ref CARB_PLUGIN_IMPL. //! //! @ingroup CarbonitePluginExports //! //! @see carbGetFrameworkVersion typedef Version(CARB_ABI* GetFrameworkVersionFn)(); //! Either this or OnPluginRegisterExFn or OnPluginRegisterEx2Fn are required. Populates the given @ref //! carb::PluginRegistryEntry with the plugin's information. //! //! Prefer using @ref OnPluginRegisterExFn instead of this function. //! //! Most users will not have a need to define this function, as it is defined by default via @ref CARB_PLUGIN_IMPL. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginRegister typedef void(CARB_ABI* OnPluginRegisterFn)(Framework* framework, PluginRegistryEntry* outEntry); //! Either this or OnPluginRegisterFn or OnPluginRegisterEx2 are required. Populates the given @ref //! carb::PluginRegistryEntry with the plugin's information. //! //! Use @ref CARB_PLUGIN_IMPL to have this function generated for your plugin. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginRegisterEx typedef void(CARB_ABI* OnPluginRegisterExFn)(PluginFrameworkDesc* framework, PluginRegistryEntry* outEntry); //! Either this or OnPluginRegisterEx2Fn or OnPluginRegisterFn are required. Populates the given //! carb::PluginRegistryEntry2 with the plugin's information. //! //! Use @ref CARB_PLUGIN_IMPL to have this function generated for your plugin. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginRegisterEx2 typedef void(CARB_ABI* OnPluginRegisterEx2Fn)(PluginFrameworkDesc* framework, PluginRegistryEntry2* outEntry); //! Optional. Called after @ref OnPluginRegisterExFn. //! //! Most users will not have a need to define this function, as it is defined by default via @ref CARB_PLUGIN_IMPL. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginPreStartup typedef void(CARB_ABI* OnPluginPreStartupFn)(); //! Optional. Called after @ref OnPluginPreStartupFn. //! //! Prefer using @ref OnPluginStartupExFn instead of this function since @ref OnPluginStartupExFn return a value that //! will cause the plugin be unloaded. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginStartup typedef void(CARB_ABI* OnPluginStartupFn)(); //! Optional. Called after @ref OnPluginPreStartupFn. //! //! This is the main user defined function for running startup code in your plugin. //! //! @returns Returns `true` if the startup was successful. If `false` is returned, the plugin will be immediately //! unloaded (only @ref OnPluginPostShutdownFn is called). //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginStartupEx typedef bool(CARB_ABI* OnPluginStartupExFn)(); //! Optional. Called after @ref OnPluginStartupExFn. //! //! Called when the @ref carb::Framework is unloading the plugin. If the framework is released with //! carb::quickReleaseFrameworkAndTerminate() and OnPluginQuickShutdownFn is available for plugin, this function is not //! called. //! //! This is the main user defined function for running shutdown code in your plugin. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginShutdown typedef void(CARB_ABI* OnPluginShutdownFn)(); //! Optional. Called if provided in lieu of OnPluginShutdownFn when the @ref carb::quickReleaseFrameworkAndTerminate() //! is performing a quick shutdown. //! //! This function should save any state necessary, and close and flush any I/O, returning as quickly as possible. This //! function is not called if the plugin is unloaded normally or through carb::releaseFramework(). //! //! @note If carb::quickReleaseFrameworkAndTerminate() is called, OnPluginQuickShutdownFn is called if it is available. //! If the function does not exist, OnPluginShutdownFn is called instead. OnPluginPostShutdownFn is always called. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginQuickShutdown typedef void(CARB_ABI* OnPluginQuickShutdownFn)(); //! Optional. Called after @ref OnPluginShutdownFn. //! //! Called when the @ref carb::Framework is unloading the plugin. //! //! Most users will not have a need to define this function, as it is defined by default via @ref CARB_PLUGIN_IMPL. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnPluginPostShutdown typedef void(CARB_ABI* OnPluginPostShutdownFn)(); //! Optional. Returns a static list of interfaces this plugin depends upon. //! //! Use @ref CARB_PLUGIN_IMPL_DEPS to have this function generated for you. //! //! @ingroup CarbonitePluginExports //! //! @see carbGetPluginDeps typedef void(CARB_ABI* GetPluginDepsFn)(InterfaceDesc** interfaceDesc, size_t* count); //! Optional. //! //! @ingroup CarbonitePluginExports //! //! @see carbOnReloadDependency typedef void(CARB_ABI* OnReloadDependencyFn)(PluginReloadState reloadState, void* pluginInterface, PluginImplDesc desc); //! Two component `float` vector. struct Float2 { float x; //!< x-component float y; //!< y-component }; //! Three component `float` vector. struct Float3 { float x; //!< x-component float y; //!< y-component float z; //!< z-component }; //! Four component `float` vector. struct Float4 { float x; //!< x-component float y; //!< y-component float z; //!< z-component float w; //!< w-component }; //! Two component `double` vector. struct Double2 { double x; //!< x-component double y; //!< y-component }; //! Three component `double` vector. struct Double3 { double x; //!< x-component double y; //!< y-component double z; //!< z-component }; //! Four component `double` vector. struct Double4 { double x; //!< x-component double y; //!< y-component double z; //!< z-component double w; //!< w-component }; //! RGBA color with templated data type. template <typename T> struct Color { T r; //!< Red T g; //!< Green T b; //!< Blue T a; //!< Alpha (transparency) }; //! RGB `float` color. struct ColorRgb { float r; //!< Red float g; //!< Green float b; //!< Blue }; //! RGBA `float` color. struct ColorRgba { float r; //!< Red float g; //!< Green float b; //!< Blue float a; //!< Alpha (transparency) }; //! RGB `double` color. struct ColorRgbDouble { double r; //!< Red double g; //!< Green double b; //!< Blue }; //! RGBA `double` color. struct ColorRgbaDouble { double r; //!< Red double g; //!< Green double b; //!< Blue double a; //!< Alpha (transparency) }; //! Two component `int32_t` vector. struct Int2 { int32_t x; //!< x-component int32_t y; //!< y-component }; //! Three component `int32_t` vector. struct Int3 { int32_t x; //!< x-component int32_t y; //!< y-component int32_t z; //!< z-component }; //! Four component `int32_t` vector. struct Int4 { int32_t x; //!< x-component int32_t y; //!< y-component int32_t z; //!< z-component int32_t w; //!< w-component }; //! Two component `uint32_t` vector. struct Uint2 { uint32_t x; //!< x-component uint32_t y; //!< y-component }; //! Three component `uint32_t` vector. struct Uint3 { uint32_t x; //!< x-component uint32_t y; //!< y-component uint32_t z; //!< z-component }; //! Four component `uint32_t` vector. struct Uint4 { uint32_t x; //!< x-component uint32_t y; //!< y-component uint32_t z; //!< z-component uint32_t w; //!< w-component }; //! A representation that can combine four character codes into a single 32-bit value for quick comparison. //! @see CARB_MAKE_FOURCC using FourCC = uint32_t; //! A macro for producing a carb::FourCC value from four characters. #define CARB_MAKE_FOURCC(a, b, c, d) \ ((FourCC)(uint8_t)(a) | ((FourCC)(uint8_t)(b) << 8) | ((FourCC)(uint8_t)(c) << 16) | ((FourCC)(uint8_t)(d) << 24)) /** * Timeout constant */ constexpr uint32_t kTimeoutInfinite = CARB_UINT32_MAX; //! A handle type for \ref Framework::addLoadHook() and \ref Framework::removeLoadHook() CARB_STRONGTYPE(LoadHookHandle, size_t); //! A value indicating an invalid load hook handle. constexpr LoadHookHandle kInvalidLoadHook{}; //! An enum that describes a binding registration for \ref carb::Framework::registerScriptBinding(). enum class BindingType : uint32_t { Owner, //!< The given client owns a script language; any interfaces acquired within the script language will be //!< considered as dependencies of the script language. Binding, //!< The given client is a binding for the given script language. Any interfaces acquired by the binding //!< will be considered as dependencies of all owners of the script language. }; } // namespace carb // these types used to be in this file but didn't really belong. we continue to include these type in this file for // backward-compat. #include "RenderingTypes.h"
18,881
C
34.293458
120
0.689158
omniverse-code/kit/include/carb/RString.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 Registered String utility. See carb::RString for more info. #pragma once #include "Defines.h" #define RSTRINGENUM_FROM_RSTRING_H #include "RStringEnum.inl" #undef RSTRINGENUM_FROM_RSTRING_H #include <memory> // for std::owner_before #include <ostream> // for std::basic_ostream #include <stdint.h> #include <string> #include <typeindex> // for std::hash namespace carb { //! Operations for RString (and variant classes) constructor. enum class RStringOp { //! Attempt to find a matching registered string, or register a new string if not found. eRegister, //! Only attempt to find a matching registered string. If the string cannot be found, the RString will be empty and //! will return `true` to RString::isEmpty(). eFindExisting, }; //! Internal definition detail. namespace detail { //! @private struct RStringBase { //! @private CARB_VIZ uint32_t m_stringId : 31; //! @private unsigned m_uncased : 1; }; //! @private // NOTE: In order to satisfy the StandardLayoutType named requirement (required for ABI safety), all non-static data // members and bit-fields must be declared in the same class. As such, this class must match RStringBase, but cannot // inherit from RStringBase. struct RStringKeyBase { //! @private CARB_VIZ uint32_t m_stringId : 31; //! @private unsigned m_uncased : 1; //! @private CARB_VIZ int32_t m_number; }; // Validate assumptions CARB_ASSERT_INTEROP_SAFE(RStringBase); CARB_ASSERT_INTEROP_SAFE(RStringKeyBase); static_assert(offsetof(RStringKeyBase, m_number) == sizeof(RStringBase), "Offset error"); /** * The base class for all registered string classes: RString, RStringU, RStringKey, and RStringUKey. * * @tparam Uncased `true` if representing an "un-cased" (i.e. case-insensitive) registered string; `false` otherwise. */ template <bool Uncased, class Base = RStringBase> class RStringTraits : protected Base { public: /** * Constant that indicates whether this is "un-cased" (i.e. case-insensitive). */ static constexpr bool IsUncased = Uncased; //! @private constexpr RStringTraits() noexcept; //! @private constexpr RStringTraits(eRString staticString) noexcept; //! @private RStringTraits(const char* str, RStringOp op); //! @private RStringTraits(const char* str, size_t len, RStringOp op); //! @private RStringTraits(const std::string& str, RStringOp op); //! @private RStringTraits(uint32_t stringId) noexcept; /** * Checks to see if this registered string has been corrupted. * * @note It is not possible for this registered string to become corrupted through normal use of the API. It could * be caused by bad casts or use-after-free. * * @returns `true` if `*this` represents a valid registered string; `false` if `*this` is corrupted. */ bool isValid() const noexcept; /** * Checks to see if this registered string represents the "" (empty) value. * * @returns `true` if `*this` is default-initialized or initialized to eRString::Empty; `false` otherwise. */ constexpr bool isEmpty() const noexcept; /** * Checks to see if this registered string represents an "un-cased" (i.e. case-insensitive) registered string. * * @returns `true` if `*this` is "un-cased" (i.e. case-insensitive); `false` if case-sensitive. */ constexpr bool isUncased() const noexcept; /** * Returns the registered string ID. This ID is only useful for debugging purposes and should not be used for * comparisons. * * @returns The string ID for this registered string. */ constexpr uint32_t getStringId() const noexcept; /** * Returns the hash value as by `carb::hashString(this->c_str())`. * * @note This value is computed once for a registered string and cached, so this operation is generally very fast. * * @returns The hash value as computed by `carb::hashString(this->c_str())`. */ size_t getHash() const; /** * Returns the hash value as by `carb::hashLowercaseString(this->c_str())`. * * @note This value is pre-computed for registered strings and cached, so this operation is always O(1). * * @returns The hash value as computed by `carb::hashLowercaseString(this->c_str())`. */ size_t getUncasedHash() const noexcept; /** * Resolves this registered string to a C-style NUL-terminated string. * * @note This operation is O(1). * * @returns The C-style string previously registered. */ const char* c_str() const noexcept; /** * An alias for c_str(); resolves this registered string to a C-style NUL-terminated string. * * @note This operation is O(1). * * @returns The C-style string previously registered. */ const char* data() const noexcept; /** * Returns the length of the registered string. If the string contains embedded NUL ('\0') characters this may * differ from `std::strlen(c_str())`. * * @note This operation is O(1). * * @returns The length of the registered string not including the NUL terminator. */ size_t length() const noexcept; #ifndef DOXYGEN_BUILD /** * Resolves this registered string to a `std::string`. * * @returns A `std::string` containing a copy of the previously registered string. */ std::string toString() const; #endif /** * Equality comparison between this registered string and another. * * @param other Another registered string. * @returns `true` if `*this` and `other` represent the same registered string; `false` otherwise. */ bool operator==(const RStringTraits& other) const; /** * Inequality comparison between this registered string and another. * * @param other Another registered string. * @returns `false` if `*this` and `other` represent the same registered string; `true` otherwise. */ bool operator!=(const RStringTraits& other) const; /** * Checks whether this registered string is stably (but not lexicographically) ordered before another registered * string. * * This ordering is to make registered strings usable as keys in ordered associative containers in O(1) time. * * @note This is NOT a lexicographical comparison; for that use one of the compare() functions. To reduce ambiguity * between a strict ordering and lexicographical comparison there is no `operator<` function for this string class. * While a lexicographical comparison would be O(n), this comparison is O(1). * * @param other Another registered string. * @returns `true` if `*this` should be ordered-before @p other; `false` otherwise. */ bool owner_before(const RStringTraits& other) const; /** * Lexicographically compares this registered string with another. * * @note If either `*this` or @p other is "un-cased" (i.e. case-insensitive), a case-insensitive compare is * performed. * * @tparam OtherUncased `true` if @p other is "un-cased" (i.e. case-insensitive); `false` otherwise. * @param other Another registered string to compare against. * @returns `0` if the strings are equal, `>0` if @p other is lexicographically ordered before `*this`, or `<0` if * `*this` is lexicographically ordered before @p other. See note above regarding case-sensitivity. */ template <bool OtherUncased, class OtherBase> int compare(const RStringTraits<OtherUncased, OtherBase>& other) const; /** * Lexicographically compares this registered string with a C-style string. * * @note If `*this` is "un-cased" (i.e. case-insensitive), a case-insensitive compare is performed. * * @param s A C-style string to compare against. * @returns `0` if the strings are equal, `>0` if @p s is lexicographically ordered before `*this`, or `<0` if * `*this` is lexicographically ordered before @p s. See note above regarding case-sensitivity. */ int compare(const char* s) const; /** * Lexicographically compares a substring of this registered string with a C-style string. * * @note If `*this` is "un-cased" (i.e. case-insensitive), a case-insensitive compare is performed. * * @param pos The starting offset of the registered string represented by `*this`. Must less-than-or-equal-to the * length of the registered string. * @param count The length from @p pos to use in the comparison. This value is automatically clamped to the end of * the registered string. * @param s A C-style string to compare against. * @returns `0` if the strings are equal, `>0` if @p s is lexicographically ordered before the substring of `*this`, * or `<0` if the substring of `*this` is lexicographically ordered before @p s. See note above regarding * case-sensitivity. */ int compare(size_t pos, size_t count, const char* s) const; /** * Lexicographically compares a substring of this registered string with a C-style string. * * @note If `*this` is "un-cased" (i.e. case-insensitive), a case-insensitive compare is performed. * * @param pos The starting offset of the registered string represented by `*this`. Must less-than-or-equal-to the * length of the registered string. * @param count The length from @p pos to use in the comparison. This value is automatically clamped to the end of * the registered string. * @param s A C-style string to compare against. * @param len The number of characters of @p s to compare against. * @returns `0` if the strings are equal, `>0` if @p s is lexicographically ordered before the substring of `*this`, * or `<0` if the substring of `*this` is lexicographically ordered before @p s. See note above regarding * case-sensitivity. */ int compare(size_t pos, size_t count, const char* s, size_t len) const; /** * Lexicographically compares this registered string with a string. * * @note If `*this` is "un-cased" (i.e. case-insensitive), a case-insensitive compare is performed. * * @param s A string to compare against. * @returns `0` if the strings are equal, `>0` if @p s is lexicographically ordered before `*this`, or `<0` if * `*this` is lexicographically ordered before @p s. See note above regarding case-sensitivity. */ int compare(const std::string& s) const; /** * Lexicographically compares a substring of this registered string with a string. * * @note If `*this` is "un-cased" (i.e. case-insensitive), a case-insensitive compare is performed. * * @param pos The starting offset of the registered string represented by `*this`. Must less-than-or-equal-to the * length of the registered string. * @param count The length from @p pos to use in the comparison. This value is automatically clamped to the end of * the registered string. * @param s A string to compare against. * @returns `0` if the strings are equal, `>0` if @p s is lexicographically ordered before the substring of `*this`, * or `<0` if the substring of `*this` is lexicographically ordered before @p s. See note above regarding * case-sensitivity. */ int compare(size_t pos, size_t count, const std::string& s) const; }; } // namespace detail class RString; class RStringU; class RStringKey; class RStringUKey; /** * Carbonite registered strings. * * The Carbonite framework has a rich <a href="https://en.wikipedia.org/wiki/String_interning">string-interning</a> * interface that is very easily used through the RString (and other) classes. This implements a <a * href="https://en.wikipedia.org/wiki/Flyweight_pattern">Flyweight pattern</a> for strings. The registered string * interface is fully @rstref{ABI-safe <abi-compatibility>} due to versioning, and can even be used in an application * prior to the `main()`, `WinMain()` or `DllMain()` functions being called. Furthermore, the API is fully thread-safe. * * Registered strings have pre-computed hashes which make them ideal for identifiers and map keys, and string * (in-)equality checks are O(1) constant time. For ordered containers, registered strings have an `owner_before()` * function that can be used for stable (though not lexicographical) ordering. If lexicographical ordering is desired, * O(n) `compare()` functions are provided. * * Variations exist around case-sensitivity. The RStringU class (the U stands for "un-cased" which is used in this API * to denote case-insensitivity) is used to register a string that will compare in a case-insensitive manner. Although * RString and RStringU cannot be directly compared for equality, RString::toUncased() exists to explicitly create a * case-insensitive RStringU from an RString which can then be compared. * * Variations also exist around using registered strings as a key value. It can be useful to have an associated number * to denote multiple instances of a registered string: hence the RStringKey and RStringUKey classes. * * To register a string, pass a string to the RString constructor RAII-style. Strings that are registered stay as such * for the entire run of the application; strings are never unregistered. Registered strings are stored in a named * section of shared memory accessible by all modules loaded by an application. The memory for registered strings is * allocated directly from the operating system to avoid cross-DLL heap issues. * * @note Registered strings are a limited resource, but there exists slots for approximately two million strings. * * Variations: * * RStringU - an "un-cased" (i.e. case-insensitive) registered string * * RStringKey - Adds a numeric component to RString to create an identifier or key. * * RStringUKey - Adds a numeric component to RStringU to create an identifier or key that is case-insensitive. */ class CARB_VIZ RString final : public detail::RStringTraits<false> { using Base = detail::RStringTraits<false>; public: /** * Constant that indicates whether this is "un-cased" (i.e. case-insensitive) (will always be `false`). */ using Base::IsUncased; /** * Default constructor. isEmpty() will report `true`. */ constexpr RString() noexcept; /** * Initializes this registered string to one of the static pre-defined registered strings. * @param staticString The pre-defined registered string to use. */ constexpr RString(eRString staticString) noexcept; /** * Finds or registers a new string. * @param str The string to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RString(const char* str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new counted string. * @note While generally not recommended, passing @p len allows the given string to contain embedded NUL ('\0') * characters. * @param str The string to find or register. * @param len The number of characters of @p str to include. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RString(const char* str, size_t len, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new `std::string`. * @note If @p str contains embedded NUL ('\0') characters, the RString will contain the embedded NUL characters as * well. * @param str The `std::string` to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RString(const std::string& str, RStringOp op = RStringOp::eRegister); /** * Truncates RStringKey into only the registered string portion. * @param other The RStringKey to truncate. */ explicit RString(const RStringKey& other) noexcept; /** * Converts this registered string into an "un-cased" (i.e. case-insensitive) registered string. * * @note The returned string may differ in case to `*this` when retrieved with c_str() or toString(). * * @returns An "un-cased" (i.e. case-insensitive) string that matches `*this` when compared in a case-insensitive * manner. */ RStringU toUncased() const noexcept; /** * Returns a copy of this registered string. * @note This function exists for compatibility with the RStringKey interface. * @returns `*this` since this string already has no number component. */ RString truncate() const noexcept; /** * Appends a number to the registered string to form a RStringKey. * * @param number An optional number to append (default = `0`). * @returns An RStringKey based on `*this` and the provided number. */ RStringKey toRStringKey(int32_t number = 0) const; /** * Equality comparison between this registered string and another. * * @param other Another registered string. * @returns `true` if `*this` and `other` represent the same registered string; `false` otherwise. */ bool operator==(const RString& other) const noexcept; /** * Inequality comparison between this registered string and another. * * @param other Another registered string. * @returns `false` if `*this` and `other` represent the same registered string; `true` otherwise. */ bool operator!=(const RString& other) const noexcept; /** * Checks whether this registered string is stably (but not lexicographically) ordered before another registered * string. * * This ordering is to make registered strings usable as keys in ordered associative containers in O(1) time. * * @note This is NOT a lexicographical comparison; for that use one of the compare() functions. To reduce ambiguity * between a strict ordering and lexicographical comparison there is no `operator<` function for this string class. * While a lexicographical comparison would be O(n), this comparison is O(1). * * @param other Another registered string. * @returns `true` if `*this` should be ordered-before @p other; `false` otherwise. */ bool owner_before(const RString& other) const noexcept; }; /** * Case-insensitive registered string. * * The "U" stands for "un-cased". * * See RString for system-level information. This class differs from RString in that it performs case-insensitive * operations. * * Since the desire is for equality comparisons to be speed-of-light (i.e. O(1) numeric comparisons), the first string * registered insensitive to casing is chosen as an "un-cased authority" and if any strings registered through RStringU * later match that string (in a case-insensitive manner), that authority string will be chosen instead. This also means * that when RStringU is used to register a string and then that string is retrieved with RStringU::c_str(), the casing * in the returned string might not match what was registered. */ class CARB_VIZ RStringU final : public detail::RStringTraits<true> { using Base = detail::RStringTraits<true>; public: /** * Constant that indicates whether this is "un-cased" (i.e. case-insensitive) (will always be `true`). */ using Base::IsUncased; /** * Default constructor. isEmpty() will report `true`. */ constexpr RStringU() noexcept; /** * Initializes this registered string to one of the static pre-defined registered strings. * @param staticString The pre-defined registered string to use. */ constexpr RStringU(eRString staticString) noexcept; /** * Finds or registers a new case-insensitive string. * * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * * @param str The string to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringU(const char* str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new counted case-insensitive string. * @note While generally not recommended, passing @p len allows the given string to contain embedded NUL ('\0') * characters. * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * @param str The string to find or register. * @param len The number of characters of @p str to include. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringU(const char* str, size_t len, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new case-insensitive `std::string`. * @note If @p str contains embedded NUL ('\0') characters, the RString will contain the embedded NUL characters as * well. * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * @param str The `std::string` to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringU(const std::string& str, RStringOp op = RStringOp::eRegister); /** * Converts a registered string into an "un-cased" (i.e. case-insensitive) registered string. * @param other The RString to convert. */ explicit RStringU(const RString& other); /** * Truncates RStringUKey into only the registered string portion. * @param other The RStringUKey to truncate. */ explicit RStringU(const RStringUKey& other); /** * Returns a copy of this registered string. * @note This function exists for compatibility with the RString interface. * @returns `*this` since this string is already "un-cased" (i.e. case-insensitive). */ RStringU toUncased() const noexcept; /** * Returns a copy of this registered string. * @note This function exists for compatibility with the RStringKey interface. * @returns `*this` since this string already has no number component. */ RStringU truncate() const noexcept; /** * Appends a number to the registered string to form a RStringUKey. * * @param number An optional number to append (default = `0`). * @returns An RStringUKey based on `*this` and the provided number. */ RStringUKey toRStringKey(int32_t number = 0) const; /** * Equality comparison between this registered string and another. * * @note A case-insensitive compare is performed. * * @param other Another registered string. * @returns `true` if `*this` and `other` represent the same registered string; `false` otherwise. */ bool operator==(const RStringU& other) const noexcept; /** * Inequality comparison between this registered string and another. * * @note A case-insensitive compare is performed. * * @param other Another registered string. * @returns `false` if `*this` and `other` represent the same registered string; `true` otherwise. */ bool operator!=(const RStringU& other) const noexcept; /** * Checks whether this registered string is stably (but not lexicographically) ordered before another registered * string. * * This ordering is to make registered strings usable as keys in ordered associative containers in O(1) time. * * @note This is NOT a lexicographical comparison; for that use one of the compare() functions. To reduce ambiguity * between a strict ordering and lexicographical comparison there is no `operator<` function for this string class. * While a lexicographical comparison would be O(n), this comparison is O(1). * * @param other Another registered string. * @returns `true` if `*this` should be ordered-before @p other; `false` otherwise. */ bool owner_before(const RStringU& other) const noexcept; }; /** * A registered string key. * * See \ref RString for high-level information about the registered string system. * * RStringKey is formed by appending a numeric component to a registered string. This numeric component can be used as a * unique instance identifier alongside the registered string. Additionally, the RStringKey::toString() function will * append a non-zero numeric component following an underscore. */ class CARB_VIZ RStringKey final : public detail::RStringTraits<false, detail::RStringKeyBase> { using Base = detail::RStringTraits<false, detail::RStringKeyBase>; public: /** * Constant that indicates whether this is "un-cased" (i.e. case-insensitive) (will always be `false`). */ using Base::IsUncased; /** * Default constructor. isEmpty() will report `true` and getNumber() will return `0`. */ constexpr RStringKey() noexcept; /** * Initializes this registered string to one of the static pre-defined registered strings. * @param staticString The pre-defined registered string to use. * @param number The number that will be returned by getNumber(). */ constexpr RStringKey(eRString staticString, int32_t number = 0) noexcept; /** * Finds or registers a new string. * @param str The string to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringKey(const char* str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new string with a given number component. * @param number The number that will be returned by getNumber(). * @param str The string to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ RStringKey(int32_t number, const char* str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new counted string. * @note While generally not recommended, passing @p len allows the given string to contain embedded NUL ('\0') * characters. * @param str The string to find or register. * @param len The number of characters of @p str to include. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringKey(const char* str, size_t len, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new counted string with a given number component. * @note While generally not recommended, passing @p len allows the given string to contain embedded NUL ('\0') * characters. * @param number The number that will be returned by getNumber(). * @param str The string to find or register. * @param len The number of characters of @p str to include. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringKey(int32_t number, const char* str, size_t len, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new `std::string`. * @note If @p str contains embedded NUL ('\0') characters, the RString will contain the embedded NUL characters as * well. * @param str The `std::string` to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringKey(const std::string& str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new `std::string` with a number component. * @note If @p str contains embedded NUL ('\0') characters, the RString will contain the embedded NUL characters as * well. * @param number The number that will be returned by getNumber(). * @param str The `std::string` to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringKey(int32_t number, const std::string& str, RStringOp op = RStringOp::eRegister); /** * Appends a number component to a registered string to form a key. * @param str The registered string to decorate. * @param number The number that will be returned by getNumber(). */ RStringKey(const RString& str, int32_t number = 0); /** * Converts this registered string key into an "un-cased" (i.e. case-insensitive) registered string key. * * @note The returned string may differ in case to `*this` when retrieved with c_str() or toString(). * * @returns An "un-cased" (i.e. case-insensitive) string that matches `*this` when compared in a case-insensitive * manner. The returned registered string key will have the same number component as `*this`. */ RStringUKey toUncased() const noexcept; /** * Returns a registered string without the number component. * @returns A registered string that matches `*this` without a number component. */ RString truncate() const noexcept; /** * Equality comparison between this registered string key and another. * * @param other Another registered string. * @returns `true` if `*this` and `other` represent the same registered string and have matching number components; * `false` otherwise. */ bool operator==(const RStringKey& other) const noexcept; /** * Inequality comparison between this registered string key and another. * * @param other Another registered string. * @returns `false` if `*this` and `other` represent the same registered string and have matching number components; * `true` otherwise. */ bool operator!=(const RStringKey& other) const noexcept; /** * Checks whether this registered string key is stably (but not lexicographically) ordered before another registered * string. The number component is also compared and keys with a lower number component will be ordered before. * * This ordering is to make registered strings usable as keys in ordered associative containers in O(1) time. * * @note This is NOT a lexicographical comparison; for that use one of the compare() functions. To reduce ambiguity * between a strict ordering and lexicographical comparison there is no `operator<` function for this string class. * While a lexicographical comparison would be O(n), this comparison is O(1). * * @param other Another registered string. * @returns `true` if `*this` should be ordered-before @p other; `false` otherwise. */ bool owner_before(const RStringKey& other) const noexcept; #ifndef DOXYGEN_BUILD // Sphinx warns about Duplicate C++ declaration /** * Returns the hash value as by `carb::hashString(this->truncate().c_str())` combined with the number component. * * @note This value is computed once for a registered string and cached, so this operation is generally very fast. * * @returns The hash value as computed by `carb::hashString(this->truncate().c_str())`. */ size_t getHash() const; /** * Returns the hash value as by `carb::hashLowercaseString(this->truncate().c_str())` combined with the number * component. * * @note This value is pre-computed for registered strings and cached, so this operation is always O(1). * * @returns The hash value as computed by `carb::hashLowercaseString(this->truncate().c_str())`. */ size_t getUncasedHash() const noexcept; #endif /** * Returns a string containing the registered string, and if getNumber() is not zero, the number appended. * * Example: RStringKey(eRString::RS_carb, 1).toString() would produce "carb_1". * @returns A string containing the registered string. If getNumber() is non-zero, an underscore and the number are * appended. */ std::string toString() const; /** * Returns the number component of this key. * @returns The number component previously specified in the constructor or with setNumber() or via number(). */ int32_t getNumber() const noexcept; /** * Sets the number component of this key. * @param num The new number component. */ void setNumber(int32_t num) noexcept; /** * Direct access to the number component for manipulation or atomic operations via `atomic_ref`. * @returns A reference to the number component. */ int32_t& number() noexcept; private: // Hide these functions since they are incomplete using Base::c_str; using Base::data; using Base::length; }; /** * A case-insensitive registered string key. * * See \ref RString for high-level information about the registered string system. * * RStringUKey is formed by appending a numeric component to an "un-cased" (i.e. case-insensitive) registered string. * This numeric component can be used as a unique instance identifier alongside the registered string. Additionally, the * RStringUKey::toString() function will append a non-zero numeric component following an underscore. */ class CARB_VIZ RStringUKey final : public detail::RStringTraits<true, detail::RStringKeyBase> { using Base = detail::RStringTraits<true, detail::RStringKeyBase>; public: /** * Constant that indicates whether this is "un-cased" (i.e. case-insensitive) (will always be `true`). */ using Base::IsUncased; /** * Default constructor. isEmpty() will report `true` and getNumber() will return `0`. */ constexpr RStringUKey() noexcept; /** * Initializes this registered string to one of the static pre-defined registered strings. * @param staticString The pre-defined registered string to use. * @param number The number that will be returned by getNumber(). */ constexpr RStringUKey(eRString staticString, int32_t number = 0) noexcept; /** * Finds or registers a new case-insensitive string. * * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * * @param str The string to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ RStringUKey(const char* str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new string with a given number component. * @param number The number that will be returned by getNumber(). * @param str The string to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ RStringUKey(int32_t number, const char* str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new counted case-insensitive string. * @note While generally not recommended, passing @p len allows the given string to contain embedded NUL ('\0') * characters. * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * @param str The string to find or register. * @param len The number of characters of @p str to include. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringUKey(const char* str, size_t len, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new counted case-insensitive string with a given number component. * @note While generally not recommended, passing @p len allows the given string to contain embedded NUL ('\0') * characters. * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * @param number The number that will be returned by getNumber(). * @param str The string to find or register. * @param len The number of characters of @p str to include. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringUKey(int32_t number, const char* str, size_t len, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new case-insensitive `std::string`. * @note If @p str contains embedded NUL ('\0') characters, the RString will contain the embedded NUL characters as * well. * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * @param str The `std::string` to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringUKey(const std::string& str, RStringOp op = RStringOp::eRegister); /** * Finds or registers a new case-insensitive `std::string` with a number component. * @note If @p str contains embedded NUL ('\0') characters, the RString will contain the embedded NUL characters as * well. * @note The casing of the string actually used may be different than @p str when reported by c_str() or toString(). * @param number The number that will be returned by getNumber(). * @param str The `std::string` to find or register. * @param op The operation to perform. If directed to RStringOp::eFindExisting and the string has not been * previously registered, `*this` is initialized as if with the default constructor. */ explicit RStringUKey(int32_t number, const std::string& str, RStringOp op = RStringOp::eRegister); /** * Appends a number component to a registered string to form a key. * @param str The registered string to decorate. * @param number The number that will be returned by getNumber(). */ RStringUKey(const RStringU& str, int32_t number = 0); /** * Converts a registered string key into an "un-cased" (i.e. case-insensitive) registered string key. * @param other The RStringKey to convert. The number component is maintained. */ explicit RStringUKey(const RStringKey& other); /** * Returns a copy of this registered string key. * @note This function exists for compatibility with the RStringKey interface. * @returns `*this` since this string is already "un-cased" (i.e. case-insensitive). The number component will be * the same as the number for `*this`. */ RStringUKey toUncased() const noexcept; /** * Returns a registered string without the number component. * @returns A registered string that matches `*this` without a number component. */ RStringU truncate() const noexcept; /** * Equality comparison between this registered string key and another. * * @note A case-insensitive compare is performed. * * @param other Another registered string. * @returns `true` if `*this` and `other` represent the same registered string and have matching number components; * `false` otherwise. */ bool operator==(const RStringUKey& other) const noexcept; /** * Inequality comparison between this registered string key and another. * * @note A case-insensitive compare is performed. * * @param other Another registered string. * @returns `false` if `*this` and `other` represent the same registered string and have matching number components; * `true` otherwise. */ bool operator!=(const RStringUKey& other) const noexcept; /** * Checks whether this registered string key is stably (but not lexicographically) ordered before another registered * string. The number component is also compared and keys with a lower number component will be ordered before. * * This ordering is to make registered strings usable as keys in ordered associative containers in O(1) time. * * @note This is NOT a lexicographical comparison; for that use one of the compare() functions. To reduce ambiguity * between a strict ordering and lexicographical comparison there is no `operator<` function for this string class. * While a lexicographical comparison would be O(n), this comparison is O(1). * * @param other Another registered string. * @returns `true` if `*this` should be ordered-before @p other; `false` otherwise. */ bool owner_before(const RStringUKey& other) const noexcept; #ifndef DOXYGEN_BUILD // Sphinx warns about Duplicate C++ declaration /** * Returns the hash value as by `carb::hashString(this->truncate().c_str())` combined with the number component. * * @note This value is computed once for a registered string and cached, so this operation is generally very fast. * * @returns The hash value as computed by `carb::hashString(this->truncate().c_str())`. */ size_t getHash() const; /** * Returns the hash value as by `carb::hashLowercaseString(this->truncate().c_str())` combined with the number * component. * * @note This value is pre-computed for registered strings and cached, so this operation is always O(1). * * @returns The hash value as computed by `carb::hashLowercaseString(this->truncate().c_str())`. */ size_t getUncasedHash() const noexcept; #endif /** * Returns a string containing the registered string, and if getNumber() is not zero, the number appended. * * Example: RStringUKey(eRString::RS_carb, 1).toString() would produce "carb_1". * @returns A string containing the registered string. If getNumber() is non-zero, an underscore and the number are * appended. */ std::string toString() const; /** * Returns the number component of this key. * @returns The number component previously specified in the constructor or with setNumber() or via number(). */ int32_t getNumber() const noexcept; /** * Sets the number component of this key. * @param num The new number component. */ void setNumber(int32_t num) noexcept; /** * Direct access to the number component for manipulation or atomic operations via `atomic_ref`. * @returns A reference to the number component. */ int32_t& number() noexcept; private: // Hide these functions since they are incomplete using Base::c_str; using Base::data; using Base::length; }; // Can use ADL specialization for global operator<< for stream output /** * Global stream output operator for RString. * @param o The output stream to write to. * @param s The registered string to output. * @returns The output stream, @p o. */ template <class CharT, class Traits> ::std::basic_ostream<CharT, Traits>& operator<<(::std::basic_ostream<CharT, Traits>& o, const RString& s) { o << s.c_str(); return o; } /** * Global stream output operator for RStringU. * @param o The output stream to write to. * @param s The registered string to output. * @returns The output stream, @p o. */ template <class CharT, class Traits> ::std::basic_ostream<CharT, Traits>& operator<<(::std::basic_ostream<CharT, Traits>& o, const RStringU& s) { o << s.c_str(); return o; } /** * Global stream output operator for RStringKey. * @param o The output stream to write to. * @param s The registered string to output. * @returns The output stream, @p o. */ template <class CharT, class Traits> ::std::basic_ostream<CharT, Traits>& operator<<(::std::basic_ostream<CharT, Traits>& o, const RStringKey& s) { o << s.toString(); return o; } /** * Global stream output operator for RStringUKey. * @param o The output stream to write to. * @param s The registered string to output. * @returns The output stream, @p o. */ template <class CharT, class Traits> ::std::basic_ostream<CharT, Traits>& operator<<(::std::basic_ostream<CharT, Traits>& o, const RStringUKey& s) { o << s.toString(); return o; } } // namespace carb // Specializations for std::hash and std::owner_less per type /** * RString specialization for `std::hash`. */ template <> struct std::hash<::carb::RString> { /** * Returns the hash * @param v The registered string. * @returns The hash as via the getHash() function. */ size_t operator()(const ::carb::RString& v) const { return v.getHash(); } }; /** * RString specialization for `std::owner_less`. */ template <> struct std::owner_less<::carb::RString> { /** * Returns true if @p lhs should be ordered-before @p rhs. * @param lhs A registered string. * @param rhs A registered string. * @returns `true` if @p lhs should be ordered-before @p rhs; `false` otherwise. */ bool operator()(const ::carb::RString& lhs, const ::carb::RString& rhs) const { return lhs.owner_before(rhs); } }; /** * RStringU specialization for `std::hash`. */ template <> struct std::hash<::carb::RStringU> { /** * Returns the hash * @param v The registered string. * @returns The hash as via the getHash() function. */ size_t operator()(const ::carb::RStringU& v) const { return v.getHash(); } }; /** * RStringU specialization for `std::owner_less`. */ template <> struct std::owner_less<::carb::RStringU> { /** * Returns true if @p lhs should be ordered-before @p rhs. * @param lhs A registered string. * @param rhs A registered string. * @returns `true` if @p lhs should be ordered-before @p rhs; `false` otherwise. */ bool operator()(const ::carb::RStringU& lhs, const ::carb::RStringU& rhs) const { return lhs.owner_before(rhs); } }; /** * RStringKey specialization for `std::hash`. */ template <> struct std::hash<::carb::RStringKey> { /** * Returns the hash * @param v The registered string. * @returns The hash as via the getHash() function. */ size_t operator()(const ::carb::RStringKey& v) const { return v.getHash(); } }; /** * RStringKey specialization for `std::owner_less`. */ template <> struct std::owner_less<::carb::RStringKey> { /** * Returns true if @p lhs should be ordered-before @p rhs. * @param lhs A registered string. * @param rhs A registered string. * @returns `true` if @p lhs should be ordered-before @p rhs; `false` otherwise. */ bool operator()(const ::carb::RStringKey& lhs, const ::carb::RStringKey& rhs) const { return lhs.owner_before(rhs); } }; /** * RStringUKey specialization for `std::hash`. */ template <> struct std::hash<::carb::RStringUKey> { /** * Returns the hash * @param v The registered string. * @returns The hash as via the getHash() function. */ size_t operator()(const ::carb::RStringUKey& v) const { return v.getHash(); } }; /** * RStringUKey specialization for `std::owner_less`. */ template <> struct std::owner_less<::carb::RStringUKey> { /** * Returns true if @p lhs should be ordered-before @p rhs. * @param lhs A registered string. * @param rhs A registered string. * @returns `true` if @p lhs should be ordered-before @p rhs; `false` otherwise. */ bool operator()(const ::carb::RStringUKey& lhs, const ::carb::RStringUKey& rhs) const { return lhs.owner_before(rhs); } }; #include "RString.inl"
49,729
C
39.762295
120
0.683102
omniverse-code/kit/include/carb/Memory.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 DLL Boundary safe memory management functions #pragma once #include "Defines.h" #include "Types.h" #include "cpp/Bit.h" #include "detail/DeferredLoad.h" //! Internal function used by all other allocation functions. //! //! This function is the entry point into `carb.dll`/`libcarb.so` for @ref carb::allocate(), @ref carb::deallocate(), //! and @ref carb::reallocate(). There are four modes to this function: //! - If @p p is `nullptr` and @p size is `0`, no action is taken and `nullptr` is returned. //! - If @p p is not `nullptr` and @p size is `0`, the given pointer is deallocated and `nullptr` is returned. //! - If @p p is `nullptr` and @p size is non-zero, memory of the requested @p size and alignment specified by @p align //! is allocated and returned. If an allocation error occurs, `nullptr` is returned. //! - If @p p is not `nullptr` and @p size is non-zero, the memory is reallocated and copied (as if by `std::memcpy`) to //! the new memory block, which is returned. If @p p can be resized in situ, the same @p p value is returned. If an //! error occurs, `nullptr` is returned. //! //! @note Using this function requires explicitly linking with `carb.dll`/`libcarb.so` if @ref CARB_REQUIRE_LINKED is //! `1`. Otherwise, the caller must ensure that `carb.dll`/`libcarb.so` is already loaded before calling this function. //! Use in situations where the Carbonite Framework is already loaded (i.e. plugins) does not require explicitly linking //! against Carbonite as this function will be found dynamically at runtime. //! //! @warning Do not call this function directly. Instead call @ref carb::allocate(), @ref carb::deallocate(), or //! @ref carb::reallocate() //! //! @see carb::allocate() carb::reallocate() carb::deallocate() //! @param p The pointer to re-allocate or free. May be `nullptr`. See explanation above. //! @param size The requested size of the memory region in bytes. See explanation above. //! @param align The requested alignment of the memory region in bytes. Must be a power of two. See explanation above. //! @returns Allocated memory, or `nullptr` upon deallocation, or `nullptr` on allocation when an error occurs. #if CARB_REQUIRE_LINKED CARB_DYNAMICLINK void* carbReallocate(void* p, size_t size, size_t align); #else CARB_DYNAMICLINK void* carbReallocate(void* p, size_t size, size_t align) CARB_ATTRIBUTE(weak); #endif namespace carb { //! \cond DEV namespace detail { CARB_DETAIL_DEFINE_DEFERRED_LOAD(getCarbReallocate, carbReallocate, (void* (*)(void*, size_t, size_t))); } // namespace detail //! \endcond //! Allocates a block of memory. //! //! @note Any plugin (or the executable) may @ref allocate the memory and a different plugin (or the executable) may //! @ref deallocate or @ref reallocate it. //! //! @note If carb.dll/libcarb.so is not loaded, this function will always return `nullptr`. //! //! @param size The size of the memory block requested, in bytes. Specifying '0' will return a valid pointer that //! can be passed to @ref deallocate but cannot be used to store any information. //! @param align The minimum alignment (in bytes) of the memory block requested. Must be a power of two. Values less //! than `sizeof(size_t)` are ignored. `0` indicates to use default system alignment (typically //! `2 * sizeof(void*)`). //! @returns A non-`nullptr` memory block of @p size bytes with minimum alignment @p align. If an error occurred, //! or memory could not be allocated, `nullptr` is returned. The memory is not initialized. inline void* allocate(size_t size, size_t align = 0) noexcept { if (auto impl = detail::getCarbReallocate()) return impl(nullptr, size, align); else return nullptr; } //! Deallocates a block of memory previously allocated with @ref allocate(). //! //! @note Any plugin (or the executable) may @ref allocate the memory and a different plugin (or the executable) may //! @ref deallocate or @ref reallocate it. //! //! @note If carb.dll/libcarb.so is not loaded, this function will silently do nothing. Since @ref allocate would have //! returned `nullptr` in this case, this function should never be called. //! //! @param p The block of memory previously returned from @ref allocate() or @ref reallocate(), or `nullptr`. inline void deallocate(void* p) noexcept { if (p) { if (auto impl = detail::getCarbReallocate()) impl(p, 0, 0); } } //! Reallocates a block of memory previously allocated with @ref allocate(). //! //! This function changes the size of the memory block pointed to by @p p to @p size bytes with @p align alignment. //! The contents are unchanged from the start of the memory block up to the minimum of the old size and @p size. If //! @p size is larger than the old size, the added memory is not initialized. If @p p is `nullptr`, the call is //! equivalent to `allocate(size, align)`; if @p size is `0` and @p p is not `nullptr`, the call is equivalent to //! `deallocate(p)`. Unless @p p is `nullptr`, it must have been retrieved by an earlier call to @ref allocate() or //! @ref reallocate(). If the memory region was moved in order to resize it, @p p will be freed as with `deallocate(p)`. //! //! @note Any plugin (or the executable) may @ref allocate the memory and a different plugin (or the executable) may //! @ref deallocate or @ref reallocate it. //! //! @note If carb.dll/libcarb.so is not loaded, this function will always return @p p without side-effects. //! //! @param p The block of memory previously returned from @ref allocate() or @ref reallocate() if resizing is //! resizing is desired. If `nullptr` is passed as this parameter, the call behaves as if //! `allocate(size, align)` was called. //! @param size The size of the memory block requested, in bytes. See above for further explanation. //! @param align The minimum alignment (in bytes) of the memory block requested. Must be a power of two. Values less //! than `sizeof(size_t)` are ignored. Changing the alignment from a previous allocation is undefined behavior. //! `0` indicates to use default system alignment (typically `2 * sizeof(void*)`). //! @returns A pointer to a block of memory of @p size bytes with minimum alignment @p align, unless an error //! occurs in which case `nullptr` is returned. If @p p is `nullptr` and @p size is `0` then `nullptr` is also //! returned. inline void* reallocate(void* p, size_t size, size_t align = 0) noexcept { if (auto impl = detail::getCarbReallocate()) return impl(p, size, align); else return p; } /** * A class implementing the 'Allocator' C++ Named Requirement. * * This class is usable for C++ classes that require an allocator, such as `std::vector`. * @note This class requires dynamic or static linking to carb.dll/libcarb.so/libcarb.dylib in order to function. * @tparam T The type to allocate * @tparam Align The requested alignment. Must be zero or a power of two. Zero indicates to use `T`'s required * alignment. */ template <class T, size_t Align = 0> class Allocator { public: using pointer = T*; //!< pointer using const_pointer = const T*; //!< const_pointer using reference = T&; //!< reference using const_reference = const T&; //!< const_reference using void_pointer = void*; //!< void_pointer using const_void_pointer = const void*; //!< const_void_pointer using value_type = T; //!< value_type using size_type = std::size_t; //!< size_type using difference_type = std::ptrdiff_t; //!< difference_type static_assert(!Align || ::carb::cpp::has_single_bit(Align), "Must be a power of two"); constexpr static size_t alignment = Align; //!< Alignment (non-standard) //! A struct that allows determining an allocator for class `U` through the `other` type. template <class U> struct rebind { //! The type of `Allocator<U>` using other = Allocator<U, alignment>; }; //! Constructor constexpr Allocator() noexcept = default; //! Copy constructor constexpr Allocator(const Allocator&) noexcept = default; //! Copy-assign operator constexpr Allocator& operator=(const Allocator&) noexcept = default; //! Copy constructor template <class U, size_t UAlign> constexpr Allocator(const Allocator<U, UAlign>& other) noexcept { CARB_UNUSED(other); } //! Copy-assign operator template <class U, size_t UAlign> constexpr Allocator& operator=(const Allocator<U, UAlign>& other) noexcept { CARB_UNUSED(other); return *this; } //! Destructor ~Allocator() = default; //! Equality operator constexpr bool operator==(const Allocator& other) const noexcept { CARB_UNUSED(other); return true; } //! Inequality operator constexpr bool operator!=(const Allocator& other) const noexcept { CARB_UNUSED(other); return false; } /** * Allocates suitable storage for an array object of type `T[n]` and creates the array, but does not construct array * elements. * * If \ref alignment is suitable (that is, not less than the required alignment of `T`) it is used, otherwise the * required alignment of `T` is used. * @param n The number of elements of `T` to allocate space for. * @returns A pointer to memory that can contain an array of type `T[n]`, but no array elements have been * constructed. */ pointer allocate(size_type n = 1) noexcept /*strengthened*/ { auto align = ::carb_max(+alignment, std::alignment_of<T>::value); return pointer(::carb::allocate(sizeof(T) * n, align)); } /** * Same as \ref allocate(size_type) but may use \p p (`nullptr` or a pointer obtained from \ref allocate()) to aid * locality. * @param n The number of elements of `T` to allocate space for. * @param p May be `nullptr` or a pointer obtained from \ref allocate(). If non-`nullptr`, \p p is returned. * @returns A pointer to memory that can contain an array of type `T[n]`, but no array elements have been * constructed. */ pointer allocate(size_type n, const_void_pointer p) noexcept /*strengthened*/ { return p ? pointer(p) : allocate(n); } /** * Deallocates storage pointed to by `p`, which must be a value returned by a previous call to \ref allocate() that * has not been invalidated by an intervening call to `deallocate`. * @param p A value returned by a previous call to \ref allocate() and not previously passed to `deallocate`. * @param n Must be the same size value that was originally passed to \ref allocate(). */ void deallocate(pointer p, size_type n) noexcept /*strengthened*/ { CARB_UNUSED(n); ::carb::deallocate(p); } /** * Returns the largest value that can be passed to \ref allocate(). * @returns the largest value that can be passed to \ref allocate(). */ size_type max_size() const noexcept { return size_type(-1); } /** * Constructs an object of type `X` in previously-allocated storage at the address pointed to by `p`, using `args` * as the constructor arguments. * @param p The pointer at which to construct. * @param args The constructor arguments. */ template <class X, class... Args> void construct(X* const p, Args&&... args) { ::new (const_cast<void*>(static_cast<const volatile void*>(p))) X(std::forward<Args>(args)...); } /** * Destructs an object of type `X` pointed to by `p` but does not deallocate any storage. * @param p The pointer to an object of type `X` to destroy. */ template <class X> void destroy(X* const p) { p->~X(); } }; /** * An object can inherit from this class in order to use Carbonite allocation functions for creation/deletion. */ template <size_t Align = 0> class UseCarbAllocatorAligned { public: //! The alignment amount used by this allocator constexpr static size_t alignment = Align; //! \cond DEV void* operator new(std::size_t count) { return carb::allocate(count, alignment); } void* operator new[](std::size_t count) { return carb::allocate(count, alignment); } void operator delete(void* ptr) { carb::deallocate(ptr); } void operator delete[](void* ptr) { carb::deallocate(ptr); } #if CARB_HAS_CPP17 void* operator new(std::size_t count, std::align_val_t al) { return carb::allocate(count, ::carb_max(alignment, size_t(al))); } void* operator new[](std::size_t count, std::align_val_t al) { return carb::allocate(count, ::carb_max(alignment, size_t(al))); } void operator delete(void* ptr, std::align_val_t al) { CARB_UNUSED(al); carb::deallocate(ptr); } void operator delete[](void* ptr, std::align_val_t al) { CARB_UNUSED(al); carb::deallocate(ptr); } #endif //! \endcond }; /** Allocated object deleter helper class. This is suitable for use in various STL container * classes that accept a functor responsible for deleting an object that was allocated using * an allocation system other than new/delete. This particular implementation ensures the * object is destructed before deallocating its memory. */ template <class T> class Deleter { public: /** Functor operator to destruct and deallocate an object that was allocated and constructed * using one of the carb::allocate() family of functions. * * @tparam T The data type of the object to delete. * @param[in] p The object to be destroyed. */ void operator()(T* p) noexcept { p->~T(); carb::deallocate(p); } }; /** * An object can inherit from this class in order to use Carbonite allocation functions for creation/deletion. */ using UseCarbAllocator = UseCarbAllocatorAligned<>; } // namespace carb
14,513
C
39.093923
120
0.673741
omniverse-code/kit/include/carb/ClientUtils.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 Utilities for Carbonite clients #pragma once #include "Framework.h" #include "assert/AssertUtils.h" #include "crashreporter/CrashReporterUtils.h" #include "l10n/L10nUtils.h" #include "logging/Log.h" #include "logging/StandardLogger.h" #include "profiler/Profile.h" #include "../omni/core/Omni.h" #include <vector> namespace carb { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { inline void registerBuiltinFileSystem(Framework* f) { f->registerPlugin(g_carbClientName, f->getBuiltinFileSystemDesc()); } inline void registerBuiltinLogging(Framework* f) { f->registerPlugin(g_carbClientName, f->getBuiltinLoggingDesc()); } inline void registerBuiltinAssert(Framework* f) { f->registerPlugin(g_carbClientName, f->getBuiltinAssertDesc()); } inline void registerBuiltinThreadUtil(Framework* f) { f->registerPlugin(g_carbClientName, f->getBuiltinThreadUtilDesc()); } inline void registerAtexitHandler() { # if CARB_PLATFORM_WINDOWS && !defined _DLL // Since we're not using the dynamic runtime, we need to notify carb.dll if the executable's atexit() functions run. // We only do this if this is compiled into the executable here, so check that auto exeHandle = GetModuleHandleW(NULL); HMODULE myHandle; if (GetModuleHandleExW( CARBWIN_GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | CARBWIN_GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)&registerAtexitHandler, &myHandle) && myHandle == exeHandle) { // Verified that this function is compiled into the executable and without dynamic runtime. auto carbHandle = GetModuleHandleW(L"carb.dll"); auto proc = (void (*)(void*))(carbHandle ? GetProcAddress(carbHandle, "carbControlAtexit") : nullptr); if (proc) { // Call our undocumented function and pass our atexit() function so that carb.dll can register a callback // to know when the first-chance (executable) atexit happens. proc((void*)&atexit); } } # endif } } // namespace detail #endif /** * Main acquisition of the Carbonite Framework for Clients (applications and plugins). * * \warning It is typically not necessary to call this, since macros such as \ref OMNI_CORE_INIT already ensure that * this function is called properly. * * At a high level, this function: * * - Calls \ref carb::acquireFramework() and assigns it to a global variable within this module: \ref g_carbFramework. * - Calls \ref logging::registerLoggingForClient(), \ref assert::registerAssertForClient(), and * \ref l10n::registerLocalizationForClient(). * - Calls \ref OMNI_CORE_START(). * * @param args Arguments passed to \ref OMNI_CORE_START * @returns A pointer to the Carbonite Framework, if initialization was successful; `nullptr` otherwise. */ inline Framework* acquireFrameworkAndRegisterBuiltins(const OmniCoreStartArgs* args = nullptr) { // Acquire framework and set into global variable Framework* framework = acquireFramework(g_carbClientName); if (framework) { g_carbFramework = framework; static_assert( kFrameworkVersion.major == 0, "The framework automatically registers builtins now; the registerXXX functions can be removed once the framework version changes."); detail::registerAtexitHandler(); // Starting up logging detail::registerBuiltinLogging(framework); logging::registerLoggingForClient(); // Starting up filesystem detail::registerBuiltinFileSystem(framework); detail::registerBuiltinAssert(framework); detail::registerBuiltinThreadUtil(framework); // grab the assertion helper interface. assert::registerAssertForClient(); // grab the l10n interface. l10n::registerLocalizationForClient(); // start up ONI OMNI_CORE_START(args); } return framework; } /** * This function releases the Carbonite Framework. * * The options performed are essentially the teardown operations for \ref acquireFrameworkAndRegisterBuiltins(). * * At a high-level, this function: * - Calls \ref logging::deregisterLoggingForClient(), \ref assert::deregisterAssertForClient(), and * \ref l10n::deregisterLocalizationForClient(). * - Calls \ref omniReleaseStructuredLog(). * - Unloads all Carbonite plugins * - Calls \ref OMNI_CORE_STOP * - Calls \ref releaseFramework() * - Sets \ref g_carbFramework to `nullptr`. * * \note It is not necessary to manually call this function if \ref OMNI_CORE_INIT is used, since that macro will ensure * that the Framework is released. */ inline void releaseFrameworkAndDeregisterBuiltins() { if (isFrameworkValid()) { logging::deregisterLoggingForClient(); assert::deregisterAssertForClient(); l10n::deregisterLocalizationForClient(); // Release structured log before unloading plugins omniReleaseStructuredLog(); g_carbFramework->unloadAllPlugins(); OMNI_CORE_STOP(); releaseFramework(); } g_carbFramework = nullptr; } } // namespace carb /** * Defines global variables of the framework and built-in plugins. * * \note Either this macro, or \ref CARB_GLOBALS_EX or \ref OMNI_APP_GLOBALS must be specified in the global namespace * in exactly one compilation unit for a Carbonite Application. * * @param clientName The name of the client application. Must be unique with respect to any plugins loaded. Also is the * name of the default log channel. */ #define CARB_GLOBALS(clientName) CARB_GLOBALS_EX(clientName, nullptr) /** * Defines global variables of the framework and built-in plugins. * * \note Either this macro, or \ref CARB_GLOBALS or \ref OMNI_APP_GLOBALS must be specified in the global namespace in * exactly one compilation unit for a Carbonite Application. * * @param clientName The name of the client application. Must be unique with respect to any plugins loaded. Also is the * name of the default log channel. * @param clientDescription A description to use for the default log channel. */ #define CARB_GLOBALS_EX(clientName, clientDescription) \ CARB_FRAMEWORK_GLOBALS(clientName) \ CARB_LOG_GLOBALS() \ CARB_PROFILER_GLOBALS() \ CARB_ASSERT_GLOBALS() \ CARB_LOCALIZATION_GLOBALS() \ CARB_CRASH_REPORTER_GLOBALS() \ OMNI_GLOBALS_ADD_DEFAULT_CHANNEL(clientName, clientDescription)
7,507
C
37.701031
144
0.660583
omniverse-code/kit/include/carb/Strong.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 "Defines.h" #include "cpp/TypeTraits.h" #include <typeindex> // for std::hash #include <ostream> // for std::basic_ostream /** * Implements a strong type. `typedef` and `using` declarations do not declare a new type. `typedef int MyType` uses the * name `MyType` to refer to int; MyType and int are therefore interchangeable. * * CARB_STRONGTYPE(MyType, int) differs in that it creates an int-like structure named MyType which is type-safe. MyType * can be compared to `int` values, but cannot be implicitly assigned an int. */ #define CARB_STRONGTYPE(Name, T) using Name = ::carb::Strong<T, struct Name##Sig> namespace carb { // clang-format off template<class T, class Sig> class Strong final { private: T val; public: using Type = T; constexpr Strong() : val{} {} constexpr explicit Strong(T&& val_) : val(std::forward<T>(val_)) {} constexpr Strong(const Strong& rhs) = default; Strong& operator=(const Strong& rhs) = default; constexpr Strong(Strong&& rhs) = default; Strong& operator=(Strong&& rhs) = default; const T& get() const { return val; } T& get() { return val; } /// Ensure that the underlying type matches expected; recommended for printf template <class U> U ensure() const { static_assert(std::is_same<T, U>::value, "Types are not the same"); return val; } explicit operator bool () const { return !!val; } bool operator == (const Strong& rhs) const { return val == rhs.val; } bool operator == (const T& rhs) const { return val == rhs; } bool operator != (const Strong& rhs) const { return val != rhs.val; } bool operator != (const T& rhs) const { return val != rhs; } bool operator < (const Strong& rhs) const { return val < rhs.val; } void swap(Strong& rhs) noexcept(noexcept(std::swap(val, rhs.val))) { std::swap(val, rhs.val); } }; // clang-format on template <class CharT, class Traits, class T, class Sig> ::std::basic_ostream<CharT, Traits>& operator<<(::std::basic_ostream<CharT, Traits>& o, const Strong<T, Sig>& s) { o << s.get(); return o; } // Swap can be specialized with ADL template <class T, class Sig, typename = std::enable_if_t<carb::cpp::is_swappable<T>::value, bool>> void swap(Strong<T, Sig>& lhs, Strong<T, Sig>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } } // namespace carb // Specialization for std::hash template <class T, class Sig> struct std::hash<::carb::Strong<T, Sig>> { size_t operator()(const ::carb::Strong<T, Sig>& v) const { return ::std::hash<T>{}(v.get()); } };
3,024
C
35.011904
120
0.677579
omniverse-code/kit/include/carb/ObjectUtils.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. // //! @file //! //! @brief Helper utilities for Carbonite objects (carb::IObject). #pragma once #include "IObject.h" #include <atomic> namespace carb { /** * Default handler for carb::IObject reaching zero references, which calls `delete`. Can be specialized for specific * types. * @param ptr The object to delete. */ template <class T> void deleteHandler(T* ptr) { delete ptr; } } // namespace carb /** * Helper macro to implement default behavior of carb::IObject interface functions IObject::addRef() and * IObject::release(). * * Example usage: * @code * class Foo : public IObject * { * CARB_IOBJECT_IMPL * * public: * ... * }; * @endcode */ #define CARB_IOBJECT_IMPL \ public: \ /** \ * Atomically adds one to the reference count. \ * @returns The current reference count after one was added, though this value may change before read if other \ * threads are also modifying the reference count. The return value is guaranteed to be non-zero. \ */ \ size_t addRef() override \ { \ size_t prev = m_refCount.fetch_add(1, std::memory_order_relaxed); \ CARB_ASSERT(prev != 0); /* resurrected item if this occurs */ \ return prev + 1; \ } \ \ /** \ * Atomically subtracts one from the reference count. If the result is zero, carb::deleteHandler() is called for \ * `this`. \ * @returns The current reference count after one was subtracted. If zero is returned, carb::deleteHandler() was \ * called for `this`. \ */ \ size_t release() override \ { \ size_t prev = m_refCount.fetch_sub(1, std::memory_order_release); \ CARB_ASSERT(prev != 0); /* double release if this occurs */ \ if (prev == 1) \ { \ std::atomic_thread_fence(std::memory_order_acquire); \ carb::deleteHandler(this); \ } \ return prev - 1; \ } \ \ private: \ std::atomic_size_t m_refCount{ 1 };
5,159
C
58.999999
120
0.301997
omniverse-code/kit/include/carb/Framework.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 Core header for registering and acquiring interfaces. #pragma once #include "Defines.h" #include "Memory.h" #include "Types.h" #include <cstddef> #include <cstdint> // free() can be #define'd which can interfere below, so handle that here #ifdef free # define CARB_FREE_UNDEFINED # pragma push_macro("free") # undef free #endif namespace carb { //! Defines the current major version of the Carbonite framework. //! //! Incrementing this variable causes great chaos as it represents a breaking change to users. Increment only with //! great thought. #define CARBONITE_MAJOR 0 //! Defines the current minor version of the Carbonite framework. //! //! This value is increment when non-breaking changes are made to the framework. #define CARBONITE_MINOR 6 //! Defines the current version of the Carbonite framework. constexpr struct Version kFrameworkVersion = { CARBONITE_MAJOR, CARBONITE_MINOR }; //! Four character code used to identify a @ref PluginRegistrationDesc object that is likely to //! have further data provided in it. constexpr FourCC kCarb_FourCC = CARB_MAKE_FOURCC('C', 'A', 'R', 'B'); //! Describes the different functions a plugin can define for use by carb::Framework. //! //! Populate this struct and register a plugin with carb::Framework::registerPlugin() for static plugins. //! //! Dynamic plugins are registered via @ref CARB_PLUGIN_IMPL. struct PluginRegistrationDesc { //! This or @ref onPluginRegisterExFn required. Preferred over @ref onPluginRegisterExFn. OnPluginRegisterFn onPluginRegisterFn; OnPluginStartupFn onPluginStartupFn; //!< Can be `nullptr`. OnPluginShutdownFn onPluginShutdownFn; //!< Can be `nullptr`. GetPluginDepsFn getPluginDepsFn; //!< Can be `nullptr`. OnReloadDependencyFn onReloadDependencyFn; //!< Can be `nullptr`. OnPluginPreStartupFn onPluginPreStartupFn; //!< Can be `nullptr`. OnPluginPostShutdownFn onPluginPostShutdownFn; //!< Can be `nullptr`. OnPluginRegisterExFn onPluginRegisterExFn; //!< Can be `nullptr`. OnPluginStartupExFn onPluginStartupExFn = nullptr; //!< Can be `nullptr`. Preferred over @ref onPluginStartupFn. OnPluginRegisterEx2Fn onPluginRegisterEx2Fn = nullptr; //!< Can be `nullptr`. Preferred over onPluginRegisterFn and //!< onPluginRegisterExFn. //! These members exists as a version of PluginRegistrationDesc without changing the framework version to simplify //! adoption. Static plugins that use Framework::registerPlugin() but were compiled with an earlier version of this //! struct that did not have these members will not produce the required bit pattern, //! thereby instructing the Framework that the subsequent members are not valid and cannot be read. FourCC const checkValue{ kCarb_FourCC }; //! The size of this object in bytes. This is only valid if the @ref checkValue member is set //! to @ref kCarb_FourCC. If it is not, this member and other following members will not be //! accessed in order to avoid undefined behavior. size_t const sizeofThis{ sizeof(PluginRegistrationDesc) }; OnPluginQuickShutdownFn onPluginQuickShutdownFn = nullptr; //!< Can be `nullptr`. Function that will be called for //!< the plugin if //!< \ref carb::quickReleaseFrameworkAndTerminate() is //!< invoked. //! Specifies the framework version required by this plugin. Version frameworkVersion{ kFrameworkVersion }; }; //! Describes parameters for finding plugins on disk. Multiple search paths, matching wildcards, and exclusion wildcards //! can be specified. Used primarily by @ref Framework::loadPlugins. //! //! Call @ref PluginLoadingDesc::getDefault() to instantiate this object, as it will correctly set defaults. struct PluginLoadingDesc { //! List of folders in which to search for plugins. //! //! This may contain relative or absolute paths. All relative paths will be resolved relative to @ref //! carb::filesystem::IFileSystem::getAppDirectoryPath(), not the current working directory. Absolute paths in the //! list will be searched directly. If search paths configuration is invalid (e.g. search paths count is zero), the //! fallback values are taken from the default plugin desc. //! //! Defaults to the directory containing the process's executable. const char* const* searchPaths; size_t searchPathCount; //!< Number of entries in @ref searchPaths. Defaults to 1. bool searchRecursive; //!< Is search recursive in search folders. Default to `false`. //! List of Filename wildcards to select loaded files. `*` and `?` can be used, e.g. "carb.*.pl?gin" //! //! Defaults to "*.plugin". This can lead to unnecessary plugins being loaded. const char* const* loadedFileWildcards; size_t loadedFileWildcardCount; //!< Number of entries in @ref loadedFileWildcards. Defaults to 1. //! List of filename wildcards to mark loaded files as reloadable. Framework will treat them specially to allow //! overwriting source plugins and will monitor them for changes. //! //! Defaults to `nullptr`. const char* const* reloadableFileWildcards; size_t reloadableFileWildcardCount; //!< Number of entries in @ref reloadableFileWildcards. Defaults to 0. //! If `true`, load and store the plugins interface information, then immediately unload the plugin until needed. //! When one of plugin's interfaces is acquired, the library will be loaded again. //! //! Defaults to `false`. bool unloadPlugins; //! List of filename wildcards to select excluded files. `*` and `?` can be used. //! //! Defaults to `nullptr`. const char* const* excludedFileWildcards; size_t excludedFileWildcardCount; //!< Number of entries in @ref excludedFileWildcards. Defaults to 0. //! Returns a PluginLoadDesc with sensible defaults. static PluginLoadingDesc getDefault() { static constexpr const char* defaultSearchPath = ""; static constexpr const char* defaultLoadedFileWildcard = "*.plugin"; return { &defaultSearchPath, 1, false, &defaultLoadedFileWildcard, 1, nullptr, 0, false, nullptr, 0 }; } }; //! Flags for use with \ref carb::AcquireInterfaceOptions enum AcquireInterfaceFlags : uint64_t { //! Default search type, a plugin name may be specified in `typeParam`. eAIFDefaultType = 0, //! Acquire interface from interface specified in `typeParam`. eAIFFromInterfaceType, //! Acquire interface from library specified in `typeParam`. eAIFFromLibraryType, //! New types can be added here //! Count of types. eAIFNumTypes, //! A mask that contains all of the above types. fAIFTypeMask = 0xf, //! The interface acquire is optional and may fail without error logging. fAIFOptional = (1 << 4), //! The interface acquire will only succeed if the plugin is already initialized. fAIFNoInitialize = (1 << 5), }; static_assert(eAIFNumTypes <= fAIFTypeMask, "Too many types for mask"); //! A structure used with \ref Framework::internalAcquireInterface(). Typically callers should use one of the adapter //! functions such as \ref Framework::tryAcquireInterface() and not use this directly. struct AcquireInterfaceOptions { //! Size of this structure for versioning. size_t sizeofThis; //! The client requesting this interface const char* clientName; //! The interface requested InterfaceDesc desc; //! Type and flags. One Type must be specified as well as any flags. AcquireInterfaceFlags flags; //! Context interpreted based on the type specified in the `flags` member. const void* typeParam; }; CARB_ASSERT_INTEROP_SAFE(AcquireInterfaceOptions); //! Result of loading a plugin. Used by @ref carb::Framework::loadPlugin. Non-negative values indicated success. enum class LoadPluginResult : int32_t { //! Plugin was attempted to be loaded from a temporary path in use by the framework. eForbiddenPath = -3, //! Invalid argument passed to @ref Framework::loadPlugin. eInvalidArg = -2, //! An unspecified error occurred. The plugin was not loaded. eFailed = -1, //! The plugin was successfully loaded. eSucceeded = 0, //! The plugin was loaded as an ONI plugin. eSucceededAsOmniverseNativeInterface = 1, //! The plugin is already loaded. eAlreadyLoaded = 2, }; //! Release Hook function //! //! Called when the @ref carb::Framework (or an interface) is being released, before the actual release is done. Add a //! release hook with @ref carb::Framework::addReleaseHook(). Registered release hooks can be removed with @ref //! carb::Framework::removeReleaseHook(). //! //! @param iface The interface that is being released. If the framework is being released, this is `nullptr`. //! //! @param userData The data passed to @ref carb::Framework::addReleaseHook(). using ReleaseHookFn = void (*)(void* iface, void* userData); //! Load Hook function //! //! Called when a plugin is loaded for the first time and the requested interface becomes available. The interface must //! be acquired with \ref Framework::tryAcquireInterface() or \ref Framework::acquireInterface() etc. //! //! The thread that first acquires the interface will call all load hooks for that interface before the interface value //! is returned from the Framework. All other threads that acquire that interface will wait until load hooks have been //! called. Calling load hooks is done without an internal Framework mutex locked, so other threads are able to acquire //! other interfaces while load hooks are executing. //! //! It is safe for a `LoadHookFn` to call \ref Framework::removeLoadHook() for the handle that caused it to be called, //! or any other handle. //! //! @see Framework::addLoadHook() Framework::removeLoadHook() //! @param plugin The \ref PluginDesc for the plugin that has now loaded. //! @param userData The `void*` that was passed to \ref Framework::addLoadHook(). using LoadHookFn = void (*)(const PluginDesc& plugin, void* userData); //! Acquire the Carbonite framework for an application. //! //! Do not call this method directly. Rather, call a helper function such as @ref OMNI_CORE_INIT, @ref //! carb::acquireFrameworkAndRegisterBuiltins or @ref carb::acquireFrameworkForBindings. Of the methods above, @ref //! OMNI_CORE_INIT is preferred for most applications. //! //! The Carbonite framework is a singleton object, it will be created on the first acquire call. Subsequent calls to //! acquire return the same instance. //! //! This function is expected to be used by applications, which links with the framework. //! //! Plugins should not use this function. Rather, plugins should use @ref carb::getFramework(). //! //! @thread_safety This function may be called from multiple threads simultaneously. //! //! @param appName The application name requesting the framework. Must not be `nullptr`. //! //! @param frameworkVersion specifies the minimum framework version expected by the application. `nullptr` is return if //! the minimum version cannot be met. //! //! @return The Carbonite framework. Can be `nullptr`. //! //! @see @ref carb::releaseFramework(). CARB_DYNAMICLINK carb::Framework* acquireFramework(const char* appName, Version frameworkVersion = kFrameworkVersion); //! Returns `true` if the Carbonite framework has been created and is still alive. Creation happens at the first @ref //! carb::acquireFramework() call and ends at any @ref carb::releaseFramework() call. CARB_DYNAMICLINK bool isFrameworkValid(); //! Retrieves the Carbonite SDK version string, //! //! @returns A string describing the current Carbonite SDK version. This will be the same value //! as the @ref CARB_SDK_VERSION value that was set when the SDK was built. //! //! @note This version is intended for use in host apps that link directly to the `carb` library. //! Libraries that don't link directly to it such as plugins will not be able to call //! into this without first dynamically importing it. Plugins should instead call this //! through `carb::getFramework()->getSdkVersion()`. CARB_DYNAMICLINK const char* carbGetSdkVersion(); //! Tests whether the Carbonite SDK headers match the version of used to build the framework. //! //! @param[in] version The version string to compare to the version stored in the Carbonite //! framework library. This is expected to be the value of the //! @ref CARB_SDK_VERSION symbol found in `carb/SdkVersion.h`. //! @returns `true` if the version of the headers matches the version of the framework library //! that is currently loaded. Returns `false` if the version string in the headers //! does not match the version of the framework library. If the library does not //! match the headers, it is not necessarily a fatal problem. It does however //! indicate that issues may occur and that there may have been a building or //! packaging problem for the host app. #define CARB_IS_SAME_SDK_VERSION(version) (strcmp(version, carbGetSdkVersion()) == 0) //! Releases the Carbonite framework immediately. //! //! In some cases more, than one client can acquire the framework (e.g. scripting bindings), but only one of the clients //! should be responsible for releasing it. //! //! @thread_safety May be called from any thread. CARB_DYNAMICLINK void releaseFramework(); //! Releases the Carbonite framework immediately and exits the process, without running C/C++ atexit() registered //! functions or static destructors. //! //! @note This function does not return. //! //! @warning This function must not be called from within a DLL, shared object, or plugin. //! //! This function performs the following sequence: //! 1. Calls any exported \ref carbOnPluginQuickShutdown on all loaded plugins, if the framework is acquired. No plugins //! are unloaded, unregistered, nor have their interfaces destroyed. //! 2. Calls any registered Framework release hooks (see \ref carb::Framework::addReleaseHook) in reverse order of //! registration, if the framework is acquired. //! 3. Flushes stdout/stderr. //! 4. Calls `TerminateProcess()` on Windows or `_exit()` on Linux and MacOS. //! //! @thread_safety May be called from any thread. //! @param exitCode The exit code that the process will exit with. CARB_DYNAMICLINK void quickReleaseFrameworkAndTerminate [[noreturn]] (int exitCode); #if CARB_PLATFORM_WINDOWS //! Signal handler for SIGABRT for use with plugins that are statically linked to the CRT. //! //! @param[in] signal The signal that occurred. This will be SIGABRT. //! @returns No return value. //! //! @remarks This acts as a signal handler for SIGABRT signals. This is installed during //! plugin initialization. This should _never_ be called directly since it will //! result in the process aborting immediately. CARB_DYNAMICLINK void carbSignalHandler(int signal); #endif //! Defines the framework for creating Carbonite applications and plugins. //! //! See \carb_framework_overview for high-level documentation on core concepts, using @ref Framework, and creating //! plugins. //! //! Plugins are shared libraries with a .plugin.dll/.so suffix. The plugins are named with the .plugin suffix to support //! plugin discovery and support cohabitation with other supporting .dll/.so libraries in the same folder. It is a //! recommended naming pattern, but not mandatory. //! //! Plugin library file format: //! //! - Windows: <plugin-name>.plugin.dll //! - Linux: lib<plugin-name>.plugin.so //! //! A plugin implements one or many interfaces and has a name which uniquely identifies it to the framework. The //! plugin's name usually matches the filename, but it is not mandatory, the actual plugin name is provided by the //! plugin via @ref carb::OnPluginRegisterFn. //! //! "Static" plugin can also be registered with @ref Framework::registerPlugin() function, thus no shared library will //! be involved. //! //! @ref Framework comes with 3 static plugins: //! //! - @ref carb::logging::ILogging //! - @ref carb::filesystem::IFileSystem //! - @ref carb::assert::IAssert //! //! These plugins are used by @ref Framework itself. Without @ref carb::logging::ILogging, @ref Framework won't be able //! to log messages. Without @ref carb::filesystem::IFileSystem, @ref Framework won't be able to load any "dynamic" //! plugins. Without @ref carb::assert::IAssert, assertion failures will simply write a message to stderr and abort. //! //! It's up to the application to register these needed plugins. @ref OMNI_CORE_INIT() performs this registration on //! the user's behalf. //! //! The term "client" is often used across the @ref Framework API. Client is either: //! //! - A plugin. Here the client name is the same as the plugin name. //! //! - An application. The module which dynamically links with the Framework and uses @ref carb::acquireFramework(). //! //! - Scripting bindings. This is technically similar to an application, in that it dynamically links with the @ref //! Framework and uses @ref carb::acquireFramework(). //! //! Clients are uniquely identified by their name. Many functions accept client name as an argument. This allows @ref //! Framework to create a dependency tree of clients. This dependency tree allows the safe unloading of plugins. //! //! @thread_safety Unless otherwise noted, @ref Framework functions are thread-safe and may be called from multiple //! threads simultaneously. struct Framework { /** * Load and register plugins from shared libraries. */ void loadPlugins(const PluginLoadingDesc& desc = PluginLoadingDesc::getDefault()); /** * Load and register plugins from shared libraries. Prefer using @ref loadPlugins. */ void(CARB_ABI* loadPluginsEx)(const PluginLoadingDesc& desc); /** * Unloads all plugins, including registered "static" plugins (see @ref Framework::registerPlugin). */ void(CARB_ABI* unloadAllPlugins)(); /** * Acquires the typed plugin interface, optionally from a specified plugin. * * If `nullptr` is passed as @p pluginName this method selects the default plugin for the given interface type. * Default plugin selection happens on the first such acquire call for a particular interface name and locked until * after this interface is released. By default the interface with highest version is selected. * * If the plugin has not yet been started, it will be loaded and started (\ref carbOnPluginStartup called) by this * call. * * @ref Framework::setDefaultPlugin can be used to explicitly set which plugin to set as default, but it should be * called before the first acquire call. * * If acquire fails, `nullptr` is returned and an error is logged. * * @param pluginName The option to specify a plugin (implementation) that you specifically want. Pass `nullptr` to * search for all plugins. * * @return The requested plugin interface or `nullptr` if an error occurs (an error message is logged). * * @see See @ref tryAcquireInterface(const char*) for a version of this method that does not log errors. */ template <typename T> T* acquireInterface(const char* pluginName = nullptr); /** * Tries to acquire the typed plugin interface, optionally from a specified plugin. * * If `nullptr` is passed as @p pluginName this method selects the default plugin for the given interface type. * Default plugin selection happens on the first such acquire call for a particular interface name and locked until * after this interface is released. By default the interface with highest version is selected. * * If the plugin has not yet been started, it will be loaded and started (\ref carbOnPluginStartup called) by this * call. * * @ref Framework::setDefaultPlugin can be used to explicitly set which plugin to set as default, but it should be * called before the first acquire call. * * @param pluginName The option to specify a plugin (implementation) that you specifically want. Pass `nullptr` to * search for all plugins. * * @return The requested plugin interface or `nullptr` if an error occurs. */ template <typename T> T* tryAcquireInterface(const char* pluginName = nullptr); /** * Acquires the typed plugin interface from the same plugin as the provided interface. * * Example: * * @code{.cpp} * Foo* foo = framework->acquireInterface<Foo>(); * * // the returned 'bar' interface is from the same plugin as 'foo'. * Bar* bar = framework->acquireInterface<Bar>(foo); * @endcode * * If foo and bar are not nullptr, they are guaranteed to be on the same plugin. * * @param pluginInterface The interface that was returned from acquireInterface. It will be used to select a * plugin with requested interface. * * @return The typed plugin interface that is returned and will be started, or `nullptr` if the interface cannot be * acquired (an error is logged). * * @see See @ref tryAcquireInterface(const void*) for a version of this method that does not log errors. */ template <typename T> T* acquireInterface(const void* pluginInterface); /** * Tries to acquire the typed plugin interface from the same plugin as the provided interface. * * Example: * * @code{.cpp} * Foo* foo = framework->acquireInterface<Foo>(); * * // the returned 'bar' interface is from the same plugin as 'foo'. * Bar* bar = framework->tryAcquireInterface<Bar>(foo); * @endcode * * If foo and bar are not nullptr, they are guaranteed to be on the same plugin. * * @param pluginInterface The interface that was returned from acquireInterface. It will be used to select a * plugin with requested interface. * * @return The typed plugin interface that is returned and will be started, or `nullptr` if the interface cannot be * acquired. */ template <typename T> T* tryAcquireInterface(const void* pluginInterface); /** * Acquires to the typed plugin interface from the given dynamic library file. * * @note If the given library was not a registered plugin, the Framework will attempt to register the library as a * new plugin. * * If the plugin has not yet been started, it will be loaded and started (\ref carbOnPluginStartup called) by this * call. * * @param libraryPath The library path to acquire the interface from. Can be absolute or relative (to the current * working directory) path to a dynamic (.dll/.so/.dylib) library Carbonite plugin. * * @return The typed plugin interface (guaranteed to be from the given library) or `nullptr`. If `nullptr` is * returned, an error is logged. * * @see See @ref tryAcquireInterfaceFromLibrary(const char*) for a version of this method that does not log errors. */ template <typename T> T* acquireInterfaceFromLibrary(const char* libraryPath); /** * Tries to acquire the typed plugin interface from the given dynamic library file. * * @note If the given library was not a registered plugin, the Framework will attempt to register the library as a * new plugin. * * If the plugin has not yet been started, it will be loaded and started (\ref carbOnPluginStartup called) by this * call. * * This function works exactly as @ref Framework::acquireInterfaceFromLibrary(const char*), except if acquire fails * it returns `nullptr` and doesn't log an error. * * @param libraryPath The library path to acquire the interface from. Can be absolute or relative (to the current * working directory) path to a dynamic (.dll/.so/.dylib) library Carbonite plugin. * * @return The typed plugin interface or `nullptr` if the library file was not found or an error occurred. */ template <typename T> T* tryAcquireInterfaceFromLibrary(const char* libraryPath); /** * Tries to acquire the typed plugin interface if and only if it has been previously acquired, optionally from a * specified plugin. * * If `nullptr` is passed as @p pluginName this method selects the default plugin for the given interface type. * Default plugin selection happens on the first such acquire call for a particular interface name and locked until * after this interface is released. By default the interface with highest version is selected. * * Unlike \ref tryAcquireInterface, this function will only acquire an interface if the plugin providing it is * already started (it won't attempt to start the plugin). This is useful during \ref carbOnPluginShutdown when a * circularly-dependent interface may have already been released by the Framework and attempting to reload it would * result in an error. * * @ref Framework::setDefaultPlugin can be used to explicitly set which plugin to set as default, but it should be * called before the first acquire call. * * @param pluginName The option to specify a plugin (implementation) that you specifically want. Pass `nullptr` to * search for all plugins. * * @return The requested plugin interface or `nullptr` if an error occurs or the plugin is not started. */ template <typename T> T* tryAcquireExistingInterface(const char* pluginName = nullptr); /** * Gets the number of plugins with the specified interface. * * @return The number of plugins with the specified interface. */ template <typename T> uint32_t getInterfacesCount(); //! Acquires all interfaces of the given type. //! //! The given output array must be preallocated. @p interfacesSize tells this method the size of the array. //! //! If @p interfaces is to small, the array is filled as much as possible and an error is logged. //! //! If @p interfaces is to big, entries past the required size will not be written. //! //! Upon output, `nullptr` may randomly appear in `interfaces`. This represents failed internal calls to @ref //! tryAcquireInterface. No error is logged in this case. //! //! @param interfaces Preallocated array that will hold the acquired interfaces. Values in this array must be //! preset to `nullptr` in order to determine which entries in the array are valid upon output. //! //! @param interfacesSize Number of preallocated array elements. See @ref Framework::getInterfacesCount(). //! //! @rst //! .. warning:: //! Carefully read this method's documentation, as it has a slew of design issues. It's use is not //! recommended. //! @endrst template <typename T> void acquireInterfaces(T** interfaces, uint32_t interfacesSize); //! Acquires the plugin interface pointer from an interface description. //! //! This is an internal function. Use @ref Framework::acquireInterface(const char*) instead. //! //! @rst //! .. deprecated:: 135.0 //! If explicit client functionality is needed, please use ``internalAcquireInterface`` instead. //! However, note that this function will only be available beginning with Carbonite 135.0. //! @endrst //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description //! //! @param pluginName The plugin that you specifically want. If `nullptr`, the interface's "default" plugin is //! used. //! //! @return The returned function pointer for the interface being queried and started. If `nullptr` is returned, an //! error is logged. //! //! @see See @ref tryAcquireInterfaceWithClient for a version of this method that does not log errors. void*(CARB_ABI* acquireInterfaceWithClient)(const char* clientName, InterfaceDesc desc, const char* pluginName); static_assert(kFrameworkVersion.major == 0, "Remove above function in next Framework version"); //! Tries to acquires the plugin interface pointer from an interface description. //! //! This method has the same contract as @ref Framework::acquireInterfaceWithClient except an error is not logged if //! the interface could not be acquired. //! //! This is an internal function. Use @ref Framework::tryAcquireInterface(const char*) instead. //! //! @rst //! .. deprecated:: 135.0 //! If explicit client functionality is needed, please use ``internalAcquireInterface`` instead. //! However, note that this function will only be available beginning with Carbonite 135.0. //! @endrst //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description //! //! @param pluginName The plugin that you specifically want. If `nullptr`, the interface's "default" plugin is //! used. //! //! @return The returned function pointer for the interface being queried and started, or `nullptr` if an error //! occurs. void*(CARB_ABI* tryAcquireInterfaceWithClient)(const char* clientName, InterfaceDesc desc, const char* pluginName); static_assert(kFrameworkVersion.major == 0, "Remove above function in next Framework version"); //! Acquires the typed plugin interface from the same plugin as the provided interface. //! //! This is an internal function. Use @ref Framework::acquireInterface(const char*) instead. //! //! @rst //! .. deprecated:: 135.0 //! If explicit client functionality is needed, please use ``internalAcquireInterface`` instead. //! However, note that this function will only be available beginning with Carbonite 135.0. //! @endrst //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description. //! //! @param pluginInterface The interface that was returned from acquireInterface. It will be used to select a plugin //! with requested interface. //! //! @return The returned function pointer for the interface being queried and started. If `nullptr` is returned, an //! error is logged. //! //! @see See @ref tryAcquireInterfaceFromInterfaceWithClient for a version of this method that does not log errors. void*(CARB_ABI* acquireInterfaceFromInterfaceWithClient)(const char* clientName, InterfaceDesc desc, const void* pluginInterface); static_assert(kFrameworkVersion.major == 0, "Remove above function in next Framework version"); //! Tries to acquires the typed plugin interface from the same plugin as the provided interface. //! //! This method has the same contract as @ref Framework::acquireInterfaceFromInterfaceWithClient except an error is //! not logged if the interface could not be acquired. //! //! This is an internal function. Use @ref Framework::tryAcquireInterface(const char*) instead. //! //! @rst //! .. deprecated:: 135.0 //! If explicit client functionality is needed, please use ``internalAcquireInterface`` instead. //! However, note that this function will only be available beginning with Carbonite 135.0. //! @endrst //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description. //! //! @param pluginInterface The interface that was returned from acquireInterface. It will be used to select a plugin //! with requested interface. //! //! @return The returned function pointer for the interface being queried and started, or `nullptr` if an error //! occurs. void*(CARB_ABI* tryAcquireInterfaceFromInterfaceWithClient)(const char* clientName, InterfaceDesc desc, const void* pluginInterface); static_assert(kFrameworkVersion.major == 0, "Remove above function in next Framework version"); //! Acquires the plugin interface pointer from an interface description and a filename. //! //! @note If the given library was not a registered plugin, the Framework will attempt to register the library as a //! new plugin. //! //! This is an internal function. Use @ref Framework::acquireInterfaceFromLibrary(const char*) instead. //! //! @rst //! .. deprecated:: 135.0 //! If explicit client functionality is needed, please use ``internalAcquireInterface`` instead. //! However, note that this function will only be available beginning with Carbonite 135.0. //! @endrst //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description //! //! @param libraryPath The filename to acquire the interface from. Can be absolute or relative path to actual //! .dll/.so Carbonite plugin. Path is relative to the current working directory. Must not be `nullptr`. //! //! @return The returned function pointer for the interface being queried and started. If `nullptr` is returned, an //! error is logged. //! //! @see See @ref tryAcquireInterfaceFromLibraryWithClient for a version of this method that does not log errors. void*(CARB_ABI* acquireInterfaceFromLibraryWithClient)(const char* clientName, InterfaceDesc desc, const char* libraryPath); static_assert(kFrameworkVersion.major == 0, "Remove above function in next Framework version"); //! Tries to acquire the plugin interface pointer from an interface description and a filename. //! //! This method has the same contract as @ref Framework::acquireInterfaceFromLibraryWithClient except an error is //! not logged if the interface could not be acquired. //! //! @note If the given library was not a registered plugin, the Framework will attempt to register the library as a //! new plugin. //! //! This is an internal function. Use @ref Framework::tryAcquireInterfaceFromLibrary(const char*) instead. //! //! @rst //! .. deprecated:: 135.0 //! If explicit client functionality is needed, please use ``internalAcquireInterface`` instead. //! However, note that this function will only be available beginning with Carbonite 135.0. //! @endrst //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description //! //! @param libraryPath The filename to acquire the interface from. Can be absolute or relative path to actual //! .dll/.so Carbonite plugin. Path is relative to the current working directory. Must not be `nullptr`. //! //! @return The returned function pointer for the interface being queried and started, or `nullptr` on error. void*(CARB_ABI* tryAcquireInterfaceFromLibraryWithClient)(const char* clientName, InterfaceDesc desc, const char* libraryPath); static_assert(kFrameworkVersion.major == 0, "Remove above function in next Framework version"); //! Gets the number of plugins with the specified interface descriptor. //! //! @param interfaceDesc The interface descriptor to get the plugin count. //! //! @return The number of plugins with the specified interface descriptor. uint32_t(CARB_ABI* getInterfacesCountEx)(InterfaceDesc interfaceDesc); //! Acquires all interfaces of the given type. //! //! The given output array must be preallocated. @p interfacesSize tells this method the size of the array. //! //! If @p interfaces is to small, the array is filled as much as possible and an error is logged. //! //! If @p interfaces is to big, entries past the required size will not be written. //! //! Upon output, `nullptr` may randomly appear in `interfaces`. This represents failed internal calls to @ref //! tryAcquireInterface. No error is logged in this case. //! //! This is an internal function. Use @ref Framework::acquireInterfaces() instead. //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description //! //! @param interfaces Preallocated array that will hold the acquired interfaces. Values in this array must be //! preset to `nullptr` in order to determine which entries in the array are valid upon output. //! //! @param interfacesSize Number of preallocated array elements. See @ref Framework::getInterfacesCount(). //! //! @rst //! .. warning:: //! Carefully read this method's documentation, as it has a slew of design issues. It's use is not //! recommended. //! @endrst void(CARB_ABI* acquireInterfacesWithClient)(const char* clientName, InterfaceDesc interfaceDesc, void** interfaces, uint32_t interfacesSize); //! Releases the use of an interface that is no longer needed. //! //! Correct plugin interface type is expected, compile-time check is performed. //! //! @param pluginInterface The interface that was returned from acquireInterface template <typename T> void releaseInterface(T* pluginInterface); //! \cond DEV //! Releases the use of an interface that is no longer needed. //! //! This is an internal function. Use @ref Framework::releaseInterface() instead. //! //! @param clientName The client requesting the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param pluginInterface The interface that was returned from @ref Framework::acquireInterface. void(CARB_ABI* releaseInterfaceWithClient)(const char* clientName, void* pluginInterface); //! \endcond //! Gets the plugin descriptor for a specified plugin. //! //! @param pluginName The plugin that you specifically want to get the descriptor for. Must not be `nullptr`. //! //! @return The @ref PluginDesc, it will be filled with zeros if the plugin doesn't exist. The returned memory will //! be valid as long as the plugin is loaded. const PluginDesc&(CARB_ABI* getPluginDesc)(const char* pluginName); //! Gets the plugin descriptor for an interface returned from @ref Framework::acquireInterface. //! //! @param pluginInterface The interface that was returned from acquireInterface //! //! @return The PluginDesc, it will be filled with zeros if wrong interface pointer is provided. const PluginDesc&(CARB_ABI* getInterfacePluginDesc)(void* pluginInterface); //! Gets the plugins with the specified interface descriptor. //! //! @param interfaceDesc The interface descriptor to get the plugins for. //! //! @param outPlugins The array to be populated with the plugins of size @ref Framework::getInterfacesCount(). //! This array must be set to all zeros before given to this function in order to be able to tell the number of //! entries written. //! //! @rst //! .. danger:: //! //! Do not use this method. The caller will be unable to correctly size ``outPlugins``. The size of the number //! of loaded plugins matching ``interfaceDesc`` may change between the call to //! :cpp:func:`carb::Framework::getInterfacesCount` and this method. //! @endrst void(CARB_ABI* getCompatiblePlugins)(InterfaceDesc interfaceDesc, PluginDesc* outPlugins); //! Gets the number of registered plugins. //! //! @return The number of registered plugins. size_t(CARB_ABI* getPluginCount)(); //! Gets all registered plugins. //! //! @param outPlugins The array to be populated with plugin descriptors of size @ref Framework::getPluginCount(). //! //! @rst //! .. danger:: //! //! Do not use this method. The caller will be unable to correctly size ``outPlugins``. The number of plugins //! may change between the call to :cpp:member:`carb::Framework::getPluginCount` and this method. //! @endrst void(CARB_ABI* getPlugins)(PluginDesc* outPlugins); //! Attempts to reload all plugins that are currently loaded. void(CARB_ABI* tryReloadPlugins)(); //! Register a "static" plugin. //! //! While typical plugins are "dynamic" and loaded from shared libraries (see @ref Framework::loadPlugins), a //! "static" plugin can be added by calling this function from an application or another plugin. The contract is //! exactly the same: you provide a set of functions (some of which are optional), which usually are looked for in a //! shared library by the framework. It can be useful in some special scenarios where you want to hijack particular //! interfaces or limited in your ability to produce new shared libraries. //! //! It is important that the plugin name provided by @ref PluginRegistrationDesc::onPluginRegisterFn function is //! unique, registration will fail otherwise. //! //! @param clientName The client registering the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin registration description. //! //! @return If registration was successful. bool(CARB_ABI* registerPlugin)(const char* clientName, const PluginRegistrationDesc& desc); //! Try to unregister a plugin. //! //! If plugin is in use, which means one if its interfaces was acquired by someone and not yet released, the //! unregister will fail. Both "dynamic" (shared libraries) and "static" (see @ref Framework::registerPlugin) //! plugins can be unregistered. //! //! @param pluginName The plugin to be unregistered. //! //! @return If unregistration was successful. bool(CARB_ABI* unregisterPlugin)(const char* pluginName); //! The descriptor for registering builtin @ref carb::logging::ILogging interface implementation. const PluginRegistrationDesc&(CARB_ABI* getBuiltinLoggingDesc)(); //! The descriptor for registering builtin @ref carb::filesystem::IFileSystem interface implementation. const PluginRegistrationDesc&(CARB_ABI* getBuiltinFileSystemDesc)(); //! Sets the default plugin to be used when an interface type is acquired. //! //! The mechanism of default interfaces allows @ref Framework to guarantee that every call to //! `acquireInterface<Foo>()` will return the same `Foo` interface pointer for everyone. The only way to bypass it //! is by explicitly passing the `pluginName` of the interface you want to acquire. //! //! It is important to note that if the interface was previously already acquired, the effect of this function won't //! take place until it is released by all holders. So it is recommended to set defaults as early as possible. //! //! @tparam T The interface type. //! @param pluginName The name of the plugin (e.g. "carb.profiler-cpu.plugin") that will be set as default. Must not //! be `nullptr`. template <class T> void setDefaultPlugin(const char* pluginName); //! \cond DEV //! Sets the default plugin to be used when the given interface is acquired. //! //! The mechanism of default interfaces allows @ref Framework to guarantee that every call to //! `acquireInterface<Foo>()` will return the same `Foo` interface pointer for everyone. The only way to bypass it //! is by explicitly passing the `pluginName` of the interface you want to acquire. //! //! It is important to note that if the interface was previously already acquired, the effect of this function won't //! take place until it is released by all holders. So it is recommended to set defaults as early as possible. //! //! @param clientName The client registering the plugin. This is used to form a dependency graph between clients. //! Must not be `nullptr`. //! //! @param desc The plugin interface description. //! //! @param pluginName The plugin that will be set as default. Must not be `nullptr`. void(CARB_ABI* setDefaultPluginEx)(const char* clientName, InterfaceDesc desc, const char* pluginName); //! \endcond //! Sets the temporary path where the framework will store data for reloadable plugins. //! //! This function must be called before loading any reloadable plugins. By default @ref Framework creates a //! temporary folder in the executable's folder. //! //! @param tempPath Temporary folder path. void(CARB_ABI* setReloadableTempPath)(const char* tempPath); //! Returns temporary path where the framework will store data for reloadable plugins. //! //! @return Temporary path for reloadable data. The returned memory is valid until the @ref //! Framework::setReloadableTempPath is called or the @ref Framework is destroyed. const char*(CARB_ABI* getReloadableTempPath)(); //! Returns Carbonite version and build information. //! //! The format is: `v{major}.{minor} [{shortgithash} {gitbranch} {isdirty}]` where: //! //! - major - `kFrameworkVersion.major` //! - minor - `kFrameworkVersion.minor` //! - shortgithash - output of `git rev-parse --short HEAD` //! - gitbranch - output of `git rev-parse --abbrev-ref HEAD` //! - isdirty - `DIRTY` if `git status --porcelain` is not empty //! //! Examples: //! //! - `v1.0 [56ab220c master]` //! - `v0.2 [f2fc1ba1 dev/mfornander/harden DIRTY]` const char*(CARB_ABI* getBuildInfo)(); //! Checks if the provided plugin interface matches the requirements. //! //! @param interfaceCandidate The interface that was provided by the user. //! //! @return If the interface candidate matches template interface requirements, returns @p interfaceCandidate. //! Otherwise, returns `nullptr`. template <typename T> T* verifyInterface(T* interfaceCandidate); //! Checks if provided plugin interface matches the requirements. //! //! Do not directly use this method. Instead, use @ref Framework::verifyInterface. //! //! @param desc The interface description that sets the compatibility requirements. //! //! @param interfaceCandidate The interface that was provided by the user. //! //! @return if the interface candidate matches @p desc, returns @p interfaceCandidate. Otherwise, returns `nullptr`. void*(CARB_ABI* verifyInterfaceEx)(InterfaceDesc desc, void* interfaceCandidate); //! The descriptor for registering builtin @ref carb::assert::IAssert interface implementation. const PluginRegistrationDesc&(CARB_ABI* getBuiltinAssertDesc)(); //! The descriptor for registering builtin @ref carb::thread::IThreadUtil interface implementation. const PluginRegistrationDesc&(CARB_ABI* getBuiltinThreadUtilDesc)(); //! Load and register a plugin from the given filename. //! //! Call @ref unloadPlugin() to unload the plugin at @p libraryPath. //! //! @param libraryPath Name of the shared library. Must not be `nullptr`. //! //! @param reloadable Treat the plugin as reloadable. //! //! @param unload Grab the list of interfaces from the plugin and then unload it. If the user tries to acquire one //! of the retrieved interfaces, the plugin will be lazily reloaded. //! //! @return Returns a non-negative value on success, negative value otherwise. LoadPluginResult(CARB_ABI* loadPlugin)(const char* libraryPath, bool reloadable, bool unload); //! Unloads the plugin at the given shared library path. //! //! @param Path to shared library. Must not be `nullptr`. //! //! @returns Returns `true` if a plugin was loaded at the given path and successfully unloaded. `false` otherwise. bool(CARB_ABI* unloadPlugin)(const char* libraryPath); //! Adds a release hook for either the framework or a specific interface. //! //! A release hook can be added multiple times with the same or different user data, in which case it will be called //! multiple times. It is up to the caller to ensure uniqueness if uniqueness is desired. To remove a release hook, //! call @ref carb::Framework::removeReleaseHook() with the same parameters. //! //! @param iface The interface (returned by @ref carb::Framework::acquireInterface()) to monitor for release. If //! `nullptr` is specified, the release hook will be called when the @ref carb::Framework itself is unloaded. //! //! @param fn The release hook callback function that will be called. Must not be `nullptr`. //! //! @param user Data to be passed to the release hook function. May be `nullptr`. //! //! @returns Returns `true` if the interface was found and the release hook was added successfully; `false` //! otherwise. //! //! @rst //! //! .. danger:: //! //! It is *expressly forbidden* to call back into :cpp:type:`carb::Framework` in any way during the //! :cpp:type:`carb::ReleaseHookFn` callback. Doing so results in undefined behavior. The only exception to this //! rule is calling `removeReleaseHook()`. //! //! @endrst bool(CARB_ABI* addReleaseHook)(void* iface, ReleaseHookFn fn, void* user); //! Removes a release hook previously registered with @ref carb::Framework::addReleaseHook(). //! //! The same parameters supplied to @ref carb::Framework::addReleaseHook() must be provided in order to identify the //! correct release hook to remove. It is safe to call this function from within the release hook callback. //! //! @param iface The interface previously passed to @ref addReleaseHook(). //! //! @param fn The function previously passed to @ref addReleaseHook(). //! //! @param user The user data parameter previously passed to @ref addReleaseHook(). //! //! @returns Returns `true` if the release hook was found and removed. If it was not found, `false` is returned. //! //! @rst //! //! .. danger:: //! //! It is *expressly forbidden* to call back into :cpp:type:`carb::Framework` in any way during the //! :cpp:type:`carb::ReleaseHookFn` callback. Doing so results in undefined behavior. The only exception to this //! rule is calling `removeReleaseHook()`. //! //! @endrst bool(CARB_ABI* removeReleaseHook)(void* iface, ReleaseHookFn fn, void* user); //! @private CARB_DEPRECATED("Use carbReallocate() instead") void*(CARB_ABI* internalRealloc)(void* prev, size_t newSize, size_t align); static_assert(kFrameworkVersion.major == 0, "Remove Framework::internalRealloc in next Framework version"); //! Allocates a block of memory. //! //! @note Any plugin (or the executable) may allocate the memory and a different plugin (or the executable) may free //! or reallocate it. //! //! @warning It is undefined behavior to use memory allocated with this function or @ref reallocate() after the //! Carbonite framework has been shut down. //! //! @param size The size of the memory block requested, in bytes. Specifying '0' will return a valid pointer that //! can be passed to @ref free but cannot be used to store any information. //! @param align The minimum alignment (in bytes) of the memory block requested. Must be a power of two. Values less //! than `sizeof(size_t)` are ignored. `0` indicates to use default system alignment (typically //! `2 * sizeof(void*)`). //! @returns A non-`nullptr` memory block of @p size bytes with minimum alignment @p align. If an error occurred, //! or memory could not be allocated, `nullptr` is returned. The memory is not initialized. CARB_DEPRECATED("Use carb::allocate() instead") void* allocate(size_t size, size_t align = 0) { return carb::allocate(size, align); } static_assert(kFrameworkVersion.major == 0, "Remove Framework::allocate in next Framework version"); //! Frees a block of memory previously allocated with @ref allocate(). //! //! @note Any plugin (or the executable) may allocate the memory and a different plugin (or the executable) may //! free it. //! //! @param p The block of memory previously returned from @ref allocate() or @ref reallocate(), or `nullptr`. CARB_DEPRECATED("Use carb::deallocate() instead") void free(void* p) { return carb::deallocate(p); } static_assert(kFrameworkVersion.major == 0, "Remove Framework::free and CARB_FREE_UNDEFINED in next Framework version"); //! Reallocates a block of memory previously allocated with @ref allocate(). //! //! This function changes the size of the memory block pointed to by @p p to @p size bytes with @p align alignment. //! The contents are unchanged from the start of the memory block up to the minimum of the old size and @p size. If //! @p size is larger than the old size, the added memory is not initialized. If @p p is `nullptr`, the call is //! equivalent to `allocate(size, align)`; if @p size is `0` and @p p is not `nullptr`, the call is equivalent to //! `free(p)`. Unless @p p is `nullptr`, it must have been retrieved by an earlier call to @ref allocate() or //! @ref reallocate(). If the memory region was moved in order to resize it, @p p will be freed as with `free(p)`. //! //! @note Any plugin (or the executable) may allocate the memory and a different plugin (or the executable) may //! reallocate it. //! //! @warning It is undefined behavior to use memory allocated with this function or @ref allocate() after the //! Carbonite framework has been shut down. //! //! @param p The block of memory previously returned from @ref allocate() or @ref reallocate() if resizing is //! resizing is desired. If `nullptr` is passed as this parameter, the call behaves as if //! `allocate(size, align)` was called. //! @param size The size of the memory block requested, in bytes. See above for further explanation. //! @param align The minimum alignment (in bytes) of the memory block requested. Must be a power of two. Values less //! than `sizeof(size_t)` are ignored. Changing the alignment from a previous allocation is undefined behavior. //! `0` indicates to use default system alignment (typically `2 * sizeof(void*)`). //! @returns A pointer to a block of memory of @p size bytes with minimum alignment @p align, unless an error //! occurs in which case `nullptr` is returned. If @p p is `nullptr` and @p size is `0` then `nullptr` is also //! returned. CARB_DEPRECATED("Use carb::reallocate() instead") void* reallocate(void* p, size_t size, size_t align = 0) { return carb::reallocate(p, size, align); } static_assert(kFrameworkVersion.major == 0, "Remove Framework::reallocate in next Framework version"); //! Retrieves the Carbonite SDK version string, //! //! @returns A string describing the current Carbonite SDK version. This will be the same value //! as the @ref CARB_SDK_VERSION value that was set when the SDK was built. //! //! @note This version is intended for use in plugins. Since Carbonite plugins aren't directly //! linked to the `carb` library, access to carbGetSdkVersion() isn't as easy as calling //! a library function. This version just provides access to the same result from a //! location that is better guaranteed accessible to plugins. const char*(CARB_ABI* getSdkVersion)(); //! Adds a load hook that is called when an interface becomes available. //! //! No attempt is made to load the plugin. This can be used as a notification mechanism when a plugin cannot be //! loaded immediately (due to circular dependencies for instance) but may be loaded later. To remove the load hook, //! use \ref removeLoadHook(). It is possible to register multiple load hooks with the same parameters, but this is //! not recommended and will cause the function to be called multiple times with the same parameters. //! //! See \ref LoadHookFn for a discussion on how and when load hooks are called. //! //! @see LoadHookFn removeLoadHook() //! @tparam T The interface type //! @param pluginName the name of the specific plugin desired that exposes \c T, or \c nullptr for any plugin. //! @param func the \ref LoadHookFn to call when the given interface becomes available. This function may be called //! multiple times if multiple plugins that expose interface \c T are loaded. //! @param userData application-specific data that is supplied to \p func when it is called. //! @returns A \ref LoadHookHandle uniquely identifying this load hook; \ref kInvalidLoadHook if an error occurs. //! When finished with the load hook, call \ref removeLoadHook(). template <class T> LoadHookHandle addLoadHook(const char* pluginName, LoadHookFn func, void* userData); //! @private LoadHookHandle(CARB_ABI* internalAddLoadHook)( const InterfaceDesc& iface, const char* plugin, const char* clientName, LoadHookFn fn, void* user, bool add); //! Removes a previously-registered load hook. //! //! It is safe to remove the load hook from within the load hook callback. //! //! @param handle The \ref LoadHookHandle returned from \ref addLoadHook(). //! @returns Returns \c true if the load hook was found and removed. If it was not found, \c false is returned. bool(CARB_ABI* removeLoadHook)(LoadHookHandle handle); //! Registers a client as a script binding or script language owner. Typically handled by CARB_BINDINGS(). //! //! This function is used to notify the Carbonite framework of dependencies from a script language. This allows //! proper dependency tracking and shutdown ordering. For instance, if a python binding loads an interface from //! *carb.assets.plugin*, it appears to Carbonite that a non-plugin client requested the interface. However, if //! python was started from *carb.scripting-python.plugin*, then it becomes necessary to establish a dependency //! relationship between *carb.scripting-python.plugin* and any plugins loaded from python bindings. This function //! has two purposes in this example: the *carb.scripting-python.plugin* will register itself as //! \ref BindingType::Owner for @p scriptType `python`. All bindings automatically register themselves as //! \ref BindingType::Binding for @p scriptType `python` through `CARB_BINDINGS()`. Whenever the binding acquires an //! interface, all registered \ref BindingType::Owner clients gain a dependency on the acquired interface. //! //! @param type The \ref BindingType of \p clientName. //! @param clientName A plugin or binding's client name (`g_carbClientName` typically created by `CARB_GLOBALS()` or //! `CARB_BINDINGS()`). //! @param scriptType A user-defined script type, such as "python" or "lua". Must match between owner and bindings. //! Not case-sensitive. void(CARB_ABI* registerScriptBinding)(BindingType type, const char* clientName, const char* scriptType); //! The main framework access function for acquiring an interface. //! //! @note This function is generally not intended to be used directly; instead, consider one of the many type-safe //! adapter functions such as \ref tryAcquireInterface(). //! //! @warning This function will be `nullptr` in Carbonite releases prior to 135.0 //! //! @param options The structure containing the options for acquiring the interface. //! @returns The interface pointer for the interface being acquired. May be `nullptr` if the interface could not be //! acquired. Verbose logging will explain the entire acquisition process. Warning and Error logs may be //! produced depending on options. void*(CARB_ABI* internalAcquireInterface)(const AcquireInterfaceOptions& options); }; } // namespace carb //! The client's name. //! //! A "client" can be one of the following in the Carbonite framework: //! //! - A plugin. Here the client name is the same as the plugin name. //! //! - An application. //! //! - Scripting bindings. //! //! Clients are uniquely identified by their name. Many functions accept client name as an argument. This allows @ref //! carb::Framework to create a dependency tree of clients. This dependency tree allows the safe unloading of //! plugins. CARB_WEAKLINK CARB_HIDDEN const char* g_carbClientName; //! Defines the client's global @ref carb::Framework pointer. //! //! Do not directly access this pointer. Rather use helper methods like @ref carb::getFramework() and @ref //! carb::isFrameworkValid(). CARB_WEAKLINK CARB_HIDDEN carb::Framework* g_carbFramework; //! Global symbol to enforce the use of CARB_GLOBALS() in Carbonite modules. Do not modify or use //! this value. //! //! If there is an unresolved symbol linker error about this symbol (build time or run time), it //! means that the CARB_GLOBALS() macro was not called at the global scope in the module. This //! exists to ensure that all the global symbols related to each Carbonite module have been //! properly defined and initialized. extern bool g_needToCall_CARB_GLOBALS_atGlobalScope; //! Defines global variables for use by Carbonite. Call this macro from the global namespace. //! //! Do not call this macro directly. Rather: //! //! - For applications, call @ref OMNI_APP_GLOBALS. //! //! - For Carbonite plugins, call @ref CARB_PLUGIN_IMPL. //! //! - For ONI plugins, call @ref OMNI_MODULE_GLOBALS. #define CARB_FRAMEWORK_GLOBALS(clientName) \ CARB_HIDDEN bool g_needToCall_CARB_GLOBALS_atGlobalScope = carb::detail::setClientName(clientName); namespace carb { namespace detail { //! Sets the client name for the calling module. //! //! @param[in] clientName A string literal containing the name of the calling plugin or //! executable. This string must be guaranteed constant for the //! lifetime of the module. //! @returns `true`. //! //! @note This should not be called directly. This is called as part of CARB_FRAMEWORK_GLOBALS(). inline bool setClientName(const char* clientName) { g_carbClientName = clientName; return true; } } // namespace detail //! Gets the Carbonite framework. //! //! The @ref carb::Framework can be `nullptr` for applications if it hasn't acquired it (see @ref //! carb::acquireFramework()). It can also be `nullptr` for a plugin if the plugin is used externally and was not loaded //! by framework itself. //! //! After starting up, @ref carb::getFramework() can be considered a getter for a global singleton that is the @ref //! carb::Framework. //! //! @return The Carbonite framework. inline Framework* getFramework() { return g_carbFramework; } inline void Framework::loadPlugins(const PluginLoadingDesc& desc) { return this->loadPluginsEx(desc); } template <typename T> T* Framework::verifyInterface(T* interfaceCandidate) { const auto desc = T::getInterfaceDesc(); return static_cast<T*>(getFramework()->verifyInterfaceEx(desc, interfaceCandidate)); } template <typename T> T* Framework::acquireInterface(const char* pluginName) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; if (this->internalAcquireInterface) return static_cast<T*>(this->internalAcquireInterface( { sizeof(AcquireInterfaceOptions), clientName, T::getInterfaceDesc(), eAIFDefaultType, pluginName })); else return static_cast<T*>(this->acquireInterfaceWithClient(clientName, T::getInterfaceDesc(), pluginName)); } template <typename T> T* Framework::tryAcquireInterface(const char* pluginName) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; if (this->internalAcquireInterface) return static_cast<T*>( this->internalAcquireInterface({ sizeof(AcquireInterfaceOptions), clientName, T::getInterfaceDesc(), AcquireInterfaceFlags(eAIFDefaultType | fAIFOptional), pluginName })); else return static_cast<T*>(this->tryAcquireInterfaceWithClient(clientName, T::getInterfaceDesc(), pluginName)); } template <typename T> T* Framework::acquireInterface(const void* pluginInterface) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; if (this->internalAcquireInterface) return static_cast<T*>( this->internalAcquireInterface({ sizeof(AcquireInterfaceOptions), clientName, T::getInterfaceDesc(), eAIFFromInterfaceType, pluginInterface })); else return static_cast<T*>( this->acquireInterfaceFromInterfaceWithClient(clientName, T::getInterfaceDesc(), pluginInterface)); } template <typename T> T* Framework::tryAcquireInterface(const void* pluginInterface) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; if (this->internalAcquireInterface) return static_cast<T*>(this->internalAcquireInterface( { sizeof(AcquireInterfaceOptions), clientName, T::getInterfaceDesc(), AcquireInterfaceFlags(eAIFFromInterfaceType | fAIFOptional), pluginInterface })); else return static_cast<T*>( this->tryAcquireInterfaceFromInterfaceWithClient(clientName, T::getInterfaceDesc(), pluginInterface)); } template <typename T> T* Framework::acquireInterfaceFromLibrary(const char* libraryPath) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; if (this->internalAcquireInterface) return static_cast<T*>(this->internalAcquireInterface( { sizeof(AcquireInterfaceOptions), clientName, T::getInterfaceDesc(), eAIFFromLibraryType, libraryPath })); else return static_cast<T*>( this->acquireInterfaceFromLibraryWithClient(clientName, T::getInterfaceDesc(), libraryPath)); } template <typename T> T* Framework::tryAcquireInterfaceFromLibrary(const char* libraryPath) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; if (this->internalAcquireInterface) return static_cast<T*>( this->internalAcquireInterface({ sizeof(AcquireInterfaceOptions), clientName, T::getInterfaceDesc(), AcquireInterfaceFlags(eAIFFromLibraryType | fAIFOptional), libraryPath })); else return static_cast<T*>( this->tryAcquireInterfaceFromLibraryWithClient(clientName, T::getInterfaceDesc(), libraryPath)); } template <typename T> T* Framework::tryAcquireExistingInterface(const char* pluginName) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; return this->internalAcquireInterface ? static_cast<T*>(this->internalAcquireInterface( { sizeof(AcquireInterfaceOptions), clientName, T::getInterfaceDesc(), AcquireInterfaceFlags(eAIFDefaultType | fAIFOptional | fAIFNoInitialize), pluginName })) : nullptr; } template <typename T> uint32_t Framework::getInterfacesCount() { const InterfaceDesc desc = T::getInterfaceDesc(); return this->getInterfacesCountEx(desc); } template <typename T> void Framework::acquireInterfaces(T** interfaces, uint32_t interfacesSize) { const InterfaceDesc desc = T::getInterfaceDesc(); const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; this->acquireInterfacesWithClient(clientName, desc, reinterpret_cast<void**>(interfaces), interfacesSize); } template <typename T> void Framework::releaseInterface(T* pluginInterface) { (void)(T::getInterfaceDesc()); // Compile-time check that the type is plugin interface const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; this->releaseInterfaceWithClient(clientName, pluginInterface); } template <typename T> void Framework::setDefaultPlugin(const char* pluginName) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; this->setDefaultPluginEx(clientName, T::getInterfaceDesc(), pluginName); } template <typename T> LoadHookHandle Framework::addLoadHook(const char* pluginName, LoadHookFn func, void* user) { const char* clientName = g_needToCall_CARB_GLOBALS_atGlobalScope ? g_carbClientName : nullptr; return this->internalAddLoadHook(T::getInterfaceDesc(), pluginName, clientName, func, user, true); } } // namespace carb #ifdef CARB_FREE_UNDEFINED # pragma pop_macro("free") # undef CARB_FREE_UNDEFINED #endif
71,177
C
48.670621
120
0.694115
omniverse-code/kit/include/carb/BindingsPythonUtils.h
// Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "BindingsUtils.h" #include "IObject.h" #include "cpp/TypeTraits.h" #include "cpp/Functional.h" // Python uses these in modsupport.h, so undefine them now #pragma push_macro("min") #undef min #pragma push_macro("max") #undef max CARB_IGNOREWARNING_MSC_WITH_PUSH(4668) // 'X' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' #include <pybind11/chrono.h> #include <pybind11/functional.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> CARB_IGNOREWARNING_MSC_POP #pragma pop_macro("min") #pragma pop_macro("max") namespace py = pybind11; PYBIND11_DECLARE_HOLDER_TYPE(T, carb::ObjectPtr<T>, true); // Provide simple implementations of types used in multiple bindings. namespace carb { template <typename InterfaceType, typename ReturnType, typename... Args> auto wrapInterfaceFunctionReleaseGIL(ReturnType (*InterfaceType::*p)(Args...)) -> std::function<ReturnType(InterfaceType&, Args...)> { return [p](InterfaceType& c, Args... args) { py::gil_scoped_release g; return (c.*p)(args...); }; } template <typename InterfaceType, typename ReturnType, typename... Args> auto wrapInterfaceFunctionReleaseGIL(const InterfaceType* c, ReturnType (*InterfaceType::*p)(Args...)) -> std::function<ReturnType(Args...)> { return [c, p](Args... args) { py::gil_scoped_release g; return (c->*p)(args...); }; } template <typename InterfaceType, typename... PyClassArgs> py::class_<InterfaceType, PyClassArgs...> defineInterfaceClass(py::module& m, const char* className, const char* acquireFuncName, const char* releaseFuncName = nullptr, const char* classDocstring = nullptr) { auto cls = classDocstring ? py::class_<InterfaceType, PyClassArgs...>(m, className, classDocstring) : py::class_<InterfaceType, PyClassArgs...>(m, className); m.def(acquireFuncName, [](const char* pluginName, const char* libraryPath) { return libraryPath ? acquireInterfaceFromLibraryForBindings<InterfaceType>(libraryPath) : acquireInterfaceForBindings<InterfaceType>(pluginName); }, py::arg("plugin_name") = nullptr, py::arg("library_path") = nullptr, py::return_value_policy::reference); if (releaseFuncName) { m.def(releaseFuncName, [](InterfaceType* iface) { carb::getFramework()->releaseInterface(iface); }); } return cls; } /** * Assuming std::function will call into python code this function makes it safe. * It wraps it into try/catch, acquires GIL lock and log errors. */ template <typename Sig, typename... ArgsT> auto callPythonCodeSafe(const std::function<Sig>& fn, ArgsT&&... args) { using ReturnT = cpp::invoke_result_t<decltype(fn), ArgsT...>; try { if (fn) { py::gil_scoped_acquire gilLock; return fn(std::forward<ArgsT>(args)...); } } catch (const py::error_already_set& e) { CARB_LOG_ERROR("%s", e.what()); } catch (const std::runtime_error& e) { CARB_LOG_ERROR("%s", e.what()); } return ReturnT(); } /** * Helper class implement scripting callbacks. * It extends ScriptCallbackRegistry to provide facility to make safe calls of python callback. It adds GIL lock and * error handling. ScriptCallbackRegistryPython::call can be passed into C API as C function, as long as FuncT* is * passed into as userData. */ template <class KeyT, typename ReturnT, typename... Args> class ScriptCallbackRegistryPython : public ScriptCallbackRegistry<KeyT, ReturnT, Args...> { public: using typename ScriptCallbackRegistry<KeyT, ReturnT, Args...>::FuncT; static ReturnT call(Args... args, void* userData) { return callTyped((FuncT*)userData, std::forward<Args>(args)...); } static ReturnT callTyped(FuncT* f, Args&&... args) { return callPythonCodeSafe(*f, std::forward<Args>(args)...); } }; /** * Holds subscription for python in RAII way. Unsubscribe function is called when destroyed. */ class Subscription { public: template <class Unsubscribe> explicit Subscription(Unsubscribe&& unsubscribe) : m_unsubscribeFn(std::forward<Unsubscribe>(unsubscribe)) { } void unsubscribe() { if (m_unsubscribeFn) { m_unsubscribeFn(); m_unsubscribeFn = nullptr; } } ~Subscription() { unsubscribe(); } private: std::function<void()> m_unsubscribeFn; }; template <class Ret, class... Args> class PyAdapter { using Function = std::function<Ret(Args...)>; Function m_func; struct ScopedDestroy { PyAdapter* m_callable; ScopedDestroy(PyAdapter* callable) : m_callable(callable) { } ~ScopedDestroy() { delete m_callable; } }; public: PyAdapter(Function&& func) : m_func(std::move(func)) { } template <class... Args2> auto call(Args2&&... args) { using ReturnType = cpp::invoke_result_t<Function, Args2...>; try { py::gil_scoped_acquire gil; if (m_func) { return cpp::invoke(std::move(m_func), std::forward<Args2>(args)...); } } catch (const py::error_already_set& e) { CARB_LOG_ERROR("%s", e.what()); } catch (const std::runtime_error& e) { CARB_LOG_ERROR("%s", e.what()); } py::gil_scoped_acquire gil; // Hold the GIL while constructing whatever return type return ReturnType(); } // Direct adapter to Carbonite callback when userData is the last argument, the PyAdapter* is the userdata, and // multiple calls to this adapter are desired. The adapter must be deleted with `delete` or `destroy()` later. static auto adaptCallAndKeep(Args... args, void* user) { return static_cast<PyAdapter*>(user)->call(std::forward<Args>(args)...); } // Direct adapter to Carbonite callback when userData is the last argument, the PyAdapter* is the userdata, and // there will be only one call to the adapter. static auto adaptCallAndDestroy(Args... args, void* user) { PyAdapter* callable = static_cast<PyAdapter*>(user); ScopedDestroy scopedDestroy(callable); return callable->call(std::forward<Args>(args)...); } // Call the adapter with perfect forwarding and keep the adapter around for future calls. template <class... Args2> static auto callAndKeep(void* user, Args2&&... args) { return static_cast<PyAdapter*>(user)->call(std::forward<Args2>(args)...); } // Call the adapter with perfect forwarding and destroy the adapter. template <class... Args2> static auto callAndDestroy(void* user, Args2&&... args) { PyAdapter* callable = static_cast<PyAdapter*>(user); ScopedDestroy scopedDestroy(callable); return callable->call(std::forward<Args2>(args)...); } static void destroy(void* user) { delete static_cast<PyAdapter*>(user); } }; template <class Ret, class... Args> std::unique_ptr<PyAdapter<Ret, Args...>> createPyAdapter(std::function<Ret(Args...)>&& func) { return std::make_unique<PyAdapter<Ret, Args...>>(std::move(func)); } template <class Callback, class Subscribe, class Unsubscribe> std::shared_ptr<Subscription> createPySubscription(Callback&& func, Subscribe&& subscribe, Unsubscribe&& unsub) { auto callable = createPyAdapter(std::forward<Callback>(func)); using Callable = typename decltype(callable)::element_type; auto&& id = subscribe(Callable::adaptCallAndKeep, callable.get()); return std::make_shared<Subscription>( [unsub = std::forward<Unsubscribe>(unsub), id = std::move(id), callable = callable.release()] { unsub(id); delete callable; }); } /** * Set of helpers to pass std::function (from python bindings) in Carbonite interfaces. * Deprecated: use PyAdapter instead via createPyAdapter()/createPySubscription() */ template <typename ReturnT, typename... ArgsT> class FuncUtils { public: using StdFuncT = std::function<ReturnT(ArgsT...)>; using CallbackT = ReturnT (*)(ArgsT..., void*); static ReturnT callPythonCodeSafe(const std::function<ReturnT(ArgsT...)>& fn, ArgsT... args) { return carb::callPythonCodeSafe(fn, args...); } static ReturnT callbackWithUserData(ArgsT... args, void* userData) { StdFuncT* fn = (StdFuncT*)userData; if (fn) return callPythonCodeSafe(*fn, args...); else return ReturnT(); } static StdFuncT* createStdFuncCopy(const StdFuncT& fn) { return new StdFuncT(fn); } static void destroyStdFuncCopy(StdFuncT* fn) { delete fn; } /** * If you have std::function which calls into python code and an interface with pair of subscribe/unsubscribe * functions, this function: * 1. Prolong lifetime of std::function (and thus python callable) by making copy of it on heap. * 2. Subscribes to interface C-style subscribe function by passing this std::function as void* userData (and * calling it back safely) * 3. Wraps subscription id into Subscription class returned to python. Which holds subscription and * automatically unsubscribes when dead. */ template <class SubscriptionT> static std::shared_ptr<Subscription> buildSubscription(const StdFuncT& fn, SubscriptionT (*subscribeFn)(CallbackT, void*), void (*unsubscribeFn)(SubscriptionT)) { StdFuncT* funcCopy = new StdFuncT(fn); auto id = subscribeFn(callbackWithUserData, funcCopy); auto subscription = std::make_shared<Subscription>([=]() { unsubscribeFn(id); delete funcCopy; }); return subscription; } }; template <class T> struct StdFuncUtils; template <class R, class... Args> struct StdFuncUtils<std::function<R(Args...)>> : public FuncUtils<R, Args...> { }; template <class R, class... Args> struct StdFuncUtils<const std::function<R(Args...)>> : public FuncUtils<R, Args...> { }; template <class R, class... Args> struct StdFuncUtils<const std::function<R(Args...)>&> : public FuncUtils<R, Args...> { }; /** * Helper to wrap function that returns `IObject*` into the same function that returns stolen ObjectPtr<IObject> holder */ template <typename ReturnT, typename... Args> std::function<ReturnT(Args...)> wrapPythonCallback(std::function<ReturnT(Args...)>&& c) { return [c = std::move(c)](Args... args) -> ReturnT { return callPythonCodeSafe(c, std::forward<Args>(args)...); }; } } // namespace carb #ifdef DOXYGEN_BUILD /** * Macro that allows disabling pybind's use of RTTI to perform duck typing. * * Given a pointer, pybind uses RTTI to figure out the actual type of the pointer (e.g. given an `IObject*`, RTTI can be * used to figure out the pointer is really an `IWindow*`). once pybind knows the "real" type, is generates a PyObject * that contains wrappers for all of the "real" types methods. * * Unfortunately, RTTI is compiler dependent (not @rstref{ABI-safe <abi-compatibility>}) and we've disabled it in much * of our code. * * The `polymorphic_type_hook` specializations generated by this macro disables pybind from using RTTI to find the * "real" type of a pointer. this mean that when using our bindings in Python, you have to "cast" objects to access a * given interface. For example: * ```python * obj = func_that_returns_iobject() * win = IWindow(obj) # a cast. None is returned if the cast fails. * if win: * win->title = "hi" * ``` * * As an aside, since implementations can implement multiple interfaces and the actual implementations are hidden to * pybind (we create bindings for interfaces not implementations), the pybind "duck" typing approach was never going to * work for us. Said differently, some sort of "cast to this interface" was inevitable. * @param TYPE The type to disable Pythonic dynamic casting for. */ # define DISABLE_PYBIND11_DYNAMIC_CAST(TYPE) #else # define DISABLE_PYBIND11_DYNAMIC_CAST(TYPE) \ namespace pybind11 \ { \ template <> \ struct polymorphic_type_hook<TYPE> \ { \ static const void* get(const TYPE* src, const std::type_info*&) \ { \ return src; \ } \ }; \ template <typename itype> \ struct polymorphic_type_hook< \ itype, \ detail::enable_if_t<std::is_base_of<TYPE, itype>::value && !std::is_same<TYPE, itype>::value>> \ { \ static const void* get(const TYPE* src, const std::type_info*&) \ { \ return src; \ } \ }; \ } #endif DISABLE_PYBIND11_DYNAMIC_CAST(carb::IObject)
15,665
C
36.568345
120
0.557229
omniverse-code/kit/include/carb/RenderingTypes.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 "Types.h" namespace carb { /** * Defines a resource format. */ enum class Format { eUnknown, eR8_UNORM, eR8_SNORM, eR8_UINT, eR8_SINT, eRG8_UNORM, eRG8_SNORM, eRG8_UINT, eRG8_SINT, eBGRA8_UNORM, eBGRA8_SRGB, eRGBA8_UNORM, eRGBA8_SNORM, eRGBA8_UINT, eRGBA8_SINT, eRGBA8_SRGB, eR16_UNORM, eR16_SNORM, eR16_UINT, eR16_SINT, eR16_SFLOAT, eRG16_UNORM, eRG16_SNORM, eRG16_UINT, eRG16_SINT, eRG16_SFLOAT, eRGBA16_UNORM, eRGBA16_SNORM, eRGBA16_UINT, eRGBA16_SINT, eRGBA16_SFLOAT, eR32_UINT, eR32_SINT, eR32_SFLOAT, eRG32_UINT, eRG32_SINT, eRG32_SFLOAT, eRGB32_UINT, eRGB32_SINT, eRGB32_SFLOAT, eRGBA32_UINT, eRGBA32_SINT, eRGBA32_SFLOAT, eR10_G10_B10_A2_UNORM, eR10_G10_B10_A2_UINT, eR11_G11_B10_UFLOAT, eR9_G9_B9_E5_UFLOAT, eB5_G6_R5_UNORM, eB5_G5_R5_A1_UNORM, eBC1_RGBA_UNORM, eBC1_RGBA_SRGB, eBC2_RGBA_UNORM, eBC2_RGBA_SRGB, eBC3_RGBA_UNORM, eBC3_RGBA_SRGB, eBC4_R_UNORM, eBC4_R_SNORM, eBC5_RG_UNORM, eBC5_RG_SNORM, eBC6H_RGB_UFLOAT, eBC6H_RGB_SFLOAT, eBC7_RGBA_UNORM, eBC7_RGBA_SRGB, eD16_UNORM, eD24_UNORM_S8_UINT, eD32_SFLOAT, eD32_SFLOAT_S8_UINT_X24, // Formats for depth-stencil views eR24_UNORM_X8, eX24_R8_UINT, eX32_R8_UINT_X24, eR32_SFLOAT_X8_X24, // Formats for sampler-feedback eSAMPLER_FEEDBACK_MIN_MIP, eSAMPLER_FEEDBACK_MIP_REGION_USED, // Little-Endian Formats eABGR8_UNORM, eABGR8_SRGB, // Must be last eCount }; /** * Defines a sampling count for a resource. */ enum class SampleCount { e1x, e2x, e4x, e8x, e16x, e32x, e64x }; /** * Defines the presentation mode for the rendering system. */ enum class PresentMode : uint8_t { eNoTearing, //!< No tearing. eAllowTearing //!< Allow tearing. }; /** * Defines a descriptor for clearing color values. */ union ClearColorValueDesc { Color<float> rgba32f; Color<uint32_t> rgba32ui; Color<int32_t> rgba32i; }; /** * Defines a descriptor for clearing depth-stencil values. */ struct ClearDepthStencilValueDesc { float depth; uint32_t stencil; }; enum class TextureGamma { eDefault, ///< treat as linear for HDR formats, as sRGB for LDR formats (use e*_SRGB tex format or convert on load) eLinear, ///< treat as linear, leaves data unchanged eSRGB, ///< treat as sRGB, (use e*_SRGB texture format or convert on load) eCount }; } // namespace carb
3,073
C
18.832258
119
0.649203
omniverse-code/kit/include/carb/FrameworkUtils.h
// Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Framework.h" #include "extras/Path.h" #include <string> #include <unordered_set> #include <vector> namespace carb { /** * Get all registered plugins and collect folders they are located in. */ inline std::unordered_set<std::string> getPluginFolders() { Framework* framework = carb::getFramework(); std::vector<PluginDesc> plugins(framework->getPluginCount()); framework->getPlugins(plugins.data()); std::unordered_set<std::string> folders; for (const auto& desc : plugins) { extras::Path p(desc.libPath); const std::string& folder = p.getParent(); if (!folder.empty()) { folders.insert(folder); } } return folders; } } // namespace carb
1,188
C
27.999999
77
0.700337
omniverse-code/kit/include/carb/PluginUtils.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 Utilities to ease the creation of Carbonite plugins. #pragma once #include "ClientUtils.h" #include "PluginInitializers.h" #include "PluginCoreUtils.h" namespace omni { namespace structuredlog { void addModulesSchemas() noexcept; } } // namespace omni //! Plugin helper macro to define boiler-plate code to register and unregister the plugin with various other components //! in the system (e.g. logging channels, profiler, localization, etc.). //! //! Do not directly call this macro, rather call @ref CARB_PLUGIN_IMPL() which will call this macro for you. #define CARB_DEFAULT_INITIALIZERS() \ CARB_EXPORT void carbOnPluginPreStartup() \ { \ carb::pluginInitialize(); \ omni::structuredlog::addModulesSchemas(); \ } \ \ CARB_EXPORT void carbOnPluginPostShutdown() \ { \ carb::pluginDeinitialize(); \ } //! Main macro to declare a plugin implementation where multiple interface versions are not required. //! //! Authors of Carbonite plugins must use this macro in exactly one compilation unit for their plugin to generate code //! expected by the Carbonite framework. //! //! @note Carbonite plugins can provide multiple versions of an interface to remain backwards compatible with apps and //! modules that are built against earlier versions of plugins. In order to do this, see \ref CARB_PLUGIN_IMPL_EX. //! //! In particular, this macro: //! //! - Defines global variables, such as @ref g_carbFramework. //! //! - Registers a default logging channel with @ref omni::log::ILog. //! //! - Adds boiler-plate code for @oni_overview interop. //! //! - Adds boiler-plate code for plugin startup, shutdown, and registration. (See @carb_framework_overview for more //! information). //! //! This macro must be used in the global namespace. A @ref carb::PluginImplDesc must be provided as well as all //! interfaces exported by this plugin. Each interface must be declared with @ref CARB_PLUGIN_INTERFACE. There must also //! exist a @ref fillInterface(InterfaceType&) function for each interface type that is exported by this plugin. //! A trailing semicolon is optional. //! //! Example: //! @code{.cpp} //! // Plugin Implementation Descriptor //! const carb::PluginImplDesc kPluginImpl{ "carb.windowing-glfw.plugin", "Windowing (glfw).", "NVIDIA", //! carb::PluginHotReload::eDisabled, "dev" }; //! //! // Generate boilerplate code //! CARB_PLUGIN_IMPL(kPluginImpl, carb::windowing::IWindowing, carb::windowing::IGLContext) //! //! // Construct the carb::windowing::IWindowing interface //! void fillInterface(carb::windowing::IWindowing& iface) { /* ... */ } //! //! // Construct the carb::windowing::IGLContext interface //! void fillInterface(carb::windowing::IGLContext& iface) { /* ... */ } //! @endcode //! //! See @carb_framework_overview and @carb_interfaces for more information on creating Carbonite plugins. //! //! @param impl The @ref carb::PluginImplDesc constant to be used as plugin description. //! //! @param ... One or more interface types to be implemented by the plugin. An interface is a `struct` or `class` with //! a use of @ref CARB_PLUGIN_INTERFACE() inside it. These interface types are constructed by a global function //! @ref fillInterface(InterfaceType&) that must exist in the plugin. See @ref fillInterface(InterfaceType&) for more //! information about interface construction and destruction. #define CARB_PLUGIN_IMPL(impl, ...) \ CARB_GLOBALS_EX(impl.name, impl.description) \ OMNI_MODULE_GLOBALS_FOR_PLUGIN() \ CARB_PLUGIN_IMPL_WITH_INIT_0_5(impl, __VA_ARGS__) /* for backwards compatibility */ \ CARB_PLUGIN_IMPL_WITH_INIT(impl, __VA_ARGS__) \ CARB_DEFAULT_INITIALIZERS() //! Main macro to declare a plugin implementation where multiple interface versions are required. //! //! Authors of Carbonite plugins must use this macro in exactly one compilation unit for their plugin to generate code //! expected by the Carbonite framework. //! //! @note This implementation macro allows Carbonite plugins to provide multiple versions of an interface in order to //! remain backwards compatible with apps and modules that are built against earlier versions of plugins. Every //! interface exported by the plugin must have a @ref fillInterface(carb::Version*, void*) function. //! //! In particular, this macro: //! //! - Defines global variables, such as @ref g_carbFramework. //! //! - Registers a default logging channel with @ref omni::log::ILog. //! //! - Adds boiler-plate code for @oni_overview interop. //! //! - Adds boiler-plate code for plugin startup, shutdown, and registration. (See @carb_framework_overview for more //! information). //! //! This macro must be used in the global namespace. A @ref carb::PluginImplDesc must be provided as well as all //! interfaces exported by this plugin. Each interface must be declared with @ref CARB_PLUGIN_INTERFACE. There must also //! exist a @ref fillInterface(carb::Version*, void*) function for each interface type that is exported by this plugin. //! A trailing semicolon is optional. //! //! Example: //! @code{.cpp} //! // Plugin Implementation Descriptor //! const carb::PluginImplDesc kPluginImpl{ "carb.windowing-glfw.plugin", "Windowing (glfw).", "NVIDIA", //! carb::PluginHotReload::eDisabled, "dev" }; //! //! // Generate boilerplate code //! CARB_PLUGIN_IMPL_EX(kPluginImpl, carb::windowing::IWindowing, carb::windowing::IGLContext) //! //! // Construct the carb::windowing::IWindowing interface //! template <> void fillInterface<carb::windowing::IWindowing>(carb::Version* v, void* iface) { /* ... */ } //! //! // Construct the carb::windowing::IGLContext interface //! template <> void fillInterface<carb::windowing::IGLContext>(carb::Version* v, void* iface) { /* ... */ } //! @endcode //! //! See @carb_framework_overview and @carb_interfaces for more information on creating Carbonite plugins. //! //! @param impl The @ref carb::PluginImplDesc constant to be used as plugin description. //! //! @param ... One or more interface types to be implemented by the plugin. An interface is a `struct` or `class` with //! a use of @ref CARB_PLUGIN_INTERFACE() inside it. These interface types are constructed by a global explicitly- //! specialized template function @ref fillInterface(carb::Version*, void*) that must exist in the plugin. See //! @ref fillInterface(carb::Version*, void*) for more information about interface construction and destruction. #define CARB_PLUGIN_IMPL_EX(impl, ...) \ CARB_GLOBALS_EX(impl.name, impl.description) \ OMNI_MODULE_GLOBALS_FOR_PLUGIN() \ CARB_PLUGIN_IMPL_WITH_INIT_EX(impl, __VA_ARGS__) \ CARB_PLUGIN_IMPL_WITH_INIT_0_5_EX(impl, __VA_ARGS__) /* for backwards compatibility */ \ CARB_DEFAULT_INITIALIZERS() /** * Macros to declare a plugin implementation dependencies. * * If a plugin lists an interface "A" as dependency it is guaranteed that `carb::Framework::acquireInterface<A>()` call * will return it, otherwise it can return `nullptr`. The Framework checks and resolves all dependencies before loading * the plugin. If the dependency cannot be loaded (i.e. no plugin satisfies the interface, or a circular load is * discovered) then the plugin will fail to load and `nullptr` will be returned from the * carb::Framework::acquireInterface() function. * * @note Circular dependencies can exist as long as they are not stated in the CARB_PLUGIN_IMPL_DEPS() macros. For * instance, assume plugins *Alpha*, *Beta*, and *Gamma*. *Alpha* is dependent on *Beta*; *Beta* is dependent on * *Gamma*. *Gamma* is dependent on *Alpha*, but cannot list *Alpha* in its CARB_PLUGIN_IMPL_DEPS() macro, nor * attempt to acquire and use it in *Gamma*'s carbOnPluginStartup() function. At a later point from within *Gamma*, the * desired interface from *Alpha* may be acquired and used. However, in terms of unload order, *Alpha* will be unloaded * first, followed by *Beta* and finally *Gamma*. In this case the *Gamma* carbOnPluginShutdown() function must account * for the fact that *Alpha* will already be unloaded. * * @param ... One or more interface types (e.g. `carb::settings::ISettings`) to list as dependencies for this plugin. */ #define CARB_PLUGIN_IMPL_DEPS(...) \ template <typename... Types> \ static void getPluginDepsTyped(struct carb::InterfaceDesc** deps, size_t* count) \ { \ static carb::InterfaceDesc depends[] = { Types::getInterfaceDesc()... }; \ *deps = depends; \ *count = sizeof(depends) / sizeof(depends[0]); \ } \ \ CARB_EXPORT void carbGetPluginDeps(struct carb::InterfaceDesc** deps, size_t* count) \ { \ getPluginDepsTyped<__VA_ARGS__>(deps, count); \ } /** * Macro to declare a plugin without dependencies. * * Calling this macro is not required if there are no dependencies. This macro exists to make your plugin more * readable. */ #define CARB_PLUGIN_IMPL_NO_DEPS() \ CARB_EXPORT void carbGetPluginDeps(struct carb::InterfaceDesc** deps, size_t* count) \ { \ *deps = nullptr; \ *count = 0; \ } /** * Macro to declare a "minimal" plugin. * * Plugins in the Carbonite ecosystem tend to depend on other plugins. For example, plugins often want to access * Carbonite's logging system via @ref carb::logging::ILogging. When calling @ref CARB_PLUGIN_IMPL, boiler-plate code * is injected to ensure the plugin can use these "common" plugins. * * This macro avoids taking dependencies on these "common" plugins. When calling this macro, only the "minimal" boiler * plate code is generated in order for the plugin to work. It's up to the developer to add additional code to make the * plugin compatible with any desired "common" plugin. * * Use of this macro is rare in Omniverse. */ #define CARB_PLUGIN_IMPL_MINIMAL(impl, ...) \ CARB_FRAMEWORK_GLOBALS(kPluginImpl.name) \ CARB_PLUGIN_IMPL_WITH_INIT(impl, __VA_ARGS__)
13,568
C
61.819444
120
0.549455
omniverse-code/kit/include/carb/Version.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 Utilities for Carbonite version. #pragma once #include <cinttypes> #include <cstdint> #include <cstdio> #include <type_traits> // Note: Ideally this would be in Defines.h, but there is a weird circular dependency: // Defines.h -> assert/IAssert.h -> Interface.h -> Version.h //! A macro to ensure interop safety by assertion //! //! In order to have @rstref{interop safety <abi-compatibility>} a type must be //! <a href="https://en.cppreference.com/w/cpp/named_req/TriviallyCopyable">trivially-copyable</a> and conform to //! <a href="https://en.cppreference.com/w/cpp/named_req/StandardLayoutType">StandardLayoutType</a>. //! @param ... The Type to check #define CARB_ASSERT_INTEROP_SAFE(...) \ static_assert(std::is_standard_layout<__VA_ARGS__>::value, "Must have standard layout to be interop safe"); \ static_assert(std::is_trivially_copyable<__VA_ARGS__>::value, "Must be trivially copyable to be interop safe") namespace carb { /** * Defines a version consisting of a major and minor version. */ struct Version { uint32_t major; //!< The major version. uint32_t minor; //!< The minor version. }; CARB_ASSERT_INTEROP_SAFE(Version); /** * Less-than comparison operator. * * Compares two versions and reports true if the left version is lower than the right. * * @note The major and minor versions are compared independently. While the \a number `1.11` is less than the \a number * `1.9`, \a version `1.11` is considered to be higher, so `Version{ 1, 9 } < Version{ 1, 11 }` would be `true`. * @param lhs The version on the left side of the operation * @param rhs The version on the right side of the operation * @returns `true` if \p lhs is a lower version than \p rhs; `false` otherwise. */ constexpr bool operator<(const Version& lhs, const Version& rhs) noexcept { if (lhs.major == rhs.major) { return lhs.minor < rhs.minor; } return lhs.major < rhs.major; } /** * Less-than-or-equal comparison operator. * * Compares two versions and reports true if the left version is lower than or equal to the right. * * @note The major and minor versions are compared independently. While the \a number `1.11` is less than the \a number * `1.9`, \a version `1.11` is considered to be higher, so `Version{ 1, 9 } <= Version{ 1, 11 }` would be `true`. * @param lhs The version on the left side of the operation * @param rhs The version on the right side of the operation * @returns `true` if \p lhs is a version that is lower than or equal to \p rhs; `false` otherwise. */ constexpr bool operator<=(const Version& lhs, const Version& rhs) noexcept { if (lhs.major == rhs.major) { return lhs.minor <= rhs.minor; } return lhs.major < rhs.major; } /** * Equality operator. * * Compares two versions and reports true if the left version and the right version are equal. * * @param lhs The version on the left side of the operation * @param rhs The version on the right side of the operation * @returns `true` if \p lhs is equal to \p rhs; `false` otherwise. */ constexpr bool operator==(const Version& lhs, const Version& rhs) noexcept { return lhs.major == rhs.major && lhs.minor == rhs.minor; } /** * Inequality operator. * * Compares two versions and reports true if the left version and the right version are not equal. * * @param lhs The version on the left side of the operation * @param rhs The version on the right side of the operation * @returns `true` if \p lhs is not equal to \p rhs; `false` otherwise. */ constexpr bool operator!=(const Version& lhs, const Version& rhs) noexcept { return !(lhs == rhs); } /** * Checks two versions to see if they are semantically compatible. * * For more information on semantic versioning, see https://semver.org/. * * @warning A major version of `0` is considered to be the "development/experimental" version and `0.x` minor versions * may be but are not required to be compatible with each other. This function will consider \p minimum version `0.x` to * be semantically compatible to different \p candidate version `0.y`, but will emit a warning to `stderr` if a \p name * is provided. * * @param name An optional name that, if provided, will enable the warning message to `stderr` for `0.x` versions * mentioned above. * @param minimum The minimum version required. This is typically the version being tested. * @param candidate The version offered. This is typically the version being tested against. * @retval true If \p minimum and \p candidate share the same major version and \p candidate has a minor version that is * greater-than or equal to the minor version in \p minimum. * @retval false If \p minimum and \p candidate have different major versions or \p candidate has a minor version that * is lower than the minor version requested in \p minimum. */ inline bool isVersionSemanticallyCompatible(const char* name, const Version& minimum, const Version& candidate) { if (minimum.major != candidate.major) { return false; } else if (minimum.major == 0) { // Need to special case when major is equal but zero, then any difference in minor makes them // incompatible. See http://semver.org for details. // the case of version 0.x (major of 0), we are only going to "warn" the user of possible // incompatibility when a user asks for 0.x and we have an implementation 0.y (where y > x). // see https://nvidia-omniverse.atlassian.net/browse/CC-249 if (minimum.minor > candidate.minor) { return false; } else if (minimum.minor < candidate.minor && name) { // using CARB_LOG maybe pointless, as logging may not be set up yet. fprintf(stderr, "Warning: Possible version incompatibility. Attempting to load %s with version v%" PRIu32 ".%" PRIu32 " against v%" PRIu32 ".%" PRIu32 ".\n", name, candidate.major, candidate.minor, minimum.major, minimum.minor); } } else if (minimum.minor > candidate.minor) { return false; } return true; } } // namespace carb
6,741
C
39.614458
120
0.680463
omniverse-code/kit/include/carb/BindingsPythonTypes.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 A collection of opaque type definitions needed by multiple Python bindings #pragma once #ifndef DOXYGEN_BUILD namespace carb { namespace input { struct Mouse { }; struct Keyboard { }; } // namespace input namespace windowing { struct Window { }; } // namespace windowing } // namespace carb #endif
761
C
19.594594
85
0.760841
omniverse-code/kit/include/carb/FindPlugins.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 Utilities for finding plugins. #pragma once #include "Framework.h" #include "extras/Library.h" #include "filesystem/IFileSystem.h" #include "filesystem/FindFiles.h" #include "logging/Log.h" #include "../omni/str/Wildcard.h" #include <cstring> namespace carb { //! Callback that is called when a candidate plugin file is located. //! @param canonical The canonical name of the file. //! @param reloadable Indicates that the filename matches a pattern in \ref FindPluginsArgs::reloadableFileWildcards. //! @param context The `onMatchedContext` from \ref FindPluginsArgs. using FindPluginsOnMatchedFn = void(const char* canonical, bool reloadable, void* context); //! Arguments that are passed to \ref findPlugins(). struct FindPluginsArgs { //! Search folders to look for plugins in. //! //! This may contain relative or absolute paths. All relative paths will be resolved relative to //! \ref carb::filesystem::IFileSystem::getAppDirectoryPath(), not the current working directory. Absolute paths //! in the list will be searched directly. //! //! If search paths configuration is invalid (e.g. search paths count is zero), the fall-back values are taken from //! the default plugin desc. //! //! May be nullptr. const char* const* searchPaths; size_t searchPathCount; //!< Number of entries in `searchPaths`. May be 0. //! Search the given paths recursively if `true`. bool searchRecursive; //! Filename wildcards to select loaded files. `*` and `?` can be used, e.g. "carb.*.pl?gin" //! //! If nullptr, a reasonable default is used. const char* const* loadedFileWildcards; size_t loadedFileWildcardCount; //!< Number of entries in `loadedFileWildcards`. May be 0. //! Filename wildcards to mark loaded files as reloadable. Framework will treat them specially to allow //! overwriting source plugins and will monitor them for changes. //! //! May be nullptr. const char* const* reloadableFileWildcards; size_t reloadableFileWildcardCount; //!< Number of entries in `reloadableFileWildcards`. May be 0. //! Filename wildcards to select excluded files. `*` and `?` can be used. //! //! May be nullptr. const char* const* excludedFileWildcards; size_t excludedFileWildcardCount; //!< Number of entries in `excludedFileWildcards`. May be 0. //! Callback when a file is matched but not excluded. //! //! @warning Must not be nullptr. FindPluginsOnMatchedFn* onMatched; void* onMatchedContext; //!< Context for onMatched. May be nullptr. //! Callback when a file is matched and excluded. //! //! May be nullptr. filesystem::FindFilesOnExcludedFn* onExcluded; void* onExcludedContext; //!< Context for onExcluded. May be nullptr. //! Callback when a file is not match one of the "loadedFileWildcard" patterns //! //! May be nullptr. filesystem::FindFilesOnSkippedFn* onSkipped; void* onSkippedContext; //!< Context for onSkipped. May be nullptr. //! Callback invoked before searching one of the given directories. //! //! May be nullptr. filesystem::FindFilesOnSearchPathFn* onSearchPath; void* onSearchPathContext; //!< Context for onSearchPath. May be nullptr. //! IFileSystem object to use to walk the file system. //! //! If nullptr, tryAcquireInterface<IFileSystem> is called. filesystem::IFileSystem* fs; }; #ifndef DOXYGEN_BUILD namespace detail { inline bool caseInsensitiveEndsWith(const char* str, const char* tail) { const size_t strLen = std::strlen(str); const size_t tailLen = std::strlen(tail); // String should be at least as long as tail if (strLen < tailLen) { return false; } // Compare with tail, character by character for (size_t i = 0; i < tailLen; ++i) { // Tail is assumed to already be lowercase if (tail[tailLen - i - 1] != std::tolower(str[strLen - i - 1])) { return false; } } return true; } } // namespace detail #endif //! Helper function to find plugins in a given list of search paths. //! //! See \ref FindPluginsArgs for argument documentation. //! //! When finding plugins, the following assumptions are made: //! //! * The file's extension is ignored. //! * On Linux, the "lib" prefix is ignored. //! * Tokens such as ${MY_ENV_VAR} in a search path is replaced with the corresponding env var. //! //! \param inArgs The arguments to use. //! \returns `true` if the filesystem was searched; `false` otherwise (i.e. bad args). inline bool findPlugins(const FindPluginsArgs& inArgs) noexcept { filesystem::FindFilesArgs args{}; args.searchPaths = inArgs.searchPaths; args.searchPathsCount = uint32_t(inArgs.searchPathCount); PluginLoadingDesc defaultPluginDesc = PluginLoadingDesc::getDefault(); if (!args.searchPaths || (0 == args.searchPathsCount)) { // If search path count it not specified, fall back to the default desc search paths args.searchPaths = defaultPluginDesc.searchPaths; args.searchPathsCount = uint32_t(defaultPluginDesc.searchPathCount); } args.matchWildcards = inArgs.loadedFileWildcards; args.matchWildcardsCount = uint32_t(inArgs.loadedFileWildcardCount); args.excludeWildcards = inArgs.excludedFileWildcards; args.excludeWildcardsCount = uint32_t(inArgs.excludedFileWildcardCount); #if CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS constexpr const char* const kIgnorePrefixes[] = { "lib" }; constexpr uint32_t kIgnorePrefixesCount = 1; #elif CARB_PLATFORM_WINDOWS constexpr const char* const* kIgnorePrefixes = nullptr; constexpr uint32_t kIgnorePrefixesCount = 0; #else CARB_UNSUPPORTED_PLATFORM(); #endif args.ignorePrefixes = kIgnorePrefixes; args.ignorePrefixesCount = kIgnorePrefixesCount; args.fs = inArgs.fs; // to avoid the expensive filename canonicalization and pattern matching, we do a quick check to make sure the // extension is for a plugin args.onFilterNonCanonical = [](const char* path, void*) { if (detail::caseInsensitiveEndsWith(path, carb::extras::getDefaultLibraryExtension())) { return filesystem::WalkAction::eContinue; // could be a plugin (i.e. correct .ext) } else { return filesystem::WalkAction::eSkip; // not a plug .ext. skip } }; args.onMatched = [](const char* canonical, void* context) { auto inArgs = static_cast<FindPluginsArgs*>(context); bool reloadable = false; if (inArgs->reloadableFileWildcards && inArgs->reloadableFileWildcardCount) { extras::Path path(canonical); auto stemBuffer = path.getStem(); const char* stem = stemBuffer.getStringBuffer(); reloadable = omni::str::matchWildcards( stem, inArgs->reloadableFileWildcards, uint32_t(inArgs->reloadableFileWildcardCount)); #if CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS if (!reloadable) { if (extras::startsWith(stem, "lib")) { stem += 3; reloadable = omni::str::matchWildcards( stem, inArgs->reloadableFileWildcards, uint32_t(inArgs->reloadableFileWildcardCount)); } } #endif } inArgs->onMatched(canonical, reloadable, inArgs->onMatchedContext); }; args.onMatchedContext = const_cast<FindPluginsArgs*>(&inArgs); args.onExcluded = inArgs.onExcluded; args.onExcludedContext = inArgs.onExcludedContext; if (!args.onExcluded) { args.onExcluded = [](const char* canonical, void*) { CARB_LOG_VERBOSE("Excluding potential plugin file: %s.", canonical); }; } args.onSkipped = inArgs.onSkipped; args.onSkippedContext = inArgs.onSkippedContext; args.onSearchPath = inArgs.onSearchPath; args.onSearchPathContext = inArgs.onSearchPathContext; if (!args.onSearchPath) { args.onSearchPath = [](const char* path, void* context) { auto inArgs = static_cast<FindPluginsArgs*>(context); CARB_LOG_VERBOSE("Searching plugins %sin folder: %s", (inArgs->searchRecursive ? "recursively " : ""), path); }; args.onSearchPathContext = const_cast<FindPluginsArgs*>(&inArgs); } args.flags = (filesystem::kFindFilesFlagMatchStem | filesystem::kFindFilesFlagReplaceEnvironmentVariables); if (inArgs.searchRecursive) { args.flags |= filesystem::kFindFilesFlagRecursive; } return filesystem::findFiles(args); } } // namespace carb
9,173
C
35.11811
121
0.678622
omniverse-code/kit/include/carb/Format.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. // #pragma once #include <cstring> #include <sstream> namespace carb { namespace fmt { namespace detail { inline void format(std::ostringstream& stream, const char* str) { stream << str; } template <class Arg, class... Args> inline void format(std::ostringstream& stream, const char* str, Arg&& arg, Args&&... args) { const char* p = strstr(str, "{}"); if (p) { stream.write(str, p - str); stream << arg; format(stream, p + 2, std::forward<Args>(args)...); } else { stream << str; } } } // namespace detail /** * Formats a string similar to the {fmt} library (https://fmt.dev), but header-only and without requiring an external * library be included * * NOTE: This is not intended to be a full replacement for {fmt}. Only '{}' is supported (i.e. no non-positional * support). And any type can be formatted, but must be streamable (i.e. have an appropriate operator<<) * * Example: format("{}, {} and {}: {}", "Peter", "Paul", "Mary", 42) would produce the string "Peter, Paul and Mary: 42" * @param str The format string. Use '{}' to indicate where the next parameter would be inserted. * @returns The formatted string */ template <class... Args> inline std::string format(const char* str, Args&&... args) { std::ostringstream stream; detail::format(stream, str, std::forward<Args>(args)...); return stream.str(); } } // namespace fmt } // namespace carb
1,887
C
26.764705
120
0.674616
omniverse-code/kit/include/carb/Interface.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 Macros for defining a Carbonite interface. #pragma once #include "Version.h" #include <type_traits> namespace carb { //! Defines a descriptor for the plugin interface. //! //! In order to get this information from an interface, call the interface's `getInterfaceDesc` function. struct InterfaceDesc { const char* name = nullptr; //!< Name of the interface. Version version = { 0, 0 }; //!< Version of the interface. }; CARB_ASSERT_INTEROP_SAFE(InterfaceDesc); } // namespace carb //! Macro to declare a `struct` as a Carbonite interface. //! //! This macro must be used in a public section of the interface `struct`. It is recommended to have it be the first //! public "member" of the struct. //! //! @param name The name of the interface. //! //! @param major The major <a href="https://semver.org/">Semantic Version</a> of the interface. It is recommended to //! start at `1`. //! @param minor The minor <a href="https://semver.org/">Semantic Version</a> of the interface. It is recommended to //! start at `0`. //! //! For plugins that support multiple interface versions through @ref CARB_PLUGIN_IMPL_EX, the @p major and @p minor //! version represent the highest version available. This version will also be requested immediately after plugin //! registration and **must** succeed. //! //! When using, a trailing semicolon is optional. //! //! @note A @p major of `0` has special significance to <a href="https://semver.org/">Semantic Versioning</a>: every //! iteration of @p minor is also considered a breaking change. However, @ref carb::isVersionSemanticallyCompatible will //! warn on different \a minor versions if the \a major version is `0`, but still report `true`. //! //! See @carb_framework_overview and @carb_interfaces for more information on creating Carbonite plugins. //! @code{.cpp} //! // Effective implementation //! #define CARB_PLUGIN_INTERFACE(name, major, minor) //! static constexpr carb::InterfaceDesc getInterfaceDesc() //! { //! return carb::InterfaceDesc{ name, { major, minor } }; //! } //! @endcode #define CARB_PLUGIN_INTERFACE(name, major, minor) \ /** \ * Returns information about this interface. Auto-generated by @ref CARB_PLUGIN_INTERFACE(). \ * @returns The @ref carb::InterfaceDesc struct with information about this interface. \ */ \ static constexpr carb::InterfaceDesc getInterfaceDesc() \ { \ return carb::InterfaceDesc{ name, { major, minor } }; \ } // note that this needs to be included last to avoid a circular include dependency in // 'carb/Defines.h'. A lot of source files and tests depend on 'carb/Interface.h' // also pulling in 'carb/Defines.h'. Since nothing here strictly requires 'Defines.h', // we'll just defer it's include until everything else useful in here has been defined. #include "Defines.h"
3,877
C
48.717948
120
0.608718
omniverse-code/kit/include/carb/PluginCoreUtils.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 Utilities to ease the creation of Carbonite plugins. Most code will include carb/PluginUtils.h //! instead of this file. #pragma once #include "Defines.h" #include "../omni/core/Api.h" // OMNI_API #include "../omni/core/Omni.h" #include <cstddef> #include <cstdint> //! See @ref carb::GetFrameworkVersionFn. Required by plugins. const char* const kCarbGetFrameworkVersionFnName = "carbGetFrameworkVersion"; //! See @ref carb::OnPluginRegisterFn. Required by plugins. const char* const kCarbOnPluginRegisterFnName = "carbOnPluginRegister"; //! See @ref carb::OnPluginRegisterExFn. Required by plugins. const char* const kCarbOnPluginRegisterExFnName = "carbOnPluginRegisterEx"; //! See @ref carb::OnPluginRegisterEx2Fn. Required by plugins. const char* const kCarbOnPluginRegisterEx2FnName = "carbOnPluginRegisterEx2"; //! See @ref carb::OnPluginPreStartupFn. Optional for plugins. const char* const kCarbOnPluginPreStartupFnName = "carbOnPluginPreStartup"; //! See @ref carb::OnPluginStartupFn. Optional for plugins. const char* const kCarbOnPluginStartupFnName = "carbOnPluginStartup"; //! See @ref carb::OnPluginStartupExFn. Optional for plugins. const char* const kCarbOnPluginStartupExFnName = "carbOnPluginStartupEx"; //! See @ref carb::OnPluginShutdownFn. Optional for plugins. const char* const kCarbOnPluginShutdownFnName = "carbOnPluginShutdown"; //! See @ref carb::OnPluginQuickShutdownFn. Optional for plugins. const char* const kCarbOnPluginQuickShutdownFnName = "carbOnPluginQuickShutdown"; //! See @ref carb::OnPluginPostShutdownFn. Optional for plugins. const char* const kCarbOnPluginPostShutdownFnName = "carbOnPluginPostShutdown"; //! See @ref carb::GetPluginDepsFn. Optional for plugins. const char* const kCarbGetPluginDepsFnName = "carbGetPluginDeps"; //! See @ref carb::OnReloadDependencyFn. Optional for plugins. const char* const kCarbOnReloadDependencyFnName = "carbOnReloadDependency"; namespace omni { namespace core { OMNI_DECLARE_INTERFACE(ITypeFactory) // forward declaration } namespace log { class ILog; // forward declaration } } // namespace omni /// @cond DEV /** * Helper macro to declare globals needed by Carbonite plugins. * * Do not directly use this macro. Rather use @ref CARB_PLUGIN_IMPL() which will call it for you. */ #define OMNI_MODULE_GLOBALS_FOR_PLUGIN() \ namespace \ { \ ::omni::core::ITypeFactory* s_omniTypeFactory = nullptr; \ ::omni::log::ILog* s_omniLog = nullptr; \ ::omni::structuredlog::IStructuredLog* s_omniStructuredLog = nullptr; \ } \ OMNI_MODULE_DEFINE_LOCATION_FUNCTIONS() \ OMNI_MODULE_GLOBALS_BUILD_CONFIG_SYMBOLS(); \ OMNI_API void* omniGetBuiltInWithoutAcquire(::OmniBuiltIn type) \ { \ switch (type) \ { \ case ::OmniBuiltIn::eITypeFactory: \ return s_omniTypeFactory; \ case ::OmniBuiltIn::eILog: \ return s_omniLog; \ case ::OmniBuiltIn::eIStructuredLog: \ return s_omniStructuredLog; \ default: \ return nullptr; \ } \ } /** * Populates the Omniverse interfaces portion of @ref carb::PluginFrameworkDesc. * * Do not directly use this macro. This macro is called by default by the @ref CARB_PLUGIN_IMPL_WITH_INIT() provided * version of @ref carb::OnPluginRegisterFn. */ #define OMNI_MODULE_SET_GLOBALS_FOR_PLUGIN(in_) \ s_omniTypeFactory = (in_)->omniTypeFactory; \ s_omniLog = (in_)->omniLog; \ s_omniStructuredLog = (in_)->omniStructuredLog; #ifndef DOXYGEN_SHOULD_SKIP_THIS // FOR_EACH macro implementation, use as FOR_EACH(OTHER_MACRO, p0, p1, p2,) # define EXPAND(x) x # define FE_1(WHAT, X) EXPAND(WHAT(X)) # define FE_2(WHAT, X, ...) EXPAND(WHAT(X) FE_1(WHAT, __VA_ARGS__)) # define FE_3(WHAT, X, ...) EXPAND(WHAT(X) FE_2(WHAT, __VA_ARGS__)) # define FE_4(WHAT, X, ...) EXPAND(WHAT(X) FE_3(WHAT, __VA_ARGS__)) # define FE_5(WHAT, X, ...) EXPAND(WHAT(X) FE_4(WHAT, __VA_ARGS__)) # define FE_6(WHAT, X, ...) EXPAND(WHAT(X) FE_5(WHAT, __VA_ARGS__)) # define FE_7(WHAT, X, ...) EXPAND(WHAT(X) FE_6(WHAT, __VA_ARGS__)) # define FE_8(WHAT, X, ...) EXPAND(WHAT(X) FE_7(WHAT, __VA_ARGS__)) # define FE_9(WHAT, X, ...) EXPAND(WHAT(X) FE_8(WHAT, __VA_ARGS__)) # define FE_10(WHAT, X, ...) EXPAND(WHAT(X) FE_9(WHAT, __VA_ARGS__)) # define FE_11(WHAT, X, ...) EXPAND(WHAT(X) FE_10(WHAT, __VA_ARGS__)) # define FE_12(WHAT, X, ...) EXPAND(WHAT(X) FE_11(WHAT, __VA_ARGS__)) # define FE_13(WHAT, X, ...) EXPAND(WHAT(X) FE_12(WHAT, __VA_ARGS__)) # define FE_14(WHAT, X, ...) EXPAND(WHAT(X) FE_13(WHAT, __VA_ARGS__)) # define FE_15(WHAT, X, ...) EXPAND(WHAT(X) FE_14(WHAT, __VA_ARGS__)) # define FE_16(WHAT, X, ...) EXPAND(WHAT(X) FE_15(WHAT, __VA_ARGS__)) # define FE_17(WHAT, X, ...) EXPAND(WHAT(X) FE_16(WHAT, __VA_ARGS__)) # define FE_18(WHAT, X, ...) EXPAND(WHAT(X) FE_17(WHAT, __VA_ARGS__)) # define FE_19(WHAT, X, ...) EXPAND(WHAT(X) FE_18(WHAT, __VA_ARGS__)) # define FE_20(WHAT, X, ...) EXPAND(WHAT(X) FE_19(WHAT, __VA_ARGS__)) # define FE_21(WHAT, X, ...) EXPAND(WHAT(X) FE_20(WHAT, __VA_ARGS__)) # define FE_22(WHAT, X, ...) EXPAND(WHAT(X) FE_21(WHAT, __VA_ARGS__)) # define FE_23(WHAT, X, ...) EXPAND(WHAT(X) FE_22(WHAT, __VA_ARGS__)) # define FE_24(WHAT, X, ...) EXPAND(WHAT(X) FE_23(WHAT, __VA_ARGS__)) # define FE_25(WHAT, X, ...) EXPAND(WHAT(X) FE_24(WHAT, __VA_ARGS__)) # define FE_26(WHAT, X, ...) EXPAND(WHAT(X) FE_25(WHAT, __VA_ARGS__)) # define FE_27(WHAT, X, ...) EXPAND(WHAT(X) FE_26(WHAT, __VA_ARGS__)) # define FE_28(WHAT, X, ...) EXPAND(WHAT(X) FE_27(WHAT, __VA_ARGS__)) # define FE_29(WHAT, X, ...) EXPAND(WHAT(X) FE_28(WHAT, __VA_ARGS__)) # define FE_30(WHAT, X, ...) EXPAND(WHAT(X) FE_29(WHAT, __VA_ARGS__)) # define FE_31(WHAT, X, ...) EXPAND(WHAT(X) FE_30(WHAT, __VA_ARGS__)) # define FE_32(WHAT, X, ...) EXPAND(WHAT(X) FE_31(WHAT, __VA_ARGS__)) //... repeat as needed # define GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, \ _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, NAME, ...) \ NAME # define FOR_EACH(action, ...) \ EXPAND(GET_MACRO(__VA_ARGS__, FE_32, FE_31, FE_30, FE_29, FE_28, FE_27, FE_26, FE_25, FE_24, FE_23, FE_22, \ FE_21, FE_20, FE_19, FE_18, FE_17, FE_16, FE_15, FE_14, FE_13, FE_12, FE_11, FE_10, FE_9, \ FE_8, FE_7, FE_6, FE_5, FE_4, FE_3, FE_2, FE_1)(action, __VA_ARGS__)) # define DECLARE_FILL_FUNCTION(X) void fillInterface(X& iface); // carbOnPluginRegisterEx2() was added with carbonite version 0.5 without changing the carbonite version number. // Therefore, this exists only to support older carbonite version 0.5 instances that are not aware of // carbOnPluginRegisterEx2. This macro can be safely removed when Framework version 0.5 is no longer supported. static_assert(carb::kFrameworkVersion.major == 0, "Remove CARB_PLUGIN_IMPL_WITH_INIT_0_5"); # define CARB_PLUGIN_IMPL_WITH_INIT_0_5(impl, ...) \ FOR_EACH(DECLARE_FILL_FUNCTION, __VA_ARGS__) \ template <typename T1> \ void fillInterface0_5(carb::PluginRegistryEntry::Interface* interfaces) \ { \ interfaces[0].desc = T1::getInterfaceDesc(); \ static T1 s_pluginInterface{}; \ fillInterface(s_pluginInterface); \ interfaces[0].ptr = &s_pluginInterface; \ interfaces[0].size = sizeof(T1); \ } \ template <typename T1, typename T2, typename... Types> \ void fillInterface0_5(carb::PluginRegistryEntry::Interface* interfaces) \ { \ fillInterface0_5<T1>(interfaces); \ fillInterface0_5<T2, Types...>(interfaces + 1); \ } \ template <typename... Types> \ static void onPluginRegister0_5(carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry* outEntry) \ { \ static carb::PluginRegistryEntry::Interface s_interfaces[sizeof...(Types)] = {}; \ fillInterface0_5<Types...>(s_interfaces); \ outEntry->interfaces = s_interfaces; \ outEntry->interfaceCount = sizeof(s_interfaces) / sizeof(s_interfaces[0]); \ outEntry->implDesc = impl; \ \ g_carbFramework = frameworkDesc->framework; \ g_carbClientName = impl.name; \ OMNI_MODULE_SET_GLOBALS_FOR_PLUGIN(frameworkDesc) \ } \ CARB_EXPORT void carbOnPluginRegisterEx( \ carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry* outEntry) \ { \ onPluginRegister0_5<__VA_ARGS__>(frameworkDesc, outEntry); \ } # define CARB_PLUGIN_IMPL_WITH_INIT_0_5_EX(impl, ...) \ template <typename T1> \ void fillInterface0_5(carb::PluginRegistryEntry::Interface* interfaces) \ { \ interfaces->desc = T1::getInterfaceDesc(); \ static void* s_pluginInterface[(sizeof(T1) / sizeof(void*)) + 1] = {}; \ carb::Version ver = interfaces->desc.version; \ bool b = fillInterface<T1>(&ver, s_pluginInterface); \ CARB_FATAL_UNLESS(b, "Failed to construct interface for type %s", interfaces->desc.name); \ CARB_FATAL_UNLESS( \ ver == interfaces->desc.version, \ "Interface %s constructor requested version %u.%u but got %u.%u (must match exactly as the interface declared itself to be this version)", \ interfaces[0].desc.name, interfaces->desc.version.major, interfaces->desc.version.minor, ver.major, \ ver.minor); \ interfaces->ptr = &s_pluginInterface; \ interfaces->size = sizeof(T1); \ } \ template <typename T1, typename T2, typename... Types> \ void fillInterface0_5(carb::PluginRegistryEntry::Interface* interfaces) \ { \ fillInterface0_5<T1>(interfaces); \ fillInterface0_5<T2, Types...>(interfaces + 1); \ } \ template <typename... Types> \ static void onPluginRegister0_5(carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry* outEntry) \ { \ static carb::PluginRegistryEntry::Interface s_interfaces[sizeof...(Types)]; \ fillInterface0_5<Types...>(s_interfaces); \ outEntry->interfaces = s_interfaces; \ outEntry->interfaceCount = sizeof(s_interfaces) / sizeof(s_interfaces[0]); \ outEntry->implDesc = impl; \ \ g_carbFramework = frameworkDesc->framework; \ g_carbClientName = impl.name; \ OMNI_MODULE_SET_GLOBALS_FOR_PLUGIN(frameworkDesc) \ } \ CARB_EXPORT void carbOnPluginRegisterEx( \ carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry* outEntry) \ { \ onPluginRegister0_5<__VA_ARGS__>(frameworkDesc, outEntry); \ } #endif // DOXYGEN_SHOULD_SKIP_THIS /** * Defines boiler-plate code to declare the plugin's interfaces and registration code. * * Rather than directly calling this macro, consider calling @ref CARB_PLUGIN_IMPL which calls this macro for you. * * This macro does the following: * * - Defines `carbGetFrameworkVersion` and `carbOnPluginRegisterEx2` functions. * * - Sets the @ref g_carbFramework variable so @ref carb::getFramework() works. * * - Sets the plugin client variable: @ref g_carbClientName. The client name is used by @ref carb::Framework to * create a graph of client inter-dependencies. * * - Advertises to @ref carb::Framework the interfaces implemented by this plugin. * * - Enables the usage of ONI (see @oni_overview) in the plugin. * * This macro must be defined in the global namespace. * * @param impl The PluginImplDesc constant to be used as plugin description. * * @param ... One or more interface types to be implemented by the plugin. An interface is a `struct` with * a call to @ref CARB_PLUGIN_INTERFACE() inside it. These interface types are constructed during plugin registration * (prior to the plugin startup) and destructed immediately after plugin shutdown. A global fillInterface() function * must exist and will be called immediately after instantiating the interface type. The interface types need not be * trivially constructed or destructed, but their constructors and destructors MUST NOT use any Carbonite framework * functions. */ #define CARB_PLUGIN_IMPL_WITH_INIT(impl, ...) \ \ /* Forward declare fill functions for every interface */ \ FOR_EACH(DECLARE_FILL_FUNCTION, __VA_ARGS__) \ \ template <typename T1> \ void populate(carb::PluginRegistryEntry2::Interface2* iface) \ { \ iface->sizeofThisStruct = sizeof(carb::PluginRegistryEntry2::Interface2); \ iface->desc = T1::getInterfaceDesc(); \ iface->size = sizeof(T1); \ iface->align = alignof(T1); \ iface->Constructor = [](void* p) { fillInterface(*new (p) T1); }; \ iface->Destructor = [](void* p) { static_cast<T1*>(p)->~T1(); }; \ } \ \ template <typename T1, typename T2, typename... Types> \ void populate(carb::PluginRegistryEntry2::Interface2* interfaces) \ { \ populate<T1>(interfaces); \ populate<T2, Types...>(interfaces + 1); \ } \ \ template <typename... Types> \ static void registerPlugin(carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry2* outEntry) \ { \ outEntry->sizeofThisStruct = sizeof(carb::PluginRegistryEntry2); \ static carb::PluginRegistryEntry2::Interface2 s_interfaces[sizeof...(Types)] = {}; \ populate<Types...>(s_interfaces); \ outEntry->interfaces = s_interfaces; \ outEntry->interfaceCount = CARB_COUNTOF(s_interfaces); \ outEntry->implDesc = impl; \ \ g_carbFramework = frameworkDesc->framework; \ g_carbClientName = impl.name; \ OMNI_MODULE_SET_GLOBALS_FOR_PLUGIN(frameworkDesc) \ } \ \ CARB_EXPORT void carbOnPluginRegisterEx2( \ carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry2* outEntry) \ { \ registerPlugin<__VA_ARGS__>(frameworkDesc, outEntry); \ } \ \ CARB_EXPORT carb::Version carbGetFrameworkVersion() \ { \ return carb::kFrameworkVersion; \ } #define CARB_PLUGIN_IMPL_WITH_INIT_EX(impl, ...) \ /* forward declare fillInterface function */ \ template <class T1> \ bool fillInterface(carb::Version*, void*); \ template <class T1> \ void destroyInterface(carb::Version, void*) \ { \ } \ \ template <typename T1> \ void populate(carb::PluginRegistryEntry2::Interface2* iface) \ { \ iface->sizeofThisStruct = sizeof(carb::PluginRegistryEntry2::Interface2); \ iface->desc = T1::getInterfaceDesc(); \ iface->size = sizeof(T1); \ iface->align = alignof(T1); \ iface->Constructor = nullptr; \ iface->Destructor = nullptr; \ iface->VersionedConstructor = &fillInterface<T1>; \ iface->VersionedDestructor = &destroyInterface<T1>; \ } \ \ template <typename T1, typename T2, typename... Types> \ void populate(carb::PluginRegistryEntry2::Interface2* interfaces) \ { \ populate<T1>(interfaces); \ populate<T2, Types...>(interfaces + 1); \ } \ \ template <typename... Types> \ static void registerPlugin(carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry2* outEntry) \ { \ outEntry->sizeofThisStruct = sizeof(carb::PluginRegistryEntry2); \ static carb::PluginRegistryEntry2::Interface2 s_interfaces[sizeof...(Types)] = {}; \ populate<Types...>(s_interfaces); \ outEntry->interfaces = s_interfaces; \ outEntry->interfaceCount = CARB_COUNTOF(s_interfaces); \ outEntry->implDesc = impl; \ \ g_carbFramework = frameworkDesc->framework; \ g_carbClientName = impl.name; \ OMNI_MODULE_SET_GLOBALS_FOR_PLUGIN(frameworkDesc) \ } \ \ CARB_EXPORT void carbOnPluginRegisterEx2( \ carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry2* outEntry) \ { \ registerPlugin<__VA_ARGS__>(frameworkDesc, outEntry); \ } \ \ CARB_EXPORT carb::Version carbGetFrameworkVersion() \ { \ return carb::kFrameworkVersion; \ } /// @endcond #if CARB_COMPILER_MSC # pragma section(".state", read, write) #endif /** * Macro to mark static and global variables to keep them when plugin is hot-reloaded. * * @rst .. deprecated:: 132.0 Hot reloading support has been removed. No replacement will be provided. Note that any symbol this decorator is used on will generate a deprecation warning. @endrst */ #define CARB_STATE \ CARB_DEPRECATED("hot reload has been removed") CARB_DECLSPEC(allocate(".state")) CARB_ATTRIBUTE(section(".state")) // The below is for documentation only #ifdef DOXYGEN_BUILD /** * An automatically-generated function exported by Carbonite plugins used to check the plugin's Framework compatibility. * * \note This function is automatically generated for each plugin by the \ref CARB_PLUGIN_IMPL macro. It is called by * the Framework when registering a plugin. This serves as documentation of this function only. * * The type of this function is \ref carb::GetFrameworkVersionFn and named \ref kCarbGetFrameworkVersionFnName. * * @returns The Framework version that the plugin was built against. The Framework uses this result to check if the * plugin is <a href="https://semver.org/">semantically compatible</a> with the Framework in order to continue loading. */ CARB_EXPORT carb::Version carbGetFrameworkVersion(); /** * An automatically-generated function exported by some Carbonite plugins (now deprecated). * * \note This function is automatically generated in some older plugins by the \ref CARB_PLUGIN_IMPL macro. It may be * called by the Framework when registering a plugin. This serves as documentation of this function only. * * \warning This function has been superseded by \ref carbOnPluginRegisterEx and \ref carbOnPluginRegisterEx2 in * Framework version 0.5. The Framework will look for and call the first available function from the following list: * \ref carbOnPluginRegisterEx2, \ref carbOnPluginRegisterEx, `carbOnPluginRegister` (this function). * * The type of this function is \ref carb::OnPluginRegisterFn and named \ref kCarbOnPluginRegisterFnName. * * Only plugins built with Framework versions prior to 0.5 export this function. * * @param framework The Framework will pass this function a pointer to itself when calling. * @param outEntry The plugin will populate this structure to inform the Framework about itself. */ CARB_EXPORT void carbOnPluginRegister(carb::Framework* framework, carb::PluginRegistryEntry* outEntry); /** * An automatically-generated function exported by some Carbonite plugins (now deprecated). * * \note This function is automatically generated in some older plugins by the \ref CARB_PLUGIN_IMPL macro. It may be * called by the Framework when registering a plugin. This serves as documentation of this function only. * * \warning This function has been superseded by \ref carbOnPluginRegisterEx2 in Framework version 0.5. The Framework * will look for and call the first available function from the following list: * \ref carbOnPluginRegisterEx2, `carbOnPluginRegisterEx` (this function), \ref carbOnPluginRegister. * * The type of this function is \ref carb::OnPluginRegisterExFn and named \ref kCarbOnPluginRegisterExFnName. * * This function is generated for all plugins built against Framework 0.5. Since \ref carbOnPluginRegisterEx2 was added * to Framework version 0.5 without changing the Framework version (in Carbonite release v111.17), this function exists * and is exported in all plugins compatible with Framework version 0.5 to allow the plugins to load properly in earlier * editions of Framework version 0.5. * * @param frameworkDesc A description of the Framework provided by the Framework when it calls this function. * @param outEntry The plugin will populate this structure to inform the Framework about itself. */ CARB_EXPORT void carbOnPluginRegisterEx(carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry* outEntry); /** * An automatically-generated function exported by some Carbonite plugins. * * \note This function is automatically generated in plugins by the \ref CARB_PLUGIN_IMPL macro. It is called by the * Framework when registering a plugin. This serves as documentation of this function only. * * \note Older versions of this function exist in older plugins. This is the most current registration function as of * Framework version 0.5 and intended to be "future proof" for future Framework versions. The Framework will look for * and call the first available function from the following list: * `carbOnPluginRegisterEx2` (this function), \ref carbOnPluginRegisterEx, \ref carbOnPluginRegister. * * The type of this function is \ref carb::OnPluginRegisterEx2Fn and named \ref kCarbOnPluginRegisterEx2FnName. * * This function is generated for all plugins built against Carbonite v111.17 and later. Prior Carbonite releases with * Framework version 0.5 will use the \ref carbOnPluginRegisterEx function, whereas Carbonite releases v111.17 and later * will use this function to register a plugin. * * @param frameworkDesc A description of the Framework provided by the Framework when it calls this function. * @param outEntry The plugin will populate this structure to inform the Framework about itself. */ CARB_EXPORT void carbOnPluginRegisterEx2(carb::PluginFrameworkDesc* frameworkDesc, carb::PluginRegistryEntry2* outEntry); /** * An automatically-generated function exported by Carbonite plugins. * * \note This function is automatically generated in plugins by the \ref CARB_DEFAULT_INITIALIZERS macro via the * \ref CARB_PLUGIN_IMPL macro. It is called by the Framework when starting the plugin (the first time an interface is * acquired from the plugin) prior to calling \ref carbOnPluginStartup. This serves as documentation of the generated * function only. * * This function starts up various Framework-provided subsystems for the plugin: logging, profiling, asserts, * localization and structured logging. The following functions are called in the plugin context: * - \ref carb::logging::registerLoggingForClient * - \ref carb::profiler::registerProfilerForClient * - \ref carb::assert::registerAssertForClient * - \ref carb::l10n::registerLocalizationForClient * - \ref omni::structuredlog::addModulesSchemas() * * The type of this function is \ref carb::OnPluginPreStartupFn and named \ref kCarbOnPluginPreStartupFnName. */ CARB_EXPORT void carbOnPluginPreStartup(); /** * An optional function that a plugin author can export from their plugin to start their plugin. * * The Framework will call this function after \ref carbOnPluginPreStartup when starting the plugin (the first time an * interface is acquired from the plugin). This serves as a guide for plugin authors. * * Providing this function is completely optional. * * Generally, if this function is provided, a \ref carbOnPluginShutdown should also be provided to cleanup any work * done by this function. * * This function is superseded by \ref carbOnPluginStartupEx, which allows startup to fail gracefully. If that function * does not exist, this function is called if it exists. * * Any interfaces declared as a dependency in \ref CARB_PLUGIN_IMPL_DEPS will be available to this plugin by the time * this function is called. * * This function is allowed to acquire interfaces and interact with the Framework normally (e.g. add hooks, etc.). * However, keep in mind that this function is called by the Framework when the Application or another plugin is trying * to acquire an interface from this plugin; actions that result in recursively starting the plugin will result in * failure to acquire the interface. However, your plugin is allowed to acquire other interfaces from itself in this * function. * * Once this function returns, the Framework considers your plugin as initialized. * * Typical things this function might do: * - Allocate memory and data structures for your plugin * - Load settings from \ref carb::settings::ISettings (if available) * - Start up libraries and subsystems * * The type of this function is \ref carb::OnPluginStartupFn and named \ref kCarbOnPluginStartupFnName. * * @note The thread context must be the same when this function returns as when the function is called (i.e. if called * within a fiber context, the same thread must return). However, if carb.tasking.plugin is used, this need not be the * case as Carbonite can handle that case properly. */ CARB_EXPORT void carbOnPluginStartup(); /** * An optional function that a plugin author can export from their plugin to start their plugin. * * The Framework will call this function after \ref carbOnPluginPreStartup when starting the plugin (the first time an * interface is acquired from the plugin). This serves as a guide for plugin authors. * * Providing this function is completely optional. * * Generally, if this function is provided, a \ref carbOnPluginShutdown should also be provided to cleanup any work * done by this function. * * This function supersedes \ref carbOnPluginStartup. The main difference is that this function allows the plugin to * indicate if startup fails (such as if a required subsystem fails to start) and allow the Framework to fail acquiring * an interface gracefully. If this function does not exist, \ref carbOnPluginStartup is called if it exists. * * Any interfaces declared as a dependency in \ref CARB_PLUGIN_IMPL_DEPS will be available to this plugin by the time * this function is called. * * This function is allowed to acquire interfaces and interact with the Framework normally (e.g. add hooks, etc.). * However, keep in mind that this function is called by the Framework when the Application or another plugin is trying * to acquire an interface from this plugin; actions that result in recursively starting the plugin will result in * failure to acquire the interface. However, your plugin is allowed to acquire other interfaces from itself in this * function. * * Once this function returns successfully, the Framework considers your plugin as initialized. If this function reports * failure, the plugin will be unloaded but remain registered. Attempting to acquire an interface from this plugin in * the future will reload the plugin and attempt to call this function again. * * Typical things this function might do: * - Allocate memory and data structures for your plugin * - Load settings from \ref carb::settings::ISettings (if available) * - Start up libraries and subsystems * * The type of this function is \ref carb::OnPluginStartupExFn and named \ref kCarbOnPluginStartupExFnName. * @returns `true` if the plugin started successfully; `false` otherwise. * * @note The thread context must be the same when this function returns as when the function is called (i.e. if called * within a fiber context, the same thread must return). However, if carb.tasking.plugin is used, this need not be the * case as Carbonite can handle that case properly. */ CARB_EXPORT bool carbOnPluginStartupEx(); /** * An optional function that a plugin author can export from their plugin to shutdown their plugin. * * The Framework will call this function when directed to unload a plugin, immediately before calling * \ref carbOnPluginPostShutdown and before requesting that the OS release the plugin library. This function will also * be called if \ref carb::Framework::unloadAllPlugins is called, but *not* if * \ref carb::quickReleaseFrameworkAndTerminate is called. This serves as a guide for plugin authors. * * This function is mutually exclusive with \ref carbOnPluginQuickShutdown; either this function or that one is called * depending on the shutdown type. * * Providing this function is completely optional. * * Generally, this function should be provided if \ref carbOnPluginStartup or \ref carbOnPluginStartupEx is provided in * order to clean up the work done in the startup function. * * Any interfaces declared as a dependency in \ref CARB_PLUGIN_IMPL_DEPS will still be available to this plugin when * this function is called. * * \warning This function should not attempt to acquire any interfaces that the plugin has not previously acquired. * In other words, only use interfaces in this function that the plugin has already acquired. * * During shutdown, if a circular reference exists between interfaces acquired by this plugin and those interfaces * (possibly indirectly) acquiring interfaces from this plugin, then it is possible that interfaces acquired by this * plugin may already be shut down. Using \ref carb::getCachedInterface or \ref carb::Framework::tryAcquireInterface may * result in an error log being issued. In this case, \ref carb::Framework::tryAcquireExistingInterface will only * acquire the interface if the plugin providing it is still started. * * Once this function returns successfully, the Framework considers your plugin as shut down and will typically proceed * to unload the library. * * Typical things this function might do: * - Deallocate memory and data structures for your plugin * - Report on leaked objects * - Shut down libraries and subsystems * * The type of this function is \ref carb::OnPluginShutdownFn and named \ref kCarbOnPluginShutdownFnName. * * @note The thread context must be the same when this function returns as when the function is called (i.e. if called * within a fiber context, the same thread must return). This function *does not* allow context switches even when * used with carb.tasking.plugin. */ CARB_EXPORT void carbOnPluginShutdown(); /** * An optional function that a plugin author can export from their plugin to quick-shutdown their plugin. * * The Framework will call this function for each plugin only when \ref carb::quickReleaseFrameworkAndTerminate is * called, in the unload order determined by the Framework. This serves as a guide for plugin authors. * * This function is mutually exclusive with \ref carbOnPluginShutdown; either this function or that one is called * depending on the shutdown type. * * Providing this function is completely optional. * * Since \ref carb::quickReleaseFrameworkAndTerminate will terminate the process without running static destructors or * closing files/connections/etc., this function should be provided to do the bare minimum of work as quickly as * possible to ensure data is written out and stable. * * Any interfaces declared as a dependency in \ref CARB_PLUGIN_IMPL_DEPS will still be available to this plugin when * this function is called. * * While this function can acquire new interfaces (unlike \ref carbOnPluginShutdown), it is generally undesired to do * so as that can be time-consuming and antithetical to quick shutdown. * * Typical things this function might do: * - Close network connections * - Commit database transactions * - Flush and close files open for write * * The type of this function is \ref carb::OnPluginQuickShutdownFn and named \ref kCarbOnPluginQuickShutdownFnName. */ CARB_EXPORT void carbOnPluginQuickShutdown(); /** * An automatically-generated function exported by Carbonite plugins. * * \note This function is automatically generated in plugins by the \ref CARB_DEFAULT_INITIALIZERS macro via the * \ref CARB_PLUGIN_IMPL macro. It is called by the Framework when shutting down the plugin immediately after calling * \ref carbOnPluginShutdown. This serves as documentation of the generated function only. * * This function shuts down various Framework-provided subsystems for the plugin: logging, profiling, asserts, and * localization. The following functions are called in the plugin context: * - \ref carb::assert::deregisterAssertForClient * - \ref carb::profiler::deregisterProfilerForClient * - \ref carb::logging::deregisterLoggingForClient * - \ref carb::l10n::deregisterLocalizationForClient * * The type of this function is \ref carb::OnPluginPostShutdownFn and named \ref kCarbOnPluginPostShutdownFnName. */ CARB_EXPORT void carbOnPluginPostShutdown(); /** * An automatically-generated function exported by some Carbonite plugins. * * \note This function is automatically generated in plugins by the \ref CARB_PLUGIN_IMPL_DEPS or * \ref CARB_PLUGIN_IMPL_NO_DEPS macros. It is called by the Framework when registering a plugin in order to determine * dependencies for the plugin. This serves as documentation of the generated function only. * * If neither of the above macros are used, this function is not generated for the plugin. The Framework considers this * function optional. * * The type of this function is \ref carb::GetPluginDepsFn and named \ref kCarbGetPluginDepsFnName. * * @param deps Assigned to static memory inside the plugin that is the array of interfaces the plugin is dependent on. * May be `nullptr` if there are no dependencies (in this case \p count must be `0`). * @param count Assigned to the number of items in the array of interfaces the plugin is dependent on. */ CARB_EXPORT void carbGetPluginDeps(struct carb::InterfaceDesc** deps, size_t* count); /** * An optional function that a plugin author can export from their plugin to receive dependency reload notifications. * * When \ref carb::Framework::tryReloadPlugins is called, if a plugin is reloaded, any plugins which have acquired * interfaces from the reloading plugin will receive notifications before and after the plugin is reloaded via this * function. This serves as a guide for plugin authors. * * Providing this function is completely optional. * * Typical things this function might do (\p reloadState == `eBefore`): * - Release objects created from the interface * - Clear cached pointers to the interface * * Typical things this function might do (\p reloadState == `eAfter`): * - Update pointers to the new interface * - Reinstate objects * * The type of this function is \ref carb::OnReloadDependencyFn and named \ref kCarbOnReloadDependencyFnName. * * @param reloadState the callback phase * @param pluginInterface a pointer to the interface * @param desc a descriptor for the plugin */ CARB_EXPORT void carbOnReloadDependency(carb::PluginReloadState reloadState, void* pluginInterface, carb::PluginImplDesc desc); //! A dummy type representing a Carbonite Interface for documentation purposes. struct InterfaceType { CARB_PLUGIN_INTERFACE("carb::InterfaceType", 1, 0); }; /** * A required function that a plugin author must provide to construct an interface. * * @note This version of the function is required when using \ref CARB_PLUGIN_IMPL. When using \ref CARB_PLUGIN_IMPL_EX, * \ref fillInterface(carb::Version*, void*) is used instead. * * This function is called by the framework when the plugin is loaded, after calling \ref carbOnPluginRegisterEx2. The * plugin will fail to link if this function is not provided for all of the interfaces specified in the use of the * \ref CARB_PLUGIN_IMPL macro. * * @code{.cpp} * // Example * void fillInterface(carb::tasking::IFiberEvents& iface) * { * using namespace carb::fibereventtest; * iface = * { * notifyFiberStart, * notifyFiberStop, * }; * } * @endcode * * @param iface This must be a reference to an interface struct exported by your plugin. The members of this struct must * be set before returning. The underlying memory for `iface` is allocated and owned by the plugin and previously * constructed with placement new. This type will be destructed by calling the destructor explicitly immediately * before the plugin is unloaded. */ void fillInterface(InterfaceType& iface); /** * A required function that a plugin author must provide to construct a requested version of an interface. * * @note This version of the function is required when using \ref CARB_PLUGIN_IMPL_EX. When using \ref CARB_PLUGIN_IMPL, * \ref fillInterface(InterfaceType&) is used instead. * * This function can be called at any time after \ref carbOnPluginRegisterEx2 is called by the framework when the plugin * is loaded. Generally this is called immediately for all interfaces for the version specified in their * \ref CARB_PLUGIN_INTERFACE declaration, and at later points when a different interface version is requested. The * plugin will fail to link if this function is not provided for all of the interfaces specified in the use of the * \ref CARB_PLUGIN_IMPL_EX macro. * * @warning This function **must** succeed (return `true`) with \p v unchanged when called with \p v equal to the * version specified in \ref CARB_PLUGIN_INTERFACE, otherwise the plugin will fail to register or load. * * @warning If the type `T` that you're explicitly specializing is a complex type, make sure to provide a * \ref destroyInterface function to destruct the interface. * * @code{.cpp} * // Example * template <> * bool fillInterface<carb::stats::IStats>(carb::Version* v, void* iface) * { * using namespace carb::stats; * switch (v->major) * { * case IStats::getInterfaceDesc().version.major: * *v = IStats::getInterfaceDesc().version; * *static_cast<IStats*>(iface) = { addStat, removeStat, addValue, getValue, getCount }; * return true; * * default: * return false; * } * } * @endcode * * @tparam T The interface type handled by this function. The generic class template for any type `T` is declared but * not implemented by the \ref CARB_PLUGIN_IMPL_EX macro. This allows explicit specialization for the plugin author to * provide the function for their types. For instance, if you are providing the function for `carb::IObject`, your * function would be `template <> bool fillInterface<carb::IObject>(carb::Version* v, void* iface)`. * @param v When called, the framework provides the version requested. **The function must write the version constructed * into this parameter before returning.** The version constructed does not need to be the same as (or even * semantically compatible with) the version requested, but if a semantically compatible interface to the requested * version is available it should be provided. * @param buf A memory buffer that is guaranteed to be at least as large as `sizeof(T)`, allocated and owned by the * framework. For the initial allocation of an interface, this buffer is zeroed memory. If `T` is a POD type, the * memory can be cast to `T*` and filled in, or placement new can be used to construct your type. If `T` is a more * complex type, provide a \ref destroyInterface function to destruct the type. * @retval true to indicate that the type was constructed and \p v contains the version that was constructed, even if * the version is different from the value that was in \p v when the function was called. * @retval false to indicate that the requested interface version could not be constructed. */ template <class T> bool fillInterface(carb::Version* v, void* buf); /** * An optional function that a plugin author can provide to destroy an interface. * * @note This function is only optionally required when using \ref CARB_PLUGIN_IMPL_EX. When using \ref CARB_PLUGIN_IMPL * the destruction of interfaces is handled through calling the type destructor explicitly. A plugin author need not * provide this function if `T` is a POD type. * * @warning This function is called immediately before the plugin is unloaded, and after \ref carbOnPluginShutdown. It * **must not use** any Carbonite Framework functions. This function is not called in the event of shutdown via * \ref carb::quickReleaseFrameworkAndTerminate. * * @tparam T The interface type handled by this function. The generic class template for any type `T` is declared and * implemented to do nothing by the \ref CARB_PLUGIN_IMPL_EX macro, making this function optional. A plugin author may * provide an explicit specialization in order to handle destruction of the interface type. For `carb::IObject` for * example, this would be: `template <> void destroyInterface<carb::IObject>(carb::Version v, void* buf)`. * @param v The exact version that was 'returned' from \ref fillInterface(carb::Version*, void*). * @param buf The memory buffer that was passed to \ref fillInterface(carb::Version*, void*). */ template <class T> void destroyInterface(Version v, void* buf); #endif
58,453
C
69.51146
156
0.506321
omniverse-code/kit/include/carb/Error.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 Core components for error handling. //! These functions are the foundation for language-specific bindings and should not be used directly. See //! \c omni/Error.h for user-friendly C++ interfaces. #pragma once #include "Defines.h" #include "Interface.h" #include "Types.h" #include "Version.h" #include "cpp/StringView.h" #include "detail/DeferredLoad.h" #include "extras/Errors.h" #include "../omni/core/Result.h" #include "../omni/String.h" #include <cinttypes> namespace carb { //! @copydoc omni::core::Result using omni::core::Result; // bring all the kResult___ values into carb namespace //! Undocumented #define CARB_RESULT_USE_OMNI_RESULT_GEN(symbol_, ...) \ /** @copydoc omni::core::kResult##symbol_ \ */ \ using omni::core::kResult##symbol_; OMNI_RESULT_CODE_LIST(CARB_RESULT_USE_OMNI_RESULT_GEN) //! Opaque type which stores an error. Use \c ErrorApi::getErrorInfo to extract information from it. //! //! \warning //! Error pointers are intended to be owned by a single thread. They can be safely sent between threads, but it is not //! safe to access their contents from multiple threads simultaneously. class Error; //! The low-level API for interacting with the Carbonite error handling system. At the core, this system maintains a //! thread-specific error code and optional error message. //! //! The state of the error objects are maintained through `libcarb.so`/`carb.dll`, the API is accessed through //! \c carbGetErrorApi or \c ErrorApi::instance. Different versions of the API interact with the same global state. A //! call to \c ErrorApi::viewCurrentError with version 1.0 will still be able to read a \c ErrorApi::setError from a //! version 4.0 API (version 4.0 does not exist at this time). struct ErrorApi { CARB_PLUGIN_INTERFACE("carb::ErrorApi", 1, 0); //! Get the singleton instance of this API. //! //! The implementation of this is backed by `libcarb.so`/`carb.dll`, so it is a singleton instance for all loaded //! modules. This function is backed by \c carbGetErrorApi with the \c version argument provided with the value of //! the API version the calling module was built against. static ErrorApi const& instance() noexcept; //! Get a view of this thread's current error, if it is set. //! //! \warning //! The caller does not own the returned error. Any information pointed to by the returned value can be altered or //! cleared by a function calling any of the \c setError calls on this thread. Errors accessed are meant to be //! acted upon immediately. If you wish to preserve information, copy the pieces you wish to save or store the whole //! thing with \c errorClone or \c takeCurrentError. //! //! \param[out] code If not \c nullptr and there is a current error, then \c *code will be set to the error code of //! the current error. Use this to save an extra call to \c getErrorInfo when you are going to act on //! the code value. If there is no current error, then this will be set to \c kResultSuccess. //! //! \returns The current error, if it was set. If there is no error, this returns \c nullptr. Error const*(CARB_ABI* viewCurrentError)(Result* code); //! Get this thread's current error as an owned object, if it is set. After this call, this thread's current error //! will be cleared. //! //! It is the caller's responsibility to clean up the returned value, unless it is \c nullptr. //! //! This function is equivalent to cloning the current error, then resetting it: //! //! \code //! ErrorApi const& api = ErrorApi::instance(); //! Result code{}; // <- optimization only -- see viewCurrentError //! Error* my_err = api.errorClone(api.viewCurrentError(&code)); //! api.setErrorTo(nullptr); //! \endcode //! //! \param[out] code If not \c nullptr and there is a current error, then \c *code will be set to the error code of //! the current error. Use this to save an extra call to \c getErrorInfo when you are going to act on //! the code value. If there is no current error, then this will be set to \c kResultSuccess. //! \returns An owned version of the current error, if it was set. If there is no error, this returns \c nullptr. Error*(CARB_ABI* takeCurrentError)(Result* code); //! \private Result(CARB_ABI* internalSetError)(Result code, char const* message, std::size_t message_size); //! Set this thread's current error to the exact \a error or clear the current error if \a error is \c nullptr. //! Responsibility for this instance is taken by the error system, so you should not call \c errorRelease on it. //! //! \param error The error to set. If this is \c nullptr, this clears the current error. //! //! \retval kResultSuccess when the error is set without issue. //! \retval kResultInvalidOperation if `error == viewCurrentError()`. Restoring a previously-saved error should //! occur through a \c errorClone call, so doing this represents a bug in the code (note that you must have //! used \c const_cast or equivalent to get this to compile). In this case, no action is performed, as the //! current error is already set to the error. Result(CARB_ABI* setErrorTo)(Error* error); //! Set this thread's current error to a pre-allocated error indicating the system is out of memory. It will always //! succeed. void(CARB_ABI* setErrorOom)(); //! Release the \a error which was previously `errorClone`d or `errorCreate`d. //! //! \retval kResultSuccess when the error was released. //! \retval kResultInvalidOperation when `error == viewCurrentError()`. The current error does not need to be //! released. Result(CARB_ABI* errorRelease)(Error* error); //! Create a copy of the \a source error. //! //! \param source The error to clone from. If this is \c nullptr, \c nullptr will be returned without error. //! //! \returns The cloned error. In case of error, \c nullptr is returned and the current error is set with a message //! containing additional details. Error*(CARB_ABI* errorClone)(Error const* source); //! Create an error message with the \a code and pre-formatted \a message string without setting the current error. //! The parameters operate similarly to \c setError, but are more strict. Where \c setError would return a non-OK //! code but still set the current error, this function would return \c nullptr and set the current error to the //! failure. //! //! \param code The code for the created error, which callers can potentially act on. //! \param message The associated message containing additional details about the error. If this is \c nullptr, the //! default message for the \a code is used. //! \param message_size The number of bytes \a message is. //! //! \returns The created error on success. On failure, \c nullptr is returned and the current error is set with the //! reason for the failure. The code values are the same as \c setError. Error*(CARB_ABI* errorCreate)(Result code, const char* message, std::size_t message_size); //! Extract the information associated with the \a error message. The output parameters are views of the properties, //! so they are only valid as long as \a error is valid. //! //! \param error The source to extract data from. This can not be \c nullptr. //! \param[out] code If not \c nullptr, \c *code will be set to the code of this error. //! \param[out] message If not \c nullptr, \c *message will point to the error's detail message. //! \param[out] message_size If not \c nullptr, \c *message_size will be set to the size of the error's detail //! message. Note that \c *message is always null-terminated, but this is useful for optimization when //! copying. //! //! \retval kResultSuccess when the operation was successfully performed. //! \retval kResultInvalidArgument if \a error is \c nullptr. The current error is not set in this case (since the //! \a error can be \c current_error, we do not want to clear it for you. Result(CARB_ABI* getErrorInfo)(Error const* error, Result* code, char const** message, std::size_t* message_size); //! Get the name and default message for the given \a code. The \a name a symbol-like name in snake case like //! `"invalid_argument"`. The \a message is the default message for the \a code as a sentence fragment like //! `"invalid argument"`. //! //! Note that all of the output parameters are allowed to be \c nullptr. In this case, \c kResultSuccess is still //! returned. This can be useful for checking if a given \a code exists at all. //! //! \param code The error code to look up. //! \param[out] name A pointer to a place to put the name of the code. If this is \c nullptr, it will not be set. //! \param[out] name_size A pointer to place to put the size of \a name (in UTF-8 code units). Since \a name is //! null-terminated, this is not strictly needed, but can save you a \c strlen call. If this is //! \c nullptr, it will not be set. //! \param[out] message A pointer to the place to put the default message for this code. If this is \c nullptr, it //! will not be set. //! \param[out] message_size A pointer to the place to put the size of \a message (in UTF-8 code units). Since //! \a message is null-terminated, this is not strictly needed, but can save you a \c strlen call. If //! this is \c nullptr, it will not be set. //! //! \retval kResultSuccess when the operation was successfully performed. //! \retval kResultNotFound when \a code is not in the known list of error codes. The current error is not set. Result(CARB_ABI* getCodeDescription)( Result code, char const** name, std::size_t* name_size, char const** message, std::size_t* message_size); // // Inline helper functions // //! Set this thread's current error to a pre-formatted string. //! //! In the case of any error of a call to this function, the current error will always be set with \a code. However, //! the associated message of the error will be the default for that code. //! //! \param code The code for the created error, which callers can potentially act on. //! \retval kResultSuccess when the error is set without issue. //! \retval kResultInvalidArgument if the \a message is \c nullptr and \a message_size is not 0 or if \a message is //! not \c nullptr and the \a message_size is 0. The current error will still be set to \a code, but the //! message will be the default for that code. //! \retval kResultOutOfMemory if the message is too large to fit in the string buffer, but the call to allocate //! memory failed. The current error is still set to \a code, but the error message is saved as the default //! for that code. //! \retval kResultTooMuchData If the provided message is too large to fit in any error message buffer (the current //! maximum is 64 KiB). The current error will be set with a truncated version of the provided message. Result setError(Result code) const noexcept; //! \copydoc setError(Result) const noexcept //! \param message The associated message containing additional details about the error. If empty, the default //! default message for \p code is used. Result setError(Result code, const std::string& message) const noexcept; //! \copydoc setError(Result) const noexcept //! \param message The associated message containing additional details about the error. If empty, the default //! default message for \p code is used. Result setError(Result code, const omni::string& message) const noexcept; //! \copydoc setError(Result) const noexcept //! \param message The associated message containing additional details about the error. If empty, the default //! default message for \p code is used. Result setError(Result code, cpp::string_view message) const noexcept; //! \copydoc setError(Result) const noexcept //! \param message The associated message containing additional details about the error. If this is \c nullptr, the //! default message for the \a code is used. Result setError(Result code, const char* message) const noexcept; //! \copydoc setError(Result) const noexcept //! \param message The associated message containing additional details about the error. If this is \c nullptr, the //! default message for the \a code is used. //! \param message_size The number of bytes \a message is. If \a message is \c nullptr, this must be \c 0. Result setError(Result code, const char* message, std::size_t message_size) const noexcept; // // Static Inline helper functions // //! Clears any error for the current thread. //! //! This function is syntactic sugar around `setErrorTo(nullptr)`. //! \see setErrorTo static void clearError() noexcept; //! Get a view of this thread's current error. //! //! This function is syntactic sugar around \ref viewCurrentError(). If further information is desired, including //! the current thread's error message, use \ref getErrorInfo(). //! //! \see viewCurrentError() takeCurrentError() getErrorInfo() //! \returns If the calling thread has a current error, then the return value will be the result code of the current //! error. If the calling thread has no current error, the result will be \ref omni::core::kResultSuccess. static Result getError() noexcept; //! Sets the current thread's error code value based on the value of `errno`. //! //! The following table is a mapping of `errno` values to \ref omni::core::Result codes: //! @rst //! .. list-table:: Mapping of errno value to Result codes //! :widths: 50 50 //! :header-rows: 1 //! //! * - errno values //! - :cpp:type:`omni::core::Result` //! * - ``0`` //! - :cpp:member:`omni::core::kResultSuccess` //! * - ``ENOSYS`` //! - :cpp:member:`omni::core::kResultNotImplemented` //! * - ``EACCES`` //! - :cpp:member:`omni::core::kResultAccessDenied` //! * - ``ENOMEM`` //! - :cpp:member:`omni::core::kResultOutOfMemory` //! * - ``EINVAL`` //! - :cpp:member:`omni::core::kResultInvalidArgument` //! * - ``EAGAIN`` //! - :cpp:member:`omni::core::kResultTryAgain` //! * - ``EWOULDBLOCK`` //! - :cpp:member:`omni::core::kResultTryAgain` //! * - ``EINTR`` //! - :cpp:member:`omni::core::kResultInterrupted` //! * - ``EEXIST`` //! - :cpp:member:`omni::core::kResultAlreadyExists` //! * - ``EPERM`` //! - :cpp:member:`omni::core::kResultInvalidOperation` //! * - ``ENOENT`` //! - :cpp:member:`omni::core::kResultNotFound` //! * - Everything else //! - :cpp:member:`omni::core::kResultFail` //! @endrst //! @note The value of `errno` remains consistent across the call to this function. static void setFromErrno(); #if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD) //! (Windows only) Sets the current thread's error code value based on the value of `GetLastError()`. //! //! The following table is a mapping of Windows error values to \ref omni::core::Result codes: //! @rst //! .. list-table:: Mapping of Windows error value to Result code //! :widths: 50 50 //! :header-rows: 1 //! //! * - errno values //! - :cpp:type:`omni::core::Result` //! * - ``ERROR_SUCCESS`` //! - :cpp:member:`omni::core::kResultSuccess` //! * - ``ERROR_PATH_NOT_FOUND`` //! - :cpp:member:`omni::core::kResultNotFound` //! * - ``ERROR_FILE_NOT_FOUND`` //! - :cpp:member:`omni::core::kResultNotFound` //! * - ``ERROR_ACCESS_DENIED`` //! - :cpp:member:`omni::core::kResultAccessDenied` //! * - ``ERROR_ALREADY_EXISTS`` //! - :cpp:member:`omni::core::kResultAlreadyExists` //! * - ``ERROR_FILE_EXISTS`` //! - :cpp:member:`omni::core::kResultAlreadyExists` //! * - ``ERROR_OUTOFMEMORY`` //! - :cpp:member:`omni::core::kResultOutOfMemory` //! * - ``ERROR_NO_MORE_FILES`` //! - :cpp:member:`omni::core::kResultNoMoreItems` //! * - ``ERROR_NO_MORE_ITEMS`` //! - :cpp:member:`omni::core::kResultNoMoreItems` //! * - ``ERROR_NOT_IMPLEMENTED`` //! - :cpp:member:`omni::core::kResultNotImplemented` //! * - ``ERROR_WAIT_TIMEOUT`` //! - :cpp:member:`omni::core::kResultTryAgain` //! * - ``ERROR_ERROR_TIMEOUT`` //! - :cpp:member:`omni::core::kResultTryAgain` //! * - Everything else //! - :cpp:member:`omni::core::kResultFail` //! @endrst //! @note The value of `errno` remains consistent across the call to this function. static void setFromWinApiErrorCode(); #endif }; } // namespace carb //! Get the instance of the error-handling API. //! //! \param version The requested version of the error-handling API to return; this value will be set to the maximum //! supported version. //! \returns On success, this returns a pointer to the error API which is compatible with the provided \a version. #if CARB_REQUIRE_LINKED CARB_DYNAMICLINK carb::ErrorApi const* carbGetErrorApi(carb::Version* version); #else CARB_DYNAMICLINK carb::ErrorApi const* carbGetErrorApi(carb::Version* version) CARB_ATTRIBUTE(weak); #endif namespace carb { namespace detail { //! \fn getCarbErrorApiFunc //! Loads the function which loads the \c ErrorApi. CARB_DETAIL_DEFINE_DEFERRED_LOAD(getCarbErrorApiFunc, carbGetErrorApi, (carb::ErrorApi const* (*)(carb::Version*))); } // namespace detail inline ErrorApi const& ErrorApi::instance() noexcept { static ErrorApi const* const papi = []() -> ErrorApi const* { const Version expected_version = ErrorApi::getInterfaceDesc().version; Version found_version = expected_version; auto p = detail::getCarbErrorApiFunc()(&found_version); CARB_FATAL_UNLESS(p != nullptr, "Failed to load Error API for version this module was compiled against. This module was " "compiled with Error API %" PRIu32 ".%" PRIu32 ", but the maximum-supported version of the " "API in the linked %s is %" PRIu32 ".%" PRIu32, expected_version.major, expected_version.minor, CARB_PLATFORM_WINDOWS ? "carb.dll" : "libcarb.so", found_version.major, found_version.minor); return p; }(); return *papi; } inline void ErrorApi::clearError() noexcept { auto r = instance().setErrorTo(nullptr); CARB_UNUSED(r); CARB_ASSERT(r == omni::core::kResultSuccess); } inline Result ErrorApi::getError() noexcept { Result r; instance().viewCurrentError(&r); return r; } inline Result ErrorApi::setError(Result code) const noexcept { return internalSetError(code, nullptr, 0); } inline Result ErrorApi::setError(Result code, const std::string& message) const noexcept { return internalSetError(code, message.c_str(), message.length()); } inline Result ErrorApi::setError(Result code, const omni::string& message) const noexcept { return internalSetError(code, message.c_str(), message.length()); } inline Result ErrorApi::setError(Result code, cpp::string_view message) const noexcept { return internalSetError(code, message.data(), message.length()); } inline Result ErrorApi::setError(Result code, const char* message) const noexcept { return internalSetError(code, message, message ? std::strlen(message) : 0); } inline Result ErrorApi::setError(Result code, const char* message, std::size_t message_size) const noexcept { CARB_ASSERT(message_size != size_t(-1)); return internalSetError(code, message, message_size); } inline void ErrorApi::setFromErrno() { auto e = errno; switch (e) { case 0: instance().setError(kResultSuccess); break; case ENOSYS: instance().setError(kResultNotImplemented); break; case EACCES: instance().setError(kResultAccessDenied); break; case ENOMEM: instance().setError(kResultOutOfMemory); break; case EINVAL: instance().setError(kResultInvalidArgument); break; case EAGAIN: #if !CARB_POSIX // This is different on Windows but the same for POSIX case EWOULDBLOCK: #endif instance().setError(kResultTryAgain); break; case EINTR: instance().setError(kResultInterrupted); break; case EEXIST: instance().setError(kResultAlreadyExists); break; case EPERM: instance().setError(kResultInvalidOperation); break; case ENOENT: instance().setError(kResultNotFound); break; default: instance().setError(kResultFail, extras::convertErrnoToMessage(e)); break; } errno = e; } #if CARB_PLATFORM_WINDOWS inline void ErrorApi::setFromWinApiErrorCode() { auto e = GetLastError(); switch (e) { case CARBWIN_ERROR_SUCCESS: instance().setError(kResultSuccess); break; case CARBWIN_ERROR_FILE_NOT_FOUND: case CARBWIN_ERROR_PATH_NOT_FOUND: instance().setError(kResultNotFound); break; case CARBWIN_ERROR_ACCESS_DENIED: instance().setError(kResultAccessDenied); break; case CARBWIN_ERROR_ALREADY_EXISTS: case CARBWIN_ERROR_FILE_EXISTS: instance().setError(kResultAlreadyExists); break; case CARBWIN_ERROR_OUTOFMEMORY: instance().setError(kResultOutOfMemory); break; case CARBWIN_ERROR_NO_MORE_FILES: case CARBWIN_ERROR_NO_MORE_ITEMS: instance().setError(kResultNoMoreItems); break; case CARBWIN_ERROR_CALL_NOT_IMPLEMENTED: instance().setError(kResultNotImplemented); break; case CARBWIN_WAIT_TIMEOUT: case CARBWIN_ERROR_TIMEOUT: instance().setError(kResultTryAgain); break; default: instance().setError(kResultFail, extras::convertWinApiErrorCodeToMessage(e)); break; } SetLastError(e); } #endif } // namespace carb
23,763
C
45.233463
120
0.643521
omniverse-code/kit/include/carb/BindingsUtils.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 Utilities for script bindings #pragma once #include "ClientUtils.h" #include "Defines.h" #include "Format.h" #include "Framework.h" #include "InterfaceUtils.h" #include "ObjectUtils.h" #include "assert/AssertUtils.h" #include "logging/Log.h" #include "profiler/Profile.h" #include <functional> #include <sstream> #include <string> #include <unordered_map> namespace carb { /** * Wraps an interface function into a `std::function<>`. * * @tparam InterfaceType The Carbonite interface type (i.e. `logging::ILogging`); can be inferred. * @tparam ReturnType The return type of @p p; can be inferred. * @tparam Args Arguments of @p p; can be inferred. * @param p The interface function to wrap. * @returns A `std::function<ReturnType(InterfaceType&, Args...)>` wrapper around @p p. */ template <typename InterfaceType, typename ReturnType, typename... Args> auto wrapInterfaceFunction(ReturnType (*InterfaceType::*p)(Args...)) -> std::function<ReturnType(InterfaceType&, Args...)> { return [p](InterfaceType& c, Args... args) { return (c.*p)(args...); }; } /** * Wraps an interface function into a `std::function<>`. This version captures the interface so that it does not need to * be passed to every invocation. * * @tparam InterfaceType The Carbonite interface type (i.e. `logging::ILogging`); can be inferred. * @tparam ReturnType The return type of @p p; can be inferred. * @tparam Args Arguments of @p p; can be inferred. * @param c The Carbonite interface to capture as part of the wrapper function. * @param p The interface function to wrap. * @returns A `std::function<ReturnType(Args...)>` wrapper around @p p. */ template <typename InterfaceType, typename ReturnType, typename... Args> auto wrapInterfaceFunction(const InterfaceType* c, ReturnType (*InterfaceType::*p)(Args...)) -> std::function<ReturnType(Args...)> { return [c, p](Args... args) { return (c->*p)(args...); }; } /** * A helper function for \ref Framework::tryAcquireInterface() that attempts to load plugins if not found. * * @tparam InterfaceType The interface to acquire (i.e. `assets::IAssets`). Must be specified and cannot be inferred. * @param pluginName An optional specific plugin to acquire the interface from. If `nullptr`, the default plugin for the * given InterfaceType is used. * @returns A pointer to the interface. * @throws std::runtime_error if the interface cannot be acquired and exceptions are enabled, otherwise this error * condition results in a \ref CARB_FATAL_UNLESS() assertion. */ template <typename InterfaceType> InterfaceType* acquireInterfaceForBindings(const char* pluginName = nullptr) { carb::Framework* framework = carb::getFramework(); InterfaceType* iface = framework->tryAcquireInterface<InterfaceType>(pluginName); if (!iface) { // Try load plugins with default desc (all of them) carb::PluginLoadingDesc desc = carb::PluginLoadingDesc::getDefault(); framework->loadPlugins(desc); iface = framework->tryAcquireInterface<InterfaceType>(pluginName); if (!iface) { // somehow this header gets picked up by code compiled by -fno-exceptions #if !CARB_EXCEPTIONS_ENABLED OMNI_FATAL_UNLESS(iface, "Failed to acquire interface: '%s' (pluginName: '%s')", InterfaceType::getInterfaceDesc().name, pluginName ? pluginName : "nullptr"); #else throw std::runtime_error(fmt::format("Failed to acquire interface: {} (pluginName: {})", InterfaceType::getInterfaceDesc().name, pluginName ? pluginName : "nullptr")); #endif } } return iface; } /** * A helper function for \ref carb::getCachedInterface() that throws on error. * * @tparam InterfaceType The interface to acquire (i.e. `assets::IAssets`). Must be specified and cannot be inferred. * @returns A pointer to the interface. * @throws std::runtime_error if the interface cannot be acquired and exceptions are enabled, otherwise this error * condition results in a \ref CARB_FATAL_UNLESS() assertion. */ template <typename InterfaceType> InterfaceType* getCachedInterfaceForBindings() { InterfaceType* iface = carb::getCachedInterface<InterfaceType>(); if (CARB_UNLIKELY(!iface)) { // somehow this header gets picked up by code compiled by -fno-exceptions #if !CARB_EXCEPTIONS_ENABLED OMNI_FATAL_UNLESS(iface, "Failed to acquire cached interface: '%s'", InterfaceType::getInterfaceDesc().name); #else throw std::runtime_error( fmt::format("Failed to acquire cached interface: {}", InterfaceType::getInterfaceDesc().name)); #endif } return iface; } /** * Helper for \ref Framework::tryAcquireInterfaceFromLibrary() that throws on error. * * @tparam InterfaceType The interface to acquire (i.e. `assets::IAssets`). Must be specified and cannot be inferred. * @param libraryPath The library path to acquire the interface from. Must be specified. May be relative or absolute. * @returns A pointer to the interface. * @throws std::runtime_error if the interface cannot be acquired and exceptions are enabled, otherwise this error * condition results in a \ref CARB_FATAL_UNLESS() assertion. */ template <typename InterfaceType> InterfaceType* acquireInterfaceFromLibraryForBindings(const char* libraryPath) { carb::Framework* framework = carb::getFramework(); InterfaceType* iface = framework->tryAcquireInterfaceFromLibrary<InterfaceType>(libraryPath); if (!iface) { // somehow this header gets picked up by code compiled by -fno-exceptions #if !CARB_EXCEPTIONS_ENABLED OMNI_FATAL_UNLESS( "Failed to acquire interface: '%s' from: '%s')", InterfaceType::getInterfaceDesc().name, libraryPath); #else throw std::runtime_error(fmt::format( "Failed to acquire interface: {} from: {})", InterfaceType::getInterfaceDesc().name, libraryPath)); #endif } return iface; } /** * Acquires the Carbonite Framework for a script binding. * * @note This is automatically called by \ref FrameworkInitializerForBindings::FrameworkInitializerForBindings() from * \ref CARB_BINDINGS(). * * @param scriptLanguage The script language that this binding works with (i.e. "python"). This binding is registered * as via `carb::getFramework()->registerScriptBinding(BindingType::Binding, g_carbClientName, scriptLanguage)`. * @returns A pointer to the Carbonite \ref Framework, or `nullptr` on error (i.e. version mismatch). * @see Framework::registerScriptBinding() */ inline Framework* acquireFrameworkForBindings(const char* scriptLanguage) { // Acquire framework and set into global variable // Is framework was previously invalid, we are the first who calling it and it will be created during acquire. // Register builtin plugin in that case const bool firstStart = !isFrameworkValid(); Framework* f = acquireFramework(g_carbClientName); if (!f) return nullptr; g_carbFramework = f; // Register as binding for the given script language f->registerScriptBinding(BindingType::Binding, g_carbClientName, scriptLanguage); // Starting up logging if (firstStart) detail::registerBuiltinLogging(f); logging::registerLoggingForClient(); // Starting up filesystem and profiling if (firstStart) { detail::registerBuiltinFileSystem(f); detail::registerBuiltinAssert(f); detail::registerBuiltinThreadUtil(f); } profiler::registerProfilerForClient(); assert::registerAssertForClient(); l10n::registerLocalizationForClient(); return f; } /** * Releases the Carbonite Framework for a script binding. * * @note This is automatically called by the \ref FrameworkInitializerForBindings destructor from \ref CARB_BINDINGS(). */ inline void releaseFrameworkForBindings() { if (isFrameworkValid()) { profiler::deregisterProfilerForClient(); logging::deregisterLoggingForClient(); assert::deregisterAssertForClient(); l10n::deregisterLocalizationForClient(); // Leave g_carbFramework intact here since the framework itself remains valid; we are just signaling our end of // using it. There may be some static destructors (i.e. CachedInterface) that still need to use it. } else { // The framework became invalid while we were loaded. g_carbFramework = nullptr; } } /** * A helper class used by \ref CARB_BINDINGS() to acquire and release the \ref Framework for a binding. */ class FrameworkInitializerForBindings { public: /** * Acquires the Carbonite \ref Framework for this binding module. * * @note Calls \ref acquireFrameworkForBindings() and \ref OMNI_CORE_START() if the ONI core is not already started. * @param scriptLanguage The script language that this binding works with. */ FrameworkInitializerForBindings(const char* scriptLanguage = "python") { acquireFrameworkForBindings(scriptLanguage); m_thisModuleStartedOmniCore = !omniGetTypeFactoryWithoutAcquire(); if (m_thisModuleStartedOmniCore) { // at this point, the core should already be started by the omniverse host executable (i.e. app). however, // if we're in the python native interpreter, it will not automatically startup the core. here we account // for this situation by checking if the core is started, and if not, start it. // // OMNI_CORE_START internally reference counts the start/stop calls, so one would think we could always make // this call (with a corresponding call to OMNI_CORE_STOP in the destructor). // // however, the Python interpreter doesn't like unloading .pyd files, meaning our destructor will not be // called. // // this shouldn't be an issue, unless the host expects to be able to load, unload, and then reload the core. // the result here would be the internal reference count would get confused, causing the core to never be // unloaded. // // we don't expect apps to reload the core, but our unit tests do. so, here we only let python increment // the ref count if we think its the first entity to start the core (i.e. running in the interpreter). OMNI_CORE_START(nullptr); } omni::structuredlog::addModulesSchemas(); } /** * Releases the Carbonite \ref Framework for this binding module. * @note Calls \ref OMNI_CORE_STOP() if the constructor initialized the ONI core, and * \ref releaseFrameworkForBindings(). */ ~FrameworkInitializerForBindings() { if (m_thisModuleStartedOmniCore) { OMNI_CORE_STOP_FOR_BINDINGS(); m_thisModuleStartedOmniCore = false; } releaseFrameworkForBindings(); } //! A boolean indicating whether the constructor called \ref OMNI_CORE_START(). bool m_thisModuleStartedOmniCore; }; /** * A helper function for combining two hash values. * * Effectively: * ```cpp * std::size_t res = 0; * using std::hash; * res = carb::hashCombine(res, hash<T1>{}(t1)); * res = carb::hashCombine(res, hash<T2>{}(t2)); * return res; * ``` * @tparam T1 A type to hash. * @tparam T2 A type to hash. * @param t1 A value to hash. * @param t2 A value to hash. * @returns A hash combined from @p t1 and @p t2. * @see hashCombine() */ template <class T1, class T2> inline size_t hashPair(T1 t1, T2 t2) { std::size_t res = 0; using std::hash; res = carb::hashCombine(res, hash<T1>{}(t1)); res = carb::hashCombine(res, hash<T2>{}(t2)); return res; } #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Helper class to store and manage lifetime of `std::function<>` for script bindings. * * It allocates std::function copy on a heap, prolonging its lifetime. That allows passing std::function as user data * into interface subscription functions. You need to associate it with some key (provide key type with a template * KeyT), usually it is some kind of Subscription Id. When unsubscribing call ScriptCallbackRegistry::removeAndDestroy * with corresponding key. The usage: * * ```cpp * std::function<int(float, char)> myFunc; * static ScriptCallbackRegistry<size_t, int, float, char> s_registry; * std::function<int(float, char)>* myFuncCopy = s_registry.create(myFunc); * // myFuncCopy can now passed into C API as user data * s_registry.add(id, myFuncCopy); * // ... * s_registry.removeAndDestroy(id); * ``` */ template <class KeyT, typename ReturnT, typename... Args> class ScriptCallbackRegistry { public: using FuncT = std::function<ReturnT(Args...)>; static FuncT* create(const FuncT& f) { return new FuncT(f); } static void destroy(FuncT* f) { delete f; } void add(const KeyT& key, FuncT* ptr) { if (!m_map.insert({ key, ptr }).second) { CARB_LOG_ERROR("Scripting callback with that key already exists."); } } bool tryRemoveAndDestroy(const KeyT& key) { auto it = m_map.find(key); if (it != m_map.end()) { destroy(it->second); m_map.erase(it); return true; } return false; } void removeAndDestroy(const KeyT& key) { if (!tryRemoveAndDestroy(key)) { CARB_LOG_ERROR("Removing unknown scripting callback."); } } private: std::unordered_map<KeyT, FuncT*> m_map; }; template <typename ClassT, typename ObjectT, typename... Args> auto wrapInStealObject(ObjectT* (ClassT::*f)(Args...)) { return [f](ClassT* c, Args... args) { return carb::stealObject<ObjectT>((c->*f)(args...)); }; } #endif } // namespace carb /** * Declare a compilation unit as script language bindings. * * @param clientName The string to pass to CARB_GLOBALS which will be used as `g_carbClientName` for the module. * @param ... Arguments passed to \ref carb::FrameworkInitializerForBindings::FrameworkInitializerForBindings(), * typically the script language. */ #define CARB_BINDINGS(clientName, ...) \ CARB_GLOBALS(clientName) \ carb::FrameworkInitializerForBindings g_carbFrameworkInitializerForBindings{ __VA_ARGS__ }; /** * Declare a compilation unit as script language bindings. * * @param clientName_ The string to pass to CARB_GLOBALS_EX which will be used as `g_carbClientName` for the module. * @param desc_ The description passed to `omni::LogChannel` for the default log channel. * @param ... Arguments passed to \ref carb::FrameworkInitializerForBindings::FrameworkInitializerForBindings(), * typically the script language. */ #define CARB_BINDINGS_EX(clientName_, desc_, ...) \ CARB_GLOBALS_EX(clientName_, desc_) \ carb::FrameworkInitializerForBindings g_carbFrameworkInitializerForBindings{ __VA_ARGS__ };
15,870
C
37.615572
120
0.67133
omniverse-code/kit/include/carb/InterfaceUtils.h
// Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! //! @brief Utilities for Carbonite Interface management. #pragma once #include "Framework.h" #include "cpp/Atomic.h" namespace carb { #ifndef DOXYGEN_BUILD namespace detail { template <typename InterfaceT, const char* PluginName> class CachedInterface { public: constexpr CachedInterface() = default; ~CachedInterface() { reset(); } InterfaceT* get() { auto iface = m_cachedInterface.load(std::memory_order_relaxed); if (CARB_LIKELY(iface)) { return iface; } return getInternal(); } void reset() { ::carb::Framework* framework = ::carb::getFramework(); if (!framework) { // Framework no longer valid or already unloaded. return; } auto iface = m_cachedInterface.exchange(nullptr, std::memory_order_relaxed); if (iface) { framework->removeReleaseHook(iface, sReleaseHook, this); } framework->removeReleaseHook(nullptr, sFrameworkReleased, this); m_reqState.store(NotRequested, std::memory_order_release); m_reqState.notify_all(); } private: enum RequestState { NotRequested, Requesting, Finished, }; std::atomic<InterfaceT*> m_cachedInterface{ nullptr }; carb::cpp::atomic<RequestState> m_reqState{ NotRequested }; static void sReleaseHook(void* iface, void* this_) { static_cast<CachedInterface*>(this_)->releaseHook(iface); } static void sFrameworkReleased(void*, void* this_) { // The Framework is fully released. Reset our request state. static_cast<CachedInterface*>(this_)->reset(); } void releaseHook(void* iface) { // Clear the cached interface pointer, but don't fully reset. Further attempts to get() will proceed to // getInternal(), but will not attempt to acquire the interface again. CARB_ASSERT(iface == m_cachedInterface); CARB_UNUSED(iface); m_cachedInterface.store(nullptr, std::memory_order_relaxed); } CARB_NOINLINE InterfaceT* getInternal() { ::carb::Framework* framework = ::carb::getFramework(); if (!framework) { return nullptr; } RequestState state = m_reqState.load(std::memory_order_acquire); while (state != Finished) { if (state == NotRequested && m_reqState.compare_exchange_weak( state, Requesting, std::memory_order_relaxed, std::memory_order_relaxed)) { InterfaceT* iface = framework->tryAcquireInterface<InterfaceT>(PluginName); if (!iface) { // Failed to acquire. Reset to initial state m_reqState.store(NotRequested, std::memory_order_release); m_reqState.notify_all(); return nullptr; } if (CARB_UNLIKELY(!framework->addReleaseHook(iface, sReleaseHook, this))) { // This could only happen if something released the interface between us acquiring it and adding // the release hook. Repeat the process again. state = NotRequested; m_reqState.store(state, std::memory_order_release); m_reqState.notify_all(); continue; } bool b = framework->addReleaseHook(nullptr, sFrameworkReleased, this); CARB_UNUSED(b); CARB_ASSERT(b); m_cachedInterface.store(iface, std::memory_order_relaxed); m_reqState.store(Finished, std::memory_order_release); m_reqState.notify_all(); return iface; } else if (state == Requesting) { m_reqState.wait(state, std::memory_order_relaxed); state = m_reqState.load(std::memory_order_acquire); } } return m_cachedInterface.load(std::memory_order_relaxed); } }; template <class T, const char* PluginName> CachedInterface<T, PluginName>& cachedInterface() { static CachedInterface<T, PluginName> cached; return cached; } } // namespace detail #endif /** * Retrieves the specified interface as if from Framework::tryAcquireInterface() and caches it for fast retrieval. * * If the interface is released with Framework::releaseInterface(), the cached interface will be automatically * cleared. Calls to getCachedInterface() after this point will return `nullptr`. In order for getCachedInterface() to * call Framework::tryAcquireInterface() again, first call resetCachedInterface(). * * @note Releasing the Carbonite Framework with carb::releaseFramework() automatically calls resetCachedInterface(). * * @tparam InterfaceT The interface class to retrieve. * @tparam PluginName The name of a specific plugin to keep cached. Note: this must be a global char array or `nullptr`. * @returns The loaded and acquired interface class if successfully acquired through Framework::tryAcquireInterface(), * or a previously cached value. If the interface could not be found, or has been released with releaseFramework(), * `nullptr` is returned. */ template <typename InterfaceT, const char* PluginName = nullptr> CARB_NODISCARD inline InterfaceT* getCachedInterface() { return ::carb::detail::cachedInterface<InterfaceT, PluginName>().get(); } /** * Resets any previously-cached interface of the given type and allows it to be acquired again. * * @note This does NOT *release* the interface as if Framework::releaseInterface() were called. It merely resets the * cached state so that getCachedInterface() will call Framework::tryAcquireInterface() again. * * @tparam InterfaceT The type of interface class to evict from cache. * @tparam PluginName The name of a specific plugin that is cached. Note: this must be a global char array or `nullptr`. */ template <typename InterfaceT, const char* PluginName = nullptr> inline void resetCachedInterface() { ::carb::detail::cachedInterface<InterfaceT, PluginName>().reset(); } } // namespace carb
6,722
C
35.145161
120
0.641476
omniverse-code/kit/include/carb/CarbWindows.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 Allow access to specific parts of Windows API without including Windows.h * * This file replaces `#include <Windows.h>` for header files. *Windows.h* is monolithic and defines some oft-used * names like `min`, `max`, `count`, etc. Directives like `NOMINMAX`, `WIN32_LEAN_AND_MEAN`, and `WIN32_EXTRA_LEAN` can * help, but still leave the global namespace much more polluted than is desired. Note that the MSVC CRT does not * include *Windows.h* anywhere; instead special reserved naming conventions (such as `_PrefixedUpper`) exist to allow * the CRT to define special functions that are called by the CRT, but the implementation of those functions * (that utilize the Windows API) are hidden away in static or dynamic libraries. However, for Carbonite, since the * goal is to not require additional linking for header utilities, there is no ability for `carb` header files to * similarly hide Windows API usage in libraries. * * Anything from the Windows API that Carbonite relies upon should be defined in this file, and should not conflict in * the event that *Windows.h* is included. * * Rules for adding things to this file: * 1. Do not `#define` anything that is defined in *Windows.h*. Instead, prefix the macro name with `CARBWIN_` but give * it the same value. This is to prevent errors if *Windows.h* is included since macros may not be defined more than * once. * 2. Typedef's should be specified _exactly_ as in Windows.h * 3. Structs can be forward-declared only, otherwise definitions will conflict with *Windows.h*. If a struct * definition is required, it should be prefixed with `CARBWIN_` at the bottom of this file. *TestCarbWindows.cpp* * should then `static_assert` that the size and member offsets are the same as the *Windows.h* version. * 4. Enums cannot be redefined. Therefore, enum values needed should be changed to `#define` and prefixed with * `CARBWIN_`. * * These rules will allow compilation units to `#include <Windows.h>` before or after this file. */ #pragma once #include "Defines.h" CARB_IGNOREWARNING_MSC_WITH_PUSH(4201) // nonstandard extension used: nameless struct/union // clang-format off #if CARB_PLATFORM_WINDOWS && !defined(DOXYGEN_BUILD) #ifndef __cplusplus #define CARBWIN_NONAMELESSUNION // use strict ANSI standard #else extern "C" { #endif // Define these temporarily so that they don't conflict with Windows.h. They are #undef'd at the bottom #define CARBWIN_WINBASEAPI __declspec(dllimport) #ifndef WINBASEAPI #define WINBASEAPI CARBWIN_WINBASEAPI #define CARBWIN_WINBASEAPI_DEFINED 1 #endif #define CARBWIN_WINAPI __stdcall #ifndef WINAPI #define WINAPI CARBWIN_WINAPI #define CARBWIN_WINAPI_DEFINED 1 #endif #define CARBWIN_SHSTDAPI extern "C" __declspec(dllimport) HRESULT WINAPI #define CARBWIN_SHSTDAPI_(type) extern "C" __declspec(dllimport) type WINAPI #ifndef SHSTDAPI #define SHSTDAPI CARBWIN_SHSTDAPI #define SHSTDAPI_(type) CARBWIN_SHSTDAPI_(type) #define CARBWIN_SHSTDAPI_DEFINED 1 #endif #define CARBWIN_APIENTRY __stdcall #ifndef APIENTRY #define APIENTRY CARBWIN_APIENTRY #define CARBWIN_APIENTRY_DEFINED 1 #endif #define CARBWIN_WINADVAPI __declspec(dllimport) #ifndef WINADVAPI #define WINADVAPI CARBWIN_WINADVAPI #define CARBWIN_WINADVAPI_DEFINED 1 #endif /////////////////////////////////////////////////////////////////////////////// // #defines. Should be prefixed with CARBWIN_ and defined exactly the same as // their Windows.h counterpart. // from minwindef.h #define CARBWIN_CONST const #define CARBWIN_FALSE 0 #define CARBWIN_TRUE 1 #define CARBWIN_MAX_PATH 260 // from winnt.h #ifndef CARBWIN_DUMMYUNIONNAME #if defined(CARBWIN_NONAMELESSUNION) || !defined(_MSC_EXTENSIONS) #define CARBWIN_DUMMYUNIONNAME u #else #define CARBWIN_DUMMYUNIONNAME #endif #endif #define CARBWIN_STATUS_SUCCESS ((DWORD )0x00000000L) #define CARBWIN_STATUS_TIMEOUT ((DWORD )0x00000102L) #define CARBWIN_MEM_COMMIT 0x00001000 #define CARBWIN_MEM_RESERVE 0x00002000 #define CARBWIN_MEM_DECOMMIT 0x00004000 #define CARBWIN_MEM_RELEASE 0x00008000 #define CARBWIN_MEM_FREE 0x00010000 #define CARBWIN_MEM_PRIVATE 0x00020000 #define CARBWIN_MEM_MAPPED 0x00040000 #define CARBWIN_MEM_RESET 0x00080000 #define CARBWIN_MEM_TOP_DOWN 0x00100000 #define CARBWIN_MEM_WRITE_WATCH 0x00200000 #define CARBWIN_MEM_PHYSICAL 0x00400000 #define CARBWIN_MEM_LARGE_PAGES 0x20000000 #define CARBWIN_MEM_4MB_PAGES 0x80000000 #define CARBWIN_TOKEN_QUERY 0x0008 #ifndef CARBWIN_DUMMYSTRUCTNAME #if defined(CARBWIN_NONAMELESSUNION) || !defined(_MSC_EXTENSIONS) #define CARBWIN_DUMMYSTRUCTNAME s #else #define CARBWIN_DUMMYSTRUCTNAME #endif #endif #define CARBWIN_VOID void #define CARBWIN_DLL_PROCESS_ATTACH 1 #define CARBWIN_DLL_THREAD_ATTACH 2 #define CARBWIN_DLL_THREAD_DETACH 3 #define CARBWIN_DLL_PROCESS_DETACH 0 #define CARBWIN_VOID void #define CARBWIN_STATUS_WAIT_0 ((DWORD)0x00000000L) #define CARBWIN_RTL_SRWLOCK_INIT {0} #define CARBWIN_MAKELANGID(p, s) ((((WORD )(s)) << 10) | (WORD )(p)) #define CARBWIN_MAKELCID(lgid, srtid) ((DWORD)((((DWORD)((WORD)(srtid))) << 16) | ((DWORD)((WORD)(lgid))))) #define CARBWIN_LANG_NEUTRAL 0x00 #define CARBWIN_LANG_INVARIANT 0x7f #define CARBWIN_SUBLANG_DEFAULT 0x01 #define CARBWIN_SUBLANG_NEUTRAL 0x00 #define CARBWIN_SORT_DEFAULT 0x0 #define CARBWIN_PAGE_READONLY 0x02 #define CARBWIN_PAGE_READWRITE 0x04 #define CARBWIN_STANDARD_RIGHTS_REQUIRED (0x000F0000L) #define CARBWIN_SECTION_QUERY 0x0001 #define CARBWIN_SECTION_MAP_WRITE 0x0002 #define CARBWIN_SECTION_MAP_READ 0x0004 #define CARBWIN_SECTION_MAP_EXECUTE 0x0008 #define CARBWIN_SECTION_EXTEND_SIZE 0x0010 #define CARBWIN_SECTION_MAP_EXECUTE_EXPLICIT 0x0020 #define CARBWIN_SECTION_ALL_ACCESS (CARBWIN_STANDARD_RIGHTS_REQUIRED|CARBWIN_SECTION_QUERY|\ CARBWIN_SECTION_MAP_WRITE | \ CARBWIN_SECTION_MAP_READ | \ CARBWIN_SECTION_MAP_EXECUTE | \ CARBWIN_SECTION_EXTEND_SIZE) #define CARBWIN_LOCALE_INVARIANT \ (CARBWIN_MAKELCID(CARBWIN_MAKELANGID(CARBWIN_LANG_INVARIANT, CARBWIN_SUBLANG_NEUTRAL), CARBWIN_SORT_DEFAULT)) #define CARBWIN_LCMAP_LOWERCASE 0x00000100 #define CARBWIN_LCMAP_UPPERCASE 0x00000200 #define CARBWIN_LCMAP_TITLECASE 0x00000300 #define CARBWIN_LCMAP_SORTKEY 0x00000400 #define CARBWIN_LCMAP_BYTEREV 0x00000800 #define CARBWIN_LCMAP_HIRAGANA 0x00100000 #define CARBWIN_LCMAP_KATAKANA 0x00200000 #define CARBWIN_LCMAP_HALFWIDTH 0x00400000 #define CARBWIN_LCMAP_FULLWIDTH 0x00800000 #define CARBWIN_LCMAP_LINGUISTIC_CASING 0x01000000 #define CARBWIN_LCMAP_SIMPLIFIED_CHINESE 0x02000000 #define CARBWIN_LCMAP_TRADITIONAL_CHINESE 0x04000000 #define CARBWIN_LCMAP_SORTHANDLE 0x20000000 #define CARBWIN_LCMAP_HASH 0x00040000 #define CARBWIN_FILE_SHARE_READ 0x00000001 #define CARBWIN_FILE_SHARE_WRITE 0x00000002 #define CARBWIN_FILE_SHARE_DELETE 0x00000004 #define CARBWIN_GENERIC_READ (0x80000000L) #define CARBWIN_GENERIC_WRITE (0x40000000L) #define CARBWIN_GENERIC_EXECUTE (0x20000000L) #define CARBWIN_GENERIC_ALL (0x10000000L) #define CARBWIN_EXCEPTION_NONCONTINUABLE 0x1 #define CARBWIN_EVENTLOG_SEQUENTIAL_READ 0x0001 #define CARBWIN_EVENTLOG_SEEK_READ 0x0002 #define CARBWIN_EVENTLOG_FORWARDS_READ 0x0004 #define CARBWIN_EVENTLOG_BACKWARDS_READ 0x0008 #define CARBWIN_EVENTLOG_SUCCESS 0x0000 #define CARBWIN_EVENTLOG_ERROR_TYPE 0x0001 #define CARBWIN_EVENTLOG_WARNING_TYPE 0x0002 #define CARBWIN_EVENTLOG_INFORMATION_TYPE 0x0004 #define CARBWIN_EVENTLOG_AUDIT_SUCCESS 0x0008 #define CARBWIN_EVENTLOG_AUDIT_FAILURE 0x0010 #define CARBWIN_EVENTLOG_START_PAIRED_EVENT 0x0001 #define CARBWIN_EVENTLOG_END_PAIRED_EVENT 0x0002 #define CARBWIN_EVENTLOG_END_ALL_PAIRED_EVENTS 0x0004 #define CARBWIN_EVENTLOG_PAIRED_EVENT_ACTIVE 0x0008 #define CARBWIN_EVENTLOG_PAIRED_EVENT_INACTIVE 0x0010 #define CARBWIN_FILE_ATTRIBUTE_READONLY 0x00000001 #define CARBWIN_FILE_ATTRIBUTE_HIDDEN 0x00000002 #define CARBWIN_FILE_ATTRIBUTE_SYSTEM 0x00000004 #define CARBWIN_FILE_ATTRIBUTE_DIRECTORY 0x00000010 #define CARBWIN_FILE_ATTRIBUTE_ARCHIVE 0x00000020 #define CARBWIN_FILE_ATTRIBUTE_DEVICE 0x00000040 #define CARBWIN_FILE_ATTRIBUTE_TEMPORARY 0x00000100 #define CARBWIN_FILE_ATTRIBUTE_SPARSE_FILE 0x00000200 #define CARBWIN_FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 #define CARBWIN_FILE_ATTRIBUTE_COMPRESSED 0x00000800 #define CARBWIN_FILE_ATTRIBUTE_OFFLINE 0x00001000 #define CARBWIN_FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000 #define CARBWIN_FILE_ATTRIBUTE_ENCRYPTED 0x00004000 #define CARBWIN_FILE_ATTRIBUTE_INTEGRITY_STREAM 0x00008000 #define CARBWIN_FILE_ATTRIBUTE_VIRTUAL 0x00010000 #define CARBWIN_FILE_ATTRIBUTE_NO_SCRUB_DATA 0x00020000 #define CARBWIN_FILE_ATTRIBUTE_EA 0x00040000 #define CARBWIN_FILE_ATTRIBUTE_PINNED 0x00080000 #define CARBWIN_FILE_ATTRIBUTE_UNPINNED 0x00100000 #define CARBWIN_FILE_ATTRIBUTE_RECALL_ON_OPEN 0x00040000 #define CARBWIN_FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS 0x00400000 #define CARBWIN_FILE_ATTRIBUTE_STRICTLY_SEQUENTIAL 0x20000000 // from intsafe.h #define CARBWIN_S_OK ((HRESULT)0L) // from handleapi.h #define CARBWIN_INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1) // from winbase.h #define CARBWIN_WAIT_OBJECT_0 ((CARBWIN_STATUS_WAIT_0) + 0) #define CARBWIN_INFINITE 0xFFFFFFFF #define CARBWIN_FORMAT_MESSAGE_ALLOCATE_BUFFER 0x00000100 #define CARBWIN_FORMAT_MESSAGE_IGNORE_INSERTS 0x00000200 #define CARBWIN_FORMAT_MESSAGE_FROM_SYSTEM 0x00001000 #define CARBWIN_FIBER_FLAG_FLOAT_SWITCH 0x1 // context switch floating point #define CARBWIN_FILE_ATTRIBUTE_NORMAL 0x80 #define CARBWIN_FILE_FLAG_BACKUP_SEMANTICS 0x02000000 // from winerror.h #define CARBWIN_ERROR_SUCCESS 0L #define CARBWIN_ERROR_FILE_NOT_FOUND 2L #define CARBWIN_ERROR_PATH_NOT_FOUND 3L #define CARBWIN_ERROR_ACCESS_DENIED 5L #define CARBWIN_ERROR_OUTOFMEMORY 14L #define CARBWIN_ERROR_NO_MORE_FILES 18L #define CARBWIN_ERROR_FILE_EXISTS 80L #define CARBWIN_ERROR_CALL_NOT_IMPLEMENTED 120L #define CARBWIN_ERROR_INSUFFICIENT_BUFFER 122L #define CARBWIN_ERROR_MOD_NOT_FOUND 126L #define CARBWIN_ERROR_ALREADY_EXISTS 183L #define CARBWIN_ERROR_FILENAME_EXCED_RANGE 206L #define CARBWIN_WAIT_TIMEOUT 258L #define CARBWIN_ERROR_NO_MORE_ITEMS 259L #define CARBWIN_ERROR_TIMEOUT 1460L #define CARBWIN_SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) #define CARBWIN_FAILED(hr) (((HRESULT)(hr)) < 0) // from synchapi.h #define CARBWIN_SRWLOCK_INIT CARBWIN_RTL_SRWLOCK_INIT // from memoryapi.h #define CARBWIN_FILE_MAP_READ CARBWIN_SECTION_MAP_READ #define CARBWIN_FILE_MAP_ALL_ACCESS CARBWIN_SECTION_ALL_ACCESS // from fileapi.h #define CARBWIN_CREATE_NEW 1 #define CARBWIN_CREATE_ALWAYS 2 #define CARBWIN_OPEN_EXISTING 3 #define CARBWIN_OPEN_ALWAYS 4 #define CARBWIN_TRUNCATE_EXISTING 5 #define CARBWIN_INVALID_FILE_ATTRIBUTES ((DWORD)-1) // from minwinbase.h #define CARBWIN_LOCKFILE_FAIL_IMMEDIATELY 0x00000001 #define CARBWIN_LOCKFILE_EXCLUSIVE_LOCK 0x00000002 // from processthreadsapi.h #define CARBWIN_TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF) // from pathcch.h #define CARBWIN_PATHCCH_ALLOW_LONG_PATHS 0x01 // from excpt.h #define CARBWIN_EXCEPTION_EXECUTE_HANDLER 1 /////////////////////////////////////////////////////////////////////////////// // typedefs, forward-declarations // Many of the typedefs below are not compatible with Forge's own version of the Windows typedefs. // These are more correct as they're declared exactly the same as in the Windows headers. #ifndef NV_FORGE_WINDEF_H // from basetsd.h static_assert(sizeof(void*) == 8, "This only supports 64-bit platforms"); typedef unsigned int UINT32, *PUINT32; typedef __int64 INT_PTR, *PINT_PTR; typedef __int64 LONG_PTR, *PLONG_PTR; typedef unsigned __int64 UINT_PTR, *PUINT_PTR; typedef unsigned __int64 ULONG_PTR, *PULONG_PTR; typedef ULONG_PTR SIZE_T, *PSIZE_T; typedef LONG_PTR SSIZE_T, *PSSIZE_T; typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR; typedef unsigned __int64 DWORD64, *PDWORD64; // from WTypesbase.h typedef wchar_t WCHAR; typedef const WCHAR *LPCWSTR; // from minwindef.h typedef int BOOL; typedef unsigned char BYTE; typedef long *LPLONG; typedef unsigned long DWORD; typedef DWORD *LPDWORD; typedef unsigned long ULONG, *PULONG; typedef void *LPVOID; typedef const void *LPCVOID; typedef void *HANDLE; typedef HANDLE HLOCAL; typedef HANDLE *PHANDLE, *LPHANDLE; typedef struct HINSTANCE__ *HINSTANCE; typedef HINSTANCE HMODULE; typedef INT_PTR (WINAPI *FARPROC)(); typedef struct _FILETIME FILETIME, *PFILETIME, *LPFILETIME; typedef struct _SYSTEMTIME SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME; typedef int INT; typedef unsigned int UINT; typedef unsigned int *PUINT; // from minwinbase.h typedef struct _SECURITY_ATTRIBUTES _SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; typedef DWORD *PDWORD; // from winnt.h typedef void *PVOID; typedef long LONG; typedef long HRESULT; typedef char CHAR; typedef wchar_t WCHAR; typedef BYTE BOOLEAN; typedef unsigned short WORD; typedef CHAR *LPSTR; typedef const CHAR *LPCSTR, *PCSTR; typedef WCHAR *NWPSTR, *LPWSTR, *PWSTR; typedef const WCHAR *LPCWSTR, *PCWSTR; typedef WCHAR *PWCHAR, *LPWCH, *PWCH; typedef __int64 LONGLONG; typedef unsigned __int64 ULONGLONG; typedef ULONGLONG DWORDLONG; typedef struct _RTL_SRWLOCK RTL_SRWLOCK, *PRTL_SRWLOCK; typedef DWORD LCID; typedef PDWORD PLCID; typedef WORD LANGID; typedef union _LARGE_INTEGER LARGE_INTEGER; typedef LARGE_INTEGER *PLARGE_INTEGER; typedef struct _EVENTLOGRECORD EVENTLOGRECORD, *PEVENTLOGRECORD; /////////////////////////////////////////////////////////////////////////////// // Struct redefines // See instructions for adding at the bottom of this block. struct CARBWIN_SRWLOCK { PVOID Ptr; }; struct CARBWIN_PROCESS_MEMORY_COUNTERS { DWORD cb; DWORD PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; }; struct CARBWIN_MEMORYSTATUSEX { DWORD dwLength; DWORD dwMemoryLoad; DWORDLONG ullTotalPhys; DWORDLONG ullAvailPhys; DWORDLONG ullTotalPageFile; DWORDLONG ullAvailPageFile; DWORDLONG ullTotalVirtual; DWORDLONG ullAvailVirtual; DWORDLONG ullAvailExtendedVirtual; }; struct CARBWIN_SYSTEM_INFO { union { DWORD dwOemId; // Obsolete field...do not use struct { WORD wProcessorArchitecture; WORD wReserved; } CARBWIN_DUMMYSTRUCTNAME; } CARBWIN_DUMMYUNIONNAME; DWORD dwPageSize; LPVOID lpMinimumApplicationAddress; LPVOID lpMaximumApplicationAddress; DWORD_PTR dwActiveProcessorMask; DWORD dwNumberOfProcessors; DWORD dwProcessorType; DWORD dwAllocationGranularity; WORD wProcessorLevel; WORD wProcessorRevision; }; struct CARBWIN_OVERLAPPED { ULONG_PTR Internal; ULONG_PTR InternalHigh; union { struct { DWORD Offset; DWORD OffsetHigh; } CARBWIN_DUMMYSTRUCTNAME; PVOID Pointer; } CARBWIN_DUMMYUNIONNAME; HANDLE hEvent; }; struct _OVERLAPPED; typedef struct _OVERLAPPED* LPOVERLAPPED; struct CARBWIN_FILE_NOTIFY_INFORMATION { DWORD NextEntryOffset; DWORD Action; DWORD FileNameLength; WCHAR FileName[1]; }; struct CARBWIN_FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; }; struct CARBWIN_SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; }; typedef union CARBWIN_LARGE_INTEGER { struct { DWORD LowPart; LONG HighPart; } CARBWIN_DUMMYSTRUCTNAME; struct { DWORD LowPart; LONG HighPart; } u; LONGLONG QuadPart; } CARBWIN_LARGE_INTEGER; struct CARBWIN_EVENTLOGRECORD { DWORD Length; // Length of full record DWORD Reserved; // Used by the service DWORD RecordNumber; // Absolute record number DWORD TimeGenerated; // Seconds since 1-1-1970 DWORD TimeWritten; // Seconds since 1-1-1970 DWORD EventID; WORD EventType; WORD NumStrings; WORD EventCategory; WORD ReservedFlags; // For use with paired events (auditing) DWORD ClosingRecordNumber; // For use with paired events (auditing) DWORD StringOffset; // Offset from beginning of record DWORD UserSidLength; DWORD UserSidOffset; DWORD DataLength; DWORD DataOffset; // Offset from beginning of record // // Then follow: // // WCHAR SourceName[] // WCHAR Computername[] // SID UserSid // WCHAR Strings[] // BYTE Data[] // CHAR Pad[] // DWORD Length; // }; struct CARBWIN_PROCESSOR_NUMBER { WORD Group; BYTE Number; BYTE Reserved; }; typedef ULONG_PTR CARBWIN_KAFFINITY; struct CARBWIN_GROUP_AFFINITY { CARBWIN_KAFFINITY Mask; WORD Group; WORD Reserved[3]; }; // ADD NEW STRUCT REDEFINES HERE // - add to TestCarbWindows.cpp // - add forward-declared typedefs exactly for Windows types above // - Must be prefixed with CARBWIN_ and defined exactly as in Windows.h /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // functions // from winbase.h typedef void (WINAPI *PFIBER_START_ROUTINE)(LPVOID lpFiberParameter); typedef PFIBER_START_ROUTINE LPFIBER_START_ROUTINE; WINBASEAPI HLOCAL WINAPI LocalFree(HLOCAL hMem); WINBASEAPI DWORD WINAPI FormatMessageW(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPWSTR lpBuffer, DWORD nSize, va_list *Arguments); WINBASEAPI int WINAPI lstrlenW(LPCWSTR lpString); WINBASEAPI LPVOID WINAPI CreateFiber(SIZE_T dwStackSize, LPFIBER_START_ROUTINE lpStartAddress, LPVOID lpParameter); WINBASEAPI LPVOID WINAPI CreateFiberEx(SIZE_T dwStackCommitSize, SIZE_T dwStackReserveSize, DWORD dwFlags, LPFIBER_START_ROUTINE lpStartAddress, LPVOID lpParameter); WINBASEAPI void WINAPI DeleteFiber(LPVOID lpFiber); WINBASEAPI void WINAPI SwitchToFiber(LPVOID lpFiber); WINBASEAPI LPVOID WINAPI ConvertThreadToFiber(LPVOID lpParameter); WINBASEAPI LPVOID WINAPI ConvertThreadToFiberEx(LPVOID lpParameter, DWORD dwFlags); WINBASEAPI BOOL WINAPI ConvertFiberToThread(); WINBASEAPI DWORD_PTR WINAPI SetThreadAffinityMask(HANDLE hThread, DWORD_PTR dwThreadAffinityMask); WINADVAPI HANDLE WINAPI OpenEventLogW(LPCWSTR lpUNCServerName, LPCWSTR lpSourceName); WINADVAPI BOOL WINAPI CloseEventLog(HANDLE hEventLog); WINADVAPI BOOL WINAPI ReadEventLogW(HANDLE hEventLog, DWORD dwReadFlags, DWORD dwRecordOffset, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, DWORD *pnBytesRead, DWORD *pnMinNumberOfBytesNeeded); WINADVAPI BOOL WINAPI OpenProcessToken(LPVOID, DWORD, PHANDLE); // from debugapi.h WINBASEAPI BOOL WINAPI IsDebuggerPresent(void); WINBASEAPI void WINAPI DebugBreak(void); WINBASEAPI void WINAPI OutputDebugStringA(LPCSTR lpOutputString); // from synchapi.h typedef RTL_SRWLOCK SRWLOCK, *PSRWLOCK; WINBASEAPI HANDLE WINAPI CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCWSTR lpName); WINBASEAPI BOOL WINAPI ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount); WINBASEAPI DWORD WINAPI WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds); WINBASEAPI void WINAPI InitializeSRWLock(PSRWLOCK SRWLock); WINBASEAPI void WINAPI ReleaseSRWLockExclusive(PSRWLOCK SRWLock); WINBASEAPI void WINAPI ReleaseSRWLockShared(PSRWLOCK SRWLock); WINBASEAPI void WINAPI AcquireSRWLockExclusive(PSRWLOCK SRWLock); WINBASEAPI void WINAPI AcquireSRWLockShared(PSRWLOCK SRWLock); WINBASEAPI BOOLEAN WINAPI TryAcquireSRWLockExclusive(PSRWLOCK SRWLock); WINBASEAPI BOOLEAN WINAPI TryAcquireSRWLockShared(PSRWLOCK SRWLock); WINBASEAPI HANDLE WINAPI CreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOnwer, LPCSTR lpName); WINBASEAPI HANDLE WINAPI CreateMutexW(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName); WINBASEAPI BOOL WINAPI ReleaseMutex(HANDLE hMutex); WINBASEAPI HANDLE WINAPI CreateEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName); WINBASEAPI HANDLE WINAPI CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCWSTR lpName); WINBASEAPI void WINAPI Sleep(DWORD dwMilliseconds); WINBASEAPI DWORD WINAPI SleepEx(DWORD dwMilliseconds, BOOL bAlertable); // Note that these functions are not in DLLs; you must link with synchronization.lib BOOL WINAPI WaitOnAddress(volatile void* Address, PVOID CompareAddress, SIZE_T AddressSize, DWORD dwMilliseconds); void WINAPI WakeByAddressSingle(PVOID Address); void WINAPI WakeByAddressAll(PVOID Address); // from shellapi.h SHSTDAPI_(LPWSTR *) CommandLineToArgvW(LPCWSTR lpCmdLine, int* pNumArgs); // from processenv.h WINBASEAPI LPWSTR WINAPI GetCommandLineW(void); WINBASEAPI LPWCH WINAPI GetEnvironmentStringsW(void); WINBASEAPI BOOL WINAPI FreeEnvironmentStringsW(LPWCH penv); WINBASEAPI BOOL WINAPI SetEnvironmentVariableW(LPCWSTR lpName, LPCWSTR lpValue); WINBASEAPI DWORD WINAPI GetEnvironmentVariableW(LPCWSTR lpName, LPWSTR lpBuffer, DWORD nSize); // from handleapi.h WINBASEAPI BOOL WINAPI CloseHandle(HANDLE hObject); // from errhandlingapi.h WINBASEAPI void WINAPI RaiseException(DWORD, DWORD, DWORD, const ULONG_PTR*); WINBASEAPI DWORD WINAPI GetLastError(void); WINBASEAPI void WINAPI SetLastError(DWORD dwErrCode); // from processthreadsapi.h typedef struct _PROCESSOR_NUMBER PROCESSOR_NUMBER, *PPROCESSOR_NUMBER; WINBASEAPI HANDLE WINAPI GetCurrentProcess(void); WINBASEAPI DWORD WINAPI GetCurrentProcessId(void); WINBASEAPI HANDLE WINAPI GetCurrentThread(void); WINBASEAPI DWORD WINAPI GetCurrentThreadId(void); WINBASEAPI DWORD WINAPI GetThreadId(HANDLE); WINBASEAPI BOOL WINAPI TerminateProcess(HANDLE, UINT); WINBASEAPI DWORD WINAPI TlsAlloc(void); WINBASEAPI LPVOID WINAPI TlsGetValue(DWORD dwTlsIndex); WINBASEAPI BOOL WINAPI TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue); WINBASEAPI BOOL WINAPI TlsFree(DWORD dwTlsIndex); WINBASEAPI BOOL WINAPI GetProcessTimes(HANDLE hProcess, LPFILETIME lpCreationTime, LPFILETIME lpExitTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime); WINBASEAPI void WINAPI GetCurrentProcessorNumberEx(PPROCESSOR_NUMBER); // from porcesstoplogyapi.h typedef struct _GROUP_AFFINITY GROUP_AFFINITY, *PGROUP_AFFINITY; WINBASEAPI BOOL WINAPI GetThreadGroupAffinity(HANDLE hThread, PGROUP_AFFINITY GroupAffinity); WINBASEAPI BOOL WINAPI SetThreadGroupAffinity(HANDLE hThread, const GROUP_AFFINITY* GroupAffinity, PGROUP_AFFINITY PreviousGroupAffinity); // from sysinfoapi.h typedef struct _MEMORYSTATUSEX MEMORYSTATUSEX, *LPMEMORYSTATUSEX; typedef struct _SYSTEM_INFO SYSTEM_INFO, *LPSYSTEM_INFO; WINBASEAPI BOOL WINAPI GlobalMemoryStatusEx(LPMEMORYSTATUSEX lpBuffer); WINBASEAPI void WINAPI GetSystemInfo(LPSYSTEM_INFO lpSystemInfo); WINBASEAPI void WINAPI GetSystemTimeAsFileTime(LPFILETIME lpSystemTimeAsFileTime); WINBASEAPI void WINAPI GetSystemTimePreciseAsFileTime(LPFILETIME lpSystemTimeAsFileTime); WINBASEAPI DWORD WINAPI GetTickCount(void); WINBASEAPI ULONGLONG WINAPI GetTickCount64(void); // from timezoneapi.h WINBASEAPI BOOL WINAPI FileTimeToSystemTime(const FILETIME* lpFileTime, LPSYSTEMTIME lpSystemTime); // from libloaderapi.h WINBASEAPI FARPROC WINAPI GetProcAddress(HMODULE hModule, LPCSTR lpProcName); WINBASEAPI HMODULE WINAPI GetModuleHandleA(LPCSTR lpModuleName); WINBASEAPI HMODULE WINAPI GetModuleHandleW(LPCWSTR lpModuleName); #if defined(ISOLATION_AWARE_ENABLED) && ISOLATION_AWARE_ENABLED != 0 // LoadLibraryExW is #defined to be IsolationAwareLoadLibraryExW, which is an inline function in winbase.inl. That // function is not replicated here; if you need it, you need to either #include <Windows.h> or replicate the inline // function in your module or header file. #else WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); #endif WINBASEAPI BOOL WINAPI FreeLibrary(HMODULE hLibModule); WINBASEAPI BOOL WINAPI SetDefaultDllDirectories(DWORD DirectoryFlags); typedef PVOID DLL_DIRECTORY_COOKIE, *PDLL_DIRECTORY_COOKIE; WINBASEAPI BOOL WINAPI RemoveDllDirectory(DLL_DIRECTORY_COOKIE Cookie); #define CARBWIN_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR 0x00000100 #define CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000 WINBASEAPI BOOL WINAPI GetModuleHandleExW(DWORD dwFlags, LPCWSTR lpModuleName, HMODULE* phModule); #define CARBWIN_GET_MODULE_HANDLE_EX_FLAG_PIN (0x00000001) #define CARBWIN_GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT (0x00000002) #define CARBWIN_GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS (0x00000004) WINBASEAPI DWORD WINAPI GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize); WINBASEAPI DWORD WINAPI GetModuleFileNameW(HMODULE hModule, LPWSTR lpFilename, DWORD nSize); // from memoryapi.h WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCWSTR lpName); WINBASEAPI HANDLE WINAPI OpenFileMappingW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName); WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap); WINBASEAPI LPVOID WINAPI MapViewOfFileEx(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap, LPVOID lpBaseAddress); WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID lpBaseAddress); WINBASEAPI LPVOID WINAPI VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); WINBASEAPI BOOL WINAPI VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType); // from heapapi.h WINBASEAPI HANDLE WINAPI GetProcessHeap(void); // from fileapi.h WINBASEAPI BOOL WINAPI CreateDirectoryW(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); WINBASEAPI DWORD WINAPI GetFullPathNameW(LPCWSTR lpFileName, DWORD nBufferLength, LPWSTR lpBuffer, LPWSTR* lpFilePart); WINBASEAPI DWORD WINAPI GetFinalPathNameByHandleW(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags); WINBASEAPI HANDLE WINAPI CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); WINBASEAPI DWORD WINAPI GetFileAttributesW(LPCWSTR lpFileName); WINBASEAPI BOOL WINAPI LockFileEx(HANDLE hFile, DWORD dwFlags, DWORD dwReserved, DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh, LPOVERLAPPED lpOverlapped); WINBASEAPI BOOL WINAPI UnlockFileEx(HANDLE hFile, DWORD dwReserved, DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh, LPOVERLAPPED lpOverlapped); WINBASEAPI BOOL WINAPI DeleteFileA(LPCSTR lpFileName); WINBASEAPI BOOL WINAPI DeleteFileW(LPCWSTR lpFileName); WINBASEAPI BOOL WINAPI GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize); WINBASEAPI BOOL WINAPI WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped); WINBASEAPI BOOL WINAPI FlushFileBuffers(HANDLE hFile); // from profileapi.h WINBASEAPI BOOL WINAPI QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount); WINBASEAPI BOOL WINAPI QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency); /////////////////////////////////////////////////////////////////////////////// // Header files below are not include with Windows.h // from psapi.h typedef struct _PROCESS_MEMORY_COUNTERS PROCESS_MEMORY_COUNTERS, *PPROCESS_MEMORY_COUNTERS; BOOL WINAPI K32GetProcessMemoryInfo(HANDLE hProcess, PPROCESS_MEMORY_COUNTERS ppsmemCounters, DWORD cb); // from pathcch.h WINBASEAPI HRESULT APIENTRY PathAllocCanonicalize(PCWSTR pszPathIn, ULONG dwFlags, PWSTR* ppszPathOut); // from WinNls.h WINBASEAPI int WINAPI LCMapStringW(LCID Locale, DWORD dwMapFlags, LPCWSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest); // from userenv.h WINBASEAPI BOOL WINAPI GetUserProfileDirectoryW(HANDLE,LPWSTR,LPDWORD); #endif // NV_FORGE_WINDEF_H // Undef temporary defines #ifdef CARBWIN_WINBASEAPI_DEFINED #undef WINBASEAPI #undef CARBWIN_WINBASEAPI_DEFINED #endif #ifdef CARBWIN_WINAPI_DEFINED #undef WINAPI #undef CARBWIN_WINAPI_DEFINED #endif #ifdef CARBWIN_SHSTDAPI_DEFINED #undef SHSTDAPI #undef SHSTDAPI_ #undef CARBWIN_SHSTDAPI_DEFINED #endif #ifdef CARBWIN_APIENTRY_DEFINED #undef APIENTRY #undef CARBWIN_APIENTRY_DEFINED #endif #ifdef CARBWIN_WINADVAPI_DEFINED #undef WINADVAPI #undef CARBWIN_WINADVAPI_DEFINED #endif #ifdef __cplusplus } #endif #endif // clang-format on CARB_IGNOREWARNING_MSC_POP
30,582
C
41.183448
222
0.749264
omniverse-code/kit/include/carb/FrameworkBindingsPython.h
// Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "BindingsPythonUtils.h" #include "ClientUtils.h" #include "StartupUtils.h" #include "filesystem/IFileSystem.h" #include "logging/Logger.h" #include <memory> #include <string> #include <vector> namespace carb { namespace filesystem { struct File { }; } // namespace filesystem namespace detail { template <typename VT, typename T, size_t S> T getVectorValue(const VT& vector, size_t i) { if (i >= S) { throw py::index_error(); } const T* components = reinterpret_cast<const T*>(&vector); return components[i]; } template <typename VT, typename T, size_t S> void setVectorValue(VT& vector, size_t i, T value) { if (i >= S) { throw py::index_error(); } T* components = reinterpret_cast<T*>(&vector); components[i] = value; } template <typename VT, typename T, size_t S> py::list getVectorSlice(const VT& s, const py::slice& slice) { size_t start, stop, step, slicelength; if (!slice.compute(S, &start, &stop, &step, &slicelength)) throw py::error_already_set(); py::list returnList; for (size_t i = 0; i < slicelength; ++i) { returnList.append(getVectorValue<VT, T, S>(s, start)); start += step; } return returnList; } template <typename VT, typename T, size_t S> void setVectorSlice(VT& s, const py::slice& slice, const py::sequence& value) { size_t start, stop, step, slicelength; if (!slice.compute(S, &start, &stop, &step, &slicelength)) throw py::error_already_set(); if (slicelength != value.size()) throw std::runtime_error("Left and right hand size of slice assignment have different sizes!"); for (size_t i = 0; i < slicelength; ++i) { setVectorValue<VT, T, S>(s, start, value[i].cast<T>()); start += step; } } template <typename TupleT, class T, size_t S> py::class_<TupleT> defineTupleCommon(py::module& m, const char* name, const char* docstring) { py::class_<TupleT> c(m, name, docstring); c.def(py::init<>()); // Python special methods for iterators, [], len(): c.def("__len__", [](const TupleT& t) { CARB_UNUSED(t); return S; }); c.def("__getitem__", [](const TupleT& t, size_t i) { return getVectorValue<TupleT, T, S>(t, i); }); c.def("__setitem__", [](TupleT& t, size_t i, T v) { setVectorValue<TupleT, T, S>(t, i, v); }); c.def("__getitem__", [](const TupleT& t, py::slice slice) -> py::list { return getVectorSlice<TupleT, T, S>(t, slice); }); c.def("__setitem__", [](TupleT& t, py::slice slice, const py::sequence& value) { setVectorSlice<TupleT, T, S>(t, slice, value); }); // That allows passing python sequence into C++ function which accepts concrete TupleT: py::implicitly_convertible<py::sequence, TupleT>(); return c; } template <typename TupleT, class T> py::class_<TupleT> defineTuple(py::module& m, const char* typeName, const char* varName0, T TupleT::*var0, const char* varName1, T TupleT::*var1, const char* docstring = "") { py::class_<TupleT> c = detail::defineTupleCommon<TupleT, T, 2>(m, typeName, docstring); // Ctors: c.def(py::init<T, T>()); c.def(py::init([](py::sequence s) -> TupleT { return { s[0].cast<T>(), s[1].cast<T>() }; })); // Properties: c.def_readwrite(varName0, var0); c.def_readwrite(varName1, var1); // Formatting: c.def("__str__", [var0, var1](const TupleT& t) { return fmt::format("({},{})", t.*var0, t.*var1); }); c.def("__repr__", [typeName, var0, var1](const TupleT& t) { return fmt::format("carb.{}({},{})", typeName, t.*var0, t.*var1); }); // Pickling: c.def(py::pickle( // __getstate__ [var0, var1](const TupleT& t) { return py::make_tuple(t.*var0, t.*var1); }, // __setstate__ [](py::tuple t) { return TupleT{ t[0].cast<T>(), t[1].cast<T>() }; })); return c; } template <typename TupleT, class T> py::class_<TupleT> defineTuple(py::module& m, const char* typeName, const char* varName0, T TupleT::*var0, const char* varName1, T TupleT::*var1, const char* varName2, T TupleT::*var2, const char* docstring = "") { py::class_<TupleT> c = detail::defineTupleCommon<TupleT, T, 3>(m, typeName, docstring); // Ctors: c.def(py::init<T, T, T>()); c.def(py::init([](py::sequence s) -> TupleT { return { s[0].cast<T>(), s[1].cast<T>(), s[2].cast<T>() }; })); // Properties: c.def_readwrite(varName0, var0); c.def_readwrite(varName1, var1); c.def_readwrite(varName2, var2); // Formatting: c.def("__str__", [var0, var1, var2](const TupleT& t) { return fmt::format("({},{},{})", t.*var0, t.*var1, t.*var2); }); c.def("__repr__", [typeName, var0, var1, var2](const TupleT& t) { return fmt::format("carb.{}({},{},{})", typeName, t.*var0, t.*var1, t.*var2); }); // Pickling: c.def(py::pickle( // __getstate__ [var0, var1, var2](const TupleT& t) { return py::make_tuple(t.*var0, t.*var1, t.*var2); }, // __setstate__ [](py::tuple t) { return TupleT{ t[0].cast<T>(), t[1].cast<T>(), t[2].cast<T>() }; })); return c; } template <typename TupleT, class T> py::class_<TupleT> defineTuple(py::module& m, const char* type, const char* varName0, T TupleT::*var0, const char* varName1, T TupleT::*var1, const char* varName2, T TupleT::*var2, const char* varName3, T TupleT::*var3, const char* docstring = "") { py::class_<TupleT> c = detail::defineTupleCommon<TupleT, T, 4>(m, type, docstring); // Ctors: c.def(py::init<T, T, T, T>()); c.def(py::init([](py::sequence s) -> TupleT { return { s[0].cast<T>(), s[1].cast<T>(), s[2].cast<T>(), s[3].cast<T>() }; })); // Properties: c.def_readwrite(varName0, var0); c.def_readwrite(varName1, var1); c.def_readwrite(varName2, var2); c.def_readwrite(varName3, var3); // Formatting: c.def("__str__", [var0, var1, var2, var3](const TupleT& t) { return fmt::format("({},{},{},{})", t.*var0, t.*var1, t.*var2, t.*var3); }); c.def("__repr__", [type, var0, var1, var2, var3](const TupleT& t) { return fmt::format("carb.{}({},{},{},{})", type, t.*var0, t.*var1, t.*var2, t.*var3); }); // Pickling: c.def(py::pickle( // __getstate__ [var0, var1, var2, var3](const TupleT& t) { return py::make_tuple(t.*var0, t.*var1, t.*var2, t.*var3); }, // __setstate__ [](py::tuple t) { return TupleT{ t[0].cast<T>(), t[1].cast<T>(), t[2].cast<T>(), t[3].cast<T>() }; })); return c; } static void log( const char* source, int32_t level, const char* fileName, const char* functionName, int lineNumber, const char* message) { if (g_carbLogFn && g_carbLogLevel <= level) { g_carbLogFn(source, level, fileName, functionName, lineNumber, "%s", message); } } } // namespace detail inline void definePythonModule(py::module& m) { //////// Common //////// using namespace carb::detail; defineTuple<Float2>(m, "Float2", "x", &Float2::x, "y", &Float2::y, R"( Pair of floating point values. These can be accessed via the named attributes, `x` & `y`, but also support sequence access, making them work where a list or tuple is expected. >>> f = carb.Float2(1.0, 2.0) >>> f[0] 1.0 >>> f.y 2.0 )"); defineTuple<Float3>( m, "Float3", "x", &Float3::x, "y", &Float3::y, "z", &Float3::z, R"(A triplet of floating point values. These can be accessed via the named attributes, `x`, `y` & `z`, but also support sequence access, making them work where a list or tuple is expected. >>> v = [1, 2, 3] f = carb.Float3(v) >>> f[0] 1.0 >>> f.y 2.0 >>> f[2] 3.0 )"); defineTuple<Float4>( m, "Float4", "x", &Float4::x, "y", &Float4::y, "z", &Float4::z, "w", &Float4::w, R"(A quadruplet of floating point values. These can be accessed via the named attributes, `x`, `y`, `z` & `w`, but also support sequence access, making them work where a list or tuple is expected. >>> v = [1, 2, 3, 4] f = carb.Float4(v) >>> f[0] 1.0 >>> f.y 2.0 >>> f[2] 3.0 >>> f.w 4.0 )"); defineTuple<Int2>(m, "Int2", "x", &Int2::x, "y", &Int2::y); defineTuple<Int3>(m, "Int3", "x", &Int3::x, "y", &Int3::y, "z", &Int3::z); defineTuple<Int4>(m, "Int4", "x", &Int4::x, "y", &Int4::y, "z", &Int4::z, "w", &Int4::w); defineTuple<Uint2>(m, "Uint2", "x", &Uint2::x, "y", &Uint2::y); defineTuple<Uint3>(m, "Uint3", "x", &Uint3::x, "y", &Uint3::y, "z", &Uint3::z); defineTuple<Uint4>(m, "Uint4", "x", &Uint4::x, "y", &Uint4::y, "z", &Uint4::z, "w", &Uint4::w); defineTuple<Double2>(m, "Double2", "x", &Double2::x, "y", &Double2::y); defineTuple<Double3>(m, "Double3", "x", &Double3::x, "y", &Double3::y, "z", &Double3::z); defineTuple<Double4>(m, "Double4", "x", &Double4::x, "y", &Double4::y, "z", &Double4::z, "w", &Double4::w); defineTuple<ColorRgb>(m, "ColorRgb", "r", &ColorRgb::r, "g", &ColorRgb::g, "b", &ColorRgb::b); defineTuple<ColorRgbDouble>( m, "ColorRgbDouble", "r", &ColorRgbDouble::r, "g", &ColorRgbDouble::g, "b", &ColorRgbDouble::b); defineTuple<ColorRgba>( m, "ColorRgba", "r", &ColorRgba::r, "g", &ColorRgba::g, "b", &ColorRgba::b, "a", &ColorRgba::a); defineTuple<ColorRgbaDouble>(m, "ColorRgbaDouble", "r", &ColorRgbaDouble::r, "g", &ColorRgbaDouble::g, "b", &ColorRgbaDouble::b, "a", &ColorRgbaDouble::a); //////// Python Utils //////// py::class_<Subscription, std::shared_ptr<Subscription>>(m, "Subscription", R"( Subscription holder. This object is returned by different subscription functions. Subscription lifetime is associated with this object. You can it while you need subscribed callback to be called. Then you can explicitly make it equal to `None` or call `unsubscribe` method or `del` it to unsubscribe. Quite common patter of usage is when you have a class which subscribes to various callbacks and you want to subscription to stay valid while class instance is alive. .. code-block:: python class Foo: def __init__(self): events = carb.events.get_events_interface() stream = events.create_event_stream() self._event_sub = stream.subscribe_to_pop(0, self._on_event) def _on_event(self, e): print(f'event {e}') >>> f = Foo() >>> # f receives some events >>> f._event_sub = None >>> f = None )") .def(py::init([](std::function<void()> unsubscribeFn) { return std::make_shared<Subscription>(wrapPythonCallback(std::move(unsubscribeFn))); })) .def("unsubscribe", &Subscription::unsubscribe); //////// ILogging //////// m.def("log", detail::log, py::arg("source"), py::arg("level"), py::arg("fileName"), py::arg("functionName"), py::arg("lineNumber"), py::arg("message")); py::module loggingModule = m.def_submodule("logging"); { py::enum_<logging::LogSettingBehavior>(loggingModule, "LogSettingBehavior") .value("INHERIT", logging::LogSettingBehavior::eInherit) .value("OVERRIDE", logging::LogSettingBehavior::eOverride); using LogFn = std::function<void(const char*, int32_t, const char*, int, const char*)>; struct PyLogger : public logging::Logger { LogFn logFn; }; static std::unordered_map<PyLogger*, std::shared_ptr<PyLogger>> s_loggers; py::class_<PyLogger>(loggingModule, "LoggerHandle"); defineInterfaceClass<logging::ILogging>(loggingModule, "ILogging", "acquire_logging") .def("set_level_threshold", wrapInterfaceFunction(&logging::ILogging::setLevelThreshold)) .def("get_level_threshold", wrapInterfaceFunction(&logging::ILogging::getLevelThreshold)) .def("set_log_enabled", wrapInterfaceFunction(&logging::ILogging::setLogEnabled)) .def("is_log_enabled", wrapInterfaceFunction(&logging::ILogging::isLogEnabled)) .def("set_level_threshold_for_source", wrapInterfaceFunction(&logging::ILogging::setLevelThresholdForSource)) .def("set_log_enabled_for_source", wrapInterfaceFunction(&logging::ILogging::setLogEnabledForSource)) .def("reset", wrapInterfaceFunction(&logging::ILogging::reset)) .def("add_logger", [](const logging::ILogging* ls, const LogFn& logFn) { auto logger = std::make_shared<PyLogger>(); logger->logFn = logFn; s_loggers[logger.get()] = logger; logger->handleMessage = [](logging::Logger* logger, const char* source, int32_t level, const char* filename, const char* functionName, int lineNumber, const char* message) { CARB_UNUSED(functionName); (static_cast<PyLogger*>(logger)->logFn)(source, level, filename, lineNumber, message); }; ls->addLogger(logger.get()); return logger.get(); }, py::return_value_policy::reference) .def("remove_logger", [](const logging::ILogging* ls, PyLogger* logger) { auto it = s_loggers.find(logger); if (it != s_loggers.end()) { ls->removeLogger(it->second.get()); s_loggers.erase(it); } else { CARB_LOG_ERROR("remove_logger: wrong Logger Handle"); } }); loggingModule.attr("LEVEL_VERBOSE") = py::int_(logging::kLevelVerbose); loggingModule.attr("LEVEL_INFO") = py::int_(logging::kLevelInfo); loggingModule.attr("LEVEL_WARN") = py::int_(logging::kLevelWarn); loggingModule.attr("LEVEL_ERROR") = py::int_(logging::kLevelError); loggingModule.attr("LEVEL_FATAL") = py::int_(logging::kLevelFatal); } //////// IFileSystem //////// py::module filesystemModule = m.def_submodule("filesystem"); { using namespace filesystem; py::class_<filesystem::File>(filesystemModule, "File"); py::enum_<DirectoryItemType>(filesystemModule, "DirectoryItemType") .value("FILE", DirectoryItemType::eFile) .value("DIRECTORY", DirectoryItemType::eDirectory); defineInterfaceClass<IFileSystem>(filesystemModule, "IFileSystem", "acquire_filesystem") .def("get_current_directory_path", wrapInterfaceFunction(&IFileSystem::getCurrentDirectoryPath)) .def("set_current_directory_path", wrapInterfaceFunction(&IFileSystem::setCurrentDirectoryPath)) .def("get_app_directory_path", wrapInterfaceFunction(&IFileSystem::getAppDirectoryPath)) .def("set_app_directory_path", wrapInterfaceFunction(&IFileSystem::setAppDirectoryPath)) .def("exists", wrapInterfaceFunction(&IFileSystem::exists)) .def("is_directory", wrapInterfaceFunction(&IFileSystem::isDirectory)) .def("open_file_to_read", wrapInterfaceFunction(&IFileSystem::openFileToRead), py::return_value_policy::reference) .def("open_file_to_write", wrapInterfaceFunction(&IFileSystem::openFileToWrite), py::return_value_policy::reference) .def("open_file_to_append", wrapInterfaceFunction(&IFileSystem::openFileToAppend), py::return_value_policy::reference) .def("close_file", wrapInterfaceFunction(&IFileSystem::closeFile)) .def("get_file_size", wrapInterfaceFunction(&IFileSystem::getFileSize)) //.def("get_file_mod_time", wrapInterfaceFunction(&IFileSystem::getFileModTime)) .def("get_mod_time", wrapInterfaceFunction(&IFileSystem::getModTime)) //.def("read_file_chunk", wrapInterfaceFunction(&IFileSystem::readFileChunk)) //.def("write_file_chunk", wrapInterfaceFunction(&IFileSystem::writeFileChunk)) //.def("read_file_line", wrapInterfaceFunction(&IFileSystem::readFileLine)) //.def("write_file_line", wrapInterfaceFunction(&IFileSystem::writeFileLine)) .def("flush_file", wrapInterfaceFunction(&IFileSystem::flushFile)) .def("make_temp_directory", [](IFileSystem* iface) -> py::object { char buffer[1024]; if (iface->makeTempDirectory(buffer, CARB_COUNTOF(buffer))) { return py::str(std::string(buffer)); } return py::none(); }) .def("make_directory", wrapInterfaceFunction(&IFileSystem::makeDirectory)) .def("remove_directory", wrapInterfaceFunction(&IFileSystem::removeDirectory)) .def("copy", wrapInterfaceFunction(&IFileSystem::copy)) //.def("for_each_directory_item", wrapInterfaceFunction(&IFileSystem::forEachDirectoryItem)) //.def("for_each_directory_item_recursive", wrapInterfaceFunction( //&IFileSystem::forEachDirectoryItemRecursive)) // .def("subscribe_to_change_events", wrapInterfaceFunction( //&IFileSystem::createChangeSubscription)) .def("unsubscribe_to_change_events", wrapInterfaceFunction( //&IFileSystem::destroyChangeSubscription)) ; } //////// Framework //////// py::enum_<PluginHotReload>(m, "PluginHotReload") .value("DISABLED", PluginHotReload::eDisabled) .value("ENABLED", PluginHotReload::eEnabled); py::class_<PluginImplDesc>(m, "PluginImplDesc") .def_readonly("name", &PluginImplDesc::name) .def_readonly("description", &PluginImplDesc::description) .def_readonly("author", &PluginImplDesc::author) .def_readonly("hotReload", &PluginImplDesc::hotReload) .def_readonly("build", &PluginImplDesc::build); py::class_<Version>(m, "Version") .def(py::init<>()) .def(py::init<uint32_t, uint32_t>()) .def_readonly("major", &Version::major) .def_readonly("minor", &Version::minor) .def("__repr__", [](const Version& v) { return fmt::format("v{}.{}", v.major, v.minor); }); py::class_<InterfaceDesc>(m, "InterfaceDesc") .def_readonly("name", &InterfaceDesc::name) .def_readonly("version", &InterfaceDesc::version) .def("__repr__", [](const InterfaceDesc& d) { return fmt::format("\"{} v{}.{}\"", d.name, d.version.major, d.version.minor); }); py::class_<PluginDesc>(m, "PluginDesc") .def_readonly("impl", &PluginDesc::impl) .def_property_readonly("interfaces", [](const PluginDesc& d) { return std::vector<InterfaceDesc>(d.interfaces, d.interfaces + d.interfaceCount); }) .def_property_readonly("dependencies", [](const PluginDesc& d) { return std::vector<InterfaceDesc>(d.dependencies, d.dependencies + d.dependencyCount); }) .def_readonly("libPath", &PluginDesc::libPath); m.def("get_framework", []() { return getFramework(); }, py::return_value_policy::reference); py::class_<Framework>(m, "Framework") .def("startup", [](const Framework* framework, std::vector<std::string> argv, const char* config, std::vector<std::string> initialPluginsSearchPaths, const char* configFormat) { CARB_UNUSED(framework); std::vector<char*> argv_(argv.size()); for (size_t i = 0; i < argv.size(); i++) { argv_[i] = (char*)argv[i].c_str(); } std::vector<char*> initialPluginsSearchPaths_(initialPluginsSearchPaths.size()); for (size_t i = 0; i < initialPluginsSearchPaths.size(); i++) { initialPluginsSearchPaths_[i] = (char*)initialPluginsSearchPaths[i].c_str(); } carb::StartupFrameworkDesc startupParams = carb::StartupFrameworkDesc::getDefault(); startupParams.configString = config; startupParams.argv = argv_.size() ? argv_.data() : nullptr; startupParams.argc = static_cast<int>(argv_.size()); startupParams.initialPluginsSearchPaths = initialPluginsSearchPaths_.size() ? initialPluginsSearchPaths_.data() : nullptr; startupParams.initialPluginsSearchPathCount = initialPluginsSearchPaths_.size(); startupParams.configFormat = configFormat; startupFramework(startupParams); }, py::arg("argv") = std::vector<std::string>(), py::arg("config") = nullptr, py::arg("initial_plugins_search_paths") = std::vector<std::string>(), py::arg("config_format") = "toml") .def("load_plugins", [](const Framework* framework, std::vector<std::string> loadedFileWildcards, std::vector<std::string> searchPaths) { std::vector<const char*> loadedFileWildcards_(loadedFileWildcards.size()); for (size_t i = 0; i < loadedFileWildcards.size(); i++) { loadedFileWildcards_[i] = loadedFileWildcards[i].c_str(); } std::vector<const char*> searchPaths_(searchPaths.size()); for (size_t i = 0; i < searchPaths.size(); i++) { searchPaths_[i] = searchPaths[i].c_str(); } carb::PluginLoadingDesc desc = carb::PluginLoadingDesc::getDefault(); desc.loadedFileWildcardCount = loadedFileWildcards_.size(); desc.loadedFileWildcards = loadedFileWildcards_.data(); if (searchPaths_.size() > 0) { desc.searchPathCount = searchPaths_.size(); desc.searchPaths = searchPaths_.data(); } framework->loadPluginsEx(desc); }, py::arg("loaded_file_wildcards") = std::vector<std::string>(), py::arg("search_paths") = std::vector<std::string>()) .def("unload_all_plugins", wrapInterfaceFunction(&Framework::unloadAllPlugins)) .def("get_plugins", [](const Framework* framework) { std::vector<PluginDesc> plugins(framework->getPluginCount()); framework->getPlugins(plugins.data()); return plugins; }) .def("try_reload_plugins", wrapInterfaceFunction(&Framework::tryReloadPlugins)); py::options options; // options.disable_function_signatures(); m.def("answer_question", [](const char* message) { CARB_UNUSED(message); return std::string("blarg"); }, py::arg("question"), R"( This function can answer some questions. It currently only answers a limited set of questions so don't expect it to know everything. Args: question: The question passed to the function, trailing question mark is not necessary and casing is not important. Returns: The answer to the question or empty string if it doesn't know the answer.)"); } } // namespace carb
25,252
C
40.534539
173
0.556708
omniverse-code/kit/include/carb/extras/Base64.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /** @file * @brief Provides a Base64 encoding and decoding helper class. */ #pragma once #include <stdint.h> #include <string.h> /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { /** Encoder and decoder helper for Base64 data. This allows for processing Base64 data in multiple * different standard and non-standard variants of the algorithm, plus custom encodings. Padding * bytes are always optional but will be generated by default by all non-custom variants. A * custom variant without padding bytes can be specified by setting the padding byte to 0. No * data verification is done on decoded data - that is left up to the caller. Any invalid input * data is simply ignored. */ class Base64 { public: /** Special value for the @a size parameters to encode() and decode() to indicate that the * input data buffer is a null terminated string. This is only safe on encode() if the * input to be encoded is known to be a standard C string. If binary data is provided * to be encoded, an explicit size must always be given. On decode(), this value should * only be used if the encoded data being passed as input is known to be null terminated. * encoded data produced by this object will always be null terminated. */ static constexpr size_t kNullTerminated = ~0ull; /** Various variants of the Base64 algorithm. The only differences these cause in the * generated encoded data are in the bytes used for the values 62 and 63, as well as * the padding byte. All other encoded values will always use A-Z, a-z, and 0-9. The * correct variant must also be known ahead of time when decoding data. No auto-detection * on the input data will be done. For most applications, the @ref Variant::eDefault * and @ref Variant::eFilenameSafe variants should be the most useful. */ enum class Variant { eDefault, ///< Default encoding set. ePem, ///< Encoding set for privacy-enhanced mail (RFC 1421, deprecated). eMime, ///< Encoding set for standard MIME Base64 (RFC 2045). eRfc4648, ///< Encoding set for RFC 4648. eFilenameSafe, ///< Encoding set for URL and filename safe Base64 (RFC 4648, section 5). eOpenPgp, ///< Encoding set for OpenPGP (RFC 4880). eUtf7, ///< Encoding set for UTF-7 (RFC 2152). eImap, ///< Encoding set for IMAP mailbox names (RFC 3501). eYui, ///< Encoding set for Y64 URL-sage Base64 from the YUI library. eProgramId1, ///< Encoding set for Program identifier Base64 variant 1 (non-standard). eProgramId2, ///< Encoding set for Program identifier Base64 variant 2 (non-standard). eFreenetUrl, ///< Encoding set for Freenet URL-safe Base64 (non-standard). }; /** Constructor: creates a new object supporting the default Base64 encoding. */ Base64() : Base64(Variant::eDefault) { } /** Constructor: creates a new object supporting a specific known Base64 encoding. * * @param[in] variant The algorithm variant to use. This controls which additional two * encoding bytes and which padding byte will be used. The variant * specifics about line lengths, checksums, and optional versus * mandatory padding will be ignored. */ Base64(Variant variant) { switch (variant) { default: case Variant::eDefault: case Variant::ePem: case Variant::eMime: case Variant::eRfc4648: case Variant::eOpenPgp: case Variant::eUtf7: initCodec('+', '/', '='); break; case Variant::eFilenameSafe: initCodec('-', '_', '='); break; case Variant::eImap: initCodec('+', ',', '='); break; case Variant::eYui: initCodec('.', '_', '-'); break; case Variant::eProgramId1: initCodec('_', '-', '='); break; case Variant::eProgramId2: initCodec('.', '_', '='); break; case Variant::eFreenetUrl: initCodec('~', '-', '='); break; } } /** Constructor: creates a new object supporting a custom Base64 encoding. * * @param[in] byte62 The byte that will be used to represent the encoding for the value * 62 (0x3e). This may be any non-zero byte outside of the ranges * [A-Z, a-z, 0-9]. This may not be equal to @p byte63 or @p padding. * @param[in] byte63 The byte that will be used to represent the encoding for the value * 63 (0x3f). This may be any non-zero byte outside of the ranges * [A-Z, a-z, 0-9]. This may not be equal to @p byte62 or @p padding. * @param[in] padding The padding byte to use at the end of an encoded block to identify * an unaligned block. This may be 0 to indicate that no specific * padding byte is used. This may not be equal to @p byte62 or * @p byte63 and must not be in the range [A-Z, a-z, 0-9]. The usual * padding byte for this value in most variants is '='. This defaults * to 0. */ Base64(uint8_t byte62, uint8_t byte63, uint8_t padding = 0) { initCodec(byte62, byte63, padding); } /** Calculates the required output size for encoding a given number of bytes. * * @param[in] inputSize The size of the input buffer in bytes. This may not be 0. * @returns The number of bytes required to store the encoded data for the given input * size. This will always include space for a null terminator byte so that the * encoded data can always be treated as a C string for further processing. * The actual size of the encoded data should always come from the value returned * by encode(). */ static size_t getEncodeOutputSize(size_t inputSize) { return 4 * ((inputSize + 2) / 3) + 1; } /** Calculates the require input buffer size for a given output buffer length. * @param[in] outputSize The size of the output to write. * @returns The number of bytes that needs to be input to produce a given * output size without padding. * This is useful if you want to split up a base64 encode across * multiple buffers. Breaking up the input into a series of chunks * of this size will allow the output base64 chunks to be * concatenated together without creating an invalid base64 string. */ static size_t getEncodeInputSize(size_t outputSize) { return ((outputSize - 1) / 4 * 3) / 3 * 3; } /** Calculates the required output size for decoding a given number of bytes. * * @param[in] inputSize The size of the input buffer in bytes. This may not be 0. * @returns The number of bytes required to store the decoded data for the given input * size. This may include some extra space depending on whether the input * buffer is null terminated or not. The actual size of the decoded data * should always come from the value returned by decode(). */ static size_t getDecodeOutputSize(size_t inputSize) { return 3 * ((inputSize + 3) / 4); } /** Encodes a block of binary data into Base64. * * @param[in] buffer The input buffer to be encoded. This may not be `nullptr`. * @param[in] size The size of the input buffer in bytes. This may not be `0`. This may * be @ref kNullTerminated to indicate that the input data is a null * terminated C string. The actual length of the input will be * calculated by finding the length of the string. * @param[out] output Receives the encoded output as long as it is large enough to contain * the entire encoded output. No work will be done if the output buffer * is not large enough. Encoding into the same buffer as @p buffer is * not safe since the input data will be overwritten as it is processed * resulting in a corrupted encoding. This output buffer will always * be null terminated so that the output data can be processed as a * standard C string. * @param[in] maxOut The size of the output buffer in bytes. This may be larger than is * strictly required by the encoding operation. This must be large * enough to hold the entire encoded result. * @returns The number of bytes of encoded data written to the output buffer, not including * the null terminator. Note that this byte count may not be aligned to a multiple * of 4 if padding is ignored (ie: this object was initialized to use a padding byte * of 0). * @returns `0` if the output buffer is not large enough to hold the full encoded output. * * @note If the encoded data block is expected to be transmitted to a generic destination * (ie: one not controlled by this process or something related to it), the caller * is responsible for ensuring that the data can be properly interpreted by the * receiver regardless of endianness. Since base64 encoding simply sees the block * of data as a simple string of bytes, it has no knowledge of any internal structure * and can therefore not properly do an kind of network byte order swapping. The * caller would be the one with the knowledge of internal structure and should * byte swap the incoming data as needed before attempting to encode it. */ size_t encode(const void* buffer, size_t size, char* output, size_t maxOut) { uint32_t data; size_t j = 0; size_t stop; size_t extra; size_t paddingCount = (m_padding == 0) ? 0 : 1; // null terminated C string input data => calculate its length. if (size == kNullTerminated) size = strlen(reinterpret_cast<const char*>(buffer)); // the output buffer is not large enough => fail. if (maxOut < getEncodeOutputSize(size)) return 0; // calculate the number of input bytes that can be bulk processed. stop = (size / 3) * 3; extra = size - stop; // bulk process all aligned input bytes. Each three byte input block will produce // four output bytes. for (size_t i = 0; i < stop; i += 3) { data = (reinterpret_cast<const uint8_t*>(buffer)[i + 0] << 16) | (reinterpret_cast<const uint8_t*>(buffer)[i + 1] << 8) | (reinterpret_cast<const uint8_t*>(buffer)[i + 2] << 0); output[j + 0] = m_encode[(data >> 18) & 0x3f]; output[j + 1] = m_encode[(data >> 12) & 0x3f]; output[j + 2] = m_encode[(data >> 6) & 0x3f]; output[j + 3] = m_encode[(data >> 0) & 0x3f]; j += 4; } // process any remaining bytes. Note that a value of 0 indicates that the original // input data was a multiple of 3 bytes and no unaligned data needs to be processed. switch (extra) { // one extra unaligned input byte was provided. This will produce two output bytes // followed by two padding bytes. case 1: data = reinterpret_cast<const uint8_t*>(buffer)[stop + 0] << 16; output[j + 0] = m_encode[(data >> 18) & 0x3f]; output[j + 1] = m_encode[(data >> 12) & 0x3f]; output[j + 2] = m_padding; output[j + 3] = m_padding; j += 2 + (paddingCount * 2); break; // two extra unaligned input bytes were provided. This will produce three output // bytes followed by one padding byte. case 2: data = (reinterpret_cast<const uint8_t*>(buffer)[stop + 0] << 16) | (reinterpret_cast<const uint8_t*>(buffer)[stop + 1] << 8); output[j + 0] = m_encode[(data >> 18) & 0x3f]; output[j + 1] = m_encode[(data >> 12) & 0x3f]; output[j + 2] = m_encode[(data >> 6) & 0x3f]; output[j + 3] = m_padding; j += 3 + paddingCount; break; // another count of destination characters (!?) -> should never happen for any value // other than 0 => ignore it. default: break; } // always null terminate the output buffer so that it can be treated as a C string by // the caller. output[j] = 0; return j; } /** Decodes a block of binary data from Base64. * * @param[in] buffer The input buffer to be decoded. This may not be `nullptr`. This * buffer may be optionally null terminated. * @param[in] size The size of the input buffer in bytes. This may not be `0`. This may * be @ref kNullTerminated to indicate that the input buffer is a null * terminated C string. In this case, the length of the input buffer * will be calculated as the length of the string. * @param[out] output Receives the decoded data as long as it is large enough to contain * the entire decoded output. No work will be done if the output buffer * is not large enough. Decoding into the same buffer as @p buffer is * safe since the input data will be always be longer than the output. * No null terminator or extra data will ever be written to the decoded * data buffer. * @param[in] maxOut The size of the output buffer in bytes. This may be larger than is * strictly required by the decoding operation. This must be large * enough to hold the entire decoded result. * @returns The number of bytes of decoded data written to the output buffer. Note that * this byte count will not have a particular alignment and will always match * that of the original encoded data exactly. * @returns `0` if the output buffer is not large enough to hold the full decoded output. * * @note This will decode the block exactly as it was encoded and assuming a little endian * byte ordering. Since base64 always treats the data block as a simple string of * bytes, the caller is responsible for doing any kind of endianness checks and * byte swapping as necessary after decoding. */ size_t decode(const char* buffer, size_t size, void* output, size_t maxOut) { uint32_t data; size_t j = 0; size_t stop; size_t extra; uint8_t* out = reinterpret_cast<uint8_t*>(output); // the input buffer is a null terminated C string => calculate its length. if (size == kNullTerminated) size = strlen(reinterpret_cast<const char*>(buffer)); // the output buffer is not large enough => fail. if (maxOut < getDecodeOutputSize(size)) return 0; // invalid encoding length -> decodes to less than 1 byte => fail. if (size < 2) return 0; // calculate the number of input bytes that can be bulk processed. extra = size & 3; stop = size - extra; // no extra unaligned input bytes were provided -> the input buffer is actually aligned // or it contains padding bytes => determine which one is correct and adjust sizes. if (extra == 0) { // two padding bytes were specified => produces one byte in the last block. if (buffer[size - 2] == m_padding) { extra = 2; stop -= 4; } // one padding byte was specified => produces two bytes in the last block. else if (buffer[size - 1] == m_padding) { extra = 3; stop -= 4; } // at this point, we know the input is either block aligned or is corrupt. Either // way we don't care and will just continue decoding. It is left up to the caller // to verify the validity of the decoded data. All we are interested in here is // the actual decoding process. } // bulk process the aligned input data. Each four byte block will produce three output // bytes. for (size_t i = 0; i < stop; i += 4) { data = (m_decode[static_cast<size_t>(buffer[i + 0])] << 18) | (m_decode[static_cast<size_t>(buffer[i + 1])] << 12) | (m_decode[static_cast<size_t>(buffer[i + 2])] << 6) | (m_decode[static_cast<size_t>(buffer[i + 3])] << 0); out[j + 0] = (data >> 16) & 0xff; out[j + 1] = (data >> 8) & 0xff; out[j + 2] = (data >> 0) & 0xff; j += 3; } // process any extra unaligned bytes. This will allow extra or optional padding bytes to // be ignored in the input buffer. switch (extra) { // two extra bytes (plus two optional padding bytes) were provided. This produces one // output byte. case 2: data = (m_decode[static_cast<size_t>(buffer[stop + 0])] << 18) | (m_decode[static_cast<size_t>(buffer[stop + 1])] << 12); out[j + 0] = (data >> 16) & 0xff; j += 1; break; // three extra bytes (plus one optional padding byte) were provided. This produces two // output bytes. case 3: data = (m_decode[static_cast<size_t>(buffer[stop + 0])] << 18) | (m_decode[static_cast<size_t>(buffer[stop + 1])] << 12) | (m_decode[static_cast<size_t>(buffer[stop + 2])] << 6); out[j + 0] = (data >> 16) & 0xff; out[j + 1] = (data >> 8) & 0xff; j += 2; break; // invalid 'extra' count (!?) or no extra bytes => fail. default: break; } // return the number of decoded bytes. return j; } private: /** Initializes the encoding and decoding tables for this object. * * @param[in] char62 The byte that will be used to represent the encoding for the value * 62 (0x3e). This may be any non-zero byte outside of the ranges * [A-Z, a-z, 0-9]. This may not be equal to @p byte63 or @p padding. * @param[in] char63 The byte that will be used to represent the encoding for the value * 63 (0x3f). This may be any non-zero byte outside of the ranges * [A-Z, a-z, 0-9]. This may not be equal to @p byte62 or @p padding. * @param[in] padding The padding byte to use at the end of an encoded block to identify * an unaligned block. This may be 0 to indicate that no specific * padding byte is used. This may not be equal to @p byte62 or * @p byte63 and must not be in the range [A-Z, a-z, 0-9]. The usual * padding byte for this value in most variants is '='. This defaults * to 0. * @returns No return value. */ void initCodec(uint8_t char62, uint8_t char63, uint8_t padding) { // generate the encoding map. for (size_t i = 0; i < 26; i++) { m_encode[i] = ('A' + i) & 0xff; m_encode[i + 26] = ('a' + i) & 0xff; } for (size_t i = 0; i < 10; i++) m_encode[i + 52] = ('0' + i) & 0xff; m_encode[62] = char62; m_encode[63] = char63; // generate the decoding map as a the reverse of the encoding table. memset(m_decode, 0, sizeof(m_decode)); for (size_t i = 0; i < 64; i++) m_decode[static_cast<size_t>(m_encode[i])] = i & 0xff; // store the padding byte. Note that the padding byte does not need to be part of the // decoding table since it will never be decoded. m_padding = padding; } /** The encoding table for this object. This specifies all possible encoding values for each * of the 64 input data bytes. */ char m_encode[64]; /** The decoding table for this object. This specifies the decoded bit patterns for all * possible encoded input bytes. This table will contain a zero for all invalid input * bytes. */ char m_decode[256]; /** The padding byte used by this object. This will be 0 to indicate that no padding * bytes will be generated (on encode) or expected (on decode). */ char m_padding; }; } // namespace extras } // namespace carb
22,367
C
45.794979
99
0.572138
omniverse-code/kit/include/carb/extras/MultiFreeListAllocator.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 "../Defines.h" #include "../logging/Log.h" #include "FreeListAllocator.h" #include <cstring> namespace carb { namespace extras { /** * Defines a free list that can allocate/deallocate fast and in any order from identically sized blocks. * * As long as every deallocation matches every allocation. Both allocation and deallocation are O(1) and * generally just a few instructions. The underlying memory allocator will allocate in large blocks, * with multiple elements amortizing a more costly large allocation against lots of fast small element allocations. */ class MultiFreeListAllocator { public: struct AllocDesc { size_t elementSize; size_t elementsPerBlock; }; /** * Constructor. */ MultiFreeListAllocator() { } /** * Destructor. */ ~MultiFreeListAllocator() { shutdown(); } void startup(AllocDesc* allocatorDescs, size_t allocatorCount) { // First, count the free list allocator descriptors m_freeListAllocDescs = new FreeListAllocInternalDesc[allocatorCount]; m_freeListAllocCount = static_cast<uint32_t>(allocatorCount); // Setup allocators for (uint32_t i = 0; i < m_freeListAllocCount; ++i) { size_t elemSize = CARB_ALIGNED_SIZE(allocatorDescs[i].elementSize, FreeListAllocator::kMinimalAlignment); size_t elemPerBlock = (allocatorDescs[i].elementsPerBlock == kElementsPerBlockAuto) ? kDefaultElementsPerBlock : allocatorDescs[i].elementsPerBlock; m_freeListAllocDescs[i].pureElemSize = elemSize; m_freeListAllocDescs[i].allocator.initialize(elemSize, 0, elemPerBlock); } } void shutdown() { delete[] m_freeListAllocDescs; m_freeListAllocDescs = nullptr; m_freeListAllocCount = 0; } void* allocate(size_t size) { uint8_t* originalChunk = nullptr; // Calculate total prefix size size_t prefixSize = sizeof(ChunkSizePrefixType) + sizeof(ChunkOffsetPrefixType); // Chunk size includes prefixes and the requested chunk size size_t originalChunkSize = prefixSize + size; // Get suitable allocator index based on the total chunk size uint32_t allocatorIndex = _getAllocatorIndexFromSize(originalChunkSize); if (allocatorIndex != kNoSuitableAllocator) { originalChunk = static_cast<uint8_t*>(m_freeListAllocDescs[allocatorIndex].allocator.allocate()); } else { originalChunk = static_cast<uint8_t*>(CARB_MALLOC(originalChunkSize)); } if (originalChunk == nullptr) { CARB_LOG_ERROR("Failed to allocate memory!"); return nullptr; } size_t ptrOffset = prefixSize; // Calculate final chunk address, so that prefix could be inserted uint8_t* extChunk = ptrOffset + originalChunk; // Record chunk size requested from the underlying allocator ChunkSizePrefixType* chunkSizeMem = reinterpret_cast<ChunkSizePrefixType*>(extChunk) - 1; *chunkSizeMem = static_cast<ChunkSizePrefixType>(originalChunkSize); // Record the offset from the returned memory pointer to the allocated memory chunk ChunkOffsetPrefixType* chunkOffsetMem = reinterpret_cast<ChunkOffsetPrefixType*>(chunkSizeMem) - 1; *chunkOffsetMem = static_cast<ChunkOffsetPrefixType>(ptrOffset); return extChunk; } void* allocateAligned(size_t size, size_t alignment) { // With zero alignment, call regular allocation if (alignment == 0) return allocate(size); uint8_t* originalChunk = nullptr; // Calculate aligned memory slot size for prefixes size_t prefixSize = sizeof(ChunkSizePrefixType) + sizeof(ChunkOffsetPrefixType); size_t prefixSizeAligned = CARB_ALIGNED_SIZE(prefixSize, static_cast<uint32_t>(alignment)); // Conservative chunk size includes prefixes, requested chunk size and alignment reserve size_t originalChunkAlignedSize = prefixSizeAligned + size + (alignment - 1); // Get suitable allocator index based on the total chunk size uint32_t allocatorIndex = _getAllocatorIndexFromSize(originalChunkAlignedSize); if (allocatorIndex != kNoSuitableAllocator) { originalChunk = static_cast<uint8_t*>(m_freeListAllocDescs[allocatorIndex].allocator.allocate()); } else { originalChunk = static_cast<uint8_t*>(CARB_MALLOC(originalChunkAlignedSize)); } if (originalChunk == nullptr) { CARB_LOG_ERROR("Failed to allocate memory!"); return nullptr; } // Calculate final chunk address, so that prefix could be inserted uint8_t* alignedPrefixedChunk = CARB_ALIGN(originalChunk + prefixSize, alignment); size_t ptrOffset = alignedPrefixedChunk - originalChunk; // Make sure that we don't go out-of-bounds CARB_CHECK(ptrOffset + size <= originalChunkAlignedSize); // This is effectively equal to alignedPrefixedChunk uint8_t* extChunk = ptrOffset + originalChunk; // Record chunk size requested from the underlying allocator ChunkSizePrefixType* chunkSizeMem = reinterpret_cast<ChunkSizePrefixType*>(extChunk) - 1; *chunkSizeMem = static_cast<ChunkSizePrefixType>(originalChunkAlignedSize); // Record the offset from the returned memory pointer to the allocated memory chunk ChunkOffsetPrefixType* chunkOffsetMem = reinterpret_cast<ChunkOffsetPrefixType*>(chunkSizeMem) - 1; *chunkOffsetMem = static_cast<ChunkOffsetPrefixType>(ptrOffset); return extChunk; } void deallocate(void* memory) { if (!memory) return; uint8_t* extChunk = static_cast<uint8_t*>(memory); ChunkSizePrefixType* chunkSizeMem = reinterpret_cast<ChunkSizePrefixType*>(extChunk) - 1; size_t originalChunkSize = static_cast<size_t>(*chunkSizeMem); ChunkOffsetPrefixType* chunkOffsetMem = reinterpret_cast<ChunkOffsetPrefixType*>(chunkSizeMem) - 1; size_t offset = static_cast<size_t>(*chunkOffsetMem); uint8_t* originalChunk = reinterpret_cast<uint8_t*>(extChunk) - offset; uint32_t allocatorIndex = _getAllocatorIndexFromSize(originalChunkSize); if (allocatorIndex != kNoSuitableAllocator) { m_freeListAllocDescs[allocatorIndex].allocator.deallocate(originalChunk); } else { CARB_FREE(originalChunk); } } private: struct FreeListAllocInternalDesc { FreeListAllocator allocator; size_t pureElemSize; }; FreeListAllocInternalDesc* m_freeListAllocDescs = nullptr; uint32_t m_freeListAllocCount = 0; static const size_t kUnlimitedSize = 0; static const size_t kDefaultElementsPerBlock = 100; static const size_t kElementsPerBlockAuto = 0; using ChunkSizePrefixType = uint32_t; using ChunkOffsetPrefixType = uint32_t; const uint32_t kNoSuitableAllocator = (uint32_t)-1; uint32_t _getAllocatorIndexFromSize(size_t size) { for (uint32_t i = 0; i < m_freeListAllocCount; ++i) { if (m_freeListAllocDescs[i].pureElemSize >= size) { return i; } } return kNoSuitableAllocator; } static constexpr size_t _calculateAlignedSize(size_t size, size_t alignment) { return CARB_ALIGNED_SIZE(size, static_cast<uint32_t>(alignment)); } }; } // namespace extras } // namespace carb
8,249
C
33.663865
117
0.66505
omniverse-code/kit/include/carb/extras/Semaphore.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. // #pragma once #include "../cpp/Semaphore.h" namespace carb { namespace extras { class CARB_DEPRECATED("Deprecated: carb::extras::binary_semaphore has moved to carb::cpp::binary_semaphore") binary_semaphore : public carb::cpp::binary_semaphore { public: constexpr explicit binary_semaphore(ptrdiff_t desired) : carb::cpp::binary_semaphore(desired) { } }; template <ptrdiff_t least_max_value = carb::cpp::detail::kSemaphoreValueMax> class CARB_DEPRECATED("Deprecated: carb::extras::counting_semaphore has moved to carb::cpp::counting_semaphore") counting_semaphore : public carb::cpp::counting_semaphore<least_max_value> { public: constexpr explicit counting_semaphore(ptrdiff_t desired) : carb::cpp::counting_semaphore<least_max_value>(desired) { } }; } // namespace extras } // namespace carb
1,268
C
31.538461
125
0.753943
omniverse-code/kit/include/carb/extras/EnvironmentVariable.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 Provides a helper class for getting, setting, and restoring environment variables. // #pragma once #include "../Defines.h" #include "../cpp/Optional.h" #include <cstring> #include <string> #include <utility> #if CARB_PLATFORM_LINUX # include <cstdlib> #endif #if CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" # include "../../omni/extras/ScratchBuffer.h" # include "Unicode.h" # include <vector> #endif namespace carb { namespace extras { /** * Defines an environment variable class that allows one to get, set, and restore value on destruction. */ class EnvironmentVariable final { CARB_PREVENT_COPY(EnvironmentVariable); template <typename T> using optional = ::carb::cpp::optional<T>; public: EnvironmentVariable() = delete; /** * Create instance from environment variable called @p name. * * @param name name of the environment variable */ EnvironmentVariable(std::string name) : m_name(std::move(name)), m_restore(false), m_restoreValue(carb::cpp::nullopt) { CARB_ASSERT(!m_name.empty()); } /** * Create instance from environment variable called @p name, setting it's value to @p value, to be restored to * it's original value on destruction. * * @param name name of the environment variable * @param value optional value to set variable, if not set (nullopt) then unset the variable */ EnvironmentVariable(std::string name, const optional<const std::string>& value) : m_name(std::move(name)), m_restore(false), m_restoreValue(carb::cpp::nullopt) { CARB_ASSERT(!m_name.empty()); // attempt to get and store current value std::string currentValue; if (getValue(m_name.c_str(), currentValue)) { m_restoreValue = currentValue; } // attempt to set to new value if (setValue(m_name.c_str(), value ? value->c_str() : nullptr)) { m_restore = true; } } ~EnvironmentVariable() { if (m_restore) { bool ret = setValue(m_name.c_str(), m_restoreValue ? m_restoreValue->c_str() : nullptr); CARB_ASSERT(ret); CARB_UNUSED(ret); } } /** move constructor */ EnvironmentVariable(EnvironmentVariable&& other) : m_name(std::move(other.m_name)), m_restore(std::exchange(other.m_restore, false)), m_restoreValue(std::move(other.m_restoreValue)) { } /** move operator */ EnvironmentVariable& operator=(EnvironmentVariable&& other) { m_name = std::move(other.m_name); m_restore = std::exchange(other.m_restore, false); m_restoreValue = std::move(other.m_restoreValue); return *this; } /** * Get the environment variable name * * @return environment variable name */ const std::string& getName() const noexcept { return m_name; } /** * Get the environment variable current value * * @return environment variable current value */ optional<const std::string> getValue() const noexcept { optional<const std::string> result; std::string value; if (getValue(m_name.c_str(), value)) { result = value; } return result; } /** * Sets new environment value for a variable. * * @param name Environment variable string that we want to get the value for. * @param value The value of environment variable to get (MAX 256 characters). * Can be nullptr - which means the variable should be unset. * * @return true if the operation was successful. */ static bool setValue(const char* name, const char* value) { bool result; // Set the new value #if CARB_PLATFORM_WINDOWS std::wstring nameWide = convertUtf8ToWide(name); if (value) { std::wstring valueWide = convertUtf8ToWide(value); result = (SetEnvironmentVariableW(nameWide.c_str(), valueWide.c_str()) != 0); } else { result = (SetEnvironmentVariableW(nameWide.c_str(), nullptr) != 0); } #else if (value) { result = (setenv(name, value, /*overwrite=*/1) == 0); } else { result = (unsetenv(name) == 0); } #endif return result; } /** * Static helper to get the value of the current environment variable. * * @param name Environment variable string that we want to get the value for. * @param value The value of environment variable to get. * * @return true if the variable exists */ static bool getValue(const char* name, std::string& value) { #if CARB_PLATFORM_WINDOWS std::wstring nameWide = convertUtf8ToWide(name); omni::extras::ScratchBuffer<wchar_t> buffer; while (true) { DWORD count = GetEnvironmentVariableW(nameWide.c_str(), buffer.data(), static_cast<DWORD>(buffer.size())); if (count == 0) { if (GetLastError() == 0) { // no error but no count means we got an empty env var value = ""; return true; } else { // the error case here means the env var does not exist return false; } } else if (count < buffer.size()) { // success case value = convertWideToUtf8(buffer.data()); return true; } else { // env var is too large for the current buffer -- grow it and try again buffer.resize(count + 1U); // include null termination continue; } } #else const char* buffer = getenv(name); if (buffer == nullptr) { return false; } value = buffer; // Copy string #endif return true; } private: std::string m_name; bool m_restore; optional<const std::string> m_restoreValue; }; } // namespace extras } // namespace carb
6,800
C
27.219917
118
0.576176
omniverse-code/kit/include/carb/extras/Guid.h
// Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "../Defines.h" #include <cstdio> #include <string> CARB_IGNOREWARNING_MSC_WITH_PUSH(4996) // disable complaint about _sscanf etc. on Windows, which hurts portability namespace carb { namespace extras { /** * A Global Unique Identifier (GUID) */ struct Guid { uint32_t data1; uint16_t data2; uint16_t data3; uint8_t data4[8]; }; /** * Converts string to GUID. * * @param src A reference to the source string to be converted to GUID. This string may * optionally be surrounded with curly braces (ie: "{}"). * @param guid A pointer to the output Guid. * @returns nothing */ inline bool stringToGuid(const std::string& src, Guid* guid) { const char* fmtString = "%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx"; if (src[0] == '{') fmtString = "{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}"; return sscanf(src.c_str(), fmtString, &guid->data1, &guid->data2, &guid->data3, &guid->data4[0], &guid->data4[1], &guid->data4[2], &guid->data4[3], &guid->data4[4], &guid->data4[5], &guid->data4[6], &guid->data4[7]) == 11; } /** * Converts GUID to string format. * * @param guid A pointer to the input GUID to be converted to string. * @param src A reference to the output string. * @returns nothing */ inline void guidToString(const Guid* guid, std::string& strDst) { char guidCstr[39]; // 32 chars + 4 dashes + 1 null termination snprintf(guidCstr, sizeof(guidCstr), "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", guid->data1, guid->data2, guid->data3, guid->data4[0], guid->data4[1], guid->data4[2], guid->data4[3], guid->data4[4], guid->data4[5], guid->data4[6], guid->data4[7]); strDst = guidCstr; } constexpr bool operator==(const Guid& lhs, const Guid& rhs) { return lhs.data1 == rhs.data1 && lhs.data2 == rhs.data2 && lhs.data3 == rhs.data3 && lhs.data4[0] == rhs.data4[0] && lhs.data4[1] == rhs.data4[1] && lhs.data4[2] == rhs.data4[2] && lhs.data4[3] == rhs.data4[3] && lhs.data4[4] == rhs.data4[4] && lhs.data4[5] == rhs.data4[5] && lhs.data4[6] == rhs.data4[6] && lhs.data4[7] == rhs.data4[7]; } } // namespace extras } // namespace carb namespace std { template <> struct hash<carb::extras::Guid> { using argument_type = carb::extras::Guid; using result_type = std::size_t; result_type operator()(argument_type const& s) const noexcept { // split into two 64 bit words uint64_t a = s.data1 | (uint64_t(s.data2) << 32) | (uint64_t(s.data3) << 48); uint64_t b = s.data4[0] | (uint64_t(s.data4[1]) << 8) | (uint64_t(s.data4[2]) << 16) | (uint64_t(s.data4[3]) << 24) | (uint64_t(s.data4[4]) << 32) | (uint64_t(s.data4[5]) << 40) | (uint64_t(s.data4[6]) << 48) | (uint64_t(s.data4[6]) << 56); // xor together return a ^ b; } }; inline std::string to_string(const carb::extras::Guid& s) { std::string str; guidToString(&s, str); return str; } } // namespace std #define CARB_IS_EQUAL_GUID(rguid1, rguid2) (!memcmp(&(rguid1), &(rguid2), sizeof(carb::extras::Guid))) CARB_IGNOREWARNING_MSC_POP
3,690
C
30.818965
120
0.621951
omniverse-code/kit/include/carb/extras/StringUtils.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. // #pragma once #include "../Defines.h" #include "Utf8Parser.h" #include <cstring> #include <string> #include <algorithm> #include <cctype> namespace carb { namespace extras { /** * Checks if the string begins with the given prefix. * * @param[in] str a non-null pointer to the 0-terminated string. * @param[in] prefix a non-null pointer to the 0-terminated prefix. * * @return true if the string begins with provided prefix, false otherwise. */ inline bool startsWith(const char* str, const char* prefix) { CARB_ASSERT(str != nullptr); CARB_ASSERT(prefix != nullptr); if (0 == *str) { // empty string vs empty (or not) prefix return (0 == *prefix); } else if (0 == *prefix) { // non empty string with empty prefix return true; } size_t n2 = strlen(prefix); return (0 == strncmp(str, prefix, n2)); } /** * Checks if the string begins with the given prefix. * * @param[in] str a non-null pointer to the 0-terminated string. * @param[in] prefix a const reference the std::string prefix. * * @return true if the string begins with provided prefix, false otherwise. */ inline bool startsWith(const char* str, const std::string& prefix) { CARB_ASSERT(str != nullptr); if (0 == *str) { // empty string vs empty (or not) prefix return (prefix.empty()); } else if (prefix.empty()) { // non empty string with empty prefix return true; } std::string::size_type n2 = prefix.length(); std::string::size_type n1 = strnlen(str, static_cast<size_t>(n2 + 1)); if (n1 < n2) { // string is shorter than prefix return false; } CARB_ASSERT(n2 > 0 && n1 >= n2); return (0 == prefix.compare(0, n2, str, n2)); } /** * Checks if the string begins with the given prefix. * * @param[in] str a const reference to the std::string object. * @param[in] prefix a non-null pointer to the 0-terminated prefix. * * @return true if the string begins with provided prefix, false otherwise. */ inline bool startsWith(const std::string& str, const char* prefix) { CARB_ASSERT(prefix != nullptr); if (str.empty()) { // empty string vs empty (or not) prefix return (0 == *prefix); } else if (0 == *prefix) { // non empty string with empty prefix return true; } std::string::size_type n2 = strlen(prefix); std::string::size_type n1 = str.length(); if (n1 < n2) { // string is shorter than prefix return false; } CARB_ASSERT(n2 > 0 && n1 >= n2); return (0 == str.compare(0, n2, prefix)); } /** * Checks if the string begins with the given prefix. * * @param[in] str a const reference to the std::string object. * @param[in] prefix a const reference to the std::string prefix. * * @return true if the string begins with provided prefix, false otherwise. */ inline bool startsWith(const std::string& str, const std::string& prefix) { if (str.empty()) { // empty string vs empty (or not) prefix return prefix.empty(); } else if (prefix.empty()) { // non empty string with empty prefix return true; } std::string::size_type n2 = prefix.length(); std::string::size_type n1 = str.length(); if (n1 < n2) { // string is shorter than prefix return false; } CARB_ASSERT(n2 > 0 && n1 >= n2); return (0 == str.compare(0, n2, prefix)); } /** * Checks if the string ends with the given suffix. * * @param[in] str a non-null pointer to the 0-terminated string. * @param[in] suffix a non-null pointer to the 0-terminated suffix. * * @return true if the string ends with provided suffix, false otherwise. */ inline bool endsWith(const char* str, const char* suffix) { CARB_ASSERT(str != nullptr); CARB_ASSERT(suffix != nullptr); if (0 == *str) { // empty string vs empty (or not) suffix return (0 == *suffix); } else if (0 == *suffix) { // non empty string with empty suffix return true; } size_t n2 = strlen(suffix); size_t n1 = strlen(str); if (n1 < n2) { // string is shorter than suffix return false; } CARB_ASSERT(n2 > 0 && n1 >= n2); return (0 == memcmp(str + n1 - n2, suffix, n2)); } /** * Checks if the string ends with the given suffix. * * @param[in] str a non-null pointer to the 0-terminated string. * @param[in] suffix a const reference to the std::string suffix. * * @return true if the string ends with provided suffix, false otherwise. */ inline bool endsWith(const char* str, const std::string& suffix) { CARB_ASSERT(str != nullptr); if (0 == *str) { // empty string vs empty (or not) suffix return (suffix.empty()); } else if (suffix.empty()) { // non empty string with empty suffix return true; } std::string::size_type n2 = suffix.length(); std::string::size_type n1 = strlen(str); if (n1 < n2) { // string is shorter than suffix return false; } CARB_ASSERT(n2 > 0 && n1 >= n2); return (0 == suffix.compare(0, n2, str + n1 - n2, n2)); } /** * Checks if the string ends with the given suffix. * * @param[in] str a const reference to the std::string object. * @param[in] suffix a non-null pointer to the 0-terminated suffix. * * @return true if the string ends with provided suffix, false otherwise. */ inline bool endsWith(const std::string& str, const char* suffix) { CARB_ASSERT(suffix != nullptr); if (str.empty()) { // empty string vs empty (or not) suffix return (0 == *suffix); } else if (0 == *suffix) { // non empty string with empty suffix return true; } std::string::size_type n2 = strlen(suffix); std::string::size_type n1 = str.length(); if (n1 < n2) { // string is shorter than suffix return false; } CARB_ASSERT(n2 > 0 && n1 >= n2); return (0 == str.compare(n1 - n2, n2, suffix)); } /** * Checks if the string ends with the given suffix. * * @param[in] str a const reference to the std::string object. * @param[in] suffix a const reference to the std::string suffix. * * @return true if the string ends with provided suffix, false otherwise. */ inline bool endsWith(const std::string& str, const std::string& suffix) { if (str.empty()) { // empty string vs empty (or not) prefix return suffix.empty(); } else if (suffix.empty()) { // non empty string with empty prefix return true; } std::string::size_type n2 = suffix.length(); std::string::size_type n1 = str.length(); if (n1 < n2) { // string is shorter than suffix return false; } CARB_ASSERT(n2 > 0 && n1 >= n2); return (0 == str.compare(n1 - n2, n2, suffix)); } /** * Trims start of the provided string from the whitespace characters as classified by the * currently installed C locale in-place * * @param[in,out] str for trimming */ inline void trimStringStartInplace(std::string& str) { // Note: using cast of val into `unsigned char` as std::isspace expects unsigned char values // https://en.cppreference.com/w/cpp/string/byte/isspace str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](std::string::value_type val) { return !std::isspace(static_cast<unsigned char>(val)); })); } /** * Trims end of the provided string from the whitespace characters as classified by the * currently installed C locale in-place * * @param[in,out] str for trimming */ inline void trimStringEndInplace(std::string& str) { // Note: using cast of val into `unsigned char` as std::isspace expects unsigned char values // https://en.cppreference.com/w/cpp/string/byte/isspace str.erase(std::find_if(str.rbegin(), str.rend(), [](std::string::value_type val) { return !std::isspace(static_cast<unsigned char>(val)); }) .base(), str.end()); } /** * Trims start and end of the provided string from the whitespace characters as classified by the * currently installed C locale in-place * * @param[in,out] str for trimming */ inline void trimStringInplace(std::string& str) { trimStringStartInplace(str); trimStringEndInplace(str); } /** * Creates trimmed (as classified by the currently installed C locale) * from the start copy of the provided string * * @param[in] str string for trimming * * @return trimmed from the start copy of the provided string */ inline std::string trimStringStart(std::string str) { trimStringStartInplace(str); return str; } /** * Creates trimmed (as classified by the currently installed C locale) * from the end copy of the provided string * * @param[in] str string for trimming * * @return trimmed from the end copy of the provided string */ inline std::string trimStringEnd(std::string str) { trimStringEndInplace(str); return str; } /** * Creates trimmed (as classified by the currently installed C locale) * from the start and the end copy of the provided string * * @param[in] str string for trimming * * @return trimmed from the start and the end copy of the provided string */ inline std::string trimString(std::string str) { trimStringInplace(str); return str; } /** * Trims start of the provided valid utf-8 string from the whitespace characters in-place * * @param[inout] str The UTF-8 string to be trimmed. */ inline void trimStringStartInplaceUtf8(std::string& str) { if (str.empty()) { return; } Utf8Parser::CodePoint decodedCodePoint = 0; const Utf8Parser::CodeByte* nonWhitespacePos = str.data(); while (true) { const Utf8Parser::CodeByte* nextPos = Utf8Parser::nextCodePoint( nonWhitespacePos, Utf8Parser::kNullTerminated, &decodedCodePoint, Utf8Parser::fDecodeUseDefault); // If walked through the whole string and non-whitespace encountered then the whole string is just whitespace if (!nextPos) { str.clear(); return; } if (Utf8Parser::isSpaceCodePoint(decodedCodePoint)) { // If encountered a whitespace character then proceed to the next code point nonWhitespacePos = nextPos; continue; } // Not a whitespace, stop checking break; } const size_t removedCharsCount = nonWhitespacePos - str.data(); if (removedCharsCount) { str.erase(0, removedCharsCount); } } /** * Trims end of the provided valid utf-8 string from the whitespace characters in-place * * @param[inout] str The string to be trimmed. */ inline void trimStringEndInplaceUtf8(std::string& str) { if (str.empty()) { return; } const Utf8Parser::CodeByte* dataBufStart = str.data(); const Utf8Parser::CodeByte* dataBufEnd = dataBufStart + str.size(); // Walking the provided string data in codepoints in reverse // Note: `Utf8Parser::lastCodePoint` checks the provided data from back to front thus the search of whitespace is // in linear time Utf8Parser::CodePoint decodedCodePoint{}; const Utf8Parser::CodeByte* curSearchPosAtEnd = Utf8Parser::lastCodePoint(dataBufStart, str.size(), &decodedCodePoint); const Utf8Parser::CodeByte* prevSearchPosAtEnd = dataBufEnd; while (curSearchPosAtEnd != nullptr) { if (!Utf8Parser::isSpaceCodePoint(decodedCodePoint)) { // Non-space code point was found // Remove all symbols starting with the previous codepoint if (prevSearchPosAtEnd < dataBufEnd) { str.erase(prevSearchPosAtEnd - dataBufStart); } return; } prevSearchPosAtEnd = curSearchPosAtEnd; curSearchPosAtEnd = Utf8Parser::lastCodePoint(dataBufStart, curSearchPosAtEnd - dataBufStart, &decodedCodePoint); } // Either the whole string consists from space characters or an invalid sequence was encountered str.clear(); } /** * Trims start and end of the provided valid utf-8 string from the whitespace characters in-place * * @param[inout] str The UTF-8 string to be trimmed. */ inline void trimStringInplaceUtf8(std::string& str) { trimStringStartInplaceUtf8(str); trimStringEndInplaceUtf8(str); } /** * Creates trimmed from the start copy of the provided valid utf-8 string * * @param[in] str The UTF-8 string to be trimmed. * * @return trimmed from the start copy of the provided string */ inline std::string trimStringStartUtf8(std::string str) { trimStringStartInplaceUtf8(str); return str; } /** * Creates trimmed from the end copy of the provided valid utf-8 string * * @param[in] str The UTF-8 string to be trimmed. * * @return trimmed from the end copy of the provided string */ inline std::string trimStringEndUtf8(std::string str) { trimStringEndInplaceUtf8(str); return str; } /** * Creates trimmed from the start and the end copy of the provided valid utf-8 string * * @param[in] str The UTF-8 string to be trimmed. * * @return trimmed from the start and the end copy of the provided string */ inline std::string trimStringUtf8(std::string str) { trimStringInplaceUtf8(str); return str; } } // namespace extras } // namespace carb
13,983
C
25.892308
121
0.640707
omniverse-code/kit/include/carb/extras/DomainSocket.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "../Defines.h" #if CARB_PLATFORM_LINUX # include "../logging/Log.h" # include <poll.h> # include <sys/socket.h> # include <sys/un.h> # include <sys/wait.h> # include <string> # include <unistd.h> # define CARB_INVALID_SOCKET (-1) namespace carb { namespace extras { class DomainSocket { public: DomainSocket() { } ~DomainSocket() { closeSocket(); } /** * Sends a list of FDs (file descriptors) to another process using Unix domain socket. * * @param fds A list of file descriptors to send. * @param fdCount The number of file descriptors to send. * * @return true if FD was sent successfully. */ bool sendFd(const int* fds, int fdCount) { size_t fdSize = fdCount * sizeof(int); msghdr msg = {}; cmsghdr* cmsg; size_t bufLen = CMSG_SPACE(fdSize); char* buf; char dup[s_iovLen] = "dummy payload"; iovec iov = {}; iov.iov_base = &dup; iov.iov_len = strlen(dup); buf = reinterpret_cast<char*>(alloca(bufLen)); memset(buf, 0, bufLen); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = buf; msg.msg_controllen = bufLen; cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(fdSize); memcpy(CMSG_DATA(cmsg), fds, fdSize); if (sendmsg(m_socket, &msg, 0) == (-1)) { CARB_LOG_ERROR("sendmsg failed, errno=%d/%s", errno, strerror(errno)); return false; } return true; } /** * Receives a list of FDs (file descriptors) from another process using Unix domain socket. * * @param fds A list of file descriptors to be received. * @param fdCount The number of file descriptors to be received. * * @return true if FD was received successfully. */ bool receiveFd(int* fds, int fdCount) { size_t fdSize = fdCount * sizeof(int); msghdr msg = {}; cmsghdr* cmsg; size_t bufLen = CMSG_SPACE(fdSize); char* buf; char dup[s_iovLen]; iovec iov = {}; iov.iov_base = &dup; iov.iov_len = sizeof(dup); buf = reinterpret_cast<char*>(alloca(bufLen)); memset(buf, 0, bufLen); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = buf; msg.msg_controllen = bufLen; int result = recvmsg(m_socket, &msg, 0); if (result == (-1) || result == 0) { CARB_LOG_ERROR("recvmsg failed, errno=%d/%s", errno, strerror(errno)); return false; } cmsg = CMSG_FIRSTHDR(&msg); memcpy(fds, CMSG_DATA(cmsg), fdSize); return true; } /** * Starts client to connect to a server. * * @param socketPath The name or the path of the socket. * @return true if the client was started successfully, and it is connected to a server connection. * * @remark Example of socketPath: "/tmp/fd-pass.socket" */ bool startClient(const char* socketPath) { m_socket = socket(AF_UNIX, SOCK_STREAM, 0); if (m_socket == CARB_INVALID_SOCKET) { CARB_LOG_ERROR("Failed to create socket, errno=%d/%s", errno, strerror(errno)); return false; } sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketPath); if (connect(m_socket, (const struct sockaddr*)&addr, sizeof(addr)) == -1) { CARB_LOG_ERROR("Failed to connect to socket %s, errno=%d/%s", addr.sun_path, errno, strerror(errno)); return false; } return true; } /** * Closes the connection and socket. * * @return nothing */ void closeSocket() { if (m_socket != CARB_INVALID_SOCKET) { close(m_socket); } m_socket = CARB_INVALID_SOCKET; m_socketPath.clear(); } /** * Starts server to listen for a socket. * * @param socketPath The name or the path of the socket. * @param backlog The maximum number of the allowed pending connections. * * @return true if the server was started successfully, and the client accepted the connection. */ bool startServer(const char* socketPath, int backlog = 10) { m_socket = socket(AF_UNIX, SOCK_STREAM, 0); if (m_socket == CARB_INVALID_SOCKET) { CARB_LOG_ERROR("Failed to create server socket, errno=%d/%s", errno, strerror(errno)); return false; } // try closing any previous socket if (unlink(socketPath) == -1 && errno != ENOENT) { CARB_LOG_ERROR("unlinking socket failed, errno=%d/%s", errno, strerror(errno)); return false; } sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketPath); if (bind(m_socket, (const struct sockaddr*)&addr, sizeof(addr)) == -1) { CARB_LOG_ERROR("Failed to bind the socket, errno=%d/%s", errno, strerror(errno)); return false; } if (listen(m_socket, backlog) == -1) { CARB_LOG_ERROR("Failed to listen on socket, errno=%d/%s", errno, strerror(errno)); return false; } CARB_LOG_INFO("DomainSocket: stream server started at %s", socketPath); return true; } /** * Check for incoming connection and accept it if any. * * @param server The listening DomainSocket. * * @return true if connection was accepted. */ bool acceptConnection(DomainSocket& server) { struct pollfd fds; int rc; fds.fd = server.m_socket; fds.events = POLLIN | POLLPRI; fds.revents = 0; rc = poll(&fds, 1, 0); if (rc == -1) { CARB_LOG_ERROR("an error on the server socket, errno=%d/%s", errno, strerror(errno)); return false; } else if (rc == 0) { // nothing happened return false; } sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; socklen_t addrsize = sizeof(addr); m_socket = accept(server.m_socket, (struct sockaddr*)&addr, &addrsize); if (m_socket == CARB_INVALID_SOCKET) { CARB_LOG_ERROR("accepting connection failed, errno=%d/%s", errno, strerror(errno)); return false; } // Copy the socket path m_socketPath = addr.sun_path; CARB_LOG_INFO("DomainSocket: accepted connection on %s", addr.sun_path); return true; } private: int m_socket = CARB_INVALID_SOCKET; ///< socket descriptor std::string m_socketPath; ///< socket path or name static const size_t s_iovLen = 256; ///< The length of I/O data in bytes (dummy) }; } // namespace extras } // namespace carb #endif
7,754
C
26.99639
113
0.564354
omniverse-code/kit/include/carb/extras/TestEnvironment.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /** @file * @brief Provides helper functions to check the platform a process is running on. */ #pragma once #include "Library.h" #if CARB_PLATFORM_LINUX # include "StringSafe.h" #endif /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { /** * Queries whether the calling process is the Carbonite unit tests. * * @note This requires the symbol "g_carbUnitTests" defined * in the unittest module. on linux, if the symbol is declared in * the executable and not in a shared library, the executable must * be linked with -rdynamic or -Wl,--export-dynamic, otherwise * getLibrarySymbol() will fail. typical usage would be to define * g_carbUnitTests near the unittest module's main(), for example: * * \code{.cpp} * #include <carb/Defines.h> * * CARB_EXPORT int32_t g_carbUnitTests; * int32_t g_carbUnitTests = 1; * * int main(int, char**) { * // unittest driver * return 0; * } * \endcode * * @returns `true` if the calling process is the Carbonite unit tests. * @returns `false` otherwise. */ inline bool isTestEnvironment() { LibraryHandle module; void* symbol; module = loadLibrary(nullptr); if (module == nullptr) return false; symbol = getLibrarySymbol<void*>(module, "g_carbUnitTests"); unloadLibrary(module); return symbol != nullptr; } /** Retrieves the platform distro name. * * @returns On Linux, the name of the distro the process is running under as seen in the "ID" * tag in the '/etc/os-release' file if it can be found. On MacOS, the name of the * OS code name that the process is running on is returned if it can be found. On * Windows, this returns the name "Windows". * @returns On Linux, the name "Linux" if the '/etc/os-release' file cannot be accessed or the * "ID" tag cannot be found in it. On Windows, there is no failure path. * @returns On MacOS, the name "MacOS" if the distro name cannot be found or the appropriate * tag in it cannot be found. */ inline const char* getDistroName() { #if CARB_POSIX static char distroName[64] = { 0 }; auto searchFileForTag = [](const char* filename, const char* tag, char* out, size_t length, bool atStart) -> bool { FILE* fp = fopen(filename, "r"); char buffer[1024]; if (fp == nullptr) return false; out[0] = 0; while (!feof(fp) && !ferror(fp)) { char* ptr; size_t len; ptr = fgets(buffer, CARB_COUNTOF32(buffer), fp); if (ptr == nullptr) break; // clear whitespace from the end of the line. len = strlen(buffer); while (len > 0 && (buffer[len - 1] == '\r' || buffer[len - 1] == '\n' || buffer[len - 1] == ' ' || buffer[len - 1] == '\t' || buffer[len - 1] == '\"')) { len--; } buffer[len] = 0; ptr = strstr(buffer, tag); if (ptr == nullptr || (atStart && ptr != buffer)) continue; ptr += strlen(tag); if (ptr[0] == '\"') ptr++; copyStringSafe(out, length, ptr); break; } fclose(fp); return out[0] != 0; }; if (distroName[0] == 0) { # if CARB_PLATFORM_LINUX // try to retrieve the distro name from the official OS info file. if (!searchFileForTag("/etc/os-release", "ID=", distroName, CARB_COUNTOF(distroName), true)) { copyStringSafe(distroName, CARB_COUNTOF(distroName), "Linux"); } # elif CARB_PLATFORM_MACOS // MacOS doesn't have an official way to retrieve this information either on command line // or in C/C++/ObjC. There are two common suggestions for how to get this from research: // * use a hard coded map from version numbers to OS code names. // * scrape the OS code name from the OS software license agreement HTML file. // // Both seem like terrible ideas and are highly subject to change at Apple's Whim. For // now though, scraping the license agreement text seems to be the most reliable. constexpr const char* filename = "/System/Library/CoreServices/Setup Assistant.app/Contents/" "Resources/en.lproj/OSXSoftwareLicense.html"; if (!searchFileForTag(filename, "SOFTWARE LICENSE AGREEMENT FOR ", distroName, CARB_COUNTOF(distroName), false)) { copyStringSafe(distroName, CARB_COUNTOF(distroName), "MacOS"); } else { char* ptr = strchr(distroName, '<'); if (ptr != nullptr) ptr[0] = 0; } # else CARB_UNSUPPORTED_PLATFORM(); # endif } return distroName; #elif CARB_PLATFORM_WINDOWS return "Windows"; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** Checks whether the calling process is running on CentOS. * * @returns `true` if the current platform is CentOS. * @returns `false` if the current platform is not running CentOS. */ inline bool isRunningOnCentos() { return strcmp(getDistroName(), "centos") == 0; } /** Checks whether the calling process is running on Ubuntu. * * @returns `true` if the current platform is Ubuntu. * @returns `false` if the current platform is not running Ubuntu. */ inline bool isRunningOnUbuntu() { return strcmp(getDistroName(), "ubuntu") == 0; } } // namespace extras } // namespace carb
6,118
C
30.060914
120
0.615234
omniverse-code/kit/include/carb/extras/Errors.h
// Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! \file //! \brief Carbonite error handling utilities #pragma once #include "../Defines.h" #include "../logging/Log.h" #if CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" # include "Unicode.h" # include <memory> #elif CARB_POSIX // Nothing needed for now #else CARB_UNSUPPORTED_PLATFORM(); #endif #include <cerrno> #include <string.h> #include <string> namespace carb { namespace extras { //! The decayed type of `errno` //! //! Defined as `std::decay_t<decltype(errno)>` using ErrnoType = std::decay_t<decltype(errno)>; #if defined(DOXYGEN_BUILD) || CARB_PLATFORM_WINDOWS //! (Windows only) The type of value returned from `GetLastError()` using WinApiErrorType = unsigned long; #endif /** * Returns the last value of errno. * * @return the last value of errno. */ inline ErrnoType getLastErrno() noexcept { return errno; } /** * Returns a human-readable string for a given errno value * * On Windows, this value is created from <a * href="https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strerror-s-strerror-s-wcserror-s-wcserror-s?view=msvc-170">strerror_s()</a>. * On other platforms, <a href="https://linux.die.net/man/3/strerror_r">strerror_r()</a> is used instead. If the GNU * version is available it is used, otherwise the XSI-compliant version is used. * * @warning This function does not make any guarantees about the current value of `errno` or attempts to keep `errno` * set at the same value; `errno` may be modified by this function. * * @param errorCode the error code read from `errno` * @return text message corresponding to the error code; an \p errorCode of 0 returns an empty string */ inline std::string convertErrnoToMessage(ErrnoType errorCode) { if (errorCode == 0) return {}; char buffer[1024]; constexpr size_t bufferSize = carb::countOf(buffer); #if CARB_PLATFORM_WINDOWS if (CARB_LIKELY(strerror_s(buffer, bufferSize, errorCode) == 0)) return buffer; return ("Error code " + std::to_string(errorCode)) + " failed to format"; #elif CARB_PLATFORM_MACOS || CARB_PLATFORM_LINUX // strerror_r implementation switch # if CARB_PLATFORM_MACOS || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE) // XSI-compliant strerror_r if (CARB_LIKELY(strerror_r(errorCode, buffer, bufferSize) == 0)) return buffer; return ("Error code " + std::to_string(errorCode)) + " failed to format"; # else // GNU-specific strerror_r // We always get some result in this implementation for a valid buffer return strerror_r(errorCode, buffer, bufferSize); # endif // end of strerror_r implementation switch #else CARB_UNSUPPORTED_PLATFORM(); #endif // end of platform switch } /** * Reads the current value of `errno` and returns a human-readable string for the errno value. * * @note Unlike \ref convertErrnoToMessage(), this function ensures that `errno` remains consistent by setting `errno` * to the same value after creating the string. * @see getLastErrno() convertErrnoToMessage() * @param[out] out If not `nullptr`, receives the value of `errno`. * @return string value from \ref convertErrnoToMessage() */ inline std::string getLastErrnoMessage(ErrnoType* out = nullptr) { const ErrnoType errorCode = getLastErrno(); if (out) *out = errorCode; auto str = convertErrnoToMessage(errorCode); errno = errorCode; return str; } /////////////////////////////////// /// Platform specific functions /// /////////////////////////////////// #if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD) /** * (Windows only) Returns the value of the GetLastError() Win32 API function * * @return the value of the GetLastError Win API function. */ inline WinApiErrorType getLastWinApiErrorCode() noexcept { return ::GetLastError(); } /** * (Windows only) Converts a Win32 API error code into a human-readable string. * * This function translates a Win32 API error code into a human-readable string using the `FormatMessageA` function. * * @note In some cases, the returned string may have UTF-8 encoding or format specifiers. Use caution when printing * this string. For instance, `ERROR_BAD_EXE_FORMAT` contains `"%1"`. * * @warning This function does not make any guarantees about the current value of `GetLastError()` or attempts to keep * `GetLastError()` set at the same value; `GetLastError()` may be modified by this function. * * @param errorCode the code of the Win API error * @return a human-readable message based on the error code; an \p errorCode of 0 produces an empty string */ inline std::string convertWinApiErrorCodeToMessage(WinApiErrorType errorCode) { if (errorCode == CARBWIN_ERROR_SUCCESS) { return {}; } LPWSTR resultMessageBuffer = nullptr; const DWORD kFormatFlags = CARBWIN_FORMAT_MESSAGE_ALLOCATE_BUFFER | CARBWIN_FORMAT_MESSAGE_FROM_SYSTEM | CARBWIN_FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD dwFormatResultCode = FormatMessageW(kFormatFlags, nullptr, errorCode, CARBWIN_MAKELANGID(CARBWIN_LANG_NEUTRAL, CARBWIN_SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&resultMessageBuffer), 0, nullptr); if (dwFormatResultCode == 0 || !resultMessageBuffer) { return ("Error code " + std::to_string(errorCode)) + " failed to format"; } struct Deleter { void operator()(LPWSTR str) { ::LocalFree(str); } }; std::unique_ptr<WCHAR, Deleter> systemBuffKeeper(resultMessageBuffer); return carb::extras::convertWideToUtf8(resultMessageBuffer); } /** * (Windows only) Reads the value of `GetLastError()` and converts it to a human-readable string. * * @note Unlike \ref convertWinApiErrorCodeToMessage(), this function will keep the same error code consistent. A call * to `GetLastError()` after calling this function will return the same value as prior to calling this function. * * @return the string from \ref convertWinApiErrorCodeToMessage() */ inline std::string getLastWinApiErrorMessage() { const WinApiErrorType errorCode = getLastWinApiErrorCode(); auto str = convertWinApiErrorCodeToMessage(errorCode); SetLastError(errorCode); return str; } #endif // #if CARB_PLATFORM_WINDOWS } // namespace extras } // namespace carb
6,882
C
32.906404
151
0.693694
omniverse-code/kit/include/carb/extras/VariableSetup.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. // /** @file * @brief Provides helper functions to retrieve setup variable values. */ #pragma once #include "../Framework.h" #include "../filesystem/IFileSystem.h" #include "EnvironmentVariable.h" #include "Path.h" #include <map> #include <string> /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { /** * Helper function that reads string value form the string map or the environment variable, if map doesn't hold such * key. * * @param stringMapKey Key that should be present in the map. * @param stringMap String map containing values indexed by string key. * @param envVarName Environment variable name. * @return String value. Can be empty if neither string map value nor env contain the value. */ inline std::string getStringFromMapOrEnvVar(const char* stringMapKey, const std::map<std::string, std::string>& stringMap, const char* envVarName) { std::string value; // Check if variable is specified in the command line arguments first, and otherwise - // try to read the environment variable. const auto stringMapIt = stringMap.find(stringMapKey); if (stringMapIt != stringMap.cend()) { value = stringMapIt->second; } else { extras::EnvironmentVariable::getValue(envVarName, value); } return value; } /** * Determines application path and name. Priority (for path and name separately): * 1. String map (cmd arg) * 2. Env var * 3. Executable path/name (filesystem) * * @param stringMap String map - e.g. parsed args as output from the CmdLineParser. * @param appPath Resulting application path. * @param appName Resulting application name. */ inline void getAppPathAndName(const std::map<std::string, std::string>& stringMap, std::string& appPath, std::string& appName) { Framework* f = getFramework(); filesystem::IFileSystem* fs = f->acquireInterface<filesystem::IFileSystem>(); // Initialize application path and name to the executable path and name, extras::Path execPathModified(fs->getExecutablePath()); #if CARB_PLATFORM_WINDOWS // Remove .exe extension on Windows execPathModified.replaceExtension(""); #endif appPath = execPathModified.getParent(); appName = execPathModified.getFilename(); // Override application name and path if command line argument or environment variables // are present. std::string appPathOverride = getStringFromMapOrEnvVar("app/path", stringMap, "CARB_APP_PATH"); if (!appPathOverride.empty()) { extras::Path normalizedAppPathOverride(appPathOverride); appPath = normalizedAppPathOverride.getNormalized(); } std::string appNameOverride = getStringFromMapOrEnvVar("app/name", stringMap, "CARB_APP_NAME"); if (!appNameOverride.empty()) { appName = appNameOverride; } } } // namespace extras } // namespace carb
3,527
C
33.930693
116
0.695208
omniverse-code/kit/include/carb/extras/Debugging.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 Provides some helper functions that check the state of debuggers for the calling * process. */ #pragma once #include "../Defines.h" #if CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" extern "C" { // Forge doesn't define these functions, and it can be included before CarbWindows.h in some cases // So ensure that they're defined here. __declspec(dllimport) BOOL __stdcall IsDebuggerPresent(void); __declspec(dllimport) void __stdcall DebugBreak(void); // Undocumented function from ntdll.dll, only present in ntifs.h from the Driver Development Kit __declspec(dllimport) unsigned short __stdcall RtlCaptureStackBackTrace(unsigned long, unsigned long, void**, unsigned long*); } // Some things define vsnprintf (pyerrors.h, for example) # ifdef vsnprintf # undef vsnprintf # endif #elif CARB_POSIX # include <chrono> # include <execinfo.h> # include <signal.h> # include <stdint.h> # include <string.h> # include <fcntl.h> # include <sys/types.h> # include <unistd.h> # if CARB_PLATFORM_MACOS # include <sys/sysctl.h> # include <mach/mach.h> # include <mach/vm_map.h> # include <pthread/stack_np.h> # endif #else CARB_UNSUPPORTED_PLATFORM(); #endif #include <cstdio> /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { #ifndef DOXYGEN_SHOULD_SKIP_THIS # if CARB_PLATFORM_MACOS namespace detail { inline bool getVMInfo(uint8_t const* const addr, uint8_t** top, uint8_t** bot) noexcept { vm_address_t address = (vm_address_t)addr; vm_size_t size = 0; vm_region_basic_info_data_64_t region{}; mach_msg_type_number_t regionSize = VM_REGION_BASIC_INFO_COUNT_64; mach_port_t obj{}; kern_return_t ret = vm_region_64( mach_task_self(), &address, &size, VM_REGION_BASIC_INFO_64, (vm_region_info_t)&region, &regionSize, &obj); if (ret != KERN_SUCCESS) return false; *bot = (uint8_t*)address; *top = *bot + size; return true; } # define INSTACK(a) ((a) >= stackbot && (a) <= stacktop) # if defined(__x86_64__) # define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 0) # elif defined(__i386__) # define ISALIGNED(a) ((((uintptr_t)(a)) & 0xf) == 8) # elif defined(__arm__) || defined(__arm64__) # define ISALIGNED(a) ((((uintptr_t)(a)) & 0x1) == 0) # endif // Use the ol' static-functions-in-a-template-class to prevent the linker complaining about duplicated symbols. template <class T = void> struct Utils { __attribute__((noinline)) static void internalBacktrace( vm_address_t* buffer, size_t maxCount, size_t* nb, size_t skip, void* startfp) noexcept { uint8_t *frame, *next; pthread_t self = pthread_self(); uint8_t* stacktop = static_cast<uint8_t*>(pthread_get_stackaddr_np(self)); uint8_t* stackbot = stacktop - pthread_get_stacksize_np(self); *nb = 0; // Rely on the fact that our caller has an empty stackframe (no local vars) // to determine the minimum size of a stackframe (frame ptr & return addr) frame = static_cast<uint8_t*>(__builtin_frame_address(0)); next = reinterpret_cast<uint8_t*>(pthread_stack_frame_decode_np((uintptr_t)frame, nullptr)); /* make sure return address is never out of bounds */ stacktop -= ((uintptr_t)next - (uintptr_t)frame); if (!INSTACK(frame) || !ISALIGNED(frame)) { // Possibly running as a fiber, get the region info for the memory in question if (!getVMInfo(frame, &stacktop, &stackbot)) return; if (!INSTACK(frame) || !ISALIGNED(frame)) return; } while (startfp || skip--) { if (startfp && startfp < next) break; if (!INSTACK(next) || !ISALIGNED(next) || next <= frame) return; frame = next; next = reinterpret_cast<uint8_t*>(pthread_stack_frame_decode_np((uintptr_t)frame, nullptr)); } while (maxCount--) { uintptr_t retaddr; next = reinterpret_cast<uint8_t*>(pthread_stack_frame_decode_np((uintptr_t)frame, &retaddr)); buffer[*nb] = retaddr; (*nb)++; if (!INSTACK(next) || !ISALIGNED(next) || next <= frame) return; frame = next; } } __attribute__((disable_tail_calls)) static void backtrace( vm_address_t* buffer, size_t maxCount, size_t* nb, size_t skip, void* startfp) noexcept { // callee relies upon no tailcall and no local variables internalBacktrace(buffer, maxCount, nb, skip + 1, startfp); } }; # undef INSTACK # undef ISALIGNED } // namespace detail # endif #endif /** * Checks if a debugger is attached to the calling process. * * @returns `true` if a user-mode debugger is currently attached to the calling process. * @returns `false` if the calling process does not have a debugger attached. * * @remarks This checks if a debugger is currently attached to the calling process. This will * query the current state of the debugger so that a process can disable some debug- * only checks at runtime if the debugger is ever detached. If a debugger is attached * to a running process, this will start returning `true` again. * * @note On Linux and related platforms, the debugger check is a relatively expensive * operation. To avoid unnecessary overhead explicitly checking this state each time, * the last successfully queried state will be cached for a short period. Future calls * within this period will simply return the cached state instead of querying again. */ inline bool isDebuggerAttached(void) { #if CARB_PLATFORM_WINDOWS return IsDebuggerPresent(); #elif CARB_PLATFORM_LINUX // the maximum amount of time in milliseconds that the cached debugger state is valid for. // If multiple calls to isDebuggerAttached() are made within this period, a cached state // will be returned instead of re-querying. Outside of this period however, a new call // to check the debugger state with isDebuggerAttached() will cause the state to be // refreshed. static constexpr uint64_t kDebugUtilsDebuggerCheckPeriod = 500; static bool queried = false; static bool state = false; static std::chrono::high_resolution_clock::time_point lastCheckTime = std::chrono::high_resolution_clock::now(); std::chrono::high_resolution_clock::time_point t = std::chrono::high_resolution_clock::now(); uint64_t millisecondsElapsed = std::chrono::duration_cast<std::chrono::duration<uint64_t, std::milli>>(t - lastCheckTime).count(); if (!queried || millisecondsElapsed > kDebugUtilsDebuggerCheckPeriod) { // on Android and Linux we can check the '/proc/self/status' file for the line // "TracerPid:" to check if the associated value is *not* 0. Note that this is // not a cheap check so we'll cache its result and only re-query once every few // seconds. // fopen() and fgets() can use the heap, and we may be called from the crashreporter, so avoid using those // functions to avoid heap usage. int fd = open("/proc/self/status", 0, O_RDONLY); if (fd < 0) return false; lastCheckTime = t; queried = true; char data[256]; constexpr static char TracerPid[] = "TracerPid:"; for (;;) { // Read some bytes from the file ssize_t bytes = CARB_RETRY_EINTR(read(fd, data, CARB_COUNTOF(data) - 1)); if (bytes <= 0) { // Reached the end without finding the line, shouldn't happen CARB_ASSERT(0); close(fd); state = false; break; } data[bytes] = '\0'; // Look for the 'T' in "TracerPid" auto p = strchr(data, 'T'); if (!p) continue; // Can we see the whole line? auto cr = strchr(p, '\n'); if (!cr) { if (p == data) // This line is too long; skip the 'T' and try again lseek(fd, -off_t(bytes - 1), SEEK_CUR); else // Cannot see the whole line. Back up to where we found the 'T' lseek(fd, -off_t(data + bytes - p), SEEK_CUR); continue; } // Back up to the next line for the next read lseek(fd, -off_t(data + bytes - (cr + 1)), SEEK_CUR); // TracerPid line? if (strncmp(p, TracerPid, CARB_COUNTOF(TracerPid) - 1) != 0) // Nope, on to the next line continue; // Yep, get the result. p += (CARB_COUNTOF(TracerPid) - 1); while (p != cr && (*p == '0' || isspace(*p))) ++p; // If we find any characters other than space or zero, we have a tracer state = p != cr; close(fd); break; } } return state; #elif CARB_PLATFORM_MACOS int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid(), }; struct kinfo_proc info = {}; size_t size = sizeof(info); // Ignore the return value. It'll return false if this fails. sysctl(mib, CARB_COUNTOF(mib), &info, &size, nullptr, 0); return (info.kp_proc.p_flag & P_TRACED) != 0; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Performs a software breakpoint if a debugger is currently attached to this process. * * @returns No return value. * * @remarks This performs a software breakpoint. If a debugger is attached, this will cause the * breakpoint to be caught and the debugger will take over the process' state. If no * debugger is attached, this will be ignored. This can be thought of as a more dynamic * version of CARB_ASSERT(0) where the existence of a debugger is explicitly checked * at runtime instead of at compile time. * * @note This should really only be used for local debugging purposes. The debugger check * that is used in here (isDebuggerAttached()) could potentially be expensive on some * platforms, so this should only be called when it is well known that a problem that * needs immediate debugging attention has already occurred. */ inline void debuggerBreak(void) { if (!isDebuggerAttached()) return; #if CARB_PLATFORM_WINDOWS DebugBreak(); #elif CARB_POSIX // NOTE: the __builtin_trap() call is the more 'correct and portable' way to do this. However // that unfortunately raises a SIGILL signal which is not continuable (at least not in // MSVC Android or GDB) so its usefulness in a debugger is limited. Directly raising a // SIGTRAP signal instead still gives the desired behavior and is also continuable. raise(SIGTRAP); #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Attempts to capture the callstack for the current thread. * * @note Non-debug code and lack of symbols can cause this function to be unable to capture stack frames. Function * inlining and tail-calls may result in functions being absent from the backtrace. * * @param skipFrames The number of callstack frames to skip from the start (current call point) of the backtrace. * @param array The array of pointers that is populated with the backtrace. The caller allocates this array. * @param count The number of pointers that @p array can hold; the maximum size of the captured backtrace. * * @return The number of backtrace frames captured in @p array */ inline size_t debugBacktrace(size_t skipFrames, void** array, size_t count) noexcept { #if CARB_PLATFORM_WINDOWS // Apparently RtlCaptureStackBackTrace() can "fail" (i.e. not write anything and return 0) without setting any // error for GetLastError(). Try a few times in a loop. constexpr static int kRetries = 3; for (int i = 0; i != kRetries; ++i) { unsigned short frames = ::RtlCaptureStackBackTrace((unsigned long)skipFrames, (unsigned long)count, array, nullptr); if (frames) return frames; } // Failed return 0; #elif CARB_PLATFORM_LINUX void** target = array; if (skipFrames) { target = CARB_STACK_ALLOC(void*, count + skipFrames); } size_t captured = (size_t)::backtrace(target, int(count + skipFrames)); if (captured <= skipFrames) return 0; if (skipFrames) { captured -= skipFrames; memcpy(array, target + skipFrames, sizeof(void*) * captured); } return captured; #elif CARB_PLATFORM_MACOS size_t num_frames; detail::Utils<>::backtrace(reinterpret_cast<vm_address_t*>(array), count, &num_frames, skipFrames, nullptr); while (num_frames >= 1 && array[num_frames - 1] == nullptr) num_frames -= 1; return num_frames; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Prints a formatted string to debug output. On Windows this means, OutputDebugString; on Linux, this just prints to * the console. * * @note This should never be used in production code! * * On Windows, the Sysinternals DebugView utility can be used to view the debug strings outside of a debugger. * @param fmt The printf-style format string */ void debugPrint(const char* fmt, ...) CARB_PRINTF_FUNCTION(1, 2); inline void debugPrint(const char* fmt, ...) { #if CARB_PLATFORM_WINDOWS va_list va, va2; va_start(va, fmt); va_copy(va2, va); int count = vsnprintf(nullptr, 0, fmt, va2); va_end(va2); if (count > 0) { char* buffer = CARB_STACK_ALLOC(char, size_t(count) + 1); vsnprintf(buffer, size_t(count + 1), fmt, va); ::OutputDebugStringA(buffer); } va_end(va); #else va_list va; va_start(va, fmt); vfprintf(stdout, fmt, va); va_end(va); #endif } } // namespace extras } // namespace carb
15,049
C
35.797066
117
0.614393
omniverse-code/kit/include/carb/extras/Uuid.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 UUIDv4 utilities #pragma once #include "../Defines.h" #include "../cpp/StringView.h" #include "../cpp/Bit.h" #include "StringSafe.h" #include "StringUtils.h" #include <array> #include <cctype> #include <cinttypes> #include <cstring> #include <functional> #include <iostream> #include <random> #include <string> #include <type_traits> namespace carb { namespace extras { /** * UUIDv4 Unique Identifier (RFC 4122) */ class Uuid final { public: using value_type = std::array<uint8_t, 16>; ///< UUID raw bytes /** * Initialize empty UUID, 00000000-0000-0000-0000-000000000000 */ Uuid() noexcept : m_data{ 0U } { } /** * Convert a string to a Uuid using UUID format. * * Accepts the following formats: * 00000000-0000-0000-0000-000000000000 * {00000000-0000-0000-0000-000000000000} * urn:uuid:00000000-0000-0000-0000-000000000000 * * @param uuidStr string to try and convert to Uuid from */ Uuid(const std::string& uuidStr) noexcept : m_data{ 0U } { std::array<uint8_t, 16> data{ 0U }; carb::cpp::string_view uuidView; if (uuidStr[0] == '{' && uuidStr.size() == 38) { uuidView = carb::cpp::string_view(uuidStr.c_str(), uuidStr.size()).substr(1, uuidStr.size() - 2); } else if (startsWith(uuidStr.c_str(), "urn:uuid:") && uuidStr.size() == 45) // RFC 4122 { uuidView = carb::cpp::string_view(uuidStr.c_str(), uuidStr.size()).substr(9, uuidStr.size()); } else if (uuidStr.size() == 36) { uuidView = carb::cpp::string_view(uuidStr.c_str(), uuidStr.size()); } if (!uuidView.empty()) { CARB_ASSERT(uuidView.size() == 36); size_t i = 0; size_t j = 0; while (i < uuidView.size() - 1 && j < data.size()) { if ((i == 8) || (i == 13) || (i == 18) || (i == 23)) { if (uuidView[i] == '-') { ++i; continue; } } if (std::isxdigit(uuidView[i]) && std::isxdigit(uuidView[i + 1])) { char buf[3] = { uuidView[i], uuidView[i + 1], '\0' }; data[j++] = static_cast<uint8_t>(std::strtoul(buf, nullptr, 16)); i += 2; } else { // error parsing, unknown character break; } } // if we parsed the entire view and filled the entire array, copy it if (i == uuidView.size() && j == data.size()) { m_data = data; } } } /** * Create UUIDv4 DCE compatible universally unique identifier. */ static Uuid createV4() noexcept { Uuid uuidv4; std::random_device rd; for (size_t i = 0; i < uuidv4.m_data.size(); i += 4) { // use the entire 32-bits returned by random device uint32_t rdata = rd(); uuidv4.m_data[i + 0] = (rdata >> 0) & 0xff; uuidv4.m_data[i + 1] = (rdata >> 8) & 0xff; uuidv4.m_data[i + 2] = (rdata >> 16) & 0xff; uuidv4.m_data[i + 3] = (rdata >> 24) & 0xff; } uuidv4.m_data[6] = (uuidv4.m_data[6] & 0x0f) | 0x40; // RFC 4122 for UUIDv4 uuidv4.m_data[8] = (uuidv4.m_data[8] & 0x3f) | 0x80; // RFC 4122 for UUIDv4 return uuidv4; } /** * Check if Uuid is empty * * @return true if Uuid is empty; otherwise, false */ bool isEmpty() const noexcept { auto data = m_data.data(); return *data == 0 && memcmp(data, data + 1, m_data.size() - 1) == 0; } /** * Access the binary data of the UUID * * @return array of UUID data */ const value_type& data() const noexcept { return m_data; } /** * Compare two UUIDs for equality * * @param rhs right hand side of == * @return true if uuids are equal; otherwise false */ bool operator==(const Uuid& rhs) const noexcept { return !memcmp(m_data.data(), rhs.m_data.data(), m_data.size()); } /** * Compare two UUIDs for inequality * * @param rhs right hand side of != * @return true if uuids are not equal; otherwise false */ bool operator!=(const Uuid& rhs) const noexcept { return !(*this == rhs); } #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Convert Uuid to string. * * @return string of Uuid, empty string if failed to convert */ friend std::string to_string(const Uuid& uuid) noexcept { // UUID format 00000000-0000-0000-0000-000000000000 static constexpr char kFmtString[] = "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "-%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8 "%02" SCNx8; // 32 chars + 4 dashes + 1 null termination char strBuffer[37]; formatString(strBuffer, CARB_COUNTOF(strBuffer), kFmtString, uuid.m_data[0], uuid.m_data[1], uuid.m_data[2], uuid.m_data[3], uuid.m_data[4], uuid.m_data[5], uuid.m_data[6], uuid.m_data[7], uuid.m_data[8], uuid.m_data[9], uuid.m_data[10], uuid.m_data[11], uuid.m_data[12], uuid.m_data[13], uuid.m_data[14], uuid.m_data[15]); return std::string(strBuffer); } /** * Overload operator<< for easy use with std streams * * @param os output stream * @param uuid uuid to stream * @return output stream */ friend std::ostream& operator<<(std::ostream& os, const Uuid& uuid) { return os << to_string(uuid); } #endif // DOXYGEN_SHOULD_SKIP_THIS private: value_type m_data; }; CARB_ASSERT_INTEROP_SAFE(Uuid); static_assert(std::is_trivially_move_assignable<Uuid>::value, "Uuid must be move assignable"); static_assert(sizeof(Uuid) == 16, "Uuid must be exactly 16 bytes"); } // namespace extras } // namespace carb #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace std { template <> struct hash<carb::extras::Uuid> { using argument_type = carb::extras::Uuid; using result_type = std::size_t; result_type operator()(argument_type const& uuid) const noexcept { // uuid is random bytes, so just XOR // bit_cast() won't compile unless sizes match auto parts = carb::cpp::bit_cast<std::array<result_type, 2>>(uuid.data()); return parts[0] ^ parts[1]; } }; } // namespace std #endif // DOXYGEN_SHOULD_SKIP_THIS
7,296
C
27.503906
116
0.544134
omniverse-code/kit/include/carb/extras/Barrier.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. // #pragma once #include "../cpp/Barrier.h" namespace carb { namespace extras { template <class CompletionFunction = carb::cpp::detail::NullFunction> class CARB_DEPRECATED("Deprecated: carb::extras::binary_semaphore has moved to carb::cpp::binary_semaphore") barrier : public carb::cpp::barrier<CompletionFunction> { public: constexpr explicit barrier(ptrdiff_t desired, CompletionFunction f = CompletionFunction()) : carb::cpp::barrier<CompletionFunction>(desired, std::move(f)) { } }; } // namespace extras } // namespace carb
993
C
31.064515
116
0.755287
omniverse-code/kit/include/carb/extras/Utf8Parser.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 Provides helper classes to parse and convert UTF-8 strings to and from Unicode. */ #pragma once #include "../Defines.h" #include "../../omni/extras/ScratchBuffer.h" #include <cstdint> #include <algorithm> #include <cmath> /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { /** Static helper class to allow for the processing of UTF-8 strings. This can walk individual * codepoints in a string, decode and encode codepoints, and count the number of codepoints in * a UTF-8 string. Minimal error checking is done in general and there is a common assumption * that the input string is valid. The only failure points that will be checked are ones that * prevent further decoding (ie: not enough space left in a buffer, unexpected sequences, * misaligned strings, etc). */ class Utf8Parser { public: /** The base type for a single Unicode codepoint value. This represents a decoded UTF-8 * codepoint. */ using CodePoint = char32_t; /** The base type for a single UTF-16 Unicode codepoint value. This represents a decoded * UTF-8 codepoint that fits in 16 bits, or a single member of a surrogate pair. */ using Utf16CodeUnit = char16_t; /** The base type for a point in a UTF-8 string. Ideally these values should point to the * start of an encoded codepoint in a string. */ using CodeByte = char; /** Base type for flags to various encoding and decoding functions. */ using Flags = uint32_t; /** Names to classify a decoded codepoint's membership in a UTF-16 surrogate pair. The * UTF-16 encoding allows a single Unicode codepoint to be represented using two 16-bit * codepoints. These two codepoints are referred to as the 'high' and 'low' codepoints. * The high codepoint always comes first in the pair, and the low codepoint is expected * to follow immediately after. The high codepoint is always in the range 0xd800-0xdbff. * The low codepoint is always in the range 0xdc00-0xdfff. These ranges are reserved * in the Unicode set specifically for the encoding of UTF-16 surrogate pairs and will * never appear in an encoded UTF-8 string that contains UTF-16 encoded pairs. */ enum class SurrogateMember { /** The codepoint is not part of a UTF-16 surrogate pair. This codepoint is outside * the 0xd800-0xdfff range and is either represented directly in UTF-8 or is small * enough to not require a UTF-16 encoding. */ eNone, /** The codepoint is a high value in the surrogate pair. This must be in the range * reserved for UTF-16 high surrogate pairs (ie: 0xd800-0xdbff). This codepoint must * come first in the pair. */ eHigh, /** The codepoint is a low value in the surrogate pair. This must be in the range * reserved for UTF-16 low surrogate pairs (ie: 0xdc00-0xdfff). This codepoint must * come second in the pair. */ eLow, }; /** Flag to indicate that the default codepoint should be returned instead of just a * zero when attempting to decode an invalid UTF-8 sequence. */ static constexpr Flags fDecodeUseDefault = 0x00000001; /** Flag to indicate that invalid code bytes should be skipped over in a string when searching * for the start of the next codepoint. The default behavior is to fail the operation when * an invalid sequence is encountered. */ static constexpr Flags fDecodeSkipInvalid = 0x00000002; /** Flag to indicate that UTF-16 surrogate pairs should be used when encoding large codepoints * instead of directly representing them in UTF-8. Using this flag makes UTF-8 strings more * friendly to other UTF-8 systems on Windows (though Windows decoding facilities would still * be able to decode the directly stored codepoints as well). */ static constexpr Flags fEncodeUseUtf16 = 0x00000004; /** Flag for nextCodePoint() which tells the function to ignore surrogate pairs when decoding * and just return both elements of the pair as code points. * This exists mainly for internal use. */ static constexpr Flags fEncodeIgnoreSurrogatePairs = 0x00000008; /** The string buffer is effectively null terminated. This allows the various decoding * functions to bypass some range checking with the assumption that there is a null * terminating character at some point in the buffer. */ static constexpr size_t kNullTerminated = ~0ull; /** An invalid Unicode codepoint. */ static constexpr CodePoint kInvalidCodePoint = ~0u; /** The minimum buffer size that is guaranteed to be large enough to hold an encoded UTF-8 * codepoint. This does not include space for a null terminator codepoint. */ static constexpr size_t kMaxSequenceLength = 7; /** The codepoint reserved in the Unicode standard to represent the decoded result of an * invalid UTF-8 sequence. */ static constexpr CodePoint kDefaultCodePoint = 0x0000fffd; /** Finds the start of the next UTF-8 codepoint in a string. * * @param[in] str The UTF-8 string to find the next codepoint in. This may not * be `nullptr`. This is assumed to be a valid UTF-8 encoded * string and the passed in address is assumed to be the start * of another codepoint. If the @ref fDecodeSkipInvalid flag is * used in @p flags, an attempt will be made to find the start of * the next valid codepoint in the string before failing. If a * valid lead byte is found within the bounds of the string, that * will be returned instead of failing in this case. * @param[in] lengthInBytes The remaining number of bytes in the string. This may be * @ref kNullTerminated if the string is well known to be null * terminated. This operation will not walk the string beyond * this number of bytes. Note that the operation may still end * before this many bytes have been scanned if a null terminator * is encountered. * @param[out] codepoint Receives the decoded codepoint. This may be `nullptr` if the * decoded codepoint is not needed. If this is `nullptr`, none of * the work to decode the codepoint will be done. If the next * UTF-8 codepoint is part of a UTF-16 surrogate pair, the full * codepoint will be decoded. * @param[in] flags Flags to control the behavior of this operation. This may be * 0 or one or more of the fDecode* flags. * @returns The address of the start of the next codepoint in the string if one is found. * @returns `nullptr` if the string is empty, a null terminator is found, or there are no more * bytes remaining in the string. * * @remarks This attempts to walk a UTF-8 encoded string to find the start of the next valid * codepoint. This can be used to walk from one codepoint to another and modify * the string as needed, or to just count its length in codepoints. */ static const CodeByte* nextCodePoint(const CodeByte* str, size_t lengthInBytes = kNullTerminated, CodePoint* codepoint = nullptr, Flags flags = 0) { // retrieve the next code point CodePoint high = 0; const CodeByte* next = nullptr; bool r = parseUtf8(str, &next, &high, lengthInBytes, flags); if (codepoint != nullptr) { *codepoint = high; } // parsing failed => just fail out if (!r) { return next; } // it's a surrogate pair (and we're allowed to parse those) => parse out the full pair if ((flags & fEncodeIgnoreSurrogatePairs) == 0 && classifyUtf16SurrogateMember(high) == SurrogateMember::eHigh) { // figure out the new length if it's not null terminated const size_t newLen = (lengthInBytes == kNullTerminated) ? kNullTerminated : (lengthInBytes - (next - str)); // parse out the next code point CodePoint low = 0; r = parseUtf8(next, &next, &low, newLen, flags); // invalid surrogate pair => fail if (!r || classifyUtf16SurrogateMember(low) != SurrogateMember::eLow) { if (codepoint != nullptr) { *codepoint = getFailureCodepoint(flags); } return next; } // valid surrogate pair => calculate the code point if (codepoint != nullptr) { *codepoint = (((high & kSurrogateMask) << kSurrogateBits) | (low & kSurrogateMask)) + kSurrogateBias; } return next; } return next; } /** Finds the start of the last UTF-8 codepoint in a string. * * @param[in] str The UTF-8 string to find the last codepoint in. * This is assumed to be a valid UTF-8 encoded * string and the passed in address is assumed to be the start * of another codepoint. If the @ref fDecodeSkipInvalid flag is * used in @p flags, an attempt will be made to find the start of * the last valid codepoint in the string before failing. If a * valid lead byte is found within the bounds of the string, that * will be returned instead of failing in this case. * @param[in] lengthInBytes The remaining number of bytes in the string. This may be * @ref kNullTerminated if the string is well known to be null * terminated. This operation will not walk the string beyond * this number of bytes. Note that the operation may still end * before this many bytes have been scanned if a null terminator * is encountered. * @param[out] codepoint Receives the decoded codepoint. This may be `nullptr` if the * decoded codepoint is not needed. If this is `nullptr`, none of * the work to decode the codepoint will be done. If the last * UTF-8 codepoint is part of a UTF-16 surrogate pair, the full * codepoint will be decoded. * @param[in] flags Flags to control the behavior of this operation. This may be * 0 or one or more of the fDecode* flags. * @returns The address of the start of the last codepoint in the string if one is found. * @returns `nullptr` if the string is empty, a null terminator is found, or there are no more * bytes remaining in the string. * * @remarks This function attempts to walk a UTF-8 encoded string to find the start of the last * valid codepoint. */ static const CodeByte* lastCodePoint(const CodeByte* str, size_t lengthInBytes = kNullTerminated, CodePoint* codepoint = nullptr, Flags flags = fDecodeUseDefault) { // Prepare error value result if (codepoint != nullptr) { *codepoint = getFailureCodepoint(flags); } // Check if it's a null or empty string if (!str || *str == 0) { return nullptr; } if (lengthInBytes == kNullTerminated) { lengthInBytes = std::strlen(str); } // Make sure no unexpected flags pass into used `nextCodePoint` function constexpr Flags kErrorHandlingMask = fDecodeSkipInvalid | fDecodeUseDefault; const Flags helperParserFlags = (flags & kErrorHandlingMask); size_t curCodePointSize = 0; // Keeps max number of bytes for a decoding attempt with `nextCodePoint` const bool skipInvalid = (flags & fDecodeSkipInvalid) != 0; // Walk the string backwards to find the start of the last CodePoint and decode it // Note: it can be a single byte or a sequence, also if not searching for the last valid CodePoint // the maximum number of bytes to check is just last `kMaxSequenceLength` bytes instead of the full string const CodeByte* const rIterBegin = str - 1 + lengthInBytes; const CodeByte* const rIterEnd = (flags & fDecodeSkipInvalid) ? str - 1 : CARB_MAX(str - 1, rIterBegin - kMaxSequenceLength); for (const CodeByte* rIter = rIterBegin; rIter != rIterEnd; --rIter) { const uint8_t curByte = static_cast<uint8_t>(*rIter); ++curCodePointSize; // Check if the current code byte is a direct ASCII character if (curByte < k7BitLimit) { // If parsed more than one byte then it's an error if (curCodePointSize > 1 && !skipInvalid) { return nullptr; } if (codepoint != nullptr) { *codepoint = curByte; } return rIter; } // The current code byte is a continuation byte so step further if (curByte < kMinLeadByte) { continue; } // The current code byte is a lead byte, decode the sequence and check that all bytes were used CodePoint cp{}; const CodeByte* next = nextCodePoint(rIter, curCodePointSize, &cp, helperParserFlags); if (!next) { if (skipInvalid) { curCodePointSize = 0; continue; } return nullptr; } // Validate that all bytes till the end were used if expecting no invalid bytes // Ex: "\xce\xa6\xa6" is a 2 byte sequence "\xce\xa6" for a 0x03A6 code point followed by excessive // follow up byte "\xa6". The first 2 bytes will be decoded by the `nextCodePoint` properly // and `next` will be pointing at the last "\xa6" byte if (!skipInvalid && curCodePointSize != static_cast<size_t>(next - rIter)) { return nullptr; } const SurrogateMember surrogateType = classifyUtf16SurrogateMember(cp); // Encountered the high surrogate part first which is an error if (CARB_UNLIKELY(surrogateType == SurrogateMember::eHigh)) { if (skipInvalid) { // Just skip it and search further curCodePointSize = 0; continue; } return nullptr; } // Found the low part of a surrogate pair, need to continue parsing to get the high part else if (CARB_UNLIKELY(surrogateType == SurrogateMember::eLow)) { constexpr int kSurrogatePartSize = 3; constexpr int kFullSurrogatePairSize = 2 * kSurrogatePartSize; // To prepare for possible continuation of parsing if skipping invalid bytes and no high surrogate is // found reset the possible CodePoint size curCodePointSize = 0; // For a valid UTF-8 string there are must be high surrogate (3 bytes) preceding low surrogate (3 bytes) if (rIter <= rIterEnd + kSurrogatePartSize) { if (skipInvalid) { // Skip the low surrogate data and continue to check the preceding byte continue; } return nullptr; } // Step 3 bytes preceding the low surrogate const CodeByte* const possibleHighSurStart = rIter - kSurrogatePartSize; // Check if it starts with a lead byte if (static_cast<uint8_t>(*possibleHighSurStart) < kMinLeadByte) { if (skipInvalid) { continue; } return nullptr; } // Try to parse 6 bytes (full surrogate pair size) to get the whole CodePoint without skipping invalid // bytes const CodeByte* const decodedPairEnd = nextCodePoint(possibleHighSurStart, kFullSurrogatePairSize, &cp, 0); if (!decodedPairEnd) { if (skipInvalid) { continue; } return nullptr; } // Check if used all 6 bytes (as expected from a surrogate pair) if (decodedPairEnd - possibleHighSurStart != kFullSurrogatePairSize) { if (skipInvalid) { continue; } return nullptr; } // A proper surrogate pair was parsed into the `cp` // and only the `rIter` has invalid value at this point rIter = possibleHighSurStart; // Just exit the block so the code below reports the result } if (codepoint) { *codepoint = cp; } // Everything is fine thus return start of the sequence return rIter; } // Didn't find start of a valid CodePoint return nullptr; } /** Calculates the length of a UTF-8 string in codepoints. * * @param[in] str The string to count the number of codepoints in. This may not * be `nullptr`. This is expected to be a valid UTF-8 string. * @param[in] maxLengthInBytes The maximum number of bytes to parse in the string. This can * be @ref kNullTerminated if the string is well known to be null * terminated. * @param[in] flags Flags to control the behavior of this operation. This may be * 0 or @ref fDecodeSkipInvalid. * @returns The number of valid codepoints in the given UTF-8 string. * @returns `0` if the string is empty or no valid codepoints are found. * * @remarks This can be used to count the number of codepoints in a UTF-8 string. The count * will only include valid codepoints that are found in the string. It will not * include a count for any invalid code bytes that are skipped over when the * @ref fDecodeSkipInvalid flag is used. This means that it's not necessarily safe * to use this result (when the flag is used) to allocate a decode buffer, then * decode the codepoints in the string with getCodePoint() using the * @ref fDecodeUseDefault flag. */ static size_t getLengthInCodePoints(const CodeByte* str, size_t maxLengthInBytes = kNullTerminated, Flags flags = 0) { const CodeByte* current; const CodeByte* next; size_t count = 0; // get the second codepoint in the string. current = str; next = nextCodePoint(str, maxLengthInBytes, nullptr, flags); // empty or invalid string => fail. if (next == nullptr) return 0; if (maxLengthInBytes != kNullTerminated) { maxLengthInBytes -= next - current; } count++; do { current = next; next = nextCodePoint(current, maxLengthInBytes, nullptr, flags); if (next == nullptr) return count; if (maxLengthInBytes != kNullTerminated) { maxLengthInBytes -= next - current; } count++; } while (maxLengthInBytes > 0); return count; } /** Calculates the length of a Unicode string in UTF-8 code bytes. * * @param[in] str The string to count the number of code bytes that will * be required to store it in UTF-8. This may not be * `nullptr`. This is expected to be a valid Unicode * string. * @param[in] maxLengthInCodePoints The maximum number of codepoints to parse in the * string. This can be @ref kNullTerminated if the * string is well known to be null terminated. * @param[in] flags Flags to control the behavior of this operation. * This may be 0 or @ref fEncodeUseUtf16. * @returns The number of UTF-8 code bytes required to encode this Unicode string, not * including the null terminator. * @returns `0` if the string is empty or no valid codepoints are found. * * @remarks This can be used to count the number of UTF-8 code bytes required to encode * the given Unicode string. The count will only include valid codepoints that * are found in the string. Note that if the @ref fEncodeUseUtf16 flag is not * used here to calculate the size of a buffer, it should also not be used when * converting codepoints. Otherwise the buffer could overflow. * * @note For the 32-bit codepoint variant of this function, it is assumed that UTF-16 * surrogate pairs do not exist in the source string. In the 16-bit codepoint * variant, surrogate pairs are supported. */ static size_t getLengthInCodeBytes(const CodePoint* str, size_t maxLengthInCodePoints = kNullTerminated, Flags flags = 0) { size_t count = 0; size_t largeCodePointSize = 4; if ((flags & fEncodeUseUtf16) != 0) largeCodePointSize = 6; for (size_t i = 0; str[i] != 0 && i < maxLengthInCodePoints; i++) { if (str[i] < getMaxCodePoint(0)) count++; else if (str[i] < getMaxCodePoint(1)) count += 2; else if (str[i] < getMaxCodePoint(2)) count += 3; else if (str[i] < getMaxCodePoint(3)) count += largeCodePointSize; else if (str[i] < getMaxCodePoint(4)) count += 5; else if (str[i] < getMaxCodePoint(5)) count += 6; else count += 7; } return count; } /** @copydoc getLengthInCodeBytes */ static size_t getLengthInCodeBytes(const Utf16CodeUnit* str, size_t maxLengthInCodePoints = kNullTerminated, Flags flags = 0) { size_t count = 0; size_t largeCodePointSize = 4; if ((flags & fEncodeUseUtf16) != 0) largeCodePointSize = 6; for (size_t i = 0; str[i] != 0 && i < maxLengthInCodePoints; i++) { if (str[i] < getMaxCodePoint(0)) count++; else if (str[i] < getMaxCodePoint(1)) count += 2; else { // found a surrogate pair in the string -> both of these codepoints will decode to // a single UTF-32 codepoint => skip the low surrogate and add the size of a // single encoded codepoint. if (str[i] >= kSurrogateBaseHigh && str[i] < kSurrogateBaseLow && i + 1 < maxLengthInCodePoints && str[i + 1] >= kSurrogateBaseLow && str[i + 1] <= kSurrogateMax) { i++; count += largeCodePointSize; } // not part of a UTF-16 surrogate pair => this will encode to 3 bytes in UTF-8. else count += 3; } } return count; } /** Decodes a single codepoint from a UTF-8 string. * * @param[in] str The string to decode the first codepoint from. This may not * be `nullptr`. The string is expected to be aligned to the start * of a valid codepoint. * @param[in] lengthInBytes The number of bytes remaining in the string. This can be set * to @ref kNullTerminated if the string is well known to be null * terminated. * @param[in] flags Flags to control the behavior of this operation. This may be * `0` or @ref fDecodeUseDefault. * @returns The decoded codepoint if successful. * @returns `0` if the end of the string is encountered, the string is empty, or there are not * enough bytes left in the string to decode a full codepoint, and the @p flags * parameter is zero. * @retval kDefaultCodePoint if the end of the string is encountered, the string is * empty, or there are not enough bytes left in the string to decode a full * codepoint, and the @ref fDecodeUseDefault flag is used. * * @remarks This decodes the next codepoint in a UTF-8 string. The returned codepoint may be * part of a UTF-16 surrogate pair. The classifyUtf16SurrogateMember() function can * be used to determine if this is the case. If this is part of a surrogate pair, * the caller should decode the next codepoint then decode the full pair into a * single codepoint using decodeUtf16CodePoint(). */ static CodePoint getCodePoint(const CodeByte* str, size_t lengthInBytes = kNullTerminated, Flags flags = 0) { char32_t c = 0; nextCodePoint(str, lengthInBytes, &c, flags); return c; } /** Encodes a single Unicode codepoint to UTF-8. * * @param[in] cp The codepoint to be encoded into UTF-8. This may be any valid * Unicode codepoint. * @param[out] str Receives the encoded UTF-8 codepoint. This may not be `nullptr`. * This could need to be up to seven bytes to encode any possible * Unicode codepoint. * @param[in] lengthInBytes The size of the output buffer in bytes. No more than this many * bytes will be written to the @p str buffer. * @param[out] bytesWritten Receives the number of bytes that were written to the output * buffer. This may not be `nullptr`. * @param[in] flags Flags to control the behavior of this operation. This may be * `0` or @ref fEncodeUseUtf16. * @returns The output buffer if the codepoint is successfully encoded. * @returns `nullptr` if the output buffer was not large enough to hold the encoded codepoint. */ static CodeByte* getCodeBytes(CodePoint cp, CodeByte* str, size_t lengthInBytes, size_t* bytesWritten, Flags flags = 0) { size_t sequenceLength = 0; size_t continuationLength = 0; size_t codePointCount = 1; CodePoint codePoint[2] = { cp, 0 }; CodeByte* result; // not enough room in the buffer => fail. if (lengthInBytes == 0) { *bytesWritten = 0; return nullptr; } // a 7-bit ASCII character -> this can be directly stored => store and return. if (codePoint[0] < k7BitLimit) { str[0] = (codePoint[0] & 0xff); *bytesWritten = 1; return str; } // at this point we know that the encoding for the codepoint is going to require at least // two bytes. We need to calculate the sequence length and encode the bytes. // allowing a UTF-16 surrogate pair encoding in the string and the codepoint is above the // range where a surrogate pair is necessary => calculate the low and high codepoints // for the pair and set the sequence length. if ((flags & fEncodeUseUtf16) != 0 && codePoint[0] >= kSurrogateBias) { sequenceLength = 3; continuationLength = 2; codePointCount = 2; codePoint[0] -= kSurrogateBias; codePoint[1] = kSurrogateBaseLow | (codePoint[0] & kSurrogateMask); codePoint[0] = kSurrogateBaseHigh | ((codePoint[0] >> kSurrogateBits) & kSurrogateMask); } // not using a UTF-16 surrogate pair => search for the required length of the sequence. else { // figure out the required sequence length for the given for this codepoint. for (size_t i = 1; i < kMaxSequenceBytes; i++) { if (codePoint[0] < getMaxCodePoint(i)) { sequenceLength = i + 1; continuationLength = i; break; } } // failed to find a sequence length for the given codepoint (?!?) => fail (this should // never happen). if (sequenceLength == 0) { *bytesWritten = 0; return nullptr; } } // not enough space in the buffer to store the entire sequence => fail. if (lengthInBytes < sequenceLength * codePointCount) { *bytesWritten = 0; return nullptr; } result = str; // write out each of the codepoints. If UTF-16 encoding is not being used, there will only // be one codepoint and this loop will exit after the first iteration. for (size_t j = 0; j < codePointCount; j++) { cp = codePoint[j]; // write out the lead byte. *str = getLeadByte(continuationLength) | ((cp >> (continuationLength * kContinuationShift)) & getLeadMask(continuationLength)); str++; // write out the continuation bytes. for (size_t i = 0; i < continuationLength; i++) { *str = kContinuationBits | ((cp >> ((continuationLength - i - 1) * kContinuationShift)) & kContinuationMask); str++; } } *bytesWritten = sequenceLength * codePointCount; return result; } /** Classifies a codepoint as being part of a UTF-16 surrogate pair or otherwise. * * @param[in] cp The codepoint to classify. This may be any valid Unicode codepoint. * @retval SurrogateMember::eNone if the codepoint is not part of a UTF-16 surrogate * pair. * @retval SurrogateMember::eHigh if the codepoint is a 'high' UTF-16 surrogate pair * codepoint. * @retval SurrogateMember::eLow if the codepoint is a 'low' UTF-16 surrogate pair * codepoint. */ static SurrogateMember classifyUtf16SurrogateMember(CodePoint cp) { if (cp >= kSurrogateBaseHigh && cp < kSurrogateBaseLow) return SurrogateMember::eHigh; if (cp >= kSurrogateBaseLow && cp <= kSurrogateMax) return SurrogateMember::eLow; return SurrogateMember::eNone; } /** Decodes a UTF-16 surrogate pair to a Unicode codepoint. * * @param[in] high The codepoint for the 'high' member of the UTF-16 surrogate pair. * @param[in] low The codepoint for the 'low' member of the UTF-16 surrogate pair. * @returns The decoded codepoint if the two input codepoints were a UTF-16 surrogate pair. * @returns `0` if either of the input codepoints were not part of a UTF-16 surrogate pair. */ static CodePoint decodeUtf16CodePoint(CodePoint high, CodePoint low) { CodePoint cp; // the high and low codepoints are out of the surrogate pair range -> cannot decode => fail. if (high < kSurrogateBaseHigh || high >= kSurrogateBaseLow || low < kSurrogateBaseLow || low > kSurrogateMax) return 0; // decode the surrogate pair into a single Unicode codepoint. cp = (((high & kSurrogateMask) << kSurrogateBits) | (low & kSurrogateMask)) + kSurrogateBias; return cp; } /** Encodes a Unicode codepoint into a UTF-16 codepoint. * * @param[in] cp The UTF-32 codepoint to encode. This may be any valid codepoint. * @param[out] out Receives the equivalent codepoint encoded in UTF-16. This will either be * a single UTF-32 codepoint if its value is less than the UTF-16 encoding * size of 16 bits, or it will be a UTF-16 surrogate pair for codepoint * values larger than 16 bits. In the case of a single codepoint being * written, it will occupy the lower 16 bits of this buffer. If two * codepoints are written, the 'high' surrogate pair member will be in * the lower 16 bits, and the 'low' surrogate pair member will be in the * upper 16 bits. This is suitable for use as a UTF-16 buffer to pass to * other functions that expect a surrogate pair. The number of codepoints * written can be differentiated by the return value of this function. This * may be `nullptr` if the encoded UTF-16 codepoint is not needed but only the * number of codepoints is of interest. This may safely be the same buffer * as @p cp. * @returns `1` if the requested codepoint was small enough for a direct encoding into UTF-16. * This can be interpreted as a single codepoint being written to the output * codepoint buffer. * @returns `2` if the requested codepoint was too big for direct encoding in UTF-16 and had * to be encoded as a surrogate pair. This can be interpreted as two codepoints * being written to the output codepoint buffer. */ static size_t encodeUtf16CodePoint(CodePoint cp, CodePoint* out) { CodePoint high; CodePoint low; // small enough for a direct encoding => just store it. if (cp < kSurrogateBias) { if (out != nullptr) *out = cp; return 1; } // too big for direct encoding => convert it to a surrogate pair and store both in the // output buffer. cp -= kSurrogateBias; low = kSurrogateBaseLow | (cp & kSurrogateMask); high = kSurrogateBaseHigh | ((cp >> kSurrogateBits) & kSurrogateMask); if (out != nullptr) *out = high | (low << 16); return 2; } /** Checks if the provided code point corresponds to a whitespace character * * @param[in] cp The UTF-32 codepoint to check * * @returns true if the codepoint is a whitespace character, false otherwise */ inline static bool isSpaceCodePoint(CodePoint cp) { // Taken from https://en.wikipedia.org/wiki/Whitespace_character // Note: sorted to allow binary search static constexpr CodePoint kSpaceCodePoints[] = { 0x0009, // character tabulation 0x000A, // line feed 0x000B, // line tabulation 0x000C, // form feed 0x000D, // carriage return 0x0020, // space 0x0085, // next line 0x00A0, // no-break space 0x1680, // ogham space mark 0x180E, // Mongolian vowel separator 0x2000, // en quad 0x2001, // em quad 0x2002, // en space 0x2003, // em space 0x2004, // three-per-em space 0x2005, // four-per-em space 0x2006, // six-per-em space 0x2007, // figure space 0x2008, // punctuation space 0x2009, // thin space 0x200A, // hair space 0x200B, // zero width space 0x200C, // zero width non-joiner 0x200D, // zero width joiner 0x2028, // line separator 0x2029, // paragraph separator 0x202F, // narrow no-break space 0x205F, // medium mathematical space 0x2060, // word joiner 0x3000, // ideograph space 0xFEFF, // zero width non-breaking space }; constexpr size_t kSpaceCodePointsCount = CARB_COUNTOF(kSpaceCodePoints); constexpr const CodePoint* const kSpaceCodePointsEnd = kSpaceCodePoints + kSpaceCodePointsCount; return std::binary_search(kSpaceCodePoints, kSpaceCodePointsEnd, cp); } private: /** The number of valid codepoint bits in the lead byte of a UTF-8 codepoint. This table is * indexed by the continuation length of the sequence. The first entry represents a sequence * length of 1 (ie: continuation length of 0). This table supports up to seven byte UTF-8 * sequences. Currently the UTF-8 standard only requires support for four byte sequences * since that covers the full defined Unicode set. The extra bits allows for future UTF-8 * expansion without needing to change the parser. Note that seven bytes is the theoretical * limit for a single UTF-8 sequence with the current algorithm. This allows for 36 bits of * codepoint information (which would already require a new codepoint representation anyway). * The most feasible decoding limit is a six byte sequence which allows for up to 31 bits of * codepoint information. */ static constexpr uint8_t s_leadBits[] = { 7, 5, 4, 3, 2, 1, 0 }; /** The maximum decoded codepoint currently set for the UTF-8 and Unicode standards. This * full range is representable with a four byte UTF-8 sequence. When the Unicode standard * expands beyond this limit, longer UTF-8 sequences will be required to fully encode the * new range. */ static constexpr CodePoint kMaxCodePoint = 0x0010ffff; /** The number of bits of valid codepoint information in the low bits of each continuation * byte in a sequence. */ static constexpr uint32_t kContinuationShift = 6; /** The lead bits of a continuation byte. Each continuation byte starts with the high * bit set followed by a clear bit, then the remaining bits contribute to the codepoint. */ static constexpr uint8_t kContinuationBits = 0x80; /** The mask of bits in each continuation byte that contribute to the codepoint. */ static constexpr uint8_t kContinuationMask = (1u << kContinuationShift) - 1; /** The base and bias value for a UTF-16 surrogate pair value. When encoding a surrogate * pair, this is subtracted from the original codepoint so that only 20 bits of relevant * information remain. These 20 bits are then split across the two surrogate pair values. * When decoding, this value is added to the decoded 20 bits that are extracted from the * code surrogate pair to get the final codepoint value. */ static constexpr CodePoint kSurrogateBias = 0x00010000; /** The lowest value that a UTF-16 surrogate pair codepoint can have. This will be the * low end of the range for the 'high' member of the pair. */ static constexpr CodePoint kSurrogateBaseHigh = 0x0000d800; /** The middle value that a UTF-16 surrogate pair codepoint can have. This will be the * low end of the range for the 'low' member of the pair, and one larger than the high * end of the range for the 'high' member of the pair. */ static constexpr CodePoint kSurrogateBaseLow = 0x0000dc00; /** The lowest value that any UTF-16 surrogate pair codepoint can have. */ static constexpr CodePoint kSurrogateMin = 0x0000d800; /** The highest value that any UTF-16 surrogate pair codepoint can have. This will be the * high end of the range for the 'low' member of the pair. */ static constexpr CodePoint kSurrogateMax = 0x0000dfff; /** The number of bits of codepoint information that is extracted from each member of the * UTF-16 surrogate pair. These will be the lowest bits of each of the two codepoints. */ static constexpr uint32_t kSurrogateBits = 10; /** The mask of the bits of codepoint information in each of the UTF-16 surrogate pair * members. */ static constexpr CodePoint kSurrogateMask = ((1 << kSurrogateBits) - 1); /** The maximum number of bytes that a UTF-8 codepoint sequence can have. This is the * mathematical limit of the algorithm. The current standard only supports up to four * byte sequences right now. A four byte sequence covers the full Unicode codepoint * set up to and including 0x10ffff. */ static constexpr size_t kMaxSequenceBytes = 7; /** The limit of a directly representable ASCII character in a UTF-8 sequence. All values * below this are simply directly stored in the UTF-8 sequence and can be trivially decoded * as well. */ static constexpr uint8_t k7BitLimit = 0x80; /** The minimum value that could possibly represent a lead byte in a multi-byte UTF-8 * sequence. All values below this are either directly representable in UTF-8 or indicate * a continuation byte for the sequence. Note that some byte values above this range * could still indicate an invalid sequence. See @a getContinuationLength() for more * information on this. */ static constexpr uint8_t kMinLeadByte = 0xc0; /** Retrieves the continuation length of a UTF-8 sequence for a given lead byte. * * @param[in] leadByte The lead byte of a UTF-8 sequence to retrieve the continuation * length for. This must be greater than or equal to the value of * @a kMinLeadByte. The results are undefined if the lead byte * is less than @a kMinLeadByte. * @returns The number of continuation bytes in the sequence for the given lead byte. * * @remarks This provides a lookup helper to retrieve the expected continuation length for * a given lead byte in a UTF-8 sequence. A return value of 0 indicates an invalid * sequence (either an overlong sequence or an invalid lead byte). The lead byte * values 0xc0 and 0xc1 for example represent an overlong sequence (ie: one that * unnecessarily encodes a single byte codepoint using multiple bytes). The lead * byte 0xff represents an invalid lead byte since it violates the rules of the * UTF-8 encoding. Each other value represents the number bytes that follow the * lead byte (not including the lead byte) to encode the codepoint. */ static constexpr uint8_t getContinuationLength(size_t leadByte) { constexpr uint8_t s_continuationSize[] = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xc0 - 0xcf */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0xd0 - 0xdf */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0xe0 - 0xef */ 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 0, /* 0xf0 - 0xff */ }; return s_continuationSize[leadByte - kMinLeadByte]; } /** Retrieves the lead byte mask for a given sequence continuation length. * * @param[in] continuationLength The continuation length for the sequence. This must be * less than @ref kMaxSequenceLength. * @returns The mask of bits in the lead byte that contribute to the decoded codepoint. * * @remarks This provides a lookup for the lead byte mask that determines which bits will * contribute to the codepoint. Each multi-byte sequence lead byte starts with as * many high bits set as the length of the sequence in bytes, followed by a clear * bit. The remaining bits in the lead byte contribute directly to the highest * bits of the decoded codepoint. */ static constexpr uint8_t getLeadMask(size_t continuationLength) { constexpr uint8_t s_leadMasks[] = { (1u << s_leadBits[0]) - 1, (1u << s_leadBits[1]) - 1, (1u << s_leadBits[2]) - 1, (1u << s_leadBits[3]) - 1, (1u << s_leadBits[4]) - 1, (1u << s_leadBits[5]) - 1, (1u << s_leadBits[6]) - 1 }; return s_leadMasks[continuationLength]; } /** Retrieves the lead byte bits that indicate the sequence length. * * @param[in] continuationLength The continuation length for the sequence. This must * be less than @ref kMaxSequenceLength. * @returns The high bits of the lead bytes with the given sequence length. * * @remarks This provides a lookup for the lead byte bits that indicate the sequence length * for a UTF-8 codepoint. This is used when encoding a Unicode codepoint into * UTF-8. */ static constexpr uint8_t getLeadByte(size_t continuationLength) { constexpr uint8_t s_leadBytes[] = { (0xffu << (s_leadBits[0] + 1)) & 0xff, (0xffu << (s_leadBits[1] + 1)) & 0xff, (0xffu << (s_leadBits[2] + 1)) & 0xff, (0xffu << (s_leadBits[3] + 1)) & 0xff, (0xffu << (s_leadBits[4] + 1)) & 0xff, (0xffu << (s_leadBits[5] + 1)) & 0xff, (0xffu << (s_leadBits[6] + 1)) & 0xff }; return s_leadBytes[continuationLength]; } /** Retrieves the maximum codepoint that can be represented by a given continuation length. * * @param[in] continuationLength The continuation length for the sequence. This must * be less than @ref kMaxSequenceLength. * @returns The maximum codepoint value that can be represented by the given continuation * length. This covers up to sequences with seven bytes. * * @remarks This provides a lookup for the maximum codepoint that can be represented by * a UTF-8 sequence of a given continuation length. This can be used to find the * required length for a sequence when encoding. Note that the limit for a seven * byte encoding is not currently fully representable here because it can hold * between 32 and 36 bits of codepoint information. */ static constexpr CodePoint getMaxCodePoint(size_t continuationLength) { constexpr CodePoint s_maxCodePoint[] = { 0x00000080, 0x00000800, 0x00010000, 0x00200000, 0x04000000, 0x80000000, 0xffffffff }; return s_maxCodePoint[continuationLength]; } /** Helper function to decode a single UTF-8 continuation byte. * * @param[in] byte The continuation byte to be decoded. * @param[in] continuationLength The number of continuation bytes remaining in the sequence * including the current continuation byte @p byte. * @returns The decoded codepoint bits shifted to their required position. This value should * be bitwise OR'd with the results of the previously decoded bytes in the sequence. */ inline static CodePoint decodeContinuationByte(uint8_t byte, size_t continuationLength) { return (byte & kContinuationMask) << ((continuationLength - 1) * kContinuationShift); } /** Helper function to retrieve the codepoint in a failure case. * * @param[in] flags The flags passed into the original function. Only the * @ref fDecodeUseDefault flag will be checked. * @returns `0` if the @ref fDecodeUseDefault flag is not used. * @retval kDefaultCodePoint if the flag is used. */ static constexpr CodePoint getFailureCodepoint(Flags flags) { return (flags & fDecodeUseDefault) != 0 ? kDefaultCodePoint : 0; } /** @brief Parse the next UTF-8 code point. * @param[in] str The UTF-8 input string to parse. * @param[out] outNext The pointer to the start of the next UTF-8 * character in the string. * This pointer will be set to `nullptr` if there * is no next character this string can point to * (e.g. if the string ended). * This will also be set to `nullptr` if the UTF-8 * character is invalid and @p flags does not contain * @ref fDecodeSkipInvalid. * This must not be `nullptr`. * @param[out] outCodePoint The code point that was parsed out of the UTF-8 string. * If the call fails, this will be set to a * default value depending on @p flags. * @param[in] lengthInBytes The remaining number of bytes in the string. This may be * @ref kNullTerminated if the string is well known to be null * terminated. This operation will not walk the string beyond * this number of bytes. Note that the operation may still end * before this many bytes have been scanned if a null terminator * is encountered. * @param[in] flags Flags to control the behavior of this operation. This may be * 0 or one or more of the fDecode* flags. * * @returns This returns `true` if the next UTF-8 character was parsed successfully * and `false` if the UTF-8 sequence was invalid. * `false` will also be returned if @p lengthInBytes is 0. * `true` will be returned for a null terminating character. * * @note This will not parse UTF-16 surrogate pairs. If one is encountered, * both code points will be returned in subsequent calls. */ static bool parseUtf8(const CodeByte* str, const CodeByte** outNext, CodePoint* outCodePoint, size_t lengthInBytes = kNullTerminated, Flags flags = 0) { auto fail = [&]() -> bool { // we weren't asked to attempt to skip over invalid code sequences => just fail out if ((flags & fDecodeSkipInvalid) == 0) { return false; } // walk the rest of the string skipping over continuation bytes and invalid lead bytes. // Note that we've already tested and rejected the first byte so we just need to continue // the search starting at the next byte. for (size_t i = 1; i < lengthInBytes; i++) { const auto b = static_cast<uint8_t>(str[i]); // continuation byte => skip it. if ((b & ~kContinuationMask) == kContinuationBits) continue; // invalid lead byte => skip it. if (b >= kMinLeadByte && getContinuationLength(b) == 0) continue; // invalid range of bytes if (b >= k7BitLimit && b < kMinLeadByte) continue; *outNext = str + i; return false; } // We've hit the end of the string. This mean that the sequence is // either invalid, misaligned, or an illegal overlong sequence was // used. We aren't able to write out the next character pointer if // we hit this point. return false; }; // initialize to failure values; *outCodePoint = getFailureCodepoint(flags); *outNext = nullptr; // the string doesn't have any more bytes in it -> no more codepoints => fail. if (lengthInBytes == 0) { return false; } const auto byte = static_cast<uint8_t>(*str); // the current code byte is at the null terminator -> no more codepoints => finish. if (byte == '\0') { *outCodePoint = byte; return true; } // the current code byte is a direct ASCII character => finish. if (byte < k7BitLimit) { *outCodePoint = byte; *outNext = str + 1; return true; } if (byte < kMinLeadByte) { return fail(); } // the current code byte is a lead byte => calculate the sequence length and return the // start of the next codepoint. const size_t continuationLength = getContinuationLength(byte); const size_t sequenceLength = continuationLength + 1; // not enough bytes left in the string to complete this codepoint => fail. // continuationLength of 0 is invalid => fail if (lengthInBytes < sequenceLength || continuationLength == 0) { return fail(); } // decode the codepoint. { CodePoint cp = (byte & getLeadMask(continuationLength)) << (continuationLength * kContinuationShift); for (size_t i = 0; i < continuationLength; i++) { // validate the continuation byte so we don't walk past the // end of a null terminated string if ((uint8_t(str[i + 1]) & ~kContinuationMask) != kContinuationBits) { return fail(); } cp |= decodeContinuationByte(str[i + 1], continuationLength - i); } *outCodePoint = cp; *outNext = str + sequenceLength; return true; } } }; /** A simple iterator class for walking a UTF-8 string. This is built on top of the UTF8Parser * static class and uses its functionality. Strings can only be walked forward. Random access * to codepoints in the string is not possible. If needed, the pointer to the start of the * next codepoint or the codepoint index can be retrieved. */ class Utf8Iterator { public: /** Reference the types used in Utf8Parser for more convenient use locally. * @{ */ /** @copydoc Utf8Parser::CodeByte */ using CodeByte = Utf8Parser::CodeByte; /** @copydoc Utf8Parser::CodePoint */ using CodePoint = Utf8Parser::CodePoint; /** @copydoc Utf8Parser::Flags */ using Flags = Utf8Parser::Flags; /** @} */ // Reference the special length value used for null terminated strings. /** @copydoc Utf8Parser::kNullTerminated */ static constexpr size_t kNullTerminated = Utf8Parser::kNullTerminated; Utf8Iterator() : m_prev(nullptr), m_string(nullptr), m_length(kNullTerminated), m_flags(0), m_lastCodePoint(0), m_index(0) { } /** Constructor: initializes a new iterator for a given string. * * @param[in] string The string to walk. This should be a UTF-8 encoded string. * This can be `nullptr`, but the iterator will not be valid if so. * @param[in] lengthInBytes The maximum number of bytes to walk in the string. This may * be kNullTerminated if the string is null terminated. If the * string is unterminated or only a portion of it needs to be * iterated over, this may be the size of the buffer in bytes. * @param[in] flags Flags to control the behavior of the UTF-8 parser. This may * be zero or more of the Utf8Parser::fDecode* flags. * @returns No return value. */ Utf8Iterator(const CodeByte* string, size_t lengthInBytes = kNullTerminated, Flags flags = 0) : m_prev(nullptr), m_string(string), m_length(lengthInBytes), m_flags(flags), m_lastCodePoint(0), m_index(0) { next(); } /** Copy constructor: copies another iterator into this one. * * @param[in] it The iterator to be copied. Note that if @p it is invalid, this iterator * will also become invalid. * @returns No return value. */ Utf8Iterator(const Utf8Iterator& it) { copy(it); } /** Checks if this iterator is still valid. * * @returns `true` if this iterator still has at least one more codepoint to walk. * @returns `false` if there is no more string data to walk and decode. */ operator bool() const { return isValid(); } /** Check is this iterator is invalid. * * @returns `true` if there is no more string data to walk and decode. * @returns `false` if this iterator still has at least one more codepoint to walk. */ bool operator!() const { return !isValid(); } /** Retrieves the codepoint at this iterator's current location. * * @returns The codepoint at the current location in the string. Calling this multiple * times does not cause the decoding work to be done multiple times. The decoded * codepoint is cached once decoded. * @returns `0` if there are no more codepoints to walk in the string. */ CodePoint operator*() const { return m_lastCodePoint; } /** Retrieves the address of the start of the current codepoint. * * @returns The address of the start of the current codepoint for this iterator. This can be * used as a way of copying, editing, or reworking the string during iteration. It * is the caller's responsibility to ensure the string is still properly encoded after * any change. * @returns `nullptr` if there is no more string data to walk. */ const CodeByte* operator&() const { return m_prev; } /** Pre increment operator: walk to the next codepoint in the string. * * @returns A reference to this iterator. Note that if the end of the string is reached, the * new state of this iterator will first point to the null terminator in the string * (for null terminated strings), then after another increment will return the * address `nullptr` from the '&' operator. For length limited strings, reaching the * end will immediately return `nullptr` from the '&' operator. */ Utf8Iterator& operator++() { next(); return *this; } /** Post increment operator: walk to the next codepoint in the string. * * @returns A new iterator object representing the state of this object before the increment * operation. */ Utf8Iterator operator++(int32_t) { Utf8Iterator tmp = (*this); next(); return tmp; } /** Increment operator: skip over zero or more codepoints in the string. * * @param[in] count The number of codepoints to skip over. This may be zero or larger. * Negative values will be ignored and the iterator will not advance. * @returns A reference to this iterator. */ template <typename T> Utf8Iterator& operator+=(T count) { for (T i = 0; i < count && m_prev != nullptr; i++) next(); return *this; } /** Addition operator: create a new iterator that skips zero or more codepoints. * * @param[in] count The number of codepoints to skip over. This may be zero or larger. * Negative values will be ignored and the iterator will not advance. * @returns A new iterator that has skipped over the next @p count codepoints in the string * starting from the location of this iterator. */ template <typename T> Utf8Iterator operator+(T count) const { Utf8Iterator tmp = *this; return (tmp += count); } /** Comparison operators. * * @param[in] it The iterator to compare this one to. * @returns `true` if the string position represented by @p it satisfies the requested * comparison versus this object. * @returns `false` if the string position represented by @p it does not satisfy the requested * comparison versus this object. * * @remarks This object is treated as the left side of the comparison. Only the offset into * the string contributes to this result. It is the caller's responsibility to * ensure both iterators refer to the same string otherwise the results are * undefined. */ bool operator==(const Utf8Iterator& it) const { return m_string == it.m_string; } /** @copydoc operator== */ bool operator!=(const Utf8Iterator& it) const { return m_string != it.m_string; } /** @copydoc operator== */ bool operator<(const Utf8Iterator& it) const { return m_string < it.m_string; } /** @copydoc operator== */ bool operator<=(const Utf8Iterator& it) const { return m_string <= it.m_string; } /** @copydoc operator== */ bool operator>(const Utf8Iterator& it) const { return m_string > it.m_string; } /** @copydoc operator== */ bool operator>=(const Utf8Iterator& it) const { return m_string >= it.m_string; } /** Copy assignment operator: copies another iterator into this one. * * @param[in] it The iterator to copy. * @returns A reference to this object. */ Utf8Iterator& operator=(const Utf8Iterator& it) { // Note: normally we'd check for an identity assignment in this operator overload and // ignore. Unfortunately we can't do that here since we also override the '&' // operator above. Since this copy operation should still be safe for an identity // assignment, we'll just let it proceed. copy(it); return *this; } /** String assignment operator: resets this iterator to the start of a new string. * * @param[in] str The new string to start walking. This must be a null terminated string. * If this is `nullptr`, the iterator will become invalid. Any previous flags * and length limits on this iterator will be cleared out. * @returns A reference to this object. */ Utf8Iterator& operator=(const CodeByte* str) { m_prev = nullptr; m_string = str; m_length = kNullTerminated; m_lastCodePoint = 0; m_flags = 0; m_index = 0; next(); return *this; } /** Retrieves the current codepoint index of the iterator. * * @returns The number of codepoints that have been walked so far by this iterator in the * current string. This will always start at 0 and will only increase when a * new codepoint is successfully decoded. */ size_t getIndex() const { return m_index - 1; } /** Retrieves the size of the current codepoint in bytes. * * @returns The size of the current codepoint (ie: the one returned with the '*' operator) * in bytes. This can be used along with the results of the '&' operator to copy * this encoded codepoint into another buffer or modify the string in place. */ size_t getCodepointSize() const { if (m_string == nullptr) return m_prev == nullptr ? 0 : 1; return m_string - m_prev; } private: /** Copies another iterator into this one. * * @param[in] it The iterator to copy from. * @returns No return value. */ void copy(const Utf8Iterator& it) { m_prev = it.m_prev; m_string = it.m_string; m_length = it.m_length; m_flags = it.m_flags; m_lastCodePoint = it.m_lastCodePoint; m_index = it.m_index; } /** Checks whether this iterator is still valid and has more work to do. * * @returns `true` if this iterator still has at least one more codepoint to walk. * @returns `false` if there is no more string data to walk and decode. */ bool isValid() const { return m_string != nullptr && m_lastCodePoint != 0; } /** Walks to the start of the next codepoint. * * @returns No return value. * * @remarks This walks this iterator to the start of the next codepoint. The codepoint * will be decoded and cached so that it can be retrieved. The length limit * will also be decremented to reflect the amount of string data left to parse. */ void next() { const CodeByte* ptr; if (m_string == nullptr) { m_prev = nullptr; return; } if (m_length == 0) { m_string = nullptr; m_prev = nullptr; m_lastCodePoint = 0; return; } ptr = Utf8Parser::nextCodePoint(m_string, m_length, &m_lastCodePoint, m_flags); if (m_length != kNullTerminated) m_length -= ptr - m_string; m_prev = m_string; m_string = ptr; m_index++; } /** A pointer to the start of the codepoint that was last decoded. This will be the codepoint * that has been cached in @a m_lastCodePoint. The size of this codepoint can be * calculated by subtracting this address from @a m_string. */ const CodeByte* m_prev; /** A pointer to the start of the next codepoint to be decoded. This will be `nullptr` if the * full string has been decoded. */ const CodeByte* m_string; /** The number of bytes remaining in the string or kNullTerminated. */ size_t m_length; /** Flags to control how the codepoints in the string will be decoded. */ Flags m_flags; /** The last codepoint that was successfully decoded. This is cached to prevent the need to * decode it multiple times. */ CodePoint m_lastCodePoint; /** The current codepoint index in the string. This is incremented each time a codepoint is * successfully decoded. */ size_t m_index; }; // implementation details used for string conversions - ignore this! #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { /** @brief A generic conversion between text formats. * @tparam T The type of the input string. * @tparam O The type of the output string. * @tparam toCodePoint A function that converts a null terminated string of * type T into a UTF-32 code point. * This will return a pair where the first member is the * length of the input consumed and the second is the * UTF-32 code point that was calculated. * Returning a 0 length will be treated as an error and * input parsing will stop. * @tparam fromCodePoint A function that converts a UTF-32 code point into * a string of type O. * This returns the length written to the ``out``. * This should return 0 if there is not enough space * in the output buffer; a partial character should * not be written to the output. * ``outLen`` is the amount of space available for * writing ``out``. * @param[in] str The input string to convert. This may not be `nullptr`. * @param[out] out The output buffer to hold the converted data. * This must be at least @p outLen in length, in elements. * This can be `nullptr` to calculate the required * output buffer length. * The output string written to @p out will always be * null terminated (unless @p outLen is 0), even if the * string had to be truncated. * @param[in] outLen The length of @p out, in elements. * This should be 1 if @p out is `nullptr`. * @returns If @p out is not `nullptr`, this returns the number of characters * written to @p out. This includes the null terminating character. * @returns If @p out is `nullptr`, this returns the required buffer length to * store the output string. */ template <typename T, typename O, std::pair<size_t, char32_t>(toCodePoint)(const T*), size_t(fromCodePoint)(char32_t c, O* out, size_t outLen)> inline size_t convertBetweenUnicodeFormatsRaw(const T* str, O* out, size_t outLen) { // the last element written to the output O* prev = nullptr; size_t prevLen = 0; size_t written = 0; size_t read = 0; bool fullyRead = false; if (str == nullptr) { return 0; } // no output => ignore outLen in the loop if (out == nullptr) { outLen = SIZE_MAX; } if (outLen == 0) { return 0; } for (;;) { size_t len; // decode the input to UTF-32 std::pair<size_t, char32_t> decoded = toCodePoint(str + read); // decode failed if (decoded.first == 0) { break; } // encode from UTF-32 to the output format len = fromCodePoint(decoded.second, (out == nullptr) ? nullptr : out + written, outLen - written); // out of buffer space if (len == 0) { break; } // store the last written character if (out != nullptr) { prev = out + written; } prevLen = len; // advance the indices written += len; read += decoded.first; // hit the null terminator => finished if (decoded.second == '\0') { fullyRead = true; break; } } // if the string was truncated, we need to cut out the last character // from the written count if (!fullyRead) { if (written == outLen) { written -= prevLen; written += 1; if (out != nullptr) { *prev = '\0'; } } else { if (out != nullptr) { out[written] = '\0'; } written++; } } return written; } inline std::pair<size_t, char32_t> utf8ToCodePoint(const char* str) { char32_t c = 0; const char* p = Utf8Parser::nextCodePoint(str, Utf8Parser::kNullTerminated, &c, Utf8Parser::fDecodeUseDefault); if (c == '\0') { return std::pair<size_t, char32_t>(1, '\0'); } else if (p == nullptr) { // invalid character, skip it return std::pair<size_t, char32_t>(1, c); } else { return std::pair<size_t, char32_t>(p - str, c); } } inline size_t utf32FromCodePoint(char32_t c, char32_t* out, size_t outLen) { if (outLen == 0) { return 0; } else { if (out != nullptr) { out[0] = c; } return 1; } }; inline std::pair<size_t, char32_t> utf32ToCodePoint(const char32_t* str) { return std::pair<size_t, char32_t>(1, *str); } inline size_t utf8FromCodePoint(char32_t c, char* out, size_t outLen) { char dummy[8]; size_t len = 0; char* p; if (out == nullptr) { out = dummy; outLen = CARB_MIN(outLen, CARB_COUNTOF(dummy)); } p = Utf8Parser::getCodeBytes(c, out, outLen, &len); if (p == nullptr) { return 0; } else { return len; } } inline std::pair<size_t, char32_t> utf16ToCodePoint(const char16_t* str) { char32_t c; switch (Utf8Parser::classifyUtf16SurrogateMember(str[0])) { case Utf8Parser::SurrogateMember::eHigh: c = Utf8Parser::decodeUtf16CodePoint(str[0], str[1]); if (c == 0) // invalid surrogate pair { break; } return std::pair<size_t, char32_t>(2, c); // a stray low surrogate is invalid case Utf8Parser::SurrogateMember::eLow: break; default: return std::pair<size_t, char32_t>(1, str[0]); } // failed to parse => just return the invalid character code point constexpr static auto kDefaultCodePoint_ = Utf8Parser::kDefaultCodePoint; // CC-1110 return std::pair<size_t, char32_t>(1, kDefaultCodePoint_); } inline size_t utf16FromCodePoint(char32_t c, char16_t* out, size_t outLen) { char32_t mangled = 0; size_t len; len = Utf8Parser::encodeUtf16CodePoint(c, &mangled); if (outLen < len) { return 0; } if (out != nullptr) { switch (len) { default: break; case 1: out[0] = char16_t(mangled); break; case 2: out[0] = char16_t(mangled & 0xFFFF); out[1] = char16_t(mangled >> 16); break; } } return len; } /** @brief Helper to perform a conversion using a string. * @tparam T The type of the input string. * @tparam O The type of the output string. * @tparam conv The function that will convert the input type to the output * type using raw pointers. * This should be a wrapped call to convertBetweenUnicodeFormatsRaw(). * @param[in] str The null terminated input string to convert. * @returns @p str converted to the desired output format. */ template <typename T, typename O, size_t conv(const T* str, O* out, size_t outLen)> inline std::basic_string<O> convertBetweenUnicodeFormats(const T* str) { omni::extras::ScratchBuffer<O, 4096> buffer; size_t len = conv(str, nullptr, 0); if (len == 0 || !buffer.resize(len)) { return std::basic_string<O>(); } conv(str, buffer.data(), buffer.size()); return std::basic_string<O>(buffer.data(), buffer.data() + len - 1); } } // namespace detail #endif /** Convert a UTF-8 encoded string to UTF-32. * @param[in] str The input UTF-8 string to convert. This may not be `nullptr`. * @param[out] out The output buffer to hold the UTF-32 data. * This must be at least @p outLen in length, in elements. * This can be `nullptr` to calculate the required output buffer length. * The output string written to @p out will always be null terminated * (unless @p outLen is 0), even if the string had to be truncated. * @param[in] outLen The length of @p out, in elements. * This should be 0 if @p out is `nullptr`. * @returns If @p out is not `nullptr`, this returns the number of UTF-32 characters * written to @p out. This includes the null terminating character. * @returns If @p out is `nullptr`, this returns the required buffer length to * store the output string. */ inline size_t convertUtf8StringToUtf32(const char* str, char32_t* out, size_t outLen) noexcept { return detail::convertBetweenUnicodeFormatsRaw<char, char32_t, detail::utf8ToCodePoint, detail::utf32FromCodePoint>( str, out, outLen); } /** Convert a UTF-8 encoded string to UTF-32. * @param[in] str The input UTF-8 string to convert. This may not be `nullptr`. * @returns @p str converted to UTF-32. */ inline std::u32string convertUtf8StringToUtf32(const char* str) { return detail::convertBetweenUnicodeFormats<char, char32_t, convertUtf8StringToUtf32>(str); } /** Convert a UTF-8 encoded string to UTF-32. * @param[in] str The input UTF-8 string to convert. * @returns @p str converted to UTF-32. */ inline std::u32string convertUtf8StringToUtf32(std::string str) { return convertUtf8StringToUtf32(str.c_str()); } /** Convert a UTF-32 encoded string to UTF-8. * @param[in] str The input UTF-32 string to convert. This may not be `nullptr`. * @param[out] out The output buffer to hold the UTF-8 data. * This must be at least @p outLen bytes in length. * This can be `nullptr` to calculate the required output buffer length. * The output string written to @p out will always be null terminated * (unless @p outLen is 0), even if the string had to be truncated. * @param[in] outLen The length of @p out, in bytes. * This should be 0 if @p out is `nullptr`. * @returns If @p out is not `nullptr`, this returns the number of UTF-8 bytes * written to @p out. This includes the null terminating character. * @returns If @p out is `nullptr`, this returns the required buffer length to * store the output string. */ inline size_t convertUtf32StringToUtf8(const char32_t* str, char* out, size_t outLen) { return detail::convertBetweenUnicodeFormatsRaw<char32_t, char, detail::utf32ToCodePoint, detail::utf8FromCodePoint>( str, out, outLen); } /** Convert a UTF-32 encoded string to UTF-8. * @param[in] str The input UTF-32 string to convert. This may not be `nullptr`. * @returns @p str converted to UTF-8. */ inline std::string convertUtf32StringToUtf8(const char32_t* str) { return detail::convertBetweenUnicodeFormats<char32_t, char, convertUtf32StringToUtf8>(str); } /** Convert a UTF-8 encoded string to UTF-32. * @param[in] str The input UTF-8 string to convert. * @returns @p str converted to UTF-32. */ inline std::string convertUtf32StringToUtf8(std::u32string str) { return convertUtf32StringToUtf8(str.c_str()); } /** Convert a UTF-16 encoded string to UTF-8. * @param[in] str The input UTF-16 string to convert. This may not be `nullptr`. * @param[out] out The output buffer to hold the UTF-8 data. * This must be at least @p outLen bytes in length. * This can be `nullptr` to calculate the required output buffer length. * The output string written to @p out will always be null terminated * (unless @p outLen is 0), even if the string had to be truncated. * @param[in] outLen The length of @p out, in bytes. * This should be 0 if @p out is `nullptr`. * @returns If @p out is not `nullptr`, this returns the number of UTF-8 bytes * written to @p out. This includes the null terminating character. * @returns If @p out is `nullptr`, this returns the required buffer length to * store the output string. */ inline size_t convertUtf16StringToUtf8(const char16_t* str, char* out, size_t outLen) { return detail::convertBetweenUnicodeFormatsRaw<char16_t, char, detail::utf16ToCodePoint, detail::utf8FromCodePoint>( str, out, outLen); } /** Convert a UTF-16 encoded string to UTF-8. * @param[in] str The input UTF-16 string to convert. This may not be `nullptr`. * @returns @p str converted to UTF-8. */ inline std::string convertUtf16StringToUtf8(const char16_t* str) { return detail::convertBetweenUnicodeFormats<char16_t, char, convertUtf16StringToUtf8>(str); } /** Convert a UTF-8 encoded string to UTF-32. * @param[in] str The input UTF-8 string to convert. * @returns @p str converted to UTF-32. */ inline std::string convertUtf16StringToUtf8(std::u16string str) { return convertUtf16StringToUtf8(str.c_str()); } /** Convert a UTF-8 encoded string to UTF-16. * @param[in] str The input UTF-8 string to convert. This may not be `nullptr`. * @param[out] out The output buffer to hold the UTF-16 data. * This must be at least @p outLen in length, in elements. * This can be `nullptr` to calculate the required output buffer length. * The output string written to @p out will always be null terminated * (unless @p outLen is 0), even if the string had to be truncated. * @param[in] outLen The length of @p out, in elements. * This should be 1 if @p out is `nullptr`. * @returns If @p out is not `nullptr`, this returns the number of UTF-32 characters * written to @p out. This includes the null terminating character. * @returns If @p out is `nullptr`, this returns the required buffer length to * store the output string. */ inline size_t convertUtf8StringToUtf16(const char* str, char16_t* out, size_t outLen) noexcept { return detail::convertBetweenUnicodeFormatsRaw<char, char16_t, detail::utf8ToCodePoint, detail::utf16FromCodePoint>( str, out, outLen); } /** Convert a UTF-8 encoded string to UTF-16. * @param[in] str The input UTF-8 string to convert. This may not be `nullptr`. * @returns @p str converted to UTF-16. */ inline std::u16string convertUtf8StringToUtf16(const char* str) { return detail::convertBetweenUnicodeFormats<char, char16_t, convertUtf8StringToUtf16>(str); } /** Convert a UTF-8 encoded string to UTF-16. * @param[in] str The input UTF-8 string to convert. * @returns @p str converted to UTF-16. */ inline std::u16string convertUtf8StringToUtf16(std::string str) { return convertUtf8StringToUtf16(str.c_str()); } /** Convert a UTF-8 encoded string to wide string. * @param[in] str The input UTF-8 string to convert. This may not be `nullptr`. * @param[out] out The output buffer to hold the wide data. * This must be at least @p outLen in length, in elements. * This can be `nullptr` to calculate the required output buffer length. * The output string written to @p out will always be null terminated * (unless @p outLen is 0), even if the string had to be truncated. * @param[in] outLen The length of @p out, in elements. * This should be 1 if @p out is `nullptr`. * @returns If @p out is not `nullptr`, this returns the number of wide characters * written to @p out. This includes the null terminating character. * @returns If @p out is `nullptr`, this returns the required buffer length to * store the output string. * * @note This is provided for interoperability with older systems that still use * wide strings. Please use UTF-8 or UTF-32 for new systems. */ inline size_t convertUtf8StringToWide(const char* str, wchar_t* out, size_t outLen) noexcept { #if CARB_PLATFORM_WINDOWS static_assert(sizeof(*out) == sizeof(char16_t), "unexpected wchar_t type"); return detail::convertBetweenUnicodeFormatsRaw<char, char16_t, detail::utf8ToCodePoint, detail::utf16FromCodePoint>( str, reinterpret_cast<char16_t*>(out), outLen); #else static_assert(sizeof(*out) == sizeof(char32_t), "unexpected wchar_t type"); return detail::convertBetweenUnicodeFormatsRaw<char, char32_t, detail::utf8ToCodePoint, detail::utf32FromCodePoint>( str, reinterpret_cast<char32_t*>(out), outLen); #endif } /** Convert a UTF-8 encoded string to wide. * @param[in] str The input UTF-8 string to convert. This may not be `nullptr`. * @returns @p str converted to wide. * * @note This is provided for interoperability with older systems that still use * wide strings. Please use UTF-8 or UTF-32 for new systems. */ inline std::wstring convertUtf8StringToWide(const char* str) { return detail::convertBetweenUnicodeFormats<char, wchar_t, convertUtf8StringToWide>(str); } /** Convert a UTF-8 encoded string to UTF-16. * @param[in] str The input UTF-8 string to convert. * @returns @p str converted to UTF-16. * * @note This is provided for interoperability with older systems that still use * wide strings. Please use UTF-8 or UTF-32 for new systems. */ inline std::wstring convertUtf8StringToWide(std::string str) { return convertUtf8StringToWide(str.c_str()); } /** Convert a wide encoded string to UTF-8 string. * @param[in] str The input wide string to convert to UTF-8. This may not be `nullptr`. * @param[out] out The output buffer to hold the wide data. * This must be at least @p outLen in length, in elements. * This can be `nullptr` to calculate the required output buffer length. * The output string written to @p out will always be null terminated * (unless @p outLen is 0), even if the string had to be truncated. * @param[in] outLen The length of @p out, in elements. * This should be 1 if @p out is `nullptr`. * @returns If @p out is not `nullptr`, this returns the number of wide characters * written to @p out. This includes the null terminating character. * @returns If @p out is `nullptr`, this returns the required buffer length to * store the output string. * * @note This is provided for interoperability with older systems that still use * wide strings. Please use UTF-8 or UTF-32 for new systems. */ inline size_t convertWideStringToUtf8(const wchar_t* str, char* out, size_t outLen) noexcept { #if CARB_PLATFORM_WINDOWS static_assert(sizeof(*str) == sizeof(char16_t), "unexpected wchar_t type"); return detail::convertBetweenUnicodeFormatsRaw<char16_t, char, detail::utf16ToCodePoint, detail::utf8FromCodePoint>( reinterpret_cast<const char16_t*>(str), out, outLen); #else static_assert(sizeof(*str) == sizeof(char32_t), "unexpected wchar_t type"); return detail::convertBetweenUnicodeFormatsRaw<char32_t, char, detail::utf32ToCodePoint, detail::utf8FromCodePoint>( reinterpret_cast<const char32_t*>(str), out, outLen); #endif } /** Convert a UTF-8 encoded string to wide. * @param[in] str The input UTF-8 string to convert. This may not be `nullptr`. * @returns @p str converted to wide. * * @note This is provided for interoperability with older systems that still use * wide strings. Please use UTF-8 or UTF-32 for new systems. */ inline std::string convertWideStringToUtf8(const wchar_t* str) { return detail::convertBetweenUnicodeFormats<wchar_t, char, convertWideStringToUtf8>(str); } /** Convert a UTF-8 encoded string to UTF-16. * @param[in] str The input UTF-8 string to convert. * @returns @p str converted to UTF-16. * * @note This is provided for interoperability with older systems that still use * wide strings. Please use UTF-8 or UTF-32 for new systems. */ inline std::string convertWideStringToUtf8(std::wstring str) { return convertWideStringToUtf8(str.c_str()); } } // namespace extras } // namespace carb
89,645
C
41.186353
123
0.590061
omniverse-code/kit/include/carb/extras/StringProcessor.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 "EnvironmentVariable.h" #include "../logging/Log.h" namespace carb { namespace extras { /** * Search for env vars like ${SOME_VAR} in a string and replace them with actual env var value */ inline std::string replaceEnvironmentVariables(const std::string& text) { // At least '${}' is needed for that function to do processing if (text.size() < 3) return text; std::string result; result.reserve(text.size()); size_t lastPatternIndex = 0; for (size_t i = 0; i < text.size() - 1; i++) { if (text[i] == '$' && text[i + 1] == '{') { result.append(text.substr(lastPatternIndex, i - lastPatternIndex)); size_t pos = text.find('}', i + 1); if (pos != std::string::npos) { const std::string envVarName = text.substr(i + 2, pos - i - 2); std::string var; if (!envVarName.empty() && extras::EnvironmentVariable::getValue(envVarName.c_str(), var)) { result.append(var); } else { CARB_LOG_ERROR("Environment variable: %s was not found.", envVarName.c_str()); } lastPatternIndex = pos + 1; i = pos; } } }; result.append(text.substr(lastPatternIndex, text.size() - lastPatternIndex)); return result; } } // namespace extras } // namespace carb
1,935
C
28.784615
106
0.586047
omniverse-code/kit/include/carb/extras/MemoryUsage.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 Helper to get the memory characteristics of a program. */ #pragma once #include "../Defines.h" #include "../logging/Log.h" #if CARB_PLATFORM_LINUX # include <sys/sysinfo.h> # include <stdio.h> # include <unistd.h> # include <sys/time.h> # include <sys/resource.h> #elif CARB_PLATFORM_MACOS # include <mach/task.h> # include <mach/mach_init.h> # include <mach/mach_host.h> # include <os/proc.h> # include <sys/resource.h> #elif CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" #endif namespace carb { namespace extras { /** The type of memory to query. */ enum class MemoryQueryType { eAvailable, /**< The available memory on the system. */ eTotal, /**< The total memory on the system. */ }; size_t getPhysicalMemory(MemoryQueryType type); // forward declare /** Retrieve the physical memory usage by the current process. * @returns The memory usage for the current process. * @returns 0 if the operation failed. */ inline size_t getCurrentProcessMemoryUsage() { #if CARB_PLATFORM_LINUX unsigned long rss = 0; long pageSize; pageSize = sysconf(_SC_PAGESIZE); if (pageSize < 0) { CARB_LOG_ERROR("failed to retrieve the page size"); return 0; } // fopen() and fgets() can use the heap, and we may be called from the crashreporter, so avoid using those // functions to avoid heap usage. auto fd = open("/proc/self/statm", 0, O_RDONLY); if (fd < 0) { CARB_LOG_ERROR("failed to open /proc/self/statm"); return 0; } char line[256]; auto readBytes = CARB_RETRY_EINTR(read(fd, line, CARB_COUNTOF(line) - 1)); if (readBytes > 0) { char* endp; // Skip the first, read the second strtoul(line, &endp, 10); rss = strtoul(endp, nullptr, 10); } close(fd); return rss * pageSize; #elif CARB_PLATFORM_WINDOWS CARBWIN_PROCESS_MEMORY_COUNTERS mem; mem.cb = sizeof(mem); if (!K32GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS)&mem, sizeof(mem))) { CARB_LOG_ERROR("GetProcessMemoryInfo failed"); return 0; } return mem.WorkingSetSize; #elif CARB_PLATFORM_MACOS mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT; task_basic_info info = {}; kern_return_t r = task_info(mach_task_self(), TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&info), &count); if (r != KERN_SUCCESS) { CARB_LOG_ERROR("task_info() failed (%d)", int(r)); return 0; } return info.resident_size; #else # warning "getMemoryUsage() has no implementation" return 0; #endif } /** Retrieves the peak memory usage information for the calling process. * * @returns The maximum process memory usage level in bytes. */ inline size_t getPeakProcessMemoryUsage() { #if CARB_PLATFORM_WINDOWS CARBWIN_PROCESS_MEMORY_COUNTERS mem; mem.cb = sizeof(mem); if (!K32GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS)&mem, sizeof(mem))) { CARB_LOG_ERROR("GetProcessMemoryInfo failed"); return 0; } return mem.PeakWorkingSetSize; #elif CARB_POSIX rusage usage_data; size_t scale; getrusage(RUSAGE_SELF, &usage_data); # if CARB_PLATFORM_LINUX scale = 1024; // Linux provides this value in kilobytes. # elif CARB_PLATFORM_MACOS scale = 1; // MacOS provides this value in bytes. # else CARB_UNSUPPORTED_PLATFORM(); # endif // convert to bytes. return usage_data.ru_maxrss * scale; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** Stores information about memory in the system. All values are in bytes. */ struct SystemMemoryInfo { /** The total available physical RAM in bytes. This may be reported as slightly less than * the expected amount due to some small amount of space being reserved for the OS. This * is often negligible, but when displaying the memory amount to the user, it is good to * round to the nearest mebibyte or gibibyte. */ uint64_t totalPhysical; /** The available physical RAM in bytes. This is not memory that is necessarily available * to the calling process, but rather the amount of physical RAM that the OS is not * actively using for all running processes at the moment. */ uint64_t availablePhysical; /** The total amount of page file space available to the system in bytes. When physical RAM * is filled, this space will be used to provide a backup space for memory pages of lower * priority, inactive, or background processes so that RAM can be freed up for more active * or demanding processes. */ uint64_t totalPageFile; /** The available amount of page file space in bytes. This is the unused portion of the page * file that the system can still make use of to keep foreground processes from starving. */ uint64_t availablePageFile; /** The total amount of virtual memory available to the calling process in bytes. This is * the maximum amount of addressable space and the maximum memory address that can be used. * On Windows this value should be consistent, but on Linux, this value can change depending * on the owner of the process if the administrator has set differing limits for users. */ uint64_t totalVirtual; /** The available amount of virtual memory in bytes still usable by the calling process. This * is the amount of memory that can still be allocated by the process. That said however, * the process may not be able to actually use all of that memory if the system's resources * are exhausted. Since virtual memory space is generally much larger than the amount of * available RAM and swap space on 64 bit processes, the process will still be in an out * of memory situation if all of the system's physical RAM and swap space have been consumed * by the process's demands. When looking at out of memory situations, it is also important * to consider virtual memory space along with physical and swap space. */ uint64_t availableVirtual; }; #if CARB_PLATFORM_LINUX /** Retrieves the memory size multiplier from a value suffix. * * @param[in] str The string containing the memory size suffix. This may not be `nullptr`. * @returns The multiplier to use to convert the memory value to bytes. Returns 1 if the * memory suffix is not recognized. Supported suffixes are 'KB', 'MB', 'GB', 'TB', * 'PB', 'EB', and bytes. All unknown suffixes will be treated as bytes. */ inline size_t getMemorySizeMultiplier(const char* str) { size_t multiplier = 1; // strip leading whitespace. while (*str == ' ' || *str == '\t') str++; // check the prefix of the multiplier string (ie: "kB", "gB", etc). switch (tolower(*str)) { case 'e': multiplier *= 1024ull; // fall through... CARB_FALLTHROUGH; case 'p': multiplier *= 1024ull; // fall through... CARB_FALLTHROUGH; case 't': multiplier *= 1024ull; // fall through... CARB_FALLTHROUGH; case 'g': multiplier *= 1024ull; // fall through... CARB_FALLTHROUGH; case 'm': multiplier *= 1024ull; // fall through... CARB_FALLTHROUGH; case 'k': multiplier *= 1024ull; // fall through... CARB_FALLTHROUGH; default: break; } return multiplier; } /** Retrieves a memory value by its key name in '/proc/meminfo' or other. * * @param[in] filename The name of the pseudo file to parse the information from. This may be * `nullptr` to use the default of '/proc/meminfo' instead. * @param[in] name The name of the key to search for. This may not be `nullptr`. * @param[in] nameLen The length of the key name in characters. If set to 0, the length * of the string will be calculated. * @returns The value associated with the given key name if found. Returns 0 otherwise. */ inline size_t getMemoryValueByName(const char* filename, const char* name, size_t nameLen = 0) { constexpr static char kProcMemInfo[] = "/proc/meminfo"; size_t bytes = 0; char line[256]; size_t nameLength = nameLen; if (filename == nullptr) filename = kProcMemInfo; if (nameLength == 0) nameLength = strlen(name); // fopen() and fgets() can use the heap, and we may be called from the crashreporter, so avoid using those // functions to avoid heap usage. auto fd = open(filename, 0, O_RDONLY); if (fd < 0) return 0; ssize_t readBytes; while ((readBytes = CARB_RETRY_EINTR(read(fd, line, CARB_COUNTOF(line) - 1))) > 0) { line[readBytes] = '\0'; auto lf = strchr(line, '\n'); if (lf) { *lf = '\0'; // Seek back to the start of the next line for the next read lseek(fd, -off_t(line + readBytes - lf) + 1, SEEK_CUR); } if (strncmp(line, name, nameLength) == 0) { // Found the key that we're looking for => parse its value in Kibibytes and succeed. char* endp; bytes = strtoull(line + nameLength, &endp, 10); bytes *= getMemorySizeMultiplier(endp); break; } } close(fd); return bytes; } #endif /** Retrieves the memory usage information for the system. * * @param[out] out Receives the memory totals and availability information for the system. * @returns `true` if the memory information is successfully collected. Returns `false` * otherwise. */ inline bool getSystemMemoryInfo(SystemMemoryInfo& out) { #if CARB_PLATFORM_LINUX struct sysinfo info = {}; struct rlimit limit = {}; int result; size_t bytes; // collect the total memory counts. result = sysinfo(&info); if (result != 0) { CARB_LOG_WARN("sysinfo() returned %d", result); // retrieve the values from '/proc/meminfo' instead. out.totalPhysical = getMemoryValueByName(nullptr, "MemTotal:", sizeof("MemTotal:") - 1); out.totalPageFile = getMemoryValueByName(nullptr, "SwapTotal:", sizeof("SwapTotal:") - 1); } else { out.totalPhysical = (uint64_t)info.totalram * info.mem_unit; out.totalPageFile = (uint64_t)info.totalswap * info.mem_unit; } // get the virtual memory info. if (getrlimit(RLIMIT_AS, &limit) == 0) { out.totalVirtual = limit.rlim_cur; out.availableVirtual = 0; // retrieve the total VM usage for the calling process. bytes = getMemoryValueByName("/proc/self/status", "VmSize:", sizeof("VmSize:") - 1); if (bytes != 0) { if (bytes > out.totalVirtual) { CARB_LOG_WARN( "retrieved a larger VM size than total VM space (!?) {bytes = %zu, " "totalVirtual = %" PRIu64 "}", bytes, out.totalVirtual); } else out.availableVirtual = out.totalVirtual - bytes; } } else { CARB_LOG_WARN("failed to retrieve the total address space {errno = %d/%s}", errno, strerror(errno)); out.totalVirtual = 0; out.availableVirtual = 0; } // collect the available RAM as best we can. The values in '/proc/meminfo' are typically // more accurate than what sysinfo() gives us due to the 'mem_unit' value. bytes = getMemoryValueByName(nullptr, "MemAvailable:", sizeof("MemAvailable:") - 1); if (bytes != 0) out.availablePhysical = bytes; else out.availablePhysical = (uint64_t)info.freeram * info.mem_unit; // collect the available swap space as best we can. bytes = getMemoryValueByName(nullptr, "SwapFree:", sizeof("SwapFree:") - 1); if (bytes != 0) out.availablePageFile = bytes; else out.availablePageFile = (uint64_t)info.freeswap * info.mem_unit; return true; #elif CARB_PLATFORM_WINDOWS CARBWIN_MEMORYSTATUSEX status; status.dwLength = sizeof(status); if (!GlobalMemoryStatusEx((LPMEMORYSTATUSEX)&status)) { CARB_LOG_ERROR("GlobalMemoryStatusEx() failed {error = %d}", GetLastError()); return false; } out.totalPhysical = (uint64_t)status.ullTotalPhys; out.totalPageFile = (uint64_t)status.ullTotalPageFile; out.totalVirtual = (uint64_t)status.ullTotalVirtual; out.availablePhysical = (uint64_t)status.ullAvailPhys; out.availablePageFile = (uint64_t)status.ullAvailPageFile; out.availableVirtual = (uint64_t)status.ullAvailVirtual; return true; #elif CARB_PLATFORM_MACOS int mib[2]; size_t length; mach_msg_type_number_t count; kern_return_t r; xsw_usage swap = {}; task_basic_info info = {}; struct rlimit limit = {}; // get the system's swap usage mib[0] = CTL_HW, mib[1] = VM_SWAPUSAGE; length = sizeof(swap); if (sysctl(mib, CARB_COUNTOF(mib), &swap, &length, nullptr, 0) != 0) { CARB_LOG_ERROR("sysctl() for VM_SWAPUSAGE failed (errno = %d)", errno); return false; } count = TASK_BASIC_INFO_COUNT; r = task_info(mach_task_self(), TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&info), &count); if (r != KERN_SUCCESS) { CARB_LOG_ERROR("task_info() failed (result = %d, errno = %d)", int(r), errno); return false; } // it's undocumented but RLIMIT_AS is supported if (getrlimit(RLIMIT_AS, &limit) != 0) { CARB_LOG_ERROR("getrlimit(RLIMIT_AS) failed (errno = %d)", errno); return false; } out.totalVirtual = limit.rlim_cur; out.availableVirtual = out.totalVirtual - info.virtual_size; out.totalPhysical = getPhysicalMemory(MemoryQueryType::eTotal); out.availablePhysical = getPhysicalMemory(MemoryQueryType::eAvailable); out.totalPageFile = swap.xsu_total; out.availablePageFile = swap.xsu_avail; return true; #else # warning "getSystemMemoryInfo() has no implementation" return 0; #endif } /** Retrieve the physical memory available on the system. * @param[in] type The type of memory to query. * @returns The physical memory available on the system. * @returns 0 if the operation failed. * @note On Linux, disk cache memory doesn't count as available memory, so * allocations may still succeed if available memory is near 0, but it * will contribute to system slowdown if it's using disk cache space. */ inline size_t getPhysicalMemory(MemoryQueryType type) { #if CARB_PLATFORM_LINUX // this is a linux-specific system call struct sysinfo info; int result; const char* search; size_t searchLength; size_t bytes; // attempt to read the available memory from '/proc/meminfo' first. if (type == MemoryQueryType::eTotal) { search = "MemTotal:"; searchLength = sizeof("MemTotal:") - 1; } else { search = "MemAvailable:"; searchLength = sizeof("MemAvailable:") - 1; } bytes = getMemoryValueByName(nullptr, search, searchLength); if (bytes != 0) return bytes; // fall back to sysinfo() to get the amount of free RAM if it couldn't be found in // '/proc/meminfo'. result = sysinfo(&info); if (result != 0) { CARB_LOG_ERROR("sysinfo() returned %d", result); return 0; } if (type == MemoryQueryType::eTotal) return info.totalram * info.mem_unit; else return info.freeram * info.mem_unit; #elif CARB_PLATFORM_WINDOWS CARBWIN_MEMORYSTATUSEX status; status.dwLength = sizeof(status); if (!GlobalMemoryStatusEx((LPMEMORYSTATUSEX)&status)) { CARB_LOG_ERROR("GlobalMemoryStatusEx failed"); return 0; } if (type == MemoryQueryType::eTotal) return status.ullTotalPhys; else return status.ullAvailPhys; #elif CARB_PLATFORM_MACOS int mib[2]; size_t memSize = 0; size_t length; if (type == MemoryQueryType::eTotal) { mib[0] = CTL_HW, mib[1] = HW_MEMSIZE; length = sizeof(memSize); if (sysctl(mib, CARB_COUNTOF(mib), &memSize, &length, nullptr, 0) != 0) { CARB_LOG_ERROR("sysctl() for HW_MEMSIZE failed (errno = %d)", errno); return false; } } else { mach_msg_type_number_t count; kern_return_t r; vm_statistics_data_t vm = {}; size_t pageSize = getpagesize(); count = HOST_VM_INFO_COUNT; r = host_statistics(mach_host_self(), HOST_VM_INFO, reinterpret_cast<host_info_t>(&vm), &count); if (r != KERN_SUCCESS) { CARB_LOG_ERROR("host_statistics() failed (%d)", int(r)); return false; } memSize = (vm.free_count + vm.inactive_count) * pageSize; } return memSize; #else # warning "getPhysicalMemoryAvailable() has no implementation" return 0; #endif } /** Names for the different types of common memory scales. This covers both binary * (ie: Mebibytes = 1,048,576 bytes) and decimal (ie: Megabytes = 1,000,000 bytes) * size scales. */ enum class MemoryScaleType { /** Name for the binary memory size scale. This is commonly used in operating systems * and software. All scale names are powers of 1024 bytes and typically use the naming * convention of using the suffix "bibytes" and the first two letters of the prefix of * its decimal counterpart. For example, "mebibytes" instead of "megabytes". */ eBinaryScale, /** Name for the decimal memory size scale. This is commonly used in hardware size * descriptions. All scale names are powers of 1000 byes and typically use the Greek * size prefix followed by "Bytes". For example, "megabytes", "petabytes", "kilobytes", * etc. */ eDecimalScale, }; /** Retrieves a friendly memory size and scale suffix for a given number of bytes. * * @param[in] bytes The number of bytes to convert to a friendly memory size. * @param[out] suffix Receives the name of the suffix to the converted memory size amount. * This is suitable for displaying to a user. * @param[in] scale Whether the conversion should be done using a decimal or binary scale. * This defaults to @ref MemoryScaleType::eBinaryScale. * @returns The given memory size value @p bytes converted to the next lowest memory scale value * (ie: megabytes, kilobytes, etc). The appropriate suffix string is returned through * @p suffix. */ inline double getFriendlyMemorySize(size_t bytes, const char** suffix, MemoryScaleType scale = MemoryScaleType::eBinaryScale) { constexpr size_t kEib = 1024ull * 1024 * 1024 * 1024 * 1024 * 1024; constexpr size_t kPib = 1024ull * 1024 * 1024 * 1024 * 1024; constexpr size_t kTib = 1024ull * 1024 * 1024 * 1024; constexpr size_t kGib = 1024ull * 1024 * 1024; constexpr size_t kMib = 1024ull * 1024; constexpr size_t kKib = 1024ull; constexpr size_t kEb = 1000ull * 1000 * 1000 * 1000 * 1000 * 1000; constexpr size_t kPb = 1000ull * 1000 * 1000 * 1000 * 1000; constexpr size_t kTb = 1000ull * 1000 * 1000 * 1000; constexpr size_t kGb = 1000ull * 1000 * 1000; constexpr size_t kMb = 1000ull * 1000; constexpr size_t kKb = 1000ull; constexpr size_t limits[2][6] = { { kEib, kPib, kTib, kGib, kMib, kKib }, { kEb, kPb, kTb, kGb, kMb, kKb } }; constexpr const char* suffixes[2][6] = { { "EiB", "PiB", "TiB", "GiB", "MiB", "KiB" }, { "EB", "PB", "TB", "GB", "MB", "KB" } }; if (scale != MemoryScaleType::eBinaryScale && scale != MemoryScaleType::eDecimalScale) { *suffix = "bytes"; return (double)bytes; } for (size_t i = 0; i < CARB_COUNTOF(limits[(size_t)scale]); i++) { size_t limit = limits[(size_t)scale][i]; if (bytes >= limit) { *suffix = suffixes[(size_t)scale][i]; return bytes / (double)limit; } } *suffix = "bytes"; return (double)bytes; } } // namespace extras } // namespace carb
20,871
C
32.18283
125
0.633511
omniverse-code/kit/include/carb/extras/Options.h
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /** @file * @brief Provides a set of helper functions to manage the processing of command line arguments. */ #pragma once #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Namespace for the options processing helper functions. */ namespace options { /** The possible result codes of parsing a single option. */ enum class ParseResult { eSuccess, ///< Parsing was successful and the option was consumed. eInvalidValue, ///< A token or name was expected but not found. }; /** Type names for values passed to the parser functions. */ enum class ValueType { eIgnore = -1, ///< Ignore arguments of this type. eNone, ///< No type or data. eString, ///< Value is a string (ie: const char*). eLong, ///< Value is a signed long integer (ie: long). eLongLong, ///< Value is a signed long long integer (ie: long long). eFloat, ///< Value is a single precision floating point number (ie: float). eDouble, ///< Value is a double precision floating point number (ie: double). }; /** Special failure value for getArgString() indicating that an expected argument was missing. */ constexpr int kArgFailExpectedArgument = -1; /** Special failure value for getArgString() indicating that an argument's value started with * a single or double quotation mark but did not end with the matching quotation or the ending * quotation mark was missing. */ constexpr int kArgFailExpectedQuote = -2; /** Converts a string to a number. * * @param[in] string The string to convert. * @param[out] value Receives the converted value of the string if successful. * @returns `true` if the string is successfully converted to a number. * @returns `false` if the string could not be fully converted to a number. */ template <typename T> inline bool stringToNumber(const char* string, T* value) { char* endp = nullptr; *value = strtoull(string, &endp, 10); return endp == nullptr || endp[0] == 0; } /** @copydoc stringToNumber(const char*,T*) */ template <> inline bool stringToNumber(const char* string, long* value) { char* endp = nullptr; *value = strtol(string, &endp, 10); return endp == nullptr || endp[0] == 0; } /** @copydoc stringToNumber(const char*,T*) */ template <> inline bool stringToNumber(const char* string, float* value) { char* endp = nullptr; *value = strtof(string, &endp); return endp == nullptr || endp[0] == 0; } /** @copydoc stringToNumber(const char*,T*) */ template <> inline bool stringToNumber(const char* string, double* value) { char* endp = nullptr; *value = strtod(string, &endp); return endp == nullptr || endp[0] == 0; } /** A multi-value type. This contains a single value of a specific type. The * value can only be retrieved if it can be safely converted to the requested * type. */ class Value { public: /** Constructor: initializes an object with no specific value in it. */ Value() { clear(); } /** Clears the value in this object. * * @returns No return value. */ void clear() { m_type = ValueType::eNone; m_value.string = nullptr; } /** Sets the value and type in this object. * * @param[in] value The value to set in this object. The value's type is implied * from the setter that is used. * @returns No return value. */ void set(const char* value) { m_type = ValueType::eString; m_value.string = value; } /** @copydoc set(const char*) */ void set(long value) { m_type = ValueType::eLong; m_value.integer = value; } /** @copydoc set(const char*) */ void set(long long value) { m_type = ValueType::eLongLong; m_value.longInteger = value; } /** @copydoc set(const char*) */ void set(float value) { m_type = ValueType::eFloat; m_value.floatValue = value; } /** @copydoc set(const char*) */ void set(double value) { m_type = ValueType::eDouble; m_value.doubleValue = value; } /** Retrieves the type of the value in this object. * * @returns A type name for the value in this object. */ ValueType getType() const { return m_type; } /** Retrieves the value in this object. * * @returns The value converted into the requested format if possible. */ const char* getString() const { if (m_type != ValueType::eString) return nullptr; return m_value.string; } /** @copydoc getString() */ long getLong() const { return getNumber<long>(); } /** @copydoc getString() */ long long getLongLong() const { return getNumber<long long>(); } /** @copydoc getString() */ float getFloat() const { return getNumber<float>(); } /** @copydoc getString() */ double getDouble() const { return getNumber<double>(); } private: template <typename T> T getNumber() const { switch (m_type) { default: case ValueType::eString: return 0; case ValueType::eLong: return static_cast<T>(m_value.integer); case ValueType::eLongLong: return static_cast<T>(m_value.longInteger); case ValueType::eFloat: return static_cast<T>(m_value.floatValue); case ValueType::eDouble: return static_cast<T>(m_value.doubleValue); } } ValueType m_type; ///< The type of the value in this object. /** The value contained in this object. */ union { const char* string; long integer; long long longInteger; float floatValue; double doubleValue; } m_value; }; /** Receives the results of parsing an options string. This represents the base class that * specific option parsers should inherit from. */ class Options { public: /** The original argument count from the caller. */ int argc = 0; /** The original argument list from the caller. */ char** argv = nullptr; /** The index of the first argument that was not consumed as a parsed option. */ int firstCommandArgument = -1; /** Helper function to cast the @a args parameter to a parser function. * * @returns This object cast to the requested type. */ template <typename T> T* cast() { return reinterpret_cast<T*>(this); } }; /** Prototype of a parser function to handle a single option. * * @param[in] name The name of the option being parsed. If the name and value was in a * pair separated by an equal sign ('='), both the name and value will * be present in the string. This will not be `nullptr`. * @param[in] value The value of the option if one is expected, or `nullptr` if no option * is expected. This will be the value to be passed in with the option. * @param[out] args Receives the results of parsing the option. It is the handler's * responsibility to ensure this object is filled in or initialized * properly. * @returns A @ref ParseResult result code indicating whether the parsing was successful. */ using ArgParserFunc = ParseResult (*)(const char* name, const Value* value, Options* args); /** Information about a single option and its parser. */ struct Option { /** The short name for the option. This is usually a one letter option preceded by * a dash character. */ const char* shortName; /** The long name for the option. This is usually a multi-word option preceded by * two dash characters. */ const char* longName; /** The number of arguments to be expected associated with this option. This should * either be 0 or 1. */ int expectedArgs; /** The expected argument type. */ ValueType expectedType; /** The parser function that will handle consuming the option and its argument. */ ArgParserFunc parser; /** Documentation for this option. This string should be formatted to fit on a 72 * character line. Each line of text should end with a newline character ('\n'). * The last line of text must also end in a newline character otherwise it will * be omitted from any documentation output. */ const char* documentation; }; /** Retrieves a single argument value from the next argument. * * @param[in] argc The number of arguments in the argument vector. This must be at least 1. * @param[in] argv The full argument vector to parse. This may not be `nullptr`. * @param[in] argIndex The zero-based index of the argument to parse. * @param[out] value Receives the start of the value's string. * @returns The number of arguments that were consumed. This may be 0 or 1. * @returns `-1` if no value could be found for the option. * * @remarks This parses a single option's value from the argument list. The value may either * be in the same argument as the option name itself, separated by an equal sign ('='), * or in the following argument in the list. If an argument cannot be found (ie: * no arguments remain and an equal sign is not found), this will fail. * * @note If the argument's value is quoted (single or double quotes), the entry in the original * argument string will be modified to strip off the terminating quotation mark character. * If the argument's value is not quoted, nothing will be modified in the argument string. */ inline int getArgString(int argc, char** argv, int argIndex, const char** value) { char* equal; int argsConsumed = 0; char* valueOut; equal = strchr(argv[argIndex], '='); // the argument is of the form "name=value" => parse the number from the arg itself. if (equal != nullptr) valueOut = equal + 1; // the argument is of the form "name value" => parse the number from the next arg. else if (argIndex + 1 < argc) { valueOut = argv[argIndex + 1]; argsConsumed = 1; } // not enough args given => fail. else { fprintf(stderr, "expected another argument after '%s'.\n", argv[argIndex]); return kArgFailExpectedArgument; } if (valueOut[0] == '\"' || valueOut[0] == '\'') { char openQuote = valueOut[0]; size_t len = strlen(valueOut); if (valueOut[len - 1] != openQuote) return kArgFailExpectedQuote; valueOut[len - 1] = 0; valueOut++; } *value = valueOut; return argsConsumed; } /** Parses a set of options from an argument vector. * * @param[in] supportedArgs The table of options that will be used to parse the program * arguments. This table must be terminated by an empty entry * in the list (ie: all values `nullptr` or `0`). This may not * be `nullptr`. * @param[in] argc The argument count for the program. This must be at least 1. * @param[in] argv The vector of arguments to e be parsed. This must not be `nullptr`. * @param[out] args Receives the parsed option state. It is the caller's * responsibility to ensure this is appropriately initialized before * calling. This object must inherit from the @ref Options class. * @returns `true` if all arguments are successfully parsed. * @returns `false` if an option fails to be parsed. */ inline bool parseOptions(const Option* supportedArgs, int argc, char** argv, Options* args) { const char* valueStr; bool handled; int argsConsumed; ParseResult result; Value value; Value* valueToSend; auto argMatches = [](const char* string, const char* arg, bool terminated) { size_t len = strlen(arg); if (!terminated) return strncmp(string, arg, len) == 0; return strncmp(string, arg, len) == 0 && (string[len] == 0 || string[len] == '='); }; for (int i = 1; i < argc; i++) { handled = false; for (size_t j = 0; supportedArgs[j].parser != nullptr; j++) { bool checkTermination = supportedArgs[j].expectedType != ValueType::eIgnore; if ((supportedArgs[j].shortName != nullptr && argMatches(argv[i], supportedArgs[j].shortName, checkTermination)) || (supportedArgs[j].longName != nullptr && argMatches(argv[i], supportedArgs[j].longName, checkTermination))) { valueToSend = nullptr; valueStr = nullptr; argsConsumed = 0; value.clear(); if (supportedArgs[j].expectedArgs > 0) { argsConsumed = getArgString(argc, argv, i, &valueStr); if (argsConsumed < 0) { switch (argsConsumed) { case kArgFailExpectedArgument: fprintf( stderr, "ERROR-> expected an extra argument after argument %d ('%s').", i, argv[i]); break; case kArgFailExpectedQuote: fprintf( stderr, "ERROR-> expected a matching quotation mark at the end of the argument value for argument %d ('%s').", i, argv[i]); break; default: break; } return false; } if (supportedArgs[j].expectedType == ValueType::eIgnore) { i += argsConsumed; handled = true; break; } #if !defined(DOXYGEN_SHOULD_SKIP_THIS) # define SETVALUE(value, str, type) \ do \ { \ type convertedValue; \ if (!stringToNumber(str, &convertedValue)) \ { \ fprintf(stderr, "ERROR-> expected a %s value after '%s'.\n", #type, argv[i]); \ return false; \ } \ value.set(convertedValue); \ } while (0) #endif switch (supportedArgs[j].expectedType) { default: case ValueType::eString: value.set(valueStr); break; case ValueType::eLong: SETVALUE(value, valueStr, long); break; case ValueType::eLongLong: SETVALUE(value, valueStr, long long); break; case ValueType::eFloat: SETVALUE(value, valueStr, float); break; case ValueType::eDouble: SETVALUE(value, valueStr, double); break; } valueToSend = &value; #undef SETVALUE } result = supportedArgs[j].parser(argv[i], valueToSend, args); switch (result) { default: case ParseResult::eSuccess: break; case ParseResult::eInvalidValue: fprintf(stderr, "ERROR-> unknown or invalid value in '%s'.\n", argv[i]); return false; } i += argsConsumed; handled = true; break; } } if (!handled) { if (args->firstCommandArgument < 0) args->firstCommandArgument = i; break; } } args->argc = argc; args->argv = argv; return true; } /** Prints out the documentation for an option table. * * @param[in] supportedArgs The table of options that this program can parse. This table * must be terminated by an empty entry in the list (ie: all values * `nullptr` or `0`). This may not be nullptr. The documentation * for each of the options in this table will be written out to the * selected stream. * @param[in] helpString The help string describing this program, its command line * syntax, and its commands. This should not include any * documentation for the supported options. * @param[in] stream The stream to output the documentation to. This may not be * `nullptr`. * @returns No return value. */ inline void printOptionUsage(const Option* supportedArgs, const char* helpString, FILE* stream) { const char* str; const char* newline; const char* argStr; fputs(helpString, stream); fputs("Supported options:\n", stream); for (size_t i = 0; supportedArgs[i].parser != nullptr; i++) { str = supportedArgs[i].documentation; argStr = ""; if (supportedArgs[i].expectedArgs > 0) argStr = " [value]"; if (supportedArgs[i].shortName != nullptr) fprintf(stream, " %s%s:\n", supportedArgs[i].shortName, argStr); if (supportedArgs[i].longName != nullptr) fprintf(stream, " %s%s:\n", supportedArgs[i].longName, argStr); for (newline = strchr(str, '\n'); newline != nullptr; str = newline + 1, newline = strchr(str + 1, '\n')) fprintf(stream, " %.*s\n", static_cast<int>(newline - str), str); fputs("\n", stream); } fputs("\n", stream); } } // namespace options } // namespace carb
19,763
C
32.784615
138
0.542225
omniverse-code/kit/include/carb/extras/Library.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 Provides helper functions to handle library loading and management. */ #pragma once #include "../Defines.h" #include "Path.h" #include "StringSafe.h" #include "../../omni/extras/ScratchBuffer.h" #if CARB_POSIX # if CARB_PLATFORM_LINUX # include <link.h> # elif CARB_PLATFORM_MACOS # include <mach-o/dyld.h> # endif # include <dlfcn.h> #elif CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" # include "Errors.h" # include "WindowsPath.h" #else CARB_UNSUPPORTED_PLATFORM(); #endif /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { /** Handle to a loaded library. */ #if CARB_POSIX || defined(DOXYGEN_BUILD) //! A type representing a library handle. using LibraryHandle = void*; #elif CARB_PLATFORM_WINDOWS using LibraryHandle = HMODULE; #else CARB_UNSUPPORTED_PLATFORM(); #endif /** A value representing an invalid library handle. */ constexpr LibraryHandle kInvalidLibraryHandle = {}; /** Base type for the flags to control how libraries are loaded. */ using LibraryFlags = uint32_t; /** Flag to indicate that only the module's base name was given and that the full name should * be constructed using createLibraryNameForModule() before attempting to load the library. * When this flag is used, it is assumed that neither the library's prefix (if any) nor * file extension are present in the given filename. Path components leading up to the * module name may be included as needed. This flag is ignored if the filename is either * `nullptr` or an empty string (ie: ""). */ constexpr LibraryFlags fLibFlagMakeFullLibName = 0x00000001; /** Flag to indicate that the library should be fully loaded and linked immediately. This * flag has no effect on Windows since it doesn't have the equivalent of Linux's lazy linker. * This is equivalent to passing the `RTLD_NOW` flag to [dlopen](https://linux.die.net/man/3/dlopen) and will override * any default lazy linking behavior. */ constexpr LibraryFlags fLibFlagNow = 0x00000002; /** Flag to indicate that the symbols in the library being loaded should be linked to first * and take precedence over global scope symbols of the same name from other libraries. This * is only available on Linux and is ignored on other platforms. This is equivalent to passing * the `RTLD_DEEPBIND` flag to [dlopen](https://linux.die.net/man/3/dlopen) on Linux. */ constexpr LibraryFlags fLibFlagDeepBind = 0x00000004; /** Flag to indicate that a valid library handle should only be returned if the requested library * was already loaded into the process. If the library was not already loaded in the process * the call to loadLibrary() will fail and `nullptr` will be returned instead. When this flag * is used, the returned handle (if found and non-nullptr) will always have its reference count * incremented. The returned handle must still be passed to unloadLibrary() to ensure its * reference is cleaned up when the handle is no longer needed. */ constexpr LibraryFlags fLibFlagLoadExisting = 0x00000008; #if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD) /** The default library file extension for the current platform. * This string will always begin with a dot ('.'). * The extension will always be lower case. * This version is provided as a macro so it can be added to string literals. */ # define CARB_LIBRARY_EXTENSION ".dll" /** The default executable file extension for the current platform. * This string will always begin with a dot ('.') where it is not an * empty string. The extension will always be lower case. This is * provided as a macro so it can be added to string literals. */ # define CARB_EXECUTABLE_EXTENSION ".exe" #elif CARB_PLATFORM_LINUX # define CARB_LIBRARY_EXTENSION ".so" # define CARB_EXECUTABLE_EXTENSION "" #elif CARB_PLATFORM_MACOS # define CARB_LIBRARY_EXTENSION ".dylib" # define CARB_EXECUTABLE_EXTENSION "" #else CARB_UNSUPPORTED_PLATFORM(); #endif /** Retrieves the default library file extension for the current platform. * * @returns The default library file extension for the platform. This string will always * begin with a dot ('.'). The extension will always be lower case. */ constexpr const char* getDefaultLibraryExtension() { return CARB_LIBRARY_EXTENSION; } /** Retrieves the default library file prefix for the current platform. * The prefix will always be lower case. * This version is provided as a macro so it can be added to string literals. */ #if CARB_PLATFORM_WINDOWS # define CARB_LIBRARY_PREFIX "" #elif CARB_PLATFORM_LINUX || CARB_PLATFORM_MACOS # define CARB_LIBRARY_PREFIX "lib" #else CARB_UNSUPPORTED_PLATFORM(); #endif /** Retrieves the default library file prefix for the current platform. * * @returns The default library file prefix for the platform. The prefix will always be * lower case. */ constexpr const char* getDefaultLibraryPrefix() { return CARB_LIBRARY_PREFIX; } /** A macro to build a library file's name as a string literal. * @param name A string literal name for the library. * * @remarks This will build the full platform-specific library file name; * for example "carb" will be built into "carb.dll" on Windows, * "libcarb.so" on Linux, etc. */ #define CARB_LIBRARY_GET_LITERAL_NAME(name) CARB_LIBRARY_PREFIX name CARB_LIBRARY_EXTENSION /** Creates a full library name from a module's base name. * * @param[in] baseName The base name of the module to create the library name for. This * base name should not include the file extension (ie: ".dll" or ".so") * and should not include any prefix (ie: "lib"). Path components may be * included and will also be present in the created filename. This must * not be `nullptr`. * @returns The name to use to load the named module on the current platform. This will neither * check for the existence of the named module nor will it verify that a prefix or * file extension already exists in the base name. */ inline std::string createLibraryNameForModule(const char* baseName) { const char* prefix; const char* ext; char* buffer; size_t len = 0; size_t pathLen = 0; const char* sep[2] = {}; const char* name = baseName; if (baseName == nullptr || baseName[0] == 0) return {}; sep[0] = strrchr(baseName, '/'); #if CARB_PLATFORM_WINDOWS // also handle mixed path separators on Windows. sep[1] = strrchr(baseName, '\\'); if (sep[1] > sep[0]) sep[0] = sep[1]; #endif if (sep[0] != nullptr) { pathLen = (sep[0] - baseName) + 1; name = sep[0] + 1; len += pathLen; } prefix = getDefaultLibraryPrefix(); ext = getDefaultLibraryExtension(); len += strlen(prefix) + strlen(ext); len += strlen(name) + 1; buffer = CARB_STACK_ALLOC(char, len); carb::extras::formatString(buffer, len, "%.*s%s%s%s", (int)pathLen, baseName, prefix, name, ext); return buffer; } /** Attempts to retrieve the address of a symbol from a loaded module. * * @param[in] libHandle The library to retrieve the symbol from. This should be a handle * previously returned by loadLibrary(). * @param[in] name The name of the symbol to retrieve the address of. This must exactly * match the module's exported name for the symbol including case. * @returns The address of the loaded symbol if successfully found in the requested module. * @returns `nullptr` if the symbol was not found in the requested module. * * @note The @p libHandle parameter may also be `nullptr` to achieve some special behavior when * searching for symbols. However, note that this special behavior differs between * Windows and Linux. On Windows, passing `nullptr` for the library handle will search * for the symbol in the process's main module only. Since most main executable modules * don't export anything, this is likely to return `nullptr`. On Linux however, passing * `nullptr` for the library handle will search the process's entire symbol space starting * from the main executable module. * * @note Calling this on Linux with the handle of a library that has been unloaded from memory * is considered undefined behavior. It is the caller's responsibility to ensure the * library handle is valid before attempting to call this. On Windows, passing in an * invalid library handle will technically fail gracefully, however it is still considered * undefined behavior since another library could be reloaded into the same space in * memory at a later time. */ template <typename T> T getLibrarySymbol(LibraryHandle libHandle, const char* name) { #if CARB_PLATFORM_WINDOWS return reinterpret_cast<T>(::GetProcAddress(libHandle, name)); #elif CARB_POSIX if (libHandle == nullptr || name == nullptr) return nullptr; return reinterpret_cast<T>(::dlsym(libHandle, name)); #else CARB_UNSUPPORTED_PLATFORM(); #endif } std::string getLibraryFilenameByHandle(LibraryHandle handle); // forward declare #ifndef DOXYGEN_BUILD namespace detail { struct FreeString { void operator()(char* p) noexcept { free(p); } }; using UniqueCharPtr = std::unique_ptr<char, FreeString>; # if CARB_POSIX struct FreePosixLib { void operator()(void* p) noexcept { dlclose(p); } }; using UniquePosixLib = std::unique_ptr<void, FreePosixLib>; # endif } // namespace detail #endif // clang-format off /** Attempts to load a named library into the calling process. * * This attempts to dynamically load a named library into the calling process. If the library is already loaded, the * reference count of the library is increased and a handle to it is returned. If the library was not already loaded, * it is dynamically loaded and a handle to it is returned; its reference count will be one. Each call to this function * should be balanced by a call to \ref unloadLibrary() when the library is no longer needed. * * Libraries that were loaded as part of the process's dependencies list will be 'pinned' and their reference count will * not be changed by attempting to load them. It is still safe to \ref unloadLibrary() on handles for those libraries. * * \par Windows * This function calls [LoadLibraryEx](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexw) * with `LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR` and `LOAD_LIBRARY_SEARCH_DEFAULT_DIRS` to load libraries. If this fails, * the default search path is instead used. If `ERROR_FILENAME_EXCED_RANGE` is returned, the `LoadLibraryEx` call is * repeated with the filepath preceded with a prefix to disable string parsing. If the module or a dependent module is * not found, `GetLastError()` typically reports `ERROR_MOD_NOT_FOUND`. In order to determine which DLL library is * missing there are a few options: * * Enable [Show Loader Snaps](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/show-loader-snaps) * with the *gflags* tool, which is available with * [Debugging Tools for Windows](https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools). * Running the process in a debugger or with access to debug output will then show log messages from the Windows * loader. * * The same debug output can be enabled by setting the 32-bit value at `ntdll.dll!LdrpDebugFlags` to `0x1`. This * value must be accessed in a debugger with symbols for *ntdll.dll*. * * Alternately using a modern [Dependencies tool](https://github.com/lucasg/Dependencies) will reveal missing * dependencies for a library without a debugger, although it may not show the actual error that led to `loadLibrary` * failing. * * \par Linux * This function calls [dlopen](https://linux.die.net/man/3/dlopen) with the `RTLD_LAZY` flag (or `RTLD_NOW` if * \ref fLibFlagNow is specified). If \ref fLibFlagDeepBind is specified, `RTLD_DEEPBIND` is also used. It is possible * for the underlying `dlopen()` call to succeed without a dependent library able to load. In this case, the dynamic * loader destroys the link map, so symbol lookup on the module will fail. This condition is detected and treated as an * error condition. To have dynamic loader debug output displayed, use the [LD_DEBUG](https://linux.die.net/man/8/ld.so) * environment variable set to a value such as `files`, `libs` or `all`. Typically the output is printed to *stdout*, * but the `LD_DEBUG_OUTPUT` can be set to the name of a file to instead log to the file. The * [ldd](https://linux.die.net/man/1/ldd) command-line tool can be used to print the dependent libraries required by * an executable or library. * * \par MacOS * This function calls `dlopen` with the `RTLD_LAZY` flag (or `RTLD_NOW` if \ref fLibFlagNow is specified). To have the * dynamic loader debug output displayed, use the [DYLD_PRINT_LIBRARIES](https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/LoggingDynamicLoaderEvents.html) * environment variable. The `otool` command-line tool with the `-L` option will print out the dependent libraries * required by an executable or library. * * \par MacOS * If the requested library name is `nullptr`, the expectation from the caller is that the handle to the process' * main executable image will be returned. Unfortunately on MacOS, the `RTLD_DEFAULT` symbol is returned instead * as a pseudo-handle to the main executable module. This is valid to pass to other functions such as * getLibrarySymbol() and getLibraryFilenameByHandle() however. * * @note A library may fail to load because of a dependent library, but the error message may seem like the *requested* * library is causing the failure. * * @param[in] libraryName The name of the library to attempt to load. This may be either a * relative or absolute path name. This should be a UTF-8 encoded * path. If the @ref fLibFlagMakeFullLibName flag is used, the library * name may omit any platform specific prefix or file extension. The * appropriate platform specific name will be generated internally * using createLibraryNameForModule(). If `nullptr` is provided, the executable module is * retrieved instead. On Windows this handle need not be closed with \ref unloadLibrary() as * it does not increment the reference count, but on MacOSX and Linux it increments the * reference count and should therefore be passed to \ref unloadLibrary(). * @param[in] flags Flags to control the behavior of the operation. This defaults to 0. * @returns A handle to the library if it was already loaded in the process. This handle should * be cleaned up by unloadLibrary() when it is no longer necessary. `nullptr` is returned if the library * could not be found, or loading fails for some reason (use \ref getLastLoadLibraryError()). */ // clang-format on inline LibraryHandle loadLibrary(const char* libraryName, LibraryFlags flags = 0) { std::string fullLibName; LibraryHandle handle; // asked to construct a full library name => create the name and adjust the path as needed. if (libraryName != nullptr && libraryName[0] != '\0' && (flags & fLibFlagMakeFullLibName) != 0) { fullLibName = createLibraryNameForModule(libraryName); libraryName = fullLibName.c_str(); } #if CARB_PLATFORM_WINDOWS // retrieve the main executable module's handle. if (libraryName == nullptr) return ::GetModuleHandleW(nullptr); // retrieve the handle of a specific module. std::wstring widecharName = carb::extras::convertCarboniteToWindowsPath(libraryName); // asked to only retrieve a library handle if it is already loaded. Note that this will // still increment the library's ref count on return (unless it is pinned). It is always // safe to call unloadLibrary() on the returned (non-nullptr) handle in this case. if ((flags & fLibFlagLoadExisting) != 0) { return ::GetModuleHandleExW(0, widecharName.c_str(), &handle) ? handle : nullptr; } handle = ::LoadLibraryExW(widecharName.c_str(), nullptr, CARBWIN_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); // Although convertCarboniteToWindowsPath will ensure that a path over MAX_PATH has the long-path prefix, // LoadLibraryExW complains about strings slightly smaller than that. If we get that specific error then try // again with the long-path prefix. if (!handle && ::GetLastError() == CARBWIN_ERROR_FILENAME_EXCED_RANGE) { handle = ::LoadLibraryExW((L"\\\\?\\" + widecharName).c_str(), nullptr, CARBWIN_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); } // failed to load the loading the module from the 'default search dirs' => attempt to load // it with the default system search path. Oddly enough, this is different from the search // path provided by the flags used above - it includes the current working directory and // the paths in $PATH. Another possible reason for the above failing is that the library // name was a relative path. The CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS flag used above // requires that an absolute path be used. To keep the behavior of this function on par // with Linux's behavior, we'll attempt another load from the default paths instead. if (handle == nullptr) { handle = ::LoadLibraryExW(widecharName.c_str(), nullptr, 0); // As above, try again with the long-path prefix if we get a specific error response from LoadLibrary. if (!handle && ::GetLastError() == CARBWIN_ERROR_FILENAME_EXCED_RANGE) { handle = ::LoadLibraryExW((L"\\\\?\\" + widecharName).c_str(), nullptr, 0); } } #elif CARB_POSIX int openFlags = RTLD_LAZY; if ((flags & fLibFlagNow) != 0) openFlags |= RTLD_NOW; if ((flags & fLibFlagLoadExisting) != 0) openFlags |= RTLD_NOLOAD; # if CARB_PLATFORM_LINUX if ((flags & fLibFlagDeepBind) != 0) openFlags |= RTLD_DEEPBIND; # endif handle = dlopen(libraryName, openFlags); // failed to get a module handle or load the module => check if this was a request to load the // handle for the main executable module by its path name. if (handle == nullptr && libraryName != nullptr && libraryName[0] != 0) { detail::UniqueCharPtr path(realpath(libraryName, nullptr)); if (path == nullptr) { // probably trying to load a library that doesn't exist CARB_LOG_INFO("realpath(%s) failed (errno = %d)", libraryName, errno); return nullptr; } std::string raw = getLibraryFilenameByHandle(nullptr); CARB_FATAL_UNLESS(!raw.empty(), "getLibraryFilenameByHandle(nullptr) failed"); // use realpath() to ensure the paths can be compared detail::UniqueCharPtr path2(realpath(raw.c_str(), nullptr)); CARB_FATAL_UNLESS(path2 != nullptr, "realpath(%s) failed (errno = %d)", raw.c_str(), errno); // the two names match => retrieve the main executable module's handle for return. if (strcmp(path.get(), path2.get()) == 0) { return dlopen(nullptr, openFlags); } } # if CARB_PLATFORM_LINUX if (handle != nullptr) { // Linux's dlopen() has a strange issue where it's possible to have the call succeed // even though one or more of the library's dependencies fail to load. The dlopen() // call succeeds because there are still references on the handle despite the module's // link map having been destroyed (visible from the 'LD_DEBUG=all' output). // Unfortunately, if the link map is destroyed, any attempt to retrieve a symbol from // the library with dlsym() will fail. This causes some very confusing and misleading // error messages or crashes (depending on usage) instead of just having the module load // fail. void* linkMap = nullptr; const char* errorMsg = dlerror(); if (dlinfo(handle, RTLD_DI_LINKMAP, &linkMap) == -1 || linkMap == nullptr) { CARB_LOG_WARN("Library '%s' loaded with errors '%s' and no link map. The likely cause of this is that ", libraryName, errorMsg); CARB_LOG_WARN("a dependent library or symbol in the dependency chain is missing. Use the environment "); CARB_LOG_WARN("variable 'LD_DEBUG=all' to diagnose."); // close the bad library handle. Note that this may not actually unload the bad // library since it may still have multiple references on it (part of the failure // reason). However, we can only safely clean up one reference here. dlclose(handle); return nullptr; } } # endif #else CARB_UNSUPPORTED_PLATFORM(); #endif return handle; } /** Retrieves a string explaining the most recent library load failure cause. * * @returns A string containing a message explaining the most recent failure from loadLibrary(). */ inline std::string getLastLoadLibraryError() { #if CARB_PLATFORM_WINDOWS return carb::extras::getLastWinApiErrorMessage(); #else return dlerror(); #endif } /** Unloads a loaded library. * * @param[in] libraryHandle The handle to the library to unload. This should have been * returned by a previous call to loadLibrary(). This may not be * `nullptr`. * @returns No return value. * * @remarks This unloads one reference to a library that was loaded by loadLibrary(). Note that * this may not actually unload the library from the process if other references to it * still exist. When the last reference to an unpinned library is removed, that library * will be removed from the process's memory space. * * @note Once a library has been unloaded from memory, the handle to it cannot be safely used * any more. Attempting to use it may result in undefined behavior. Effectively, as * soon as a handle is passed in here, it should be discarded. Even though the module may * remain in memory, the handle should be treated as though it has been freed upon return * from here. */ inline void unloadLibrary(LibraryHandle libraryHandle) { if (libraryHandle) { #if CARB_PLATFORM_WINDOWS if (!::FreeLibrary(libraryHandle)) { DWORD err = ::GetLastError(); CARB_LOG_WARN("FreeLibrary for handle %p failed with error: %d/%s", libraryHandle, err, convertWinApiErrorCodeToMessage(err).c_str()); } #elif CARB_POSIX if (::dlclose(libraryHandle) != 0) { CARB_LOG_WARN("Closing library handle %p failed with error: %s", libraryHandle, dlerror()); } #else CARB_UNSUPPORTED_PLATFORM(); #endif } } /** Attempts to retrieve a library's handle by its filename. * * @warning This function does not increment a library's reference count, so it is possible (though unlikely) that * another thread could be unloading the library and the handle returned from this function is invalid. Only use this * function for debugging, or when you know that the returned handle will still be valid. * * @thread_safety This function is safe to call simultaneously from multiple threads, but only as long as another thread * is not attempting to unload the library found by this function. * * @param[in] libraryName The name of the library to retrieve the handle for. This may either * be the full path for the module or just its base filename. This may * be `nullptr` to retrieve the handle for the main executable module * for the calling process. If the @ref fLibFlagMakeFullLibName flag is * used, the library name may omit any platform specific prefix or file * extension. The appropriate platform specific name will be generated * internally using createLibraryNameForModule(). * @param[in] flags Flags to control the behavior of the operation. This defaults to 0. * @returns The handle to the requested library if it is already loaded in the process. Returns * `nullptr` if the library is not loaded. This will not load the library if it is not * already present in the process. This can be used to test if a library is already * loaded. */ inline LibraryHandle getLibraryHandleByFilename(const char* libraryName, LibraryFlags flags = 0) { std::string fullLibName; if (libraryName != nullptr && libraryName[0] != '\0' && (flags & fLibFlagMakeFullLibName) != 0) { fullLibName = createLibraryNameForModule(libraryName); libraryName = fullLibName.c_str(); } #if CARB_PLATFORM_WINDOWS if (libraryName == nullptr) return ::GetModuleHandleW(nullptr); std::wstring wideCharName = carb::extras::convertCarboniteToWindowsPath(libraryName); return GetModuleHandleW(wideCharName.c_str()); #else if (libraryName != nullptr && libraryName[0] == 0) return nullptr; // A successful dlopen() with RTLD_NOLOAD increments the reference count, so we dlclose() it to make sure that // the reference count stays the same. This function is inherently racy as another thread could be unloading the // library while we're trying to load it. // Note that we can't use UniquePosixLib here because it causes clang to think that we're returning a freed // pointer. void* handle = ::dlopen(libraryName, RTLD_LAZY | RTLD_NOLOAD); if (handle != nullptr) // dlclose(nullptr) crashes { dlclose(handle); } return handle; #endif } /** Retrieves the path for a loaded library from its handle. * * @param[in] handle The handle to the library to retrieve the name for. This may be `nullptr` * to retrieve the filename of the main executable module for the process. * @returns A string containing the full path to the requested library. * @returns An empty string if the module handle was invalid or the library is no longer loaded * in the process. */ inline std::string getLibraryFilenameByHandle(LibraryHandle handle) { #if CARB_PLATFORM_WINDOWS omni::extras::ScratchBuffer<wchar_t, CARBWIN_MAX_PATH> path; // There's no way to verify the correct length, so we'll just double the buffer // size every attempt until it fits. for (;;) { DWORD res = GetModuleFileNameW(handle, path.data(), DWORD(path.size())); if (res == 0) { // CARB_LOG_ERROR("GetModuleFileNameW(%p) failed (%d)", handle, GetLastError()); return ""; } if (res < path.size()) { break; } bool suc = path.resize(path.size() * 2); OMNI_FATAL_UNLESS(suc, "failed to allocate %zu bytes", path.size() * 2); } return carb::extras::convertWindowsToCarbonitePath(path.data()); #elif CARB_PLATFORM_LINUX struct link_map* map; // requested the filename for the main executable module => dlinfo() will succeed on this case // but will give an empty string for the path. To work around this, we'll simply read the // path to the process's executable symlink. if (handle == nullptr) { detail::UniqueCharPtr path(realpath("/proc/self/exe", nullptr)); CARB_FATAL_UNLESS(path != nullptr, "calling realpath(\"/proc/self/exe\") failed (%d)", errno); return path.get(); } int res = dlinfo(handle, RTLD_DI_LINKMAP, &map); if (res != 0) { // CARB_LOG_ERROR("failed to retrieve the link map from library handle %p (%d)", handle, errno); return ""; } // for some reason, the link map doesn't provide a filename for the main executable module. // This simply gets returned as an empty string. If we get that case, we'll try getting // the main module's filename instead. if (!map->l_name || map->l_name[0] == '\0') { // first make sure the handle passed in is for our main executable module. auto binaryHandle = loadLibrary(nullptr); if (binaryHandle) { unloadLibrary(binaryHandle); } if (binaryHandle != handle) { // CARB_LOG_ERROR("library had no filename in the link map but was not the main module"); return {}; } // recursively call to get the main module's name return getLibraryFilenameByHandle(nullptr); } return map->l_name; #elif CARB_PLATFORM_MACOS // dlopen(nullptr) gives a different (non-null) result than dlopen(path_to_exe), so // we need to test against it as well. if (handle == nullptr || detail::UniquePosixLib{ dlopen(nullptr, RTLD_LAZY | RTLD_NOLOAD) }.get() == handle) { omni::extras::ScratchBuffer<char, 4096> buffer; uint32_t len = buffer.size(); int res = _NSGetExecutablePath(buffer.data(), &len); if (res != 0) { bool succ = buffer.resize(len); CARB_FATAL_UNLESS(succ, "failed to allocate %" PRIu32 " bytes", len); res = _NSGetExecutablePath(buffer.data(), &len); CARB_FATAL_UNLESS(res != 0, "_NSGetExecutablePath() failed"); } detail::UniqueCharPtr path(realpath(buffer.data(), nullptr)); CARB_FATAL_UNLESS(path != nullptr, "realpath(%s) failed (errno = %d)", buffer.data(), errno); return path.get(); } // Look through all the currently loaded libraries for the our handle. for (uint32_t i = 0;; i++) { const char* name = _dyld_get_image_name(i); if (name == nullptr) { break; } // RTLD_NOLOAD is passed to avoid unnecessarily loading a library if it happened to be unloaded concurrently // with this call. UniquePosixLib is used to release the reference that dlopen adds if successful. if (detail::UniquePosixLib{ dlopen(name, RTLD_LAZY | RTLD_NOLOAD) }.get() == handle) { return name; } } return {}; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** Retrieves the path for a loaded library from an address or symbol within it. * * @param[in] symbolAddress The address of the symbol to find the library file name for. * This may be a symbol returned from a previous call to * getLibrarySymbol() or another known symbol in the library. * This does not strictly need to be an exported symbol from the * library, just an address within that library's memory space. * @returns A string containing the name and path of the library that the symbol belongs to if * found. This path components in this string will always be delimited by '/' and * the string will always be UTF-8 encoded. * @returns An empty string if the requested address is not a part of a loaded library. */ inline std::string getLibraryFilename(const void* symbolAddress) { #if CARB_PLATFORM_WINDOWS HMODULE hm = NULL; if (0 == GetModuleHandleExW( CARBWIN_GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | CARBWIN_GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)symbolAddress, &hm)) { return {}; } return getLibraryFilenameByHandle(hm); #elif CARB_PLATFORM_LINUX Dl_info info; struct link_map* lm; if (dladdr1(symbolAddress, &info, reinterpret_cast<void**>(&lm), RTLD_DL_LINKMAP)) { if (info.dli_fname != nullptr && info.dli_fname[0] == '/') return info.dli_fname; else if (lm->l_name != nullptr && lm->l_name[0] == '/') return lm->l_name; else { // the main executable doesn't have a path set for it => retrieve it directly. This // seems to be the expected behavior for the link map for the main module. if (lm->l_name == nullptr || lm->l_name[0] == 0) return getLibraryFilenameByHandle(nullptr); // no info to retrieve the name from => fail. if (info.dli_fname == nullptr || info.dli_fname[0] == 0) return {}; // if this process was launched using a relative path, the returned name from dladdr() // will also be a relative path => convert it to a fully qualified path before return. // Note that for this to work properly, the working directory should not have // changed since the process launched. This is not necessarily a valid assumption, // but since we have no control over that behavior here, it is the best we can do. // Note that we took all possible efforts above to minimize the cases where this // step will be needed however. detail::UniqueCharPtr path(realpath(info.dli_fname, nullptr)); if (path == nullptr) return {}; return path.get(); } } return {}; #elif CARB_PLATFORM_MACOS Dl_info info; if (dladdr(symbolAddress, &info)) { if (info.dli_fname == nullptr) { return getLibraryFilenameByHandle(nullptr); } else if (info.dli_fname[0] == '/') { // path is already absolute, just return it return info.dli_fname; } else { detail::UniqueCharPtr path(realpath(info.dli_fname, nullptr)); CARB_FATAL_UNLESS(path != nullptr, "realpath(%s) failed (errno = %d)", info.dli_fname, errno); return path.get(); } } return {}; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** * Retrieves the handle for a loaded library from an address or symbol within it. * * @note The library is not referenced as if @ref loadLibrary() was called for it. Do not call @ref unloadLibrary() to * as this handle does not need to be released. * * @param[in] symbolAddress The address of the symbol to find the library handle for. This may be a symbol returned from * a previous call to @ref getLibrarySymbol() or another known symbol in the library. This does not strictly need * to be an exported symbol from the library, just an address within that library's memory space. * @returns A @ref LibraryHandle representing the library that contains @p symbolAddress; @ref kInvalidLibraryHandle if * the library containing the symbol could not be determined. */ inline LibraryHandle getLibraryHandle(const void* symbolAddress) { #if CARB_PLATFORM_WINDOWS HMODULE hm = NULL; if (0 == GetModuleHandleExW( CARBWIN_GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | CARBWIN_GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)symbolAddress, &hm)) { return kInvalidLibraryHandle; } return hm; #elif CARB_POSIX std::string module = getLibraryFilename(symbolAddress); if (!module.empty()) { // loadLibrary increments the reference count, so decrement it immediately after. auto handle = loadLibrary(module.c_str()); if (handle != kInvalidLibraryHandle) { unloadLibrary(handle); } return handle; } return kInvalidLibraryHandle; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** Retrieves the parent directory of a library. * * @param[in] handle The handle to the loaded library to retrieve the directory for. This * must be a handle that was previously returned from loadLibrary() and has * not yet been unloaded. This may be `nullptr` to retrieve the directory of * the process's main executable. * @returns A string containing the name and path of the directory that contains the library * that the symbol belongs to if found. This path components in this string will * always be delimited by '/' and the string will always be UTF-8 encoded. The trailing * path separator will always be removed. * @returns An empty string if the requested address is not a part of a loaded library. */ inline std::string getLibraryDirectoryByHandle(LibraryHandle handle) { return carb::extras::getPathParent(getLibraryFilenameByHandle(handle)); } /** Retrieves the parent directory of the library containing a given address or symbol. * * @param[in] symbolAddress The address of the symbol to find the library file name for. * This may be a symbol returned from a previous call to * getLibrarySymbol() or another known symbol in the library. * This does not strictly need to be an exported symbol from the * library, just an address within that library's memory space. * @returns A string containing the name and path of the directory that contains the library * that the symbol belongs to if found. This path components in this string will * always be delimited by '/' and the string will always be UTF-8 encoded. The * trailing path separator will always be removed. * @returns An empty string if the requested address is not a part of a loaded library. */ inline std::string getLibraryDirectory(void* symbolAddress) { return carb::extras::getPathParent(getLibraryFilename(symbolAddress)); } } // namespace extras } // namespace carb
38,957
C
43.371298
219
0.668891
omniverse-code/kit/include/carb/extras/Csv.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "../Defines.h" #include <string> #include <vector> namespace carb { namespace extras { // These routines provide very basic non-optimal support for CSV files. inline std::vector<std::string> fromCsvString(const char* string) { // The rules of CSV are pretty simple. // ',''s '"''s and new lines should be encased in "'s bool inQuote = false; bool escaped = false; std::string current; std::vector<std::string> result; while (*string) { if (escaped) { if (*string == 'n') { string += '\n'; } current += *string; escaped = false; } else if (*string == '\\') { escaped = true; } else if (inQuote) { if (*string == '\"') { if (*(string + 1) == '\"') { current += "\""; string++; } else { inQuote = false; } } else { current += *string; } } else if (*string == ',') { result.emplace_back(std::move(current)); current.clear(); } else { current += *string; } string++; } if (result.empty() && current.empty()) return result; result.emplace_back(std::move(current)); return result; } inline std::string toCsvString(const std::vector<std::string>& columns) { std::string result; for (size_t i = 0; i < columns.size(); i++) { if (i != 0) result += ","; auto& column = columns[i]; // Determine if the string has anything that needs escaping bool needsEscaping = false; for (auto c : column) { if (c == '\n' || c == '"' || c == ',') { needsEscaping = true; } } if (!needsEscaping) { result += column; } else { result += "\""; for (auto c : column) { if (c == '\n') { result += "\\n"; } if (c == '"') { result += "\"\""; } else { result += c; } } result += "\""; } } return result; } } // namespace extras } // namespace carb
3,104
C
21.830882
77
0.43299
omniverse-code/kit/include/carb/extras/Timer.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 <chrono> namespace carb { namespace extras { /** * Timer class. */ class Timer { protected: std::chrono::high_resolution_clock::time_point m_startTimePoint, m_stopTimePoint; bool m_isRunning = false; public: enum class Scale { eSeconds, eMilliseconds, eMicroseconds, eNanoseconds }; /** * Returns precision of the timer (minimal tick duration). */ double getPrecision() { return std::chrono::high_resolution_clock::period::num / (double)std::chrono::high_resolution_clock::period::den; } /** * Starts timer. */ void start() { m_startTimePoint = std::chrono::high_resolution_clock::now(); m_isRunning = true; } /** * Stops timer. */ void stop() { m_stopTimePoint = std::chrono::high_resolution_clock::now(); m_isRunning = false; } /** * Gets elapsed time in a specified form, using specified time scale. * * @param timeScale Time scale that you want to get result in. * * @return Elapsed time between timer start, and timer stop events. If timer wasn't stopped before, returns elapsed * time between timer start and this function call, timer will continue to tick. Template parameter allows to select * between integral returned elapsed time (default), and floating point elapsed time, double precision recommended. */ template <typename ReturnType = int64_t> ReturnType getElapsedTime(Scale timeScale = Scale::eMilliseconds) { std::chrono::high_resolution_clock::time_point stopTimePoint; if (m_isRunning) { stopTimePoint = std::chrono::high_resolution_clock::now(); } else { stopTimePoint = m_stopTimePoint; } auto elapsedTime = stopTimePoint - m_startTimePoint; using dblSeconds = std::chrono::duration<ReturnType, std::ratio<1>>; using dblMilliseconds = std::chrono::duration<ReturnType, std::milli>; using dblMicroseconds = std::chrono::duration<ReturnType, std::micro>; using dblNanoseconds = std::chrono::duration<ReturnType, std::nano>; switch (timeScale) { case Scale::eSeconds: return std::chrono::duration_cast<dblSeconds>(elapsedTime).count(); case Scale::eMilliseconds: return std::chrono::duration_cast<dblMilliseconds>(elapsedTime).count(); case Scale::eMicroseconds: return std::chrono::duration_cast<dblMicroseconds>(elapsedTime).count(); case Scale::eNanoseconds: return std::chrono::duration_cast<dblNanoseconds>(elapsedTime).count(); default: return std::chrono::duration_cast<dblMilliseconds>(elapsedTime).count(); } } }; } // namespace extras } // namespace carb
3,372
C
30.231481
121
0.642349
omniverse-code/kit/include/carb/extras/CpuInfo.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 Utilities for gathering information about the CPU #pragma once #include "../Defines.h" #include <array> #if CARB_X86_64 # if CARB_COMPILER_MSC extern "C" { void __cpuid(int cpuInfo[4], int function_id); } # pragma intrinsic(__cpuid) # elif CARB_COMPILER_GNUC // for some strange reason, GCC's 'cpuid.h' header does not have an include guard of any // kind. This leads to multiple definition errors when the header is included twice in // a translation unit. To avoid this, we'll add our own external include guard here. # ifndef CARB_CPUID_H_INCLUDED # define CARB_CPUID_H_INCLUDED # include "cpuid.h" # endif # else CARB_UNSUPPORTED_PLATFORM(); # endif #endif namespace carb { namespace extras { /** * Helper class for gathering and querying CPU information for x86 and x64 CPUs * * On construction this class will query the CPU information provided by CPU ID and then provides helper methods for * querying information about the CPU. */ class CpuInfo { public: /** * Constructor */ CpuInfo() : m_isValid(true) { #if CARB_X86_64 # if CARB_COMPILER_MSC __cpuid(reinterpret_cast<int32_t*>(m_data.data()), kInfoType); # else // if __get_cpuid returns 0, the cpu information is not valid. int result = __get_cpuid(kInfoType, &m_data[kEax], &m_data[kEbx], &m_data[kEcx], &m_data[kEdx]); if (result == 0) { m_isValid = false; } # endif #else m_isValid = false; #endif } /** * Checks if the popcnt instruction is supported * * @return True if popcnt is supported, false if it is not supported, or the CPU information is not valid. */ bool popcntSupported() { return m_isValid && m_data[kEcx] & (1UL << kPopCountBit); } private: static constexpr uint32_t kInfoType = 0x00000001; static constexpr uint8_t kEax = 0; static constexpr uint8_t kEbx = 1; static constexpr uint8_t kEcx = 2; static constexpr uint8_t kEdx = 3; static constexpr uint8_t kPopCountBit = 23; bool m_isValid; std::array<uint32_t, 4> m_data; }; } // namespace extras } // namespace carb
2,667
C
26.505154
116
0.664042
omniverse-code/kit/include/carb/extras/Latch.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. // #pragma once #include "../cpp/Latch.h" namespace carb { namespace extras { class CARB_DEPRECATED("Deprecated: carb::extras::latch has moved to carb::cpp::latch") latch : public carb::cpp::latch { public: constexpr explicit latch(ptrdiff_t expected) : carb::cpp::latch(expected) { } }; } // namespace extras } // namespace carb
782
C
26.964285
118
0.748082
omniverse-code/kit/include/carb/extras/Tokens.h
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // /** @file * @brief Provides helper functions to manage and evaluate token strings. */ #pragma once #include "../tokens/TokensUtils.h" /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { /** Registers a new path string alias for replacement with resolvePathAliases(). * * @param[in] alias The alias string to be replaced. This should not contain the replacement * marker around the name "${}". * @param[in] value The value to replace the alias string with. * @returns No return value. */ inline void registerPathAlias(const char* alias, const char* value) { static carb::tokens::ITokens* tokens = carb::getFramework()->acquireInterface<carb::tokens::ITokens>(); tokens->setValue(alias, value); } /** Unregisters a path string alias. * * @param[in] alias The alias string to be removed. This should not contain the replacement * marker around the name "${}". This should have been previously registered * with registerPathAlias(). * @returns No return value. */ inline void unregisterPathAlias(const char* alias) { static carb::tokens::ITokens* tokens = carb::getFramework()->acquireInterface<carb::tokens::ITokens>(); tokens->removeToken(alias); } /** Replaces path alias markers in a path with the full names. * * @param[in] srcBuf The path to potentially replace path alias markers in. Any path * alias markers in the string must be surrounded by "${" and "}" characters * (ie: "${exampleMarker}/file.txt"). The markers will only be replaced if a * path alias using the same marker name ("exampleMarker" in the previous * example) is currently registered. * @returns A string containing the resolved path if path alias markers were replaced. * @returns A string containing the original path if no path alias markers were found or * replaced. * * @remarks This resolves a path string by replacing path alias markers with their full * paths. Markers must be registered with registerPathAlias() in order to be * replaced. This will always return a new string, but not all of the markers * may have been replaced in it is unregistered markers were found. * * @remarks A replaced path will never end in a trailing path separator. It is the caller's * responsibility to ensure the marker(s) in the string are appropriately separated * from other path components. This behavior does however allow for path aliases * to be used to construct multiple path names by piecing together different parts * of a name. * * @note This operation is always thread safe. */ inline std::string resolvePathAliases(const char* srcBuf) { static carb::tokens::ITokens* tokens = carb::getFramework()->acquireInterface<carb::tokens::ITokens>(); return carb::tokens::resolveString(tokens, srcBuf); } } // namespace extras } // namespace carb
3,581
C
41.141176
107
0.694499
omniverse-code/kit/include/carb/extras/EnvironmentVariableUtils.h
// Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! @brief Provides a helper class for setting and restoring environment variables. // #pragma once #include "../logging/Log.h" #include <map> #include <vector> namespace carb { namespace extras { /** * Resolves environment variable references in the source buffer * * @param sourceBuffer buffer of text to resolve * @param sourceBufferLength length of source buffer * @param envVariables map of name/value pairs of environment variables * @return The resolved string is the first member of the returned pair * the second bool member indicates if the resolve was without errors */ inline std::pair<std::string, bool> resolveEnvVarReferences(const char* sourceBuffer, size_t sourceBufferLength, const std::map<std::string, std::string>& envVariables) noexcept { std::pair<std::string, bool> result{}; if (!sourceBuffer) { CARB_LOG_ERROR("Null source buffer for resolving environment variable references."); return result; } if (CARB_UNLIKELY(sourceBufferLength == 0)) { result.second = true; return result; } // Collecting the env vars references struct EnvVarReference { const char* referenceStart; const char* referenceEnd; }; std::vector<EnvVarReference> envReferences; constexpr const char kEnvVarPrefix[] = "$env{"; constexpr const size_t kEnvVarPrefixLength = carb::countOf(kEnvVarPrefix) - 1; constexpr const char kEnvVarPostfix = '}'; constexpr const size_t kEnvVarPostfixLength = 1; const char* endEnvPos = sourceBuffer; for (const char* curReferencePos = std::strstr(endEnvPos, kEnvVarPrefix); curReferencePos != nullptr; curReferencePos = std::strstr(endEnvPos, kEnvVarPrefix)) { endEnvPos = std::strchr(curReferencePos, kEnvVarPostfix); if (!endEnvPos) { CARB_LOG_ERROR("Couldn't find the end of the environment variable reference: '%s'", curReferencePos); return result; } endEnvPos += kEnvVarPostfixLength; envReferences.emplace_back(EnvVarReference{ curReferencePos, endEnvPos }); } if (envReferences.empty()) { result.first = std::string(sourceBuffer, sourceBufferLength); result.second = true; return result; } // return true if resolved all the env variables in the provided buffer auto envVarResolver = [&](const char* buffer, const char* bufferEnd, size_t firstRefIndexToTry, size_t& firstUnprocessedRefIndex, std::string& resolvedString) -> bool { const char* curBufPos = buffer; const size_t envReferencesSize = envReferences.size(); size_t curRefIndex = firstRefIndexToTry; bool resolved = true; while (curRefIndex < envReferencesSize && envReferences[curRefIndex].referenceStart < buffer) { ++curRefIndex; } for (; curBufPos < bufferEnd && curRefIndex < envReferencesSize; ++curRefIndex) { const EnvVarReference& curRef = envReferences[curRefIndex]; if (curRef.referenceEnd > bufferEnd) { break; } // adding the part before env variable if (curBufPos < curRef.referenceStart) { resolvedString.append(curBufPos, curRef.referenceStart); } // resolving the env variable std::string varName(curRef.referenceStart + kEnvVarPrefixLength, curRef.referenceEnd - kEnvVarPostfixLength); if (CARB_LIKELY(!varName.empty())) { auto searchResult = envVariables.find(varName); if (searchResult != envVariables.end()) { resolvedString.append(searchResult->second); } else { // Couldn't resolve the reference resolved = false; } } else { CARB_LOG_WARN("Found environment variable reference with empty name."); } curBufPos = curRef.referenceEnd; } firstUnprocessedRefIndex = curRefIndex; // adding the rest of the string if (curBufPos < bufferEnd) { resolvedString.append(curBufPos, bufferEnd); } return resolved; }; // Check for the Elvis operator constexpr const char* const kElvisOperator = "?:"; constexpr size_t kElvisOperatorLen = 2; const char* const elvisPos = ::strstr(sourceBuffer, kElvisOperator); const size_t leftPartSize = elvisPos ? elvisPos - sourceBuffer : sourceBufferLength; size_t rightPartEnvRefFirstIndex = 0; const bool allResolved = envVarResolver(sourceBuffer, sourceBuffer + leftPartSize, 0, rightPartEnvRefFirstIndex, result.first); // switch to using the right part if we couldn't resolve everything on the left part of the Elvis op if (elvisPos && !allResolved) { result.first.clear(); envVarResolver(elvisPos + kElvisOperatorLen, sourceBuffer + sourceBufferLength, rightPartEnvRefFirstIndex, rightPartEnvRefFirstIndex, result.first); } result.second = true; return result; } } // namespace extras } // namespace carb
5,923
C
33.847059
124
0.630255
omniverse-code/kit/include/carb/extras/ScopeExit.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 "../Defines.h" #include "../cpp/Exception.h" #include <type_traits> #include <utility> // // Inspired from Andrei Alexandrescu CppCon 2015 Talk: Declarative Control Flow // https://github.com/CppCon/CppCon2015/tree/master/Presentations/ // https://www.youtube.com/watch?v=WjTrfoiB0MQ // // lambda executed on scope leaving scope #define CARB_SCOPE_EXIT \ const auto CARB_ANONYMOUS_VAR(SCOPE_EXIT_STATE) = ::carb::extras::detail::ScopeGuardExit{} + [&]() // lambda executed when leaving scope because an exception was thrown #define CARB_SCOPE_EXCEPT \ const auto CARB_ANONYMOUS_VAR(SCOPE_EXCEPT_STATE) = ::carb::extras::detail::ScopeGuardOnFail{} + [&]() // lambda executed when leaving scope and no exception was thrown #define CARB_SCOPE_NOEXCEPT \ const auto CARB_ANONYMOUS_VAR(SCOPE_EXCEPT_STATE) = ::carb::extras::detail::ScopeGuardOnSuccess{} + [&]() namespace carb { namespace extras { namespace detail { template <typename Fn> class ScopeGuard final { CARB_PREVENT_COPY(ScopeGuard); public: explicit ScopeGuard(Fn&& fn) : m_fn(std::move(fn)) { } ScopeGuard(ScopeGuard&&) = default; ScopeGuard& operator=(ScopeGuard&&) = default; ~ScopeGuard() { m_fn(); } private: Fn m_fn; }; enum class ScopeGuardExit { }; template <typename Fn> ScopeGuard<typename std::decay_t<Fn>> operator+(ScopeGuardExit, Fn&& fn) { return ScopeGuard<typename std::decay_t<Fn>>(std::forward<Fn>(fn)); } class UncaughtExceptionCounter final { CARB_PREVENT_COPY(UncaughtExceptionCounter); int m_exceptionCount; public: UncaughtExceptionCounter() noexcept : m_exceptionCount(::carb::cpp::uncaught_exceptions()) { } ~UncaughtExceptionCounter() = default; UncaughtExceptionCounter(UncaughtExceptionCounter&&) = default; UncaughtExceptionCounter& operator=(UncaughtExceptionCounter&&) = default; bool isNewUncaughtException() const noexcept { return ::carb::cpp::uncaught_exceptions() > m_exceptionCount; } }; template <typename Fn, bool execOnException> class ScopeGuardForNewException { CARB_PREVENT_COPY(ScopeGuardForNewException); Fn m_fn; UncaughtExceptionCounter m_ec; public: explicit ScopeGuardForNewException(Fn&& fn) : m_fn(std::move(fn)) { } ~ScopeGuardForNewException() noexcept(execOnException) { if (execOnException == m_ec.isNewUncaughtException()) { m_fn(); } } ScopeGuardForNewException(ScopeGuardForNewException&&) = default; ScopeGuardForNewException& operator=(ScopeGuardForNewException&&) = default; }; enum class ScopeGuardOnFail { }; template <typename Fn> ScopeGuardForNewException<typename std::decay_t<Fn>, true> operator+(ScopeGuardOnFail, Fn&& fn) { return ScopeGuardForNewException<typename std::decay_t<Fn>, true>(std::forward<Fn>(fn)); } enum class ScopeGuardOnSuccess { }; template <typename Fn> ScopeGuardForNewException<typename std::decay_t<Fn>, false> operator+(ScopeGuardOnSuccess, Fn&& fn) { return ScopeGuardForNewException<typename std::decay_t<Fn>, false>(std::forward<Fn>(fn)); } } // namespace detail } // namespace extras } // namespace carb
3,939
C
25.802721
120
0.66489
omniverse-code/kit/include/carb/extras/FreeListAllocator.h
// Copyright (c) 2018-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 "../Defines.h" #include <cstring> namespace carb { namespace extras { /** * Defines a free list that can allocate/deallocate fast and in any order from identically sized blocks. * * As long as every deallocation matches every allocation. Both allocation and deallocation are O(1) and * generally just a few instructions. The underlying memory allocator will allocate in large blocks, * with multiple elements amortizing a more costly large allocation against lots of fast small element allocations. */ class FreeListAllocator { public: static const size_t kMinimalAlignment = sizeof(void*); /** * Constructor. */ FreeListAllocator() : m_top(nullptr), m_end(nullptr), m_activeBlocks(nullptr), m_freeBlocks(nullptr), m_freeElements(nullptr), m_elementSize(0), m_alignment(1), m_blockSize(0), m_blockAllocationSize(0) { } /** * Constructor. * * @param elementSize Size of an element(in bytes). * @param alignment Alignment for elements in bytes, must be a power of 2 * @param elementsPerBlock The number of elements held in a single block */ FreeListAllocator(size_t elementSize, size_t alignment, size_t elementsPerBlock) { _initialize(elementSize, alignment, elementsPerBlock); } /** * Destructor. */ ~FreeListAllocator() { _deallocateBlocks(m_activeBlocks); _deallocateBlocks(m_freeBlocks); } /** * Initialize a free list allocator. * * If called on an already initialized heap, the heap will be deallocated. * * @param elementSize Size of an element in bytes * @param alignment Alignment for elements in bytes, must be a power of 2. * @param elementsPerBlock The amount of elements held in a single block */ void initialize(size_t elementSize, size_t alignment, size_t elementsPerBlock); /** * Determines if the data incoming is a valid allocation. * * @param data Pointer to be checked if is a valid allocation. * @return true if the pointer is to a previously returned and active allocation. */ bool isValid(const void* data) const; /** * Allocates an element. * * @return The element allocated. */ void* allocate(); /** * Deallocate a block that was previously allocated with allocate * * @param data Pointer previously gained by allocate. */ void deallocate(void* data); /** * Deallocates all elements */ void deallocateAll(); /** * Resets and deallocates all blocks and frees any backing memory and resets memory blocks to initial state. */ void reset(); /** * Gets the element size. * * @return The size of an element (in bytes). */ size_t getElementSize() const; /** * Gets the total size of each individual block allocation (in bytes). * * @return The size of each block (in bytes). */ size_t getBlockSize() const; /** * Gets the allocation alignment (in bytes). * * @return Allocation alignment (in bytes). */ size_t getAlignment() const; private: struct Element { Element* m_next; }; struct Block { Block* m_next; uint8_t* m_data; }; FreeListAllocator(const FreeListAllocator& rhs) = delete; void operator=(const FreeListAllocator& rhs) = delete; void _initialize(size_t elementSize, size_t alignment, size_t elementsPerBlock) { // Alignment must be at least the size of a pointer, as when freed a pointer is stored in free blocks. m_alignment = (alignment < kMinimalAlignment) ? kMinimalAlignment : alignment; // Alignment must be a power of 2 CARB_ASSERT(((m_alignment - 1) & m_alignment) == 0); // The elementSize must at least be the size of the alignment m_elementSize = (elementSize >= m_alignment) ? elementSize : m_alignment; // The elementSize must be an integral number of alignment/s CARB_ASSERT((m_elementSize & (m_alignment - 1)) == 0); m_blockSize = m_elementSize * elementsPerBlock; // Calculate the block size need, correcting for alignment const size_t alignedBlockSize = _calculateAlignedBlockSize(m_alignment); // Make the block struct size aligned m_blockAllocationSize = m_blockSize + alignedBlockSize; m_top = nullptr; m_end = nullptr; m_activeBlocks = nullptr; m_freeBlocks = nullptr; m_freeElements = nullptr; } void* _allocateBlock() { Block* block = m_freeBlocks; if (block) { // Remove from the free blocks m_freeBlocks = block->m_next; } else { block = (Block*)CARB_MALLOC(m_blockAllocationSize); if (!block) { return nullptr; } // Do the alignment { size_t fix = (size_t(block) + sizeof(Block) + m_alignment - 1) & ~(m_alignment - 1); block->m_data = (uint8_t*)fix; } } // Attach to the active blocks block->m_next = m_activeBlocks; m_activeBlocks = block; // Set up top and end m_end = block->m_data + m_blockSize; // Return the first element uint8_t* element = block->m_data; m_top = element + m_elementSize; return element; } void _deallocateBlocks(Block* block) { while (block) { Block* next = block->m_next; CARB_FREE(block); block = next; } } static size_t _calculateAlignedBlockSize(size_t align) { return (sizeof(Block) + align - 1) & ~(align - 1); } uint8_t* m_top; uint8_t* m_end; Block* m_activeBlocks; Block* m_freeBlocks; Element* m_freeElements; size_t m_elementSize; size_t m_alignment; size_t m_blockSize; size_t m_blockAllocationSize; }; inline void FreeListAllocator::initialize(size_t elementSize, size_t alignment, size_t elementsPerBlock) { _deallocateBlocks(m_activeBlocks); _deallocateBlocks(m_freeBlocks); _initialize(elementSize, alignment, elementsPerBlock); } inline bool FreeListAllocator::isValid(const void* data) const { uint8_t* checkedData = (uint8_t*)data; Block* block = m_activeBlocks; while (block) { uint8_t* start = block->m_data; uint8_t* end = start + m_blockSize; if (checkedData >= start && checkedData < end) { // Check it's aligned correctly if ((checkedData - start) % m_elementSize) { return false; } // Non-allocated data is between top and end if (checkedData >= m_top && data < m_end) { return false; } // It can't be in the free list Element* element = m_freeElements; while (element) { if (element == (Element*)data) { return false; } element = element->m_next; } return true; } block = block->m_next; } // It's not in an active block and therefore it cannot be a valid allocation return false; } inline void* FreeListAllocator::allocate() { // Check if there are any previously deallocated elements, if so use these first { Element* element = m_freeElements; if (element) { m_freeElements = element->m_next; return element; } } // If there is no space on current block, then allocate a new block and return first element if (m_top >= m_end) { return _allocateBlock(); } // We can use top void* data = (void*)m_top; m_top += m_elementSize; return data; } inline void FreeListAllocator::deallocate(void* data) { Element* element = (Element*)data; element->m_next = m_freeElements; m_freeElements = element; } inline void FreeListAllocator::deallocateAll() { Block* block = m_activeBlocks; if (block) { // Find the end block while (block->m_next) { block = block->m_next; } // Attach to the freeblocks block->m_next = m_freeBlocks; // The list is now all freelists m_freeBlocks = m_activeBlocks; // There are no active blocks m_activeBlocks = nullptr; } m_top = nullptr; m_end = nullptr; } inline void FreeListAllocator::reset() { _deallocateBlocks(m_activeBlocks); _deallocateBlocks(m_freeBlocks); m_top = nullptr; m_end = nullptr; m_activeBlocks = nullptr; m_freeBlocks = nullptr; m_freeElements = nullptr; } inline size_t FreeListAllocator::getElementSize() const { return m_elementSize; } inline size_t FreeListAllocator::getBlockSize() const { return m_blockSize; } inline size_t FreeListAllocator::getAlignment() const { return m_alignment; } } // namespace extras } // namespace carb
9,754
C
25.508152
115
0.600472
omniverse-code/kit/include/carb/extras/Hash.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. // #pragma once #include "../Defines.h" namespace carb { namespace extras { namespace detail { #if CARB_COMPILER_GNUC using uint128_t = __uint128_t; constexpr uint128_t fnv128init(uint64_t high, uint64_t low) { return (uint128_t(high) << 64) + low; } inline void fnv128xor(uint128_t& out, uint8_t b) { out ^= b; } inline void fnv128add(uint128_t& out, uint128_t in) { out += in; } inline void fnv128mul(uint128_t& out, uint128_t in) { out *= in; } #elif CARB_COMPILER_MSC extern "C" unsigned __int64 _umul128(unsigned __int64, unsigned __int64, unsigned __int64*); extern "C" unsigned char _addcarry_u64(unsigned char, unsigned __int64, unsigned __int64, unsigned __int64*); # pragma intrinsic(_mul128) # pragma intrinsic(_addcarry_u64) struct uint128_t { uint64_t d[2]; }; constexpr uint128_t fnv128init(uint64_t high, uint64_t low) { return uint128_t{ low, high }; } inline void fnv128xor(uint128_t& out, uint8_t b) { out.d[0] ^= b; } inline void fnv128add(uint128_t& out, uint128_t in) { uint8_t c = _addcarry_u64(0, out.d[0], in.d[0], &out.d[0]); _addcarry_u64(c, out.d[1], in.d[1], &out.d[1]); } inline void fnv128mul(uint128_t& out, uint128_t in) { // 128-bit multiply with 64 bits is: // place: 64 0 // A B (out) // X C D (in) // -------------------- // D*A D*B // + C*B 0 uint64_t orig = out.d[0], temp; out.d[0] = _umul128(orig, in.d[0], &temp); out.d[1] = temp + (out.d[1] * in.d[0]) + (in.d[1] * orig); } #else CARB_UNSUPPORTED_PLATFORM(); #endif // 0x0000000001000000000000000000013B constexpr uint128_t kFnv128Prime = detail::fnv128init(0x0000000001000000, 0x000000000000013B); } // namespace detail struct hash128_t { uint64_t d[2]; }; // FNV-1a 128-bit basis: 0x6c62272e07bb014262b821756295c58d constexpr static hash128_t kFnv128Basis = { 0x62b821756295c58d, 0x6c62272e07bb0142 }; inline hash128_t hash128FromHexString(const char* buffer, const char** end = nullptr) { union { detail::uint128_t u128 = { 0 }; hash128_t hash; } ret; constexpr static detail::uint128_t n16{ 16 }; // skip 0x if necessary if (buffer[0] == '0' && buffer[1] == 'x') buffer += 2; while (*buffer) { detail::uint128_t num; if (*buffer >= '0' && *buffer <= '9') num = { unsigned(*buffer - '0') }; else if (*buffer >= 'a' && *buffer <= 'z') num = { unsigned(*buffer - 'a' + 10) }; else if (*buffer >= 'A' && *buffer <= 'Z') num = { unsigned(*buffer - 'A' + 10) }; else { // Error CARB_ASSERT(0); if (end) *end = buffer; return ret.hash; } detail::fnv128mul(ret.u128, n16); detail::fnv128add(ret.u128, num); ++buffer; } if (end) *end = buffer; return ret.hash; } // Deprecated function CARB_DEPRECATED("Use hash128FromHexString() instead") inline bool hashFromString(const char* buffer, hash128_t& hash) { const char* end; hash = hash128FromHexString(buffer, &end); return *end == '\0'; } inline hash128_t fnv128hash(const uint8_t* data, size_t size, hash128_t seed = kFnv128Basis) { union U { detail::uint128_t u128; hash128_t hash; } u; u.hash = seed; const uint8_t* const end = data + size; // Align if (CARB_UNLIKELY(!!(size_t(data) & 0x7) && (end - data) >= 8)) { do { detail::fnv128xor(u.u128, *(data++)); detail::fnv128mul(u.u128, detail::kFnv128Prime); } while (!!(size_t(data) & 0x7)); } // Unroll the loop while ((end - data) >= 8) { uint64_t val = *reinterpret_cast<const uint64_t*>(data); #define HASH_STEP(v) \ detail::fnv128xor(u.u128, uint8_t(v)); \ detail::fnv128mul(u.u128, detail::kFnv128Prime) HASH_STEP(val); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); #undef HASH_STEP data += 8; } // Handle remaining while (data != end) { detail::fnv128xor(u.u128, *(data++)); detail::fnv128mul(u.u128, detail::kFnv128Prime); } return u.hash; } namespace detail { // this can't be a lambda because there's no consistent way to add this // attribute to a lambda between GCC 7 and 9 CARB_ATTRIBUTE(no_sanitize_address) inline uint64_t read64(const void* data) { return *static_cast<const uint64_t*>(data); } } // namespace detail inline hash128_t fnv128hashString(const char* data, hash128_t seed = kFnv128Basis) { union U { detail::uint128_t u128; hash128_t hash; } u; u.hash = seed; if (!!(size_t(data) & 0x7)) { // Align for (;;) { if (*data == '\0') return u.hash; detail::fnv128xor(u.u128, uint8_t(*(data++))); detail::fnv128mul(u.u128, detail::kFnv128Prime); if (!(size_t(data) & 0x7)) break; } } // Use a bit trick often employed in strlen() implementations to return a non-zero value if any byte within a word // is zero. This can sometimes be falsely positive for UTF-8 strings, so handle those for (;;) { uint64_t val = ::carb::extras::detail::read64(data); if (CARB_LIKELY(!((val - 0x0101010101010101) & 0x8080808080808080))) { // None of the next 8 bytes are zero #define HASH_STEP(v) \ detail::fnv128xor(u.u128, uint8_t(v)); \ detail::fnv128mul(u.u128, detail::kFnv128Prime) HASH_STEP(val); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); #undef HASH_STEP } else { uint8_t b; // One of the next 8 bytes *might* be zero #define HASH_STEP(v) \ b = uint8_t(v); \ if (CARB_UNLIKELY(!b)) \ return u.hash; \ detail::fnv128xor(u.u128, b); \ detail::fnv128mul(u.u128, detail::kFnv128Prime) HASH_STEP(val); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); HASH_STEP(val >>= 8); #undef HASH_STEP } data += 8; } } constexpr bool operator==(const hash128_t& lhs, const hash128_t& rhs) { return lhs.d[0] == rhs.d[0] && lhs.d[1] == rhs.d[1]; } constexpr bool operator!=(const hash128_t& lhs, const hash128_t& rhs) { return !(lhs == rhs); } constexpr bool operator<(const hash128_t& lhs, const hash128_t& rhs) { if (lhs.d[1] < rhs.d[1]) return true; if (rhs.d[1] < lhs.d[1]) return false; return lhs.d[0] < rhs.d[0]; } constexpr bool operator>(const hash128_t& lhs, const hash128_t& rhs) { return rhs < lhs; } constexpr bool operator<=(const hash128_t& lhs, const hash128_t& rhs) { return !(lhs > rhs); } constexpr bool operator>=(const hash128_t& lhs, const hash128_t& rhs) { return !(lhs < rhs); } } // namespace extras } // namespace carb namespace std { template <> struct hash<carb::extras::hash128_t> { using argument_type = carb::extras::hash128_t; using result_type = std::size_t; result_type operator()(argument_type const& s) const noexcept { return s.d[0] ^ s.d[1]; } }; inline std::string to_string(const carb::extras::hash128_t& hash) { std::string strBuffer(32, '0'); constexpr static char nibbles[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', }; auto fill64 = [](char* buffer, uint64_t v) { buffer += 16; while (v != 0) { *(--buffer) = nibbles[v & 0xf]; v >>= 4; } }; fill64(std::addressof(strBuffer.at(16)), hash.d[0]); fill64(std::addressof(strBuffer.at(0)), hash.d[1]); return strBuffer; } } // namespace std
9,554
C
25.764706
120
0.514444
omniverse-code/kit/include/carb/extras/CmdLineParser.h
// Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "../Defines.h" #include "../cpp/StringView.h" #include "../logging/Log.h" #include "StringUtils.h" #include "Unicode.h" #include <algorithm> #include <sstream> #include <cstdlib> #include <cstring> #include <map> #include <string> #if CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" #elif CARB_PLATFORM_LINUX # include <argz.h> # include <fstream> #elif CARB_PLATFORM_MACOS # include <crt_externs.h> #endif namespace carb { namespace extras { class CmdLineParser { public: using Options = std::map<std::string, std::string>; CmdLineParser(const char* prefix) : m_prefix(prefix) { } void parse(char** argv, int argc) { if (argc > 0) { parseFromArgs(argv, argc); } else { parseFromCLI(); } } const Options& getOptions() const { return m_carbOptions; } private: void parseFromCLI() { m_currentKey.clear(); #if CARB_PLATFORM_WINDOWS LPWSTR* argv; int argc; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (nullptr == argv) { return; } parseFromArgs(argv, argc); LocalFree(argv); #elif CARB_PLATFORM_LINUX std::string cmdLine; std::getline(std::fstream("/proc/self/cmdline", std::ios::in), cmdLine); int argc = argz_count(cmdLine.c_str(), cmdLine.size()); char** argv = static_cast<char**>(std::malloc((argc + 1) * sizeof(char*))); argz_extract(cmdLine.c_str(), cmdLine.size(), argv); parseFromArgs(argv, argc); std::free(argv); #elif CARB_PLATFORM_MACOS int argc = *_NSGetArgc(); char** argv = *_NSGetArgv(); parseFromArgs(argv, argc); #endif } void parseArg(const std::string& arg) { // Waiting value for a key? if (!m_currentKey.empty()) { std::string value = arg; preprocessValue(value); m_carbOptions[m_currentKey] = value; m_currentKey.clear(); return; } // Process only keys starting with kCarbPrefix if (strncmp(arg.c_str(), m_prefix.c_str(), m_prefix.size()) == 0) { // Split to key and value std::size_t pos = arg.find("="); if (pos != std::string::npos) { const std::string key = carb::extras::trimString(arg.substr(m_prefix.size(), pos - m_prefix.size())); if (!key.empty()) { std::string value = arg.substr(pos + 1, arg.size() - pos - 1); preprocessValue(value); carb::extras::trimStringInplace(value); m_carbOptions[key] = value; } else { CARB_LOG_WARN("Encountered key-value pair with empty key in command line: %s", arg.c_str()); } } else { // Save key and wait for next value m_currentKey = arg.substr(m_prefix.size(), arg.size() - m_prefix.size()); carb::extras::trimStringInplace(m_currentKey); } } } #if CARB_PLATFORM_WINDOWS void parseFromArgs(wchar_t** argv, int argc) { if (argc < 0 || argv == nullptr) return; for (int i = 1; i < argc; ++i) { if (argv[i]) { std::string arg = extras::convertWideToUtf8(argv[i]); parseArg(arg); } } } #endif void parseFromArgs(char** argv, int argc) { if (argc < 0 || argv == nullptr) return; for (int i = 1; i < argc; ++i) { if (argv[i]) { std::string arg = argv[i]; parseArg(arg); } } } void preprocessValue(std::string& value) { // If surrounded by single quotes - replace them with double quotes for json compatibility if (!value.empty() && value[0] == '\'' && value[value.size() - 1] == '\'') { value[0] = '"'; value[value.size() - 1] = '"'; } } private: Options m_carbOptions; std::string m_currentKey; std::string m_prefix; }; /** * Converts an array of command-line arguments to a single command-line string. * * It handles spaces and quotes in the arguments. * * @param argv The array of command-line arguments. * @param argc The number of arguments in the array. * @return A string that represents the command-line arguments. */ inline std::string argvToCommandLine(const char* const* argv, size_t argc) { std::ostringstream os; for (size_t i = 0; i < argc; ++i) { if (i > 0) os << " "; // quote this argument if it contains tabs, spaces, quotes, newlines, or carriage returns cpp::string_view sv{ argv[i] }; if (sv.find_first_of(" \t\n\r\"", 0, 5) != std::string::npos) { os << "\""; os << sv.data(); os << "\""; } else { os << sv.data(); } } return os.str(); } } // namespace extras } // namespace carb
5,751
C
24.90991
117
0.530864
omniverse-code/kit/include/carb/extras/AppConfig.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. // #pragma once #include "../dictionary/DictionaryUtils.h" #include "EnvironmentVariableUtils.h" #include "StringUtils.h" #include "Path.h" #include <map> #include <string> namespace carb { namespace extras { class ConfigLoadHelper { public: using CmdLineOptionsMap = std::map<std::string, std::string>; using PathwiseEnvOverridesMap = std::map<std::string, std::string>; using EnvVariablesMap = std::map<std::string, std::string>; // If the dict item is a special raw string then it returns pointer to the buffer past the special raw string marker // In all other cases it returns nullptr static inline const char* getRawStringFromItem(carb::dictionary::IDictionary* dictInterface, const carb::dictionary::Item* item) { static constexpr char kSpecialRawStringMarker[] = "$raw:"; if (!dictInterface || !item) { return nullptr; } if (dictInterface->getItemType(item) != dictionary::ItemType::eString) { return nullptr; } const char* stringBuffer = dictInterface->getStringBuffer(item); if (!stringBuffer) { return nullptr; } constexpr size_t kMarkerLen = carb::countOf(kSpecialRawStringMarker) - 1; if (std::strncmp(stringBuffer, kSpecialRawStringMarker, kMarkerLen) != 0) { return nullptr; } return stringBuffer + kMarkerLen; } /** * Helper function to resolve references to environment variables and Elvis operators */ static inline void resolveEnvVarReferencesInDict(dictionary::IDictionary* dictInterface, dictionary::Item* dict, const EnvVariablesMap* envVariables) { if (!dict || !envVariables) { return; } const auto itemResolver = [&](dictionary::Item* item, uint32_t elementData, void* userData) { CARB_UNUSED(elementData, userData); // Working only on string items if (dictInterface->getItemType(item) != dictionary::ItemType::eString) { return 0; } // Skipping raw strings if (getRawStringFromItem(dictInterface, item) != nullptr) { return 0; } const char* stringBuffer = dictInterface->getStringBuffer(item); const size_t stringBufferLen = std::strlen(stringBuffer); // We have an empty string, no reason to resolve it if (stringBufferLen == 0) { return 0; } std::pair<std::string, bool> resolveResult = extras::resolveEnvVarReferences(stringBuffer, stringBufferLen, *envVariables); if (!resolveResult.second) { CARB_LOG_ERROR("Error while resolving environment variable references for '%s'", stringBuffer); return 0; } const std::string& resolvedString = resolveResult.first; if (!resolvedString.empty()) { dictInterface->setString(item, resolvedString.c_str()); } else { dictInterface->destroyItem(item); } return 0; }; const auto getChildByIndexMutable = [](dictionary::IDictionary* dict, dictionary::Item* item, size_t index) { return dict->getItemChildByIndexMutable(item, index); }; dictionary::walkDictionary(dictInterface, dictionary::WalkerMode::eIncludeRoot, dict, 0, itemResolver, nullptr, getChildByIndexMutable); } using GetItemFullPathFuncPtr = std::string (*)(dictionary::IDictionary* dictInterface, const dictionary::Item* item); struct UpdaterData { dictionary::IDictionary* dictInterface; const char* loadedDictPath; GetItemFullPathFuncPtr getItemFullPathFunc; }; static dictionary::UpdateAction onDictUpdateReporting(const dictionary::Item* dstItem, dictionary::ItemType dstItemType, const dictionary::Item* srcItem, dictionary::ItemType srcItemType, void* userData) { CARB_UNUSED(dstItemType, srcItem, srcItemType); const UpdaterData* updaterData = static_cast<const UpdaterData*>(userData); if (updaterData->getItemFullPathFunc) { std::string itemPath = updaterData->getItemFullPathFunc(updaterData->dictInterface, dstItem); CARB_LOG_VERBOSE("Replacing the '%s' item current value by the value from '%s' config.", itemPath.c_str(), updaterData->loadedDictPath); } if (!dstItem) { return dictionary::UpdateAction::eOverwrite; } if (updaterData->dictInterface->getItemFlag(srcItem, dictionary::ItemFlag::eUnitSubtree)) { return dictionary::UpdateAction::eReplaceSubtree; } return dictionary::UpdateAction::eOverwrite; }; static inline GetItemFullPathFuncPtr getFullPathFunc() { return logging::getLogging()->getLevelThreshold() == logging::kLevelVerbose ? dictionary::getItemFullPath : nullptr; } static dictionary::Item* resolveAndMergeNewDictIntoTarget(dictionary::IDictionary* dictInterface, dictionary::Item* targetDict, dictionary::Item* newDict, const char* newDictSource, const EnvVariablesMap* envVariablesMap) { if (!newDict) { return targetDict; } extras::ConfigLoadHelper::resolveEnvVarReferencesInDict(dictInterface, newDict, envVariablesMap); if (!targetDict) { return newDict; } UpdaterData updaterData = { dictInterface, newDictSource ? newDictSource : "Unspecified source", getFullPathFunc() }; dictInterface->update(targetDict, nullptr, newDict, nullptr, onDictUpdateReporting, &updaterData); dictInterface->destroyItem(newDict); return targetDict; }; /** Retrieve the standardized user config folder for a given system. * @param[in] envVariablesMap The environment variables to query for the * config folder path. * This may not be nullptr. * @param[in] configSubFolderName The folder name within the config directory * to append to the path. * This may be nullptr to have the returned * path be the config directory. * @returns The path to the config directory that should be used. * @returns An empty path if the required environment variables were not * set. Note that this can't happen on Linux unless a user has * explicitly broken their env vars. */ static extras::Path getConfigUserFolder(const EnvVariablesMap* envVariablesMap, const char* configSubFolderName = "nvidia") { #if CARB_PLATFORM_WINDOWS const char* kUserFolderEnvVar = "USERPROFILE"; #elif CARB_PLATFORM_LINUX const char* kUserFolderEnvVar = "XDG_CONFIG_HOME"; #elif CARB_PLATFORM_MACOS const char* kUserFolderEnvVar = "HOME"; #endif extras::Path userFolder; if (envVariablesMap) { // Resolving user folder auto searchResult = envVariablesMap->find(kUserFolderEnvVar); if (searchResult != envVariablesMap->end()) userFolder = searchResult->second; #if CARB_PLATFORM_LINUX // The XDG standard says that if XDG_CONFIG_HOME is undefined, // $HOME/.config is used if (userFolder.isEmpty()) { auto searchResult = envVariablesMap->find("HOME"); if (searchResult != envVariablesMap->end()) { userFolder = searchResult->second; userFolder /= ".config"; } } #elif CARB_PLATFORM_MACOS if (!userFolder.isEmpty()) { userFolder /= "Library/Application Support"; } #endif if (!userFolder.isEmpty() && configSubFolderName != nullptr) userFolder /= configSubFolderName; } return userFolder; } static dictionary::Item* applyPathwiseEnvOverrides(dictionary::IDictionary* dictionaryInterface, dictionary::Item* combinedConfig, const PathwiseEnvOverridesMap* pathwiseEnvOverridesMap, const EnvVariablesMap* envVariablesMap) { if (pathwiseEnvOverridesMap) { dictionary::Item* pathwiseConfig = dictionaryInterface->createItem( nullptr, "<pathwise env override config>", dictionary::ItemType::eDictionary); if (pathwiseConfig) { dictionary::setDictionaryFromStringMapping(dictionaryInterface, pathwiseConfig, *pathwiseEnvOverridesMap); return extras::ConfigLoadHelper::resolveAndMergeNewDictIntoTarget( dictionaryInterface, combinedConfig, pathwiseConfig, "environment variables override", envVariablesMap); } CARB_LOG_ERROR("Couldn't process environment variables overrides"); } return combinedConfig; } /** * Adds to the "targetDictionary" element at path "elementPath" as dictionary created from parsing elementValue as * JSON data * * @param [in] jsonSerializerInterface non-null pointer to the JSON ISerializer interface * @param [in] dictionaryInterface non-null pointer to the IDictionary interface * @param [in,out] targetDictionary dictionary into which element will be added * @param [in] elementPath path to the element in the dictionary * @param [in] elementValue JSON data */ static void addCmdLineJSONElementToDict(dictionary::ISerializer* jsonSerializerInterface, dictionary::IDictionary* dictionaryInterface, dictionary::Item* targetDictionary, const std::string& elementPath, const std::string& elementValue) { if (elementPath.empty()) { return; } CARB_ASSERT(elementValue.size() >= 2 && elementValue.front() == '{' && elementValue.back() == '}'); // Parse provided JSON data dictionary::Item* parsedDictionary = jsonSerializerInterface->createDictionaryFromStringBuffer(elementValue.c_str(), elementValue.length()); if (!parsedDictionary) { CARB_LOG_ERROR("Couldn't parse as JSON data command-line argument '%s'", elementPath.c_str()); return; } // Merge result into target dictionary dictionaryInterface->update(targetDictionary, elementPath.c_str(), parsedDictionary, nullptr, dictionary::overwriteOriginalWithArrayHandling, dictionaryInterface); // Release allocated resources dictionaryInterface->destroyItem(parsedDictionary); } /** * Merges values set in the command line into provided configuration dictionary * * @param [in] dictionaryInterface non-null pointer to the IDictionary interface * @param [in,out] combinedConfig configuration dictionary into which parameters set in the command line will be * merged * @param [in] cmdLineOptionsMap map of parameters set in the command line * @param [in] envVariablesMap map of the parameters set in the environment variables. Used for resolving references * in the values of cmdLineOptionsMap * * @return "combinedConfig" with merged parameters set in the command line */ static dictionary::Item* applyCmdLineOverrides(dictionary::IDictionary* dictionaryInterface, dictionary::Item* combinedConfig, const CmdLineOptionsMap* cmdLineOptionsMap, const EnvVariablesMap* envVariablesMap) { if (cmdLineOptionsMap) { dictionary::Item* cmdLineOptionsConfig = dictionaryInterface->createItem( nullptr, "<cmd line override config>", dictionary::ItemType::eDictionary); if (cmdLineOptionsConfig) { dictionary::ISerializer* jsonSerializer = nullptr; bool checkedJsonSerializer = false; for (const auto& kv : *cmdLineOptionsMap) { const std::string& trimmedValue = carb::extras::trimString(kv.second); // First checking if there is enough symbols to check for array/JSON parameter if (trimmedValue.size() >= 2) { // Check if value is "[ something ]" then we consider it to be an array if (trimmedValue.front() == '[' && trimmedValue.back() == ']') { // Processing the array value setDictionaryArrayElementFromStringValue( dictionaryInterface, cmdLineOptionsConfig, kv.first, trimmedValue); continue; } // Check if value is "{ something }" then we consider it to be JSON data else if (trimmedValue.front() == '{' && trimmedValue.back() == '}') { // First check if the JsonSerializer was created already if (!checkedJsonSerializer) { checkedJsonSerializer = true; jsonSerializer = getFramework()->tryAcquireInterface<dictionary::ISerializer>( "carb.dictionary.serializer-json.plugin"); if (!jsonSerializer) { CARB_LOG_ERROR( "Couldn't acquire JSON serializer for processing command line arguments"); } } if (jsonSerializer) { // Processing the JSON value addCmdLineJSONElementToDict( jsonSerializer, dictionaryInterface, cmdLineOptionsConfig, kv.first, trimmedValue); } else { CARB_LOG_ERROR("No JSON serializer acquired. Cannot process command line parameter '%s'", kv.first.c_str()); } continue; } } // Processing as string representation of a dictionary value dictionary::setDictionaryElementAutoType( dictionaryInterface, cmdLineOptionsConfig, kv.first, kv.second); } return extras::ConfigLoadHelper::resolveAndMergeNewDictIntoTarget( dictionaryInterface, combinedConfig, cmdLineOptionsConfig, "command line override", envVariablesMap); } else { CARB_LOG_ERROR("Couldn't process command line overrides"); } } return combinedConfig; } }; } // namespace extras } // namespace carb
17,234
C
40.832524
122
0.55025
omniverse-code/kit/include/carb/extras/HandleDatabase.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 HandleDatabase definition file. #pragma once #include "../Defines.h" #include "../container/LocklessQueue.h" #include "../logging/Log.h" #include "../math/Util.h" #include <algorithm> #include <atomic> #include <cstdint> #include <memory> #include <mutex> #include <stack> #include <vector> CARB_IGNOREWARNING_MSC_WITH_PUSH(4201) // nonstandard extension used: nameless struct/union namespace carb { namespace extras { template <class Mapped, class Handle, class Allocator> struct HandleRef; template <class Mapped, class Handle, class Allocator> struct ConstHandleRef; /** * Provides an OS-style mapping of a Handle to a Resource. * * Essentially HandleDatabase is a fast thread-safe reference-counted associative container. * * @thread_safety Unless otherwise mentioned, HandleDatabase functions may be called simultaneously from multiple * threads. * * A given Handle value is typically never reused, however, it is possible for a handle value to be reused if billions * of handles are requested. * * The HandleDatabase can store at most `(2^31)-1` items, or 2,147,483,647 items simultaneously, provided the memory * exists to support it. * * Implementation Details: * * HandleDatabase achieves its speed and thread-safety by having a fixed-size base array (`m_database`) where each * element is an array of size 2^(base array index). As such, these arrays double the size of the previous index array. * These base arrays are never freed, simplifying thread safety and allowing HandleDatabase to be mostly lockless. * This array-of-arrays forms a non-contiguous indexable array where the base array and offset can be computed from a * 32-bit index value (see `indexToBucketAndOffset`). * * The Handle is a 64-bit value composed of two 32-bit values. The least-significant 32 bits is the index value into the * array-of-arrays described above. The most-significant 32 bits is a lifecycle counter. Every time a new Mapped object * is constructed, the lifecycle counter is incremented. This value forms a contract between a handle and the Mapped * object at the index indicated by the Handle. If the lifecycle counter doesn't match, the Handle is invalid. As this * lifecycle counter is incremented, there is the possibility of rollover after 2^31 handles are generated at a given * index. The most significant bit will then be set as a rollover flag so that handleWasValid() continues to operate * correctly. The handleWasValid() function returns `true` for any Handle where the lifecycle counter at the given index * is greater-than-or-equal to the Handle's lifecycle counter, or if the rollover flag is set. * * @tparam Mapped The "value" type that is associated with a Handle. * @tparam Handle The "key" type. Must be an unsigned integer or pointer type and 64-bit. This is an opaque type that * cannot be dereferenced. * @tparam Allocator The allocator that will be used to allocate memory. Must be capable of allocating large contiguous * blocks of memory. */ template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>> class CARB_VIZ HandleDatabase { public: //! An alias to Mapped; the mapped value type. using MappedType = Mapped; //! An alias to Handle; the key type used to associate a mapped value type. using HandleType = Handle; //! An alias to Allocator; the allocator used to allocate memory. using AllocatorType = Allocator; //! An alias to the HandleRef for this HandleDatabase. using HandleRefType = HandleRef<Mapped, Handle, Allocator>; //! An alias to the ConstHandleRef for this HandleDatabase. using ConstHandleRefType = ConstHandleRef<Mapped, Handle, Allocator>; //! @a Deprecated: Use HandleRefType instead. using scoped_handle_ref_type = HandleRefType; /** * Constructor. * @thread_safety The constructor must complete in a single thread before any other functions may be called on * `*this`. */ constexpr HandleDatabase() noexcept; /** * Destructor. * @thread_safety All other functions on `*this` must be finished before the destructor can be called. */ ~HandleDatabase(); /** * Checks to see if a handle is valid or was ever valid in the past. * @param handle The Handle to check. * @returns `true` if a @p handle is currently valid or was valid in the past and has since been released; `false` * otherwise. */ bool handleWasValid(Handle handle) const; /** * Creates a new Mapped type with the given arguments. * @param args The arguments to pass to the Mapped constructor. * @returns A `std::pair` of the Handle that can uniquely identify the new Mapped type, and a pointer to the newly * constructed Mapped type. */ template <class... Args> std::pair<Handle, Mapped*> createHandle(Args&&... args); /** * Attempts to find the Mapped type represented by @p handle. * @thread_safety Not thread-safe as the Mapped type could be destroyed if another thread calls release(). * @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely * result in a `nullptr` result without an assert or any other side-effects. * @returns A pointer to a valid Mapped type if the handle was valid; `nullptr` otherwise. */ Mapped* getValueFromHandle(Handle handle) const; /** * Retrieves the Handle representing @p mapped. * @warning Providing @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions * is undefined. * @param mapped A Mapped type previously created with createHandle(). * @returns The Handle representing @p mapped. */ Handle getHandleFromValue(const Mapped* mapped) const; /** * Atomically attempts to add a reference for the given Handle. * @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely * result in a `nullptr` result without an assert or any other side-effects. * @returns A pointer to a valid Mapped type if a reference could be added; `nullptr` otherwise. */ Mapped* tryAddRef(Handle handle); /** * Atomically adds a reference for the given Handle; fatal if @p handle is invalid. * @param handle A valid handle previously returned from createHandle(). Invalid or previously-valid handles will * result in `std::terminate()` being called. */ void addRef(Handle handle); /** * Atomically adds a reference for the Handle representing @p mapped. * @warning Providing @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions * is undefined. * @param mapped A Mapped type previously created with createHandle(). */ void addRef(Mapped* mapped); /** * Atomically releases a reference for the given Handle, potentially freeing the associated Mapped type. * @param handle A valid handle previously returned from createHandle(). Invalid or previously-valid handles will * result in an assert in Debug builds, but return `false` with no side effects in Release builds. * @returns `true` if the last reference was released and @p handle is no longer valid; `false` if Handle is not * valid or is previously-valid or a non-final reference was released. */ bool release(Handle handle); /** * Atomically releases a reference for the Handle representing @p mapped. * @warning Provided @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions * is undefined. * @param mapped A Mapped type previously created with createHandle(). * @returns `true` if the last reference was released and @p mapped is no longer valid; `false` if a reference other * than the last reference was released. */ bool release(Mapped* mapped); /** * Atomically releases a reference if and only if it's the last reference. * @param handle A valid handle previously returned from createHandle(). Invalid or previously-valid handles will * result in an assert in Debug builds, but return `false` with no side effects in Release builds. * @returns `true` if the last reference was released and @p handle is no longer valid; `false` otherwise. */ bool releaseIfLastRef(Handle handle); /** * Atomically releases a reference if and only if it's the last reference. * @warning Provided @p mapped that is no longer valid or was not returned from one of the HandleDatabase functions * is undefined. * @param mapped A Mapped type previously created with createHandle(). * @returns `true` if the last reference was released and @p mapped is no longer valid; `false` otherwise. */ bool releaseIfLastRef(Mapped* mapped); /** * Attempts to atomically add a reference to @p handle, and returns a HandleRef to @p handle. * @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely * result in an empty \ref HandleRef result without an assert or any other side-effects. * @returns If \ref tryAddRef() would return a valid Mapped type for @p handle, then a \ref HandleRef that manages * the reference is returned; otherwise an empty \ref HandleRef is returned. */ HandleRefType makeScopedRef(Handle handle); /** * Attempts to atomically add a reference to @p handle, and returns a ConstHandleRef to @p handle. * @param handle A handle previously returned from createHandle(). Invalid or previously-valid handles will merely * result in an empty \ref ConstHandleRef result without an assert or any other side-effects. * @returns If \ref tryAddRef() would return a valid Mapped type for @p handle, then a \ref ConstHandleRef that * manages the reference is returned; otherwise an empty \ref ConstHandleRef is returned. */ ConstHandleRefType makeScopedRef(Handle handle) const; /** * Calls the provided `Func` invocable object for each valid handle and its associated mapped type. * @thread_safety This function is not safe to call if any other thread would be calling releaseIfLastRef() or * release() to release the last reference of a Handle. Other threads calling createHandle() when this function is * called may result in handles being skipped. * @param f An invocable object with signature `void(Handle, Mapped*)`. */ template <class Func> void forEachHandle(Func&& f) const; /** * Iterates over all valid handles and sets their reference counts to zero, destroying the associated mapped type. * @thread_safety This function is NOT safe to call if any other thread is calling ANY other HandleDatabase function * except for clear() or handleWasValid(). * @returns The number of handles that were released to zero. */ size_t clear(); private: CARB_VIZ static constexpr uint32_t kBuckets = sizeof(uint32_t) * 8 - 1; ///< Number of buckets static constexpr uint32_t kMaxSize = (1U << kBuckets) - 1; ///< Maximum size ever // NOTE: Making *any* change to how rollover works should enable HANDLE_DATABASE_EXTENDED_TESTS in TestExtras.cpp static constexpr uint32_t kRolloverFlag = 0x80000000u; static constexpr uint32_t kLifecycleMask = 0x7fffffffu; // A struct for mapping type Handle into its basic components of index and lifecycle struct HandleUnion { union { Handle handle; struct { uint32_t index; uint32_t lifecycle; }; }; constexpr HandleUnion(Handle h) noexcept : handle(h) { } constexpr HandleUnion(uint32_t idx, uint32_t life) noexcept : index(idx), lifecycle(life & kLifecycleMask) { } }; // A struct for tracking the refcount and lifecycle. struct alignas(uint64_t) Metadata { uint32_t refCount{ 0 }; CARB_VIZ uint32_t lifecycle{ 0 }; constexpr Metadata() noexcept = default; }; struct HandleData { // This union will either be the free link and index, or the constructed mapped type union { struct { container::LocklessQueueLink<HandleData> link; uint32_t index; }; // This `val` is only constructed when the HandleData is in use Mapped val; }; // Metadata, but the union allows us to access the refCount atomically, separately. union { CARB_VIZ std::atomic<Metadata> metadata; std::atomic_uint32_t refCount; // Must share memory address with metadata.refCount }; constexpr HandleData(uint32_t idx) noexcept : index(idx), metadata{} { } // Empty destructor, required because of the union with non-trivial types ~HandleData() noexcept { } }; static_assert(alignof(HandleData) >= alignof(Mapped), "Invalid assumption: HandleData alignment should meet or exceed Mapped alignment"); static_assert(sizeof(Handle) == sizeof(uint64_t), "Handle should be 64-bit"); using HandleDataAllocator = typename std::allocator_traits<Allocator>::template rebind_alloc<HandleData>; using AllocatorTraits = std::allocator_traits<HandleDataAllocator>; static void indexToBucketAndOffset(uint32_t index, uint32_t& bucket, uint32_t& offset); HandleData* expandDatabase(); HandleData* getHandleData(uint32_t index) const; HandleData* getHandleData(const Mapped* mapped) const; HandleData* getDbIndex(size_t index, std::memory_order = std::memory_order_seq_cst) const; // m_database is fixed size and written atomically in expandDatabase(). It never contracts and therefore // does not require a mutex CARB_VIZ std::atomic<HandleData*> m_database[kBuckets] = {}; struct Members : HandleDataAllocator { // The "tasking timing" test performs much better with m_free as a queue instead of a stack. container::LocklessQueue<HandleData, &HandleData::link> m_free; } m_emo; }; /** * A smart-reference class for a Handle associated with a HandleDatabase. * * When HandleRef is destroyed, the associated handle is released with the HandleDatabase. */ template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>> struct ConstHandleRef { public: //! An alias to Mapped; the mapped value type. using MappedType = const Mapped; //! An alias to `const Mapped&`. using ReferenceType = const Mapped&; //! An alias to `const Mapped*`. using PointerType = const Mapped*; //! An alias to Handle; the key type used to associate a mapped value type. using HandleType = Handle; //! An alias to Allocator; the allocator used to allocate memory. using AllocatorType = Allocator; //! The type specification for the associated HandleDatabase. using Database = HandleDatabase<Mapped, Handle, Allocator>; //! @a Deprecated: Use MappedType instead. using element_type = MappedType; //! @a Deprecated: Use HandleType instead. using handle_type = HandleType; /** * Default constructor. Produces an empty HandleRef. */ ConstHandleRef() = default; /** * Attempts to atomically reference a Handle from the given @p database. * @param database The HandleDatabase containing @p handle. * @param handle The handle previously returned from HandleDatabase::createHandle(). Providing an invalid or * previously-valid handle results in an empty HandleRef. */ ConstHandleRef(Database& database, Handle handle) noexcept : m_mapped(database.tryAddRef(handle)) { if (m_mapped) { m_database = std::addressof(database); m_handle = handle; } } /** * Destructor. If `*this` is non-empty, releases the associated Handle with the associated HandleDatabase. */ ~ConstHandleRef() noexcept { reset(); } /** * Move-constructor. Post-condition: @p other is an empty HandleRef. * @param other The other HandleRef to move a reference from. */ ConstHandleRef(ConstHandleRef&& other) noexcept { swap(other); } /** * Move-assign operator. Swaps state with @p other. * @param other The other HandleRef to move a reference from. */ ConstHandleRef& operator=(ConstHandleRef&& other) noexcept { swap(other); return *this; } // Specifically non-Copyable in order to reduce implicit usage. // Use the explicit `clone()` function if a copy is desired CARB_PREVENT_COPY(ConstHandleRef); /** * Explicitly adds a reference to any referenced handle and returns a HandleRef. * @returns A HandleRef holding its own reference for the contained handle. May be empty if `*this` is empty. */ ConstHandleRef clone() const noexcept { if (m_mapped) m_database->addRef(m_mapped); return ConstHandleRef{ m_database, m_handle, m_mapped }; } /** * Dereferences and returns a pointer to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A pointer to the mapped type. */ PointerType operator->() noexcept { return get(); } /** * Dereferences and returns a const pointer to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A const pointer to the mapped type. */ PointerType operator->() const noexcept { return get(); } /** * Dereferences and returns a reference to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A reference to the mapped type. */ ReferenceType operator*() noexcept { CARB_ASSERT(get()); return *get(); } /** * Dereferences and returns a const reference to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A const reference to the mapped type. */ ReferenceType operator*() const noexcept { CARB_ASSERT(get()); return *get(); } /** * Returns a pointer to the mapped type, or `nullptr` if empty. * @returns A pointer to the mapped type or `nullptr` if empty. */ PointerType get() noexcept { return this->m_mapped; } /** * Returns a const pointer to the mapped type, or `nullptr` if empty. * @returns A const pointer to the mapped type or `nullptr` if empty. */ PointerType get() const noexcept { return this->m_mapped; } /** * Returns the Handle referenced by `*this`. * @returns The Handle referenced by `*this`. */ Handle handle() const noexcept { return this->m_handle; } /** * Tests if `*this` contains a valid reference. * @returns `true` if `*this` maintains a valid reference; `false` if `*this` is empty. */ explicit operator bool() const noexcept { return get() != nullptr; } /** * Releases any associated reference and resets `*this` to empty. */ void reset() { if (auto mapped = std::exchange(m_mapped, nullptr)) m_database->release(mapped); m_database = nullptr; m_handle = HandleType{}; } /** * Swaps state with another HandleRef. */ void swap(ConstHandleRef& rhs) { std::swap(m_database, rhs.m_database); std::swap(m_handle, rhs.m_handle); std::swap(m_mapped, rhs.m_mapped); } protected: Database* m_database{}; ///< Handle database this reference points into. Handle m_handle{}; ///< Handle that this reference currently represents. Mapped* m_mapped{}; ///< The mapped value for this reference. /** * Protected constructor. Not to be used externally. */ ConstHandleRef(Database* db, Handle h, Mapped* m) noexcept : m_database(db), m_handle(h), m_mapped(m) { } }; /** * A smart-reference class for a Handle associated with a HandleDatabase. * * When HandleRef is destroyed, the associated handle is released with the HandleDatabase. */ template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>> struct HandleRef : public ConstHandleRef<Mapped, Handle, Allocator> { /** Base type used for this container. */ using BaseType = ConstHandleRef<Mapped, Handle, Allocator>; public: //! An alias to Mapped; the mapped value type. using MappedType = Mapped; //! An alias to `Mapped&`. using ReferenceType = Mapped&; //! An alias to `Mapped*`. using PointerType = Mapped*; //! An alias to Handle; the key type used to associate a mapped value type. using HandleType = Handle; //! An alias to Allocator; the allocator used to allocate memory. using AllocatorType = Allocator; //! The type specification for the associated HandleDatabase. using Database = HandleDatabase<Mapped, Handle, Allocator>; //! @a Deprecated: Use MappedType instead. using element_type = MappedType; //! @a Deprecated: Use HandleType instead. using handle_type = HandleType; /** * Default constructor. Produces an empty HandleRef. */ HandleRef() = default; /** * Attempts to atomically reference a Handle from the given @p database. * @param database The HandleDatabase containing @p handle. * @param handle The handle previously returned from HandleDatabase::createHandle(). Providing an invalid or * previously-valid handle results in an empty HandleRef. */ HandleRef(Database& database, Handle handle) noexcept : BaseType(database, handle) { } /** * Explicitly adds a reference to any referenced handle and returns a HandleRef. * @returns A HandleRef holding its own reference for the contained handle. May be empty if `*this` is empty. */ HandleRef clone() const noexcept { if (this->m_mapped) this->m_database->addRef(this->m_mapped); return HandleRef{ this->m_database, this->m_handle, this->m_mapped }; } /** * Dereferences and returns a pointer to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A pointer to the mapped type. */ PointerType operator->() noexcept { return get(); } /** * Dereferences and returns a const pointer to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A const pointer to the mapped type. */ PointerType operator->() const noexcept { return get(); } /** * Dereferences and returns a reference to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A reference to the mapped type. */ ReferenceType operator*() noexcept { CARB_ASSERT(get()); return *get(); } /** * Dereferences and returns a const reference to the mapped type. * @warning Undefined behavior if `*this` is empty. * @returns A const reference to the mapped type. */ ReferenceType operator*() const noexcept { CARB_ASSERT(get()); return *get(); } /** * Returns a pointer to the mapped type, or `nullptr` if empty. * @returns A pointer to the mapped type or `nullptr` if empty. */ PointerType get() noexcept { return this->m_mapped; } /** * Returns a const pointer to the mapped type, or `nullptr` if empty. * @returns A const pointer to the mapped type or `nullptr` if empty. */ PointerType get() const noexcept { return this->m_mapped; } /** * Swaps state with another HandleRef. */ void swap(HandleRef& rhs) { BaseType::swap(rhs); } private: HandleRef(Database* db, Handle h, Mapped* m) noexcept : BaseType(db, h, m) { } }; /** * @a Deprecated: Use HandleRef instead. */ template <class Mapped, class Handle, class Allocator = std::allocator<Mapped>> using ScopedHandleRef = HandleRef<Mapped, Handle, Allocator>; template <class Mapped, class Handle, class Allocator> inline constexpr HandleDatabase<Mapped, Handle, Allocator>::HandleDatabase() noexcept { } template <class Mapped, class Handle, class Allocator> inline HandleDatabase<Mapped, Handle, Allocator>::~HandleDatabase() { // Make sure everything is removed from the free list before we destroy it m_emo.m_free.popAll(); size_t leaks = 0; for (size_t i = 0; i < CARB_COUNTOF(m_database); i++) { HandleData* handleData = m_database[i].exchange(nullptr, std::memory_order_relaxed); if (!handleData) break; // Go through each entry and destruct any outstanding ones with a non-zero refcount size_t const kBucketSize = size_t(1) << i; for (size_t j = 0; j != kBucketSize; ++j) { Metadata meta = handleData[j].metadata.load(std::memory_order_relaxed); if (meta.refCount != 0) { handleData[j].val.~Mapped(); ++leaks; } AllocatorTraits::destroy(m_emo, handleData + j); } AllocatorTraits::deallocate(m_emo, handleData, kBucketSize); } if (leaks != 0) { CARB_LOG_WARN("%s: had %zu outstanding handle(s) at shutdown", CARB_PRETTY_FUNCTION, leaks); } } template <class Mapped, class Handle, class Allocator> inline auto HandleDatabase<Mapped, Handle, Allocator>::getHandleData(uint32_t index) const -> HandleData* { uint32_t bucketIndex, offsetInBucket; indexToBucketAndOffset(index, bucketIndex, offsetInBucket); if (bucketIndex >= CARB_COUNTOF(m_database)) { return nullptr; } auto bucket = getDbIndex(bucketIndex, std::memory_order_acquire); return bucket ? bucket + offsetInBucket : nullptr; } template <class Mapped, class Handle, class Allocator> inline auto HandleDatabase<Mapped, Handle, Allocator>::getHandleData(const Mapped* mapped) const -> HandleData* { // HandleData must have val as the first member. This would prevent us from casting // mapped to HandleData without using ugly pointer math otherwise. // static assert using offsetof() is not possible due to HandleData having a non-standard-layout type. auto pHandleData = reinterpret_cast<HandleData*>(const_cast<Mapped*>(mapped)); CARB_ASSERT(reinterpret_cast<intptr_t>(&pHandleData->val) - reinterpret_cast<intptr_t>(pHandleData) == 0); return pHandleData; } template <class Mapped, class Handle, class Allocator> inline auto HandleDatabase<Mapped, Handle, Allocator>::getDbIndex(size_t index, std::memory_order order) const -> HandleData* { static HandleData* const kLocked = reinterpret_cast<HandleData*>(size_t(-1)); CARB_ASSERT(index < kBuckets); // Spin briefly if the entry is locked HandleData* bucket = m_database[index].load(order); while (CARB_UNLIKELY(bucket == kLocked)) { CARB_HARDWARE_PAUSE(); bucket = m_database[index].load(order); } return bucket; } template <class Mapped, class Handle, class Allocator> inline bool HandleDatabase<Mapped, Handle, Allocator>::handleWasValid(Handle handle) const { HandleUnion hu(handle); HandleData* pHandleData = getHandleData(hu.index); if (pHandleData == nullptr) { return false; } Metadata meta = pHandleData->metadata.load(std::memory_order_acquire); // The zero lifecycle count isn't used if (hu.lifecycle == 0 || meta.lifecycle == 0) { return false; } // The kRolloverFlag value is always unset in hu, but possibly present in meta.lifecycle. However, this is still a // valid comparison because if the kRolloverFlag is set in meta.lifecycle, it means that every possible value has // been a valid handle at one point and the expression will always result in `true`. return hu.lifecycle <= meta.lifecycle; } template <class Mapped, class Handle, class Allocator> template <class... Args> inline std::pair<Handle, Mapped*> HandleDatabase<Mapped, Handle, Allocator>::createHandle(Args&&... args) { HandleData* handleData = m_emo.m_free.pop(); if (!handleData) handleData = expandDatabase(); CARB_ASSERT(handleData); Metadata meta = handleData->metadata.load(std::memory_order_acquire); CARB_ASSERT(((void*)std::addressof(handleData->metadata) == (void*)std::addressof(handleData->refCount)) && offsetof(Metadata, refCount) == 0); meta.refCount = 1; // Don't allow the 0 lifecycle. meta.lifecycle++; if ((meta.lifecycle & kLifecycleMask) == 0) { meta.lifecycle = 1 | kRolloverFlag; } uint32_t indexToAllocateFrom = handleData->index; Mapped* p = new (std::addressof(handleData->val)) Mapped(std::forward<Args>(args)...); handleData->metadata.store(meta, std::memory_order_release); HandleUnion hu(indexToAllocateFrom, meta.lifecycle); return std::make_pair(hu.handle, p); } template <class Mapped, class Handle, class Allocator> inline Mapped* HandleDatabase<Mapped, Handle, Allocator>::tryAddRef(Handle handle) { HandleUnion hu(handle); HandleData* pHandleData = getHandleData(hu.index); if (pHandleData == nullptr) { return nullptr; } Metadata meta = pHandleData->metadata.load(std::memory_order_acquire); for (;;) { if (meta.refCount == 0 || (meta.lifecycle & kLifecycleMask) != hu.lifecycle) { return nullptr; } Metadata desired = meta; desired.refCount++; if (pHandleData->metadata.compare_exchange_weak( meta, desired, std::memory_order_release, std::memory_order_relaxed)) { return std::addressof(pHandleData->val); } } } template <class Mapped, class Handle, class Allocator> inline void HandleDatabase<Mapped, Handle, Allocator>::addRef(Handle handle) { Mapped* mapped = tryAddRef(handle); CARB_FATAL_UNLESS(mapped != nullptr, "Attempt to addRef released handle"); } template <class Mapped, class Handle, class Allocator> inline void HandleDatabase<Mapped, Handle, Allocator>::addRef(Mapped* mapped) { HandleData* pHandleData = getHandleData(mapped); // We're working with the Mapped type here, so if it's not valid we're in UB. uint32_t prev = pHandleData->refCount.fetch_add(1, std::memory_order_relaxed); CARB_CHECK((prev + 1) > 1); // no resurrection and no rollover } template <class Mapped, class Handle, class Allocator> inline bool HandleDatabase<Mapped, Handle, Allocator>::release(Handle handle) { HandleUnion hu(handle); HandleData* pHandleData = getHandleData(hu.index); CARB_ASSERT(pHandleData); if (pHandleData == nullptr) { return false; } Metadata meta = pHandleData->metadata.load(std::memory_order_acquire); for (;;) { if (meta.refCount == 0 || (meta.lifecycle & kLifecycleMask) != hu.lifecycle) { CARB_ASSERT(0); return false; } Metadata desired = meta; bool released = --desired.refCount == 0; if (CARB_LIKELY(pHandleData->metadata.compare_exchange_weak( meta, desired, std::memory_order_release, std::memory_order_relaxed))) { if (released) { std::atomic_thread_fence(std::memory_order_acquire); pHandleData->val.~Mapped(); pHandleData->index = hu.index; m_emo.m_free.push(pHandleData); } return released; } } } template <class Mapped, class Handle, class Allocator> inline bool HandleDatabase<Mapped, Handle, Allocator>::release(Mapped* mapped) { HandleData* pHandleData = getHandleData(mapped); // We're working with the Mapped type here, so if it's not valid we're in UB. uint32_t prev = pHandleData->refCount.fetch_sub(1, std::memory_order_release); CARB_CHECK(prev >= 1); // No underflow if (prev == 1) { // Released std::atomic_thread_fence(std::memory_order_acquire); pHandleData->val.~Mapped(); pHandleData->index = HandleUnion(getHandleFromValue(mapped)).index; m_emo.m_free.push(pHandleData); return true; } return false; } template <class Mapped, class Handle, class Allocator> inline bool HandleDatabase<Mapped, Handle, Allocator>::releaseIfLastRef(Handle handle) { HandleUnion hu(handle); HandleData* pHandleData = getHandleData(hu.index); CARB_ASSERT(pHandleData); if (pHandleData == nullptr) { return false; } Metadata meta = pHandleData->metadata.load(std::memory_order_acquire); for (;;) { if (meta.refCount == 0 || (meta.lifecycle & kLifecycleMask) != hu.lifecycle) { CARB_ASSERT(0); return false; } if (meta.refCount > 1) { return false; } Metadata desired = meta; desired.refCount = 0; if (CARB_LIKELY(pHandleData->metadata.compare_exchange_weak( meta, desired, std::memory_order_release, std::memory_order_relaxed))) { std::atomic_thread_fence(std::memory_order_acquire); pHandleData->val.~Mapped(); pHandleData->index = hu.index; m_emo.m_free.push(pHandleData); return true; } } } template <class Mapped, class Handle, class Allocator> inline bool HandleDatabase<Mapped, Handle, Allocator>::releaseIfLastRef(Mapped* mapped) { HandleData* pHandleData = getHandleData(mapped); // We're working with the Mapped type here, so if it's not valid we're in UB. uint32_t refCount = pHandleData->refCount.load(std::memory_order_acquire); for (;;) { CARB_CHECK(refCount != 0); if (refCount > 1) { return false; } if (CARB_LIKELY(pHandleData->refCount.compare_exchange_weak( refCount, 0, std::memory_order_release, std::memory_order_relaxed))) { std::atomic_thread_fence(std::memory_order_acquire); pHandleData->val.~Mapped(); pHandleData->index = HandleUnion(getHandleFromValue(mapped)).index; m_emo.m_free.push(pHandleData); return true; } } } template <class Mapped, class Handle, class Allocator> inline Mapped* HandleDatabase<Mapped, Handle, Allocator>::getValueFromHandle(Handle handle) const { HandleUnion hu(handle); HandleData* pHandleData = getHandleData(hu.index); if (pHandleData == nullptr) { return nullptr; } Metadata meta = pHandleData->metadata.load(std::memory_order_acquire); return (meta.refCount != 0 && (meta.lifecycle & kLifecycleMask) == hu.lifecycle) ? std::addressof(pHandleData->val) : nullptr; } template <class Mapped, class Handle, class Allocator> inline Handle HandleDatabase<Mapped, Handle, Allocator>::getHandleFromValue(const Mapped* mapped) const { // Resolve mapped to the handle data // We're working with the Mapped type here, so if it's not valid we're in UB. HandleData* pHandleData = getHandleData(mapped); // Start setting up the handle, but we don't know the index yet. uint32_t lifecycle = pHandleData->metadata.load(std::memory_order_acquire).lifecycle; // Find the index by searching all of the buckets. for (uint32_t i = 0; i < kBuckets; ++i) { HandleData* p = getDbIndex(i, std::memory_order_acquire); if (!p) break; size_t offset = size_t(pHandleData - p); if (offset < (size_t(1) << i)) { // Found the index! uint32_t index = (uint32_t(1) << i) - 1 + uint32_t(offset); return HandleUnion(index, lifecycle).handle; } } // Given mapped doesn't exist in this HandleDatabase CARB_CHECK(0); return Handle{}; } template <class Mapped, class Handle, class Allocator> inline void HandleDatabase<Mapped, Handle, Allocator>::indexToBucketAndOffset(uint32_t index, uint32_t& bucket, uint32_t& offset) { // Bucket id bucket = 31 - math::numLeadingZeroBits(index + 1); offset = index + 1 - (1 << CARB_MIN(31u, bucket)); } template <class Mapped, class Handle, class Allocator> inline auto HandleDatabase<Mapped, Handle, Allocator>::expandDatabase() -> HandleData* { static HandleData* const kLocked = reinterpret_cast<HandleData*>(size_t(-1)); // Scan (right now O(n), but this is rare and n is small) for the first empty database. size_t bucketToAllocateFrom; for (bucketToAllocateFrom = 0; bucketToAllocateFrom != CARB_COUNTOF(m_database); bucketToAllocateFrom++) { HandleData* mem = m_database[bucketToAllocateFrom].load(std::memory_order_acquire); for (;;) { while (mem == kLocked) { // Another thread is trying to allocate this. Try to pull from the free list until it stabilizes. mem = m_emo.m_free.pop(); if (mem) return mem; mem = m_database[bucketToAllocateFrom].load(std::memory_order_acquire); } if (!mem) { // Try to lock it if (m_database[bucketToAllocateFrom].compare_exchange_strong( mem, kLocked, std::memory_order_release, std::memory_order_relaxed)) { // Successfully locked break; } // Continue if another thread has locked it if (mem == kLocked) continue; // Failed to lock, but it's not locked anymore, so see if there's a free entry now HandleData* hd = m_emo.m_free.pop(); if (hd) return hd; } CARB_ASSERT(mem != kLocked); break; } if (!mem) break; } CARB_FATAL_UNLESS(bucketToAllocateFrom < CARB_COUNTOF(m_database), "Out of handles!"); uint32_t const allocateCount = 1 << bucketToAllocateFrom; uint32_t const offset = allocateCount - 1; HandleData* handleData = AllocatorTraits::allocate(m_emo, allocateCount); // Set the indexes for (uint32_t i = 0; i < allocateCount; ++i) { AllocatorTraits::construct(m_emo, handleData + i, offset + i); } // Add entries (after the first) to the free list m_emo.m_free.push(handleData + 1, handleData + allocateCount); // Overwrite the lock with the actual pointer now HandleData* expect = m_database[bucketToAllocateFrom].exchange(handleData, std::memory_order_release); CARB_ASSERT(expect == kLocked); CARB_UNUSED(expect); // Return the first entry that we reserved for the caller AllocatorTraits::construct(m_emo, handleData, offset); return handleData; } template <class Mapped, class Handle, class Allocator> template <class Func> inline void HandleDatabase<Mapped, Handle, Allocator>::forEachHandle(Func&& f) const { for (uint32_t i = 0; i < kBuckets; ++i) { // We are done once we encounter a null pointer HandleData* data = getDbIndex(i, std::memory_order_acquire); if (!data) break; uint32_t const bucketSize = 1 << i; for (uint32_t j = 0; j != bucketSize; ++j) { Metadata meta = data[j].metadata.load(std::memory_order_acquire); if (meta.refCount != 0) { // Valid handle HandleUnion hu((bucketSize - 1) + j, meta.lifecycle); // Call the functor f(hu.handle, std::addressof(data[j].val)); } } } } template <class Mapped, class Handle, class Allocator> inline size_t HandleDatabase<Mapped, Handle, Allocator>::clear() { size_t count = 0; for (uint32_t i = 0; i != kBuckets; ++i) { HandleData* data = getDbIndex(i, std::memory_order_acquire); if (!data) break; uint32_t const bucketSize = 1u << i; for (uint32_t j = 0; j != bucketSize; ++j) { if (data[j].refCount.exchange(0, std::memory_order_release) != 0) { // Successfully set the refcount to 0. Destroy and add to the free list std::atomic_thread_fence(std::memory_order_acquire); ++count; data[j].val.~Mapped(); data[j].index = bucketSize - 1 + j; m_emo.m_free.push(std::addressof(data[j])); } } } return count; } template <class Mapped, class Handle, class Allocator> inline auto HandleDatabase<Mapped, Handle, Allocator>::makeScopedRef(Handle handle) -> HandleRefType { return HandleRef<Mapped, Handle, Allocator>(*this, handle); } template <class Mapped, class Handle, class Allocator> inline auto HandleDatabase<Mapped, Handle, Allocator>::makeScopedRef(Handle handle) const -> ConstHandleRefType { return ConstHandleRef<Mapped, Handle, Allocator>(const_cast<HandleDatabase&>(*this), handle); } // Global operators. /** * Tests equality between HandleRef and `nullptr`. * @param ref The HandleRef to test. * @returns `true` if @p ref is empty; `false` otherwise. */ template <class Mapped, class Handle, class Allocator> inline bool operator==(const HandleRef<Mapped, Handle, Allocator>& ref, std::nullptr_t) { return ref.get() == nullptr; } /** * Tests equality between HandleRef and `nullptr`. * @param ref The HandleRef to test. * @returns `true` if @p ref is empty; `false` otherwise. */ template <class Mapped, class Handle, class Allocator> inline bool operator==(std::nullptr_t, const HandleRef<Mapped, Handle, Allocator>& ref) { return ref.get() == nullptr; } /** * Tests inequality between HandleRef and `nullptr`. * @param ref The HandleRef to test. * @returns `true` if @p ref is not empty; `false` otherwise. */ template <class Mapped, class Handle, class Allocator> inline bool operator!=(const HandleRef<Mapped, Handle, Allocator>& ref, std::nullptr_t) { return ref.get() != nullptr; } /** * Tests inequality between HandleRef and `nullptr`. * @param ref The HandleRef to test. * @returns `true` if @p ref is not empty; `false` otherwise. */ template <class Mapped, class Handle, class Allocator> inline bool operator!=(std::nullptr_t, const HandleRef<Mapped, Handle, Allocator>& ref) { return ref.get() != nullptr; } } // namespace extras } // namespace carb CARB_IGNOREWARNING_MSC_POP
43,742
C
34.248187
121
0.651731
omniverse-code/kit/include/carb/extras/ArenaAllocator.h
// Copyright (c) 2018-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 "../Defines.h" #include "FreeListAllocator.h" #include <cstring> namespace carb { namespace extras { /** * Defines arena allocator where allocations are made very quickly, but that deallocations * can only be performed in reverse order, or with the client code knowing a previous deallocation (say with * deallocateAllFrom), automatically deallocates everything after it. * * @note Though named "ArenaAllocator", this is really more of a block/sequential allocator, not an arena allocator. If * you desire to actually use an arena, see @ref carb::memory::ArenaAllocator. This class may be renamed in the future. * * It works by allocating large blocks and then cutting out smaller pieces as requested. If a piece of memory is * deallocated, it either MUST be in reverse allocation order OR the subsequent allocations are implicitly * deallocated too, and therefore accessing their memory is now undefined behavior. Allocations are made * contiguously from the current block. If there is no space in the current block, the * next block (which is unused) if available is checked. If that works, an allocation is made from the next block. * If not a new block is allocated that can hold at least the allocation with required alignment. * * All memory allocated can be deallocated very quickly and without a client having to track any memory. * All memory allocated will be freed on destruction - or with reset. * * A memory arena can have requests larger than the block size. When that happens they will just be allocated * from the heap. As such 'oversized blocks' are seen as unusual and potentially wasteful they are deallocated * when deallocateAll is called, whereas regular size blocks will remain allocated for fast subsequent allocation. * * It is intentional that blocks information is stored separately from the allocations that store the * user data. This is so that alignment permitting, block allocations sizes can be passed directly to underlying * allocator. For large power of 2 backing allocations this might mean a page/pages directly allocated by the OS for * example. Also means better cache coherency when traversing blocks -> as generally they will be contiguous in memory. * * Also note that allocateUnaligned can be used for slightly faster aligned allocations. All blocks allocated internally * are aligned to the blockAlignment passed to the constructor. If subsequent allocations (of any type) sizes are of * that alignment or larger then no alignment fixing is required (because allocations are contiguous) and so * 'allocateUnaligned' will return allocations of blockAlignment alignment. */ class ArenaAllocator { public: /** * The minimum alignment of the backing memory allocator. */ static const size_t kMinAlignment = sizeof(void*); /** * Constructor. */ ArenaAllocator() { // Mark as invalid so any alloc call will fail m_blockAlignment = 0; m_blockSize = 0; // Set up as empty m_blocks = nullptr; _setCurrentBlock(nullptr); m_blockFreeList.initialize(sizeof(Block), sizeof(void*), 16); } /** * Constructor. * * @param blockSize The minimum block size (in bytes). * @param blockAlignment The power 2 block alignment that all blocks must have. */ explicit ArenaAllocator(size_t blockSize, size_t blockAlignment = kMinAlignment) { _initialize(blockSize, blockAlignment); } /** * ArenaAllocator is not copy-constructible. */ ArenaAllocator(const ArenaAllocator& rhs) = delete; /** * ArenaAllocator is not copyable. */ void operator=(const ArenaAllocator& rhs) = delete; /** * Destructor. */ ~ArenaAllocator() { _deallocateBlocks(); } /** * Initialize the arena with specified block size and alignment. * * If the arena has been previously initialized will free and deallocate all memory. * * @param blockSize The minimum block size (in bytes). * @param blockAlignment The power 2 block alignment that all blocks must have. */ void initialize(size_t blockSize, size_t blockAlignment = kMinAlignment); /** * Determines if an allocation is consistent with an allocation from this arena. * The test cannot say definitively if this was such an allocation, because the exact details * of each allocation is not kept. * * @param alloc The start of the allocation * @param sizeInBytes The size of the allocation * @return true if allocation could have been from this Arena */ bool isValid(const void* alloc, size_t sizeInBytes) const; /** * Allocate some memory of at least size bytes without having any specific alignment. * * Can be used for slightly faster *aligned* allocations if caveats in class description are met. The * Unaligned, means the method will not enforce alignment - but a client call to allocateUnaligned can control * subsequent allocations alignments via it's size. * * @param size The size of the allocation requested (in bytes and must be > 0). * @return The allocation. Can be nullptr if backing allocator was not able to request required memory */ void* allocate(size_t size); /** * Allocate some aligned memory of at least size bytes * * @param size Size of allocation wanted (must be > 0). * @param alignment Alignment of allocation - must be a power of 2. * @return The allocation (or nullptr if unable to allocate). Will be at least 'alignment' alignment or better. */ void* allocateAligned(size_t size, size_t alignment); /** * Allocates a null terminated string. * * @param str A null-terminated string * @return A copy of the string held on the arena */ const char* allocateString(const char* str); /** * Allocates a null terminated string. * * @param chars Pointer to first character * @param charCount The amount of characters NOT including terminating 0. * @return A copy of the string held on the arena. */ const char* allocateString(const char* chars, size_t charCount); /** * Allocate an element of the specified type. * * Note: Constructor for type is not executed. * * @return An allocation with correct alignment/size for the specified type. */ template <typename T> T* allocate(); /** * Allocate an array of a specified type. * * Note: Constructor for type is not executed. * * @param count The number of elements in the array * @return Returns an allocation with correct alignment/size for the specified type. */ template <typename T> T* allocateArray(size_t count); /** * Allocate an array of a specified type. * * @param count The number of elements in the array * @return An allocation with correct alignment/size for the specified type. Contents is all zeroed. */ template <typename T> T* allocateArray(size_t count, bool zeroMemory); /** * Allocate an array of a specified type, and copy array passed into it. * * @param arr. The array to copy from. * @param count. The number of elements in the array. * @return An allocation with correct alignment/size for the specified type. Contents is all zeroed. */ template <typename T> T* allocateArrayAndCopy(const T* arr, size_t count); /** * Deallocate the last allocation. * * If data is not from the last allocation then the behavior is undefined. * * @param data The data allocation to free. */ void deallocateLast(void* data); /** * Deallocate this allocation and all remaining after it. * * @param dataStart The data allocation to free from and all remaining. */ void deallocateAllFrom(void* dataStart); /** * Deallocates all allocated memory. That backing memory will generally not be released so * subsequent allocation will be fast, and from the same memory. Note though that 'oversize' blocks * will be deallocated. */ void deallocateAll(); /** * Resets to the initial state when constructed (and all backing memory will be deallocated) */ void reset(); /** * Adjusts such that the next allocate will be at least to the block alignment. */ void adjustToBlockAlignment(); /** * Gets the block alignment that is passed at initialization otherwise 0 an invalid block alignment. * * @return the block alignment */ size_t getBlockAlignment() const; private: struct Block { Block* m_next; uint8_t* m_alloc; uint8_t* m_start; uint8_t* m_end; }; void _initialize(size_t blockSize, size_t blockAlignment) { // Alignment must be a power of 2 CARB_ASSERT(((blockAlignment - 1) & blockAlignment) == 0); // Must be at least sizeof(void*) in size, as that is the minimum the backing allocator will be blockAlignment = (blockAlignment < kMinAlignment) ? kMinAlignment : blockAlignment; // If alignment required is larger then the backing allocators then // make larger to ensure when alignment correction takes place it will be aligned if (blockAlignment > kMinAlignment) { blockSize += blockAlignment; } m_blockSize = blockSize; m_blockAlignment = blockAlignment; m_blocks = nullptr; _setCurrentBlock(nullptr); m_blockFreeList.initialize(sizeof(Block), sizeof(void*), 16); } void* _allocateAligned(size_t size, size_t alignment) { CARB_ASSERT(size); // Can't be space in the current block -> so we can either place in next, or in a new block _newCurrentBlock(size, alignment); uint8_t* const current = m_current; // If everything has gone to plan, must be space here... CARB_ASSERT(current + size <= m_end); m_current = current + size; return current; } void _deallocateBlocks() { Block* currentBlock = m_blocks; while (currentBlock) { // Deallocate the block CARB_FREE(currentBlock->m_alloc); // next block currentBlock = currentBlock->m_next; } // Can deallocate all blocks to m_blockFreeList.deallocateAll(); } void _setCurrentBlock(Block* block) { if (block) { m_end = block->m_end; m_start = block->m_start; m_current = m_start; } else { m_start = nullptr; m_end = nullptr; m_current = nullptr; } m_currentBlock = block; } Block* _newCurrentBlock(size_t size, size_t alignment) { // Make sure init has been called (or has been set up in parameterized constructor) CARB_ASSERT(m_blockSize > 0); // Alignment must be a power of 2 CARB_ASSERT(((alignment - 1) & alignment) == 0); // Alignment must at a minimum be block alignment (such if reused the constraints hold) alignment = (alignment < m_blockAlignment) ? m_blockAlignment : alignment; const size_t alignMask = alignment - 1; // First try the next block (if there is one) { Block* next = m_currentBlock ? m_currentBlock->m_next : m_blocks; if (next) { // Align could be done from the actual allocation start, but doing so would mean a pointer which // didn't hit the constraint of being between start/end // So have to align conservatively using start uint8_t* memory = (uint8_t*)((size_t(next->m_start) + alignMask) & ~alignMask); // Check if can fit block in if (memory + size <= next->m_end) { _setCurrentBlock(next); return next; } } } // The size of the block must be at least large enough to take into account alignment size_t allocSize = (alignment <= kMinAlignment) ? size : (size + alignment); // The minimum block size should be at least m_blockSize allocSize = (allocSize < m_blockSize) ? m_blockSize : allocSize; // Allocate block Block* block = (Block*)m_blockFreeList.allocate(); if (!block) { return nullptr; } // Allocate the memory uint8_t* alloc = (uint8_t*)CARB_MALLOC(allocSize); if (!alloc) { m_blockFreeList.deallocate(block); return nullptr; } // Do the alignment on the allocation uint8_t* const start = (uint8_t*)((size_t(alloc) + alignMask) & ~alignMask); // Setup the block block->m_alloc = alloc; block->m_start = start; block->m_end = alloc + allocSize; block->m_next = nullptr; // Insert block into list if (m_currentBlock) { // Insert after current block block->m_next = m_currentBlock->m_next; m_currentBlock->m_next = block; } else { // Add to start of the list of the blocks block->m_next = m_blocks; m_blocks = block; } _setCurrentBlock(block); return block; } Block* _findBlock(const void* alloc, Block* endBlock = nullptr) const { const uint8_t* ptr = (const uint8_t*)alloc; Block* block = m_blocks; while (block != endBlock) { if (ptr >= block->m_start && ptr < block->m_end) { return block; } block = block->m_next; } return nullptr; } Block* _findPreviousBlock(Block* block) { Block* currentBlock = m_blocks; while (currentBlock) { if (currentBlock->m_next == block) { return currentBlock; } currentBlock = currentBlock->m_next; } return nullptr; } uint8_t* m_start; uint8_t* m_end; uint8_t* m_current; size_t m_blockSize; size_t m_blockAlignment; Block* m_blocks; Block* m_currentBlock; FreeListAllocator m_blockFreeList; }; inline void ArenaAllocator::initialize(size_t blockSize, size_t blockAlignment) { _deallocateBlocks(); m_blockFreeList.reset(); _initialize(blockSize, blockAlignment); } inline bool ArenaAllocator::isValid(const void* data, size_t size) const { CARB_ASSERT(size); uint8_t* ptr = (uint8_t*)data; // Is it in current if (ptr >= m_start && ptr + size <= m_current) { return true; } // Is it in a previous block? Block* block = _findBlock(data, m_currentBlock); return block && (ptr >= block->m_start && (ptr + size) <= block->m_end); } inline void* ArenaAllocator::allocate(size_t size) { // Align with the minimum alignment const size_t alignMask = kMinAlignment - 1; uint8_t* mem = (uint8_t*)((size_t(m_current) + alignMask) & ~alignMask); if (mem + size <= m_end) { m_current = mem + size; return mem; } else { return _allocateAligned(size, kMinAlignment); } } inline void* ArenaAllocator::allocateAligned(size_t size, size_t alignment) { // Alignment must be a power of 2 CARB_ASSERT(((alignment - 1) & alignment) == 0); // Align the pointer const size_t alignMask = alignment - 1; uint8_t* memory = (uint8_t*)((size_t(m_current) + alignMask) & ~alignMask); if (memory + size <= m_end) { m_current = memory + size; return memory; } else { return _allocateAligned(size, alignment); } } inline const char* ArenaAllocator::allocateString(const char* str) { size_t size = ::strlen(str); if (size == 0) { return ""; } char* dst = (char*)allocate(size + 1); std::memcpy(dst, str, size + 1); return dst; } inline const char* ArenaAllocator::allocateString(const char* chars, size_t charsCount) { if (charsCount == 0) { return ""; } char* dst = (char*)allocate(charsCount + 1); std::memcpy(dst, chars, charsCount); // Add null-terminating zero dst[charsCount] = 0; return dst; } template <typename T> T* ArenaAllocator::allocate() { return reinterpret_cast<T*>(allocateAligned(sizeof(T), CARB_ALIGN_OF(T))); } template <typename T> T* ArenaAllocator::allocateArray(size_t count) { return (count > 0) ? reinterpret_cast<T*>(allocateAligned(sizeof(T) * count, CARB_ALIGN_OF(T))) : nullptr; } template <typename T> T* ArenaAllocator::allocateArray(size_t count, bool zeroMemory) { if (count > 0) { const size_t totalSize = sizeof(T) * count; void* ptr = allocateAligned(totalSize, CARB_ALIGN_OF(T)); if (zeroMemory) { std::memset(ptr, 0, totalSize); } return reinterpret_cast<T*>(ptr); } return nullptr; } template <typename T> T* ArenaAllocator::allocateArrayAndCopy(const T* arr, size_t count) { if (count > 0) { const size_t totalSize = sizeof(T) * count; void* ptr = allocateAligned(totalSize, CARB_ALIGN_OF(T)); std::memcpy(ptr, arr, totalSize); return reinterpret_cast<T*>(ptr); } return nullptr; } inline void ArenaAllocator::deallocateLast(void* data) { // See if it's in current block uint8_t* ptr = (uint8_t*)data; if (ptr >= m_start && ptr < m_current) { // Then just go back m_current = ptr; } else { // Only called if not in the current block. Therefore can only be in previous Block* prevBlock = _findPreviousBlock(m_currentBlock); if (prevBlock == nullptr || (!(ptr >= prevBlock->m_start && ptr < prevBlock->m_end))) { CARB_ASSERT(!"Allocation not found"); return; } // Make the previous block the current _setCurrentBlock(prevBlock); // Make the current the alloc freed m_current = ptr; } } inline void ArenaAllocator::deallocateAllFrom(void* data) { // See if it's in current block, and is allocated (ie < m_cur) uint8_t* ptr = (uint8_t*)data; if (ptr >= m_start && ptr < m_current) { // If it's in current block, then just go back m_current = ptr; return; } // Search all blocks prior to current block Block* block = _findBlock(data, m_currentBlock); CARB_ASSERT(block); if (!block) { return; } // Make this current block _setCurrentBlock(block); // Move the pointer to the allocations position m_current = ptr; } inline void ArenaAllocator::deallocateAll() { Block** prev = &m_blocks; Block* block = m_blocks; while (block) { if (size_t(block->m_end - block->m_alloc) > m_blockSize) { // Oversized block so we need to free it and remove from the list Block* nextBlock = block->m_next; *prev = nextBlock; // Free the backing memory CARB_FREE(block->m_alloc); // Free the block m_blockFreeList.deallocate(block); // prev stays the same, now working on next tho block = nextBlock; } else { // Onto next prev = &block->m_next; block = block->m_next; } } // Make the first current (if any) _setCurrentBlock(m_blocks); } inline void ArenaAllocator::reset() { _deallocateBlocks(); m_blocks = nullptr; _setCurrentBlock(nullptr); } inline void ArenaAllocator::adjustToBlockAlignment() { const size_t alignMask = m_blockAlignment - 1; uint8_t* ptr = (uint8_t*)((size_t(m_current) + alignMask) & ~alignMask); // Alignment might push beyond end of block... if so allocate a new block // This test could be avoided if we aligned m_end, but depending on block alignment that might waste some space if (ptr > m_end) { // We'll need a new block to make this alignment _newCurrentBlock(0, m_blockAlignment); } else { // Set the position m_current = ptr; } CARB_ASSERT(size_t(m_current) & alignMask); } inline size_t ArenaAllocator::getBlockAlignment() const { return m_blockAlignment; } } // namespace extras } // namespace carb
21,204
C
29.911079
120
0.623562
omniverse-code/kit/include/carb/extras/Unicode.h
// Copyright (c) 2018-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 "../Defines.h" #include "Utf8Parser.h" #include <cstdint> #include <string> #if CARB_PLATFORM_LINUX # include <iconv.h> #else # include <codecvt> # include <locale> #endif namespace carb { namespace extras { /** * Collection of Unicode conversion utilities. * * UTF-8 encoding is used throughout this code base. However, there will be cases when you interact with OS (Windows) * or third party libraries (like glfw) where you need to convert to/from another representation. In those cases use the * conversion utilities offered here - *don't roll your own.* We know it's tempting to use std::codecvt but it's not * portable to all the operating systems we support (Tegra) and it will throw exceptions on range errors (which are * surprisingly common) if you use the default constructors (which is what everybody does). * * If you need a facility that isn't offered here then please add it to this collection. Read more about the * Unicode strategy employed in this code base at docs/Unicode.md. */ /** * Failure message returned from convertUtf32ToUtf8 code point function, usually because of invalid input code point */ const std::string kCodePointToUtf8Failure = "[?]"; /** Flags to alter the behavior of convertUtf32ToUtf8(). */ using ConvertUtf32ToUtf8Flags = uint32_t; /** When this flag is passed to convertUtf32ToUtf8(), the string returned on * conversion failure will be @ref kCodePointToUtf8Failure. * If this is flag is not passed, the UTF-8 encoding of U+FFFD (the Unicode * replacement character) will be returned on conversion failure. */ constexpr ConvertUtf32ToUtf8Flags fUseLegacyFailureString = 0x01; /** * Convert a UTF-32 code point to UTF-8 encoded string * * @param utf32CodePoint The code point to convert, in UTF-32 encoding * @param flags These alter the behavior of this function. * @return The UTF-8 encoded version of utf32CodePoint. * @return If the codepoint could not be converted to UTF-8, the returned value * depends on @p flags. * If @p flags contains @ref fUseLegacyFailureString, then @ref * kCodePointToUtf8Failure will be returned; otherwise, U+FFFD encoded * in UTF-8 is returned. */ inline std::string convertUtf32ToUtf8(uint32_t codePointUtf32, ConvertUtf32ToUtf8Flags flags = fUseLegacyFailureString) { char32_t u32Str[] = { codePointUtf32, '\0' }; std::string out = convertUtf32StringToUtf8(u32Str); // if conversion fails, the string will just end early. if (out.empty() && codePointUtf32 != 0) { return (flags & fUseLegacyFailureString) != 0 ? kCodePointToUtf8Failure : u8"\uFFFD"; } return out; } #if CARB_PLATFORM_WINDOWS /** A value that was returned by a past version of convertWideToUtf8() on failure. * Current versions will insert U+FFFD on characters that failed to parse. */ const std::string kUnicodeToUtf8Failure = "[failure-converting-to-utf8]"; /** A value that was returned by a past version of convertUtf8ToWide() on failure. * Current versions will insert U+FFFD on characters that failed to parse. */ const std::wstring kUnicodeToWideFailure = L"[failure-converting-to-wide]"; /** * Converts a Windows wide string to UTF-8 string * Do not use this function for Windows file path conversion! Instead, use extras::convertWindowsToCarbonitePath(const * std::wstring& pathW) function for proper slashes handling and long file path support. * * @param wide Input string to convert, in Windows UTF16 encoding. * @note U+FFFD is returned if an invalid Unicode sequence is encountered. */ inline std::string convertWideToUtf8(const wchar_t* wide) { return convertWideStringToUtf8(wide); } inline std::string convertWideToUtf8(const std::wstring& wide) { return convertWideStringToUtf8(wide); } /** * Converts a UTF-8 encoded string to Windows wide string * Do not use this function for Windows file path conversion! Instead, use extras::convertCarboniteToWindowsPath(const * std::string& path) function for proper slashes handling and long file path support. * * @param utf8 Input string to convert, in UTF-8 encoding. * @note U+FFFD is returned if an invalid Unicode sequence is encountered. */ inline std::wstring convertUtf8ToWide(const char* utf8) { return convertUtf8StringToWide(utf8); } inline std::wstring convertUtf8ToWide(const std::string& utf8) { return convertUtf8StringToWide(utf8); } class LocaleWrapper { public: LocaleWrapper(const char* localeName) { locale = _create_locale(LC_ALL, localeName); } ~LocaleWrapper() { _free_locale(locale); } _locale_t getLocale() { return locale; } private: _locale_t locale; }; inline auto _getSystemDefaultLocale() { static LocaleWrapper s_localeWrapper(""); return s_localeWrapper.getLocale(); } /** * Performs a case-insensitive comparison of wide strings in Unicode (Windows native) using system default locale. * * @param string1 First input string. * @param string2 Second input string. * @return < 0 if string1 less than string2, * 0 if string1 identical to string2, * > 0 if string1 greater than string2, * INT_MAX on error. */ inline int compareWideStringsCaseInsensitive(const wchar_t* string1, const wchar_t* string2) { return _wcsicmp_l(string1, string2, _getSystemDefaultLocale()); } inline int compareWideStringsCaseInsensitive(const std::wstring& string1, const std::wstring& string2) { return compareWideStringsCaseInsensitive(string1.c_str(), string2.c_str()); } /** * Converts wide string in Unicode (Windows native) to uppercase using system default locale. * * @param string Input string. * @return Uppercase string. */ inline std::wstring convertWideStringToUppercase(const std::wstring& string) { std::wstring result = string; _wcsupr_s_l(&result[0], result.size() + 1, _getSystemDefaultLocale()); return result; } /** * Converts wide string in Unicode (Windows native) to uppercase using system default locale, in-place version. * * @param string Input and output string. */ inline void convertWideStringToUppercaseInPlace(std::wstring& string) { _wcsupr_s_l(&string[0], string.size() + 1, _getSystemDefaultLocale()); } /** * Converts wide string in Unicode (Windows native) to lowercase using system default locale. * * @param string Input string. * @return Lowercase string. */ inline std::wstring convertWideStringToLowercase(const std::wstring& string) { std::wstring result = string; _wcslwr_s_l(&result[0], result.size() + 1, _getSystemDefaultLocale()); return result; } /** * Converts wide string in Unicode (Windows native) to lowercase using system default locale, in-place version. * * @param string Input and output string. */ inline void convertWideStringToLowercaseInPlace(std::wstring& string) { _wcslwr_s_l(&string[0], string.size() + 1, _getSystemDefaultLocale()); } #endif } // namespace extras } // namespace carb
7,460
C
31.723684
120
0.730965
omniverse-code/kit/include/carb/extras/EnvironmentVariableParser.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 Parses environment variables into map of key/value pairs // #pragma once #include "../Defines.h" #include "StringUtils.h" #include "Unicode.h" #include <cstring> #include <map> #include <string> #if CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" #else # ifndef DOXYGEN_BUILD extern "C" { extern char** environ; } # endif #endif namespace carb { namespace extras { /** * Parses environment variables into program options or environment variables */ class EnvironmentVariableParser { public: /** * Construct an environment parser looking for variables starting with @p prefix */ EnvironmentVariableParser(const char* prefix) : m_prefix(prefix) { } /** * Parse the environment. Variables starting with prefix given to constructor are separated * into program options, whereas all others are parsed as normal environment variables */ void parse() { m_pathwiseOverrides.clear(); CARB_MSC_ONLY(parseForMsvc()); CARB_NOT_MSC(parseForOthers()); } //! key/value pairs of the parsed environment variables using Options = std::map<std::string, std::string>; /** * The map of program options that matched prefix. * @return map of key/value options */ const Options& getOptions() { return m_pathwiseOverrides; } /** * The map of all environment variables that did not the prefix. * @return map of key/value environment variables */ const Options& getEnvVariables() { return m_envVariables; } private: #if CARB_COMPILER_MSC void parseForMsvc() { class EnvVarsBlockWatchdog { public: EnvVarsBlockWatchdog() { m_envsBlock = GetEnvironmentStringsW(); } ~EnvVarsBlockWatchdog() { if (m_envsBlock) { FreeEnvironmentStringsW(m_envsBlock); } } const wchar_t* getEnvsBlock() { return m_envsBlock; } private: wchar_t* m_envsBlock = nullptr; }; EnvVarsBlockWatchdog envVarsBlovkWatchdog; const wchar_t* envsBlock = envVarsBlovkWatchdog.getEnvsBlock(); if (!envsBlock) { return; } const wchar_t* var = (LPWSTR)envsBlock; while (*var) { std::string varUtf8 = carb::extras::convertWideToUtf8(var); size_t equalSignPos = 0; size_t varLen = (size_t)lstrlenW(var); while (equalSignPos < varLen && var[equalSignPos] != L'=') { ++equalSignPos; } var += varLen + 1; if (equalSignPos == 0 || equalSignPos == varLen) { continue; } std::string varNameUtf8(varUtf8.c_str(), equalSignPos); _processAndAddOption(varNameUtf8.c_str(), varUtf8.c_str() + equalSignPos + 1); } } #else void parseForOthers() { char** envsBlock = environ; if (!envsBlock || !*envsBlock) { return; } while (*envsBlock) { size_t equalSignPos = 0; const char* var = *envsBlock; size_t varLen = (size_t)strlen(var); while (equalSignPos < varLen && var[equalSignPos] != '=') { ++equalSignPos; } ++envsBlock; if (equalSignPos == 0 || equalSignPos == varLen) { continue; } std::string varName(var, equalSignPos); _processAndAddOption(varName.c_str(), var + equalSignPos + 1); } } #endif void _processAndAddOption(const char* varName, const char* varValue) { if (!m_prefix.empty() && startsWith(varName, m_prefix)) { std::string path = varName + m_prefix.size(); for (size_t i = 0, pathLen = path.length(); i < pathLen; ++i) { // TODO: WRONG, must be utf8-aware replacement if (path[i] == '_') path[i] = '/'; } m_pathwiseOverrides.insert(std::make_pair(path.c_str(), varValue)); } else { CARB_ASSERT(varName); CARB_ASSERT(varValue); m_envVariables[varName] = varValue; } } // Path-wise overrides Options m_pathwiseOverrides; // Explicit env variables Options m_envVariables; std::string m_prefix; }; } // namespace extras } // namespace carb
5,159
C
24.294118
95
0.557666
omniverse-code/kit/include/carb/extras/Path.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 Path interpretation utilities. #pragma once #include "../Defines.h" #include "../logging/Log.h" #include "../../omni/String.h" #include <functional> #include <iostream> #include <string> #include <utility> #include <vector> namespace carb { namespace extras { // Forward declarations class Path; inline Path operator/(const Path& left, const Path& right); inline Path operator+(const Path& left, const Path& right); inline Path operator+(const Path& left, const char* right); inline Path operator+(const Path& left, const std::string& right); inline Path operator+(const Path& left, const omni::string& right); inline Path operator+(const char* left, const Path& right); inline Path operator+(const std::string& left, const Path& right); inline Path operator+(const omni::string& left, const Path& right); /** * Path objects are used for filesystem path manipulations. * * All paths are UTF-8 encoded using forward slash as path separator. * * Note: the class supports implicit casting to a "std::string" and explicit cast to * a "const char *" pointer */ class Path { public: //! A special value depending on the context, such as "all remaining characters". static constexpr size_t npos = std::string::npos; static_assert(npos == size_t(-1), "Invalid assumption"); //-------------------------------------------------------------------------------------- // Constructors/destructor and assignment operations /** * Default constructor. */ Path() = default; /** * Constructs a Path from a counted char array containing a UTF-8 encoded string. * * The Path object converts all backslashes to forward slashes. * * @param path a pointer to the UTF-8 string data * @param pathLen the size of \p path in bytes */ Path(const char* path, size_t pathLen) { if (path && pathLen) { m_pathString.assign(path, pathLen); _sanitizePath(); } } /** * Constructs a Path from a NUL-terminated char buffer containing a UTF-8 encoded string. * * The Path object converts all backslashes to forward slashes. * * @param path a pointer to the UTF-8 string data */ Path(const char* path) { if (path) { m_pathString = path; } _sanitizePath(); } /** * Constructs a Path from a `std::string` containing a UTF-8 encoded string. * * The Path object converts all backslashes to forward slashes. * * @param path The source string */ Path(std::string path) : m_pathString(std::move(path)) { _sanitizePath(); } /** * Constructs a Path from an \ref omni::string containing a UTF-8 encoded string. * * The Path object converts all backslashes to forward slashes. * * @param path The source string */ Path(const omni::string& path) : m_pathString(path.c_str(), path.length()) { _sanitizePath(); } /** * Copy constructor. Copies a Path from another Path. * * @param other The other path to copy from */ Path(const Path& other) : m_pathString(other.m_pathString) { } /** * Move constructor. Moves a Path from another Path, which is left in a valid but unspecified state. * * @param other The other path to move from */ Path(Path&& other) noexcept : m_pathString(std::move(other.m_pathString)) { } /** * Copy-assign operator. Copies another Path into *this. * * @param other The other path to copy from * @returns `*this` */ Path& operator=(const Path& other) { m_pathString = other.m_pathString; return *this; } /** * Move-assign operator. Moves another Path into *this and leaves the other path in a valid but unspecified state. * * @param other The other path to move from * @returns `*this` */ Path& operator=(Path&& other) noexcept { m_pathString = std::move(other.m_pathString); return *this; } /** * Destructor */ ~Path() = default; //-------------------------------------------------------------------------------------- // Getting a string representation of the internal data /** * Gets the string representation of the path. * * @returns a copy of the UTF-8 string representation of the internal data */ std::string getString() const { return m_pathString; } /** * Implicit conversion operator to a string representation. * * @returns a copy of the UTF-8 string representation of the internal data */ operator std::string() const { return m_pathString; } /** * Gets the string data owned by this Path. * * @warning the return value from this function should not be retained, and may be dangling after `*this` is * modified in any way. * * @return pointer to the start of the path data */ const char* c_str() const noexcept { return m_pathString.c_str(); } /** * Gets the string data owned by this Path. * * @warning the return value from this function should not be retained, and may be dangling after `*this` is * modified in any way. * * @return pointer to the start of the path data */ const char* getStringBuffer() const noexcept { return m_pathString.c_str(); } /** * Enables outputting this Path to a stream object. * * @param os the stream to output to * @param path the Path to output */ CARB_NO_DOC(friend) // Sphinx 3.5.4 complains that this is an invalid C++ declaration, so ignore `friend` for docs. std::ostream& operator<<(std::ostream& os, const Path& path) { os << path.m_pathString; return os; } /** * Explicit conversion operator to get the string data owned by this Path. * * @warning the return value from this function should not be retained, and may be dangling after `*this` is * modified in any way. * * @return pointer to the start of the path data */ explicit operator const char*() const noexcept { return getStringBuffer(); } //-------------------------------------------------------------------------------------- // Path operations // Compare operations /** * Equality comparison * @param other a Path to compare against `*this` for equality * @returns `true` if `*this` and \p other are equal; `false` otherwise */ bool operator==(const Path& other) const noexcept { return m_pathString == other.m_pathString; } /** * Equality comparison * @param other a `std::string` to compare against `*this` for equality * @returns `true` if `*this` and \p other are equal; `false` otherwise */ bool operator==(const std::string& other) const noexcept { return m_pathString == other; } /** * Equality comparison * @param other a NUL-terminated char buffer to compare against `*this` for equality * @returns `true` if `*this` and \p other are equal; `false` otherwise (or if \p other is `nullptr`) */ bool operator==(const char* other) const noexcept { if (other == nullptr) { return false; } return m_pathString == other; } /** * Inequality comparison * @param other a Path to compare against `*this` for inequality * @returns `true` if `*this` and \p other are not equal; `false` otherwise */ bool operator!=(const Path& other) const noexcept { return !(*this == other); } /** * Inequality comparison * @param other a `std::string` to compare against `*this` for inequality * @returns `true` if `*this` and \p other are not equal; `false` otherwise */ bool operator!=(const std::string& other) const noexcept { return !(*this == other); } /** * Inequality comparison * @param other a NUL-terminated char buffer to compare against `*this` for inequality * @returns `true` if `*this` and \p other are not equal; `false` otherwise (or if \p other is `nullptr`) */ bool operator!=(const char* other) const noexcept { return !(*this == other); } /** * Gets the length of the path * * @returns the length of the path string data in bytes */ size_t getLength() const noexcept { return m_pathString.size(); } /** * Gets the length of the path * * @returns the length of the path string data in bytes */ size_t length() const noexcept { return m_pathString.size(); } /** * Gets the length of the path * * @returns the length of the path string data in bytes */ size_t size() const noexcept { return m_pathString.size(); } /** * Clears current path * * @returns `*this` */ Path& clear() { m_pathString.clear(); return *this; } /** * Checks if the path is an empty string * * @returns `true` if the path contains at least one character; `false` otherwise */ bool isEmpty() const noexcept { return m_pathString.empty(); } /** * Checks if the path is an empty string * * @returns `true` if the path contains at least one character; `false` otherwise */ bool empty() const noexcept { return m_pathString.empty(); } /** * Returns the filename component of the path, or an empty path object if there is no filename. * * Example: given `C:/foo/bar.txt`, this function would return `bar.txt`. * * @return The path object representing the filename */ Path getFilename() const { size_t offset = _getFilenameOffset(); if (offset == npos) return {}; return Path(Sanitized, m_pathString.substr(offset)); } /** * Returns the extension of the filename component of the path, including period (.), or an empty path object. * * Example: given `C:/foo/bar.txt`, this function would return `.txt`. * * @return The path object representing the extension */ Path getExtension() const { size_t ext = _getExtensionOffset(); if (ext == npos) return {}; return Path(Sanitized, m_pathString.substr(ext)); } /** * Returns the path to the parent directory, or an empty path object if there is no parent. * * Example: given `C:/foo/bar.txt`, this function would return `C:/foo`. * * @return The path object representing the parent directory */ Path getParent() const; /** * Returns the filename component of the path stripped of the extension, or an empty path object if there is no * filename. * * Example: given `C:/foo/bar.txt`, this function would return `bar`. * * @return The path object representing the stem */ Path getStem() const { size_t offset = _getFilenameOffset(); if (offset == npos) return {}; size_t ext = _getExtensionOffset(); CARB_ASSERT(ext == npos || ext >= offset); // If ext is npos, `ext - offset` results in the full filename since there is no extension return Path(Sanitized, m_pathString.substr(offset, ext - offset)); } /** * Returns the root name in the path. * * Example: given `C:/foo/bar.txt`, this function would return `C:`. * Example: given `//server/share`, this function would return `//server`. * * @return The path object representing the root name */ Path getRootName() const { size_t rootNameEnd = _getRootNameEndOffset(); if (rootNameEnd == npos) { return {}; } return Path(Sanitized, m_pathString.substr(0, rootNameEnd)); } /** * Returns the relative part of the path (the part after optional root name and root directory). * * Example: given `C:/foo/bar.txt`, this function would return `foo/bar.txt`. * Example: given `//server/share/foo.txt`, this function would return `share/foo.txt`. * * @return The path objects representing the relative part of the path */ Path getRelativePart() const { size_t relativePart = _getRelativePartOffset(); if (relativePart == npos) { return {}; } return Path(Sanitized, m_pathString.substr(relativePart)); } /** * Returns the root directory if it's present in the path. * * Example: given `C:/foo/bar.txt`, this function would return `/`. * Example: given `foo/bar.txt`, this function would return `` (empty Path). * * @note This function will only ever return an empty path or a forward slash. * * @return The path object representing the root directory */ Path getRootDirectory() const { constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110 return hasRootDirectory() ? Path(Sanitized, std::string(&kForwardSlashChar_, 1)) : Path(); } /** * Checks if the path has a root directory * * @return `true` if \ref getRootDirectory() would return `/`; `false` if \ref getRootDirectory() would return an * empty string. */ bool hasRootDirectory() const noexcept { size_t rootDirectoryEnd = _getRootDirectoryEndOffset(); if (rootDirectoryEnd == npos) { return false; } size_t rootNameEnd = _getRootNameEndOffset(); if (rootNameEnd == rootDirectoryEnd) { return false; } return true; } /** * Returns the root of the path: the root name and root directory if they are present. * * Example: given `C:/foo/bar.txt`, this function would return `C:/`. * * @return The path object representing the root of the path */ Path getRoot() const { size_t rootDirectoryEnd = _getRootDirectoryEndOffset(); if (rootDirectoryEnd == npos) { return {}; } return Path(Sanitized, m_pathString.substr(0, rootDirectoryEnd)); } /** * A helper function to append another path after *this and return as a new object. * * @note Unlike \ref join(), this function concatenates two Path objects without a path separator between them. * * @param toAppend the Path to append to `*this` * @return a new Path object that has `*this` appended with \p toAppend. */ Path concat(const Path& toAppend) const { if (isEmpty()) { return toAppend; } if (toAppend.isEmpty()) { return *this; } std::string total; total.reserve(m_pathString.length() + toAppend.m_pathString.length()); total.append(m_pathString); total.append(toAppend.m_pathString); return Path(Sanitized, std::move(total)); } /** * A helper function to append another path after *this with a separator if necessary and return as a new object. * * @param toJoin the Path object to append to `*this` * @returns a new Path object that has `*this` followed by a separator (if one is not already present at the end of * `*this` or the beginning of \p toJoin), followed by \p toJoin */ Path join(const Path& toJoin) const; /** * Appends a path to *this with a separator if necessary. * * @note Unlike \ref join(), `*this` is modified by this function. * * @param path the Path to append to `*this` * @returns `*this` */ Path& operator/=(const Path& path) { return *this = *this / path; } /** * Appends a path to *this without adding a separator. * * @note Unlike \ref concat(), `*this` is modified by this function. * * @param path The Path to append to `*this` * @returns `*this` */ Path& operator+=(const Path& path) { return *this = *this + path; } /** * Replaces the current file extension with the given extension. * * @param newExtension the new extension to use * * @returns `*this` */ Path& replaceExtension(const Path& newExtension); /** * Normalizes *this as an absolute path and returns as a new Path object. * * @warning This function does NOT make an absolute path using the CWD as a root. You need to use * \ref carb::filesystem::IFileSystem to get the current working directory and pass it to this function if desired. * * @note If `*this` is already an absolute path as determined by \ref isAbsolute(), \p root is ignored. * * @param root The root Path to prepend to `*this` * @return A new Path object representing the constructed absolute path */ Path getAbsolute(const Path& root = Path()) const { if (isAbsolute() || root.isEmpty()) { return this->getNormalized(); } return root.join(*this).getNormalized(); } /** * Returns the result of the normalization of the current path as a new path * * Example: given `C:/foo/./bar/../bat.txt`, this function would return `C:/foo/bat.txt`. * * @return A new Path object representing the normalized current path */ Path getNormalized() const; /** * Normalizes current path in place * * @note Unlike \ref getNormalized(), `*this` is modified by this function. * * Example: given `C:/foo/./bar/../bat.txt`, this function would change `*this` to contain `C:/foo/bat.txt`. * * @returns `*this` */ Path& normalize() { return *this = getNormalized(); } /** * Checks if the current path is an absolute path. * * @returns `true` if the current path is an absolute path; `false` otherwise. */ bool isAbsolute() const noexcept; /** * Checks if the current path is a relative path. * * Effectively, `!isAbsolute()`. * * @return `true` if the current path is a relative path; `false` otherwise. */ bool isRelative() const { return !isAbsolute(); } /** * Returns current path made relative to a given base as a new Path object. * * @note The paths are not normalized prior to the operation. * * @param base the base path * * @return an empty path if it's impossible to match roots (different root names, different states of being * relative/absolute with a base path, not having a root directory while the base has it), otherwise a non-empty * relative path */ Path getRelative(const Path& base) const noexcept; private: static constexpr char kDotChar = '.'; static constexpr char kForwardSlashChar = '/'; static constexpr char kColonChar = ':'; struct Sanitized_t { }; constexpr static Sanitized_t Sanitized{}; Path(Sanitized_t, std::string s) : m_pathString(std::move(s)) { // Pre-sanitized, so no need to do it again } enum class PathTokenType { Slash, RootName, Dot, DotDot, Name }; // Helper function to parse next path token from `[bufferStart, bufferEnd)` (bufferEnd is an off-the-end pointer). // On success returns pointer immediately after the token data and returns token type in the // resultType. On failure returns nullptr and `resultType` is unchanged. // Note: it doesn't determine if a Name is a RootName. (RootName is added to enum for convenience) static const char* _getTokenEnd(const char* bufferBegin, const char* bufferEnd, PathTokenType& resultType) { if (bufferBegin == nullptr || bufferEnd == nullptr || bufferEnd <= bufferBegin) { return nullptr; } // Trying to find the next slash constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110 const char* tokenEnd = std::find(bufferBegin, bufferEnd, kForwardSlashChar_); // If found a slash as the first symbol then return pointer to the data after it if (tokenEnd == bufferBegin) { resultType = PathTokenType::Slash; return tokenEnd + 1; } // If no slash found we consider all passed data as a single token if (!tokenEnd) { tokenEnd = bufferEnd; } const size_t tokenSize = tokenEnd - bufferBegin; if (tokenSize == 1 && *bufferBegin == kDotChar) { resultType = PathTokenType::Dot; } else if (tokenSize == 2 && bufferBegin[0] == kDotChar && bufferBegin[1] == kDotChar) { resultType = PathTokenType::DotDot; } else { resultType = PathTokenType::Name; } return tokenEnd; } /** * Helper function to find the pointer to the start of the filename */ size_t _getFilenameOffset() const noexcept { if (isEmpty()) { return npos; } // Find the last slash size_t offset = m_pathString.rfind(kForwardSlashChar); if (offset == npos) { // Not empty, so no slash means only filename return 0; } // If the slash is the end, no filename if ((offset + 1) == m_pathString.length()) { return npos; } return offset + 1; } /** * Helper function to find the pointer to the start of the extension */ size_t _getExtensionOffset() const noexcept { size_t filename = _getFilenameOffset(); if (filename == npos) { return npos; } size_t dot = m_pathString.rfind(kDotChar); // No extension if: // - No dot in filename portion (dot not found or last dot proceeds filename) // - filename ends with a dot if (dot == npos || dot < filename || dot == (m_pathString.length() - 1)) { return npos; } // If the only dot found starts the filename, we don't consider that an extension return dot == filename ? npos : dot; } /** * Helper function to find the pointer to the end of the root name (the pointer just after the end of the root name) */ size_t _getRootNameEndOffset() const noexcept { if (isEmpty()) { return npos; } if (m_pathString.length() < 2) { return 0; } #if CARB_PLATFORM_WINDOWS // Check if the path starts with a drive letter and colon (e.g. "C:/...") if (m_pathString.at(1) == kColonChar && std::isalpha(m_pathString.at(0))) { return 2; } #endif // Check if the path is a UNC path (e.g. "//server/location/...") // This simple check is two slashes and not a slash if (m_pathString.length() >= 3 && m_pathString.at(0) == kForwardSlashChar && m_pathString.at(1) == kForwardSlashChar && m_pathString.at(2) != kForwardSlashChar) { // Find the next slash size_t offset = m_pathString.find(kForwardSlashChar, 3); return offset == npos ? m_pathString.length() : offset; } return 0; } /** * Helper function to get the pointer to the start of the relative part of the path */ size_t _getRelativePartOffset(size_t rootNameEnd = npos) const noexcept { size_t offset = rootNameEnd != npos ? rootNameEnd : _getRootNameEndOffset(); if (offset == npos) return npos; // Find the first non-slash character constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110 return m_pathString.find_first_not_of(&kForwardSlashChar_, offset, 1); } /** * Helper function to find the pointer to the end of the root directory (the pointer just after the end of the root * directory) */ size_t _getRootDirectoryEndOffset() const noexcept { size_t rootNameEnd = _getRootNameEndOffset(); size_t relativePart = _getRelativePartOffset(rootNameEnd); if (relativePart != rootNameEnd) { if (rootNameEnd >= m_pathString.length()) { return rootNameEnd; } return rootNameEnd + 1; } return rootNameEnd; } // Patching paths in the constructors (using external string data) if needed void _sanitizePath() { #if CARB_PLATFORM_WINDOWS constexpr char kBackwardSlashChar = '\\'; // changing the backward slashes for Windows to forward ones for (char& c : m_pathString) { if (c == kBackwardSlashChar) { c = kForwardSlashChar; } } #endif } std::string m_pathString; }; /** * Concatenation operator * @see Path::concat() * @param left a Path * @param right a Path * @returns `left.concat(right)` */ inline Path operator+(const Path& left, const Path& right) { return left.concat(right); } /** * Concatenation operator * @see Path::concat() * @param left a Path * @param right a NUL-terminated char buffer representing a path * @returns `left.concat(right)` */ inline Path operator+(const Path& left, const char* right) { return left.concat(right); } /** * Concatenation operator * @see Path::concat() * @param left a Path * @param right a `std::string` representing a path * @returns `left.concat(right)` */ inline Path operator+(const Path& left, const std::string& right) { return left.concat(right); } /** * Concatenation operator * @see Path::concat() * @param left a Path * @param right an \ref omni::string representing a path * @returns `left.concat(right)` */ inline Path operator+(const Path& left, const omni::string& right) { return left.concat(right); } /** * Concatenation operator * @see Path::concat() * @param left a NUL-terminated char buffer representing a path * @param right a Path * @returns `Path(left).concat(right)` */ inline Path operator+(const char* left, const Path& right) { return Path(left).concat(right); } /** * Concatenation operator * @see Path::concat() * @param left a `std::string` representing a path * @param right a Path * @returns `Path(left).concat(right)` */ inline Path operator+(const std::string& left, const Path& right) { return Path(left).concat(right); } /** * Concatenation operator * @see Path::concat() * @param left an \ref omni::string representing a path * @param right a Path * @returns `Path(left).concat(right)` */ inline Path operator+(const omni::string& left, const Path& right) { return Path(left).concat(right); } /** * Join operator * * Performs a Path::join() operation on two Path paths. * @param left a Path * @param right a Path * @returns `left.join(right)` */ inline Path operator/(const Path& left, const Path& right) { return left.join(right); } /** * Helper function to get a Path object representing parent directory for the provided string representation of a path. * @see Path::getParent() * @param path a `std::string` representation of a path * @returns `Path(path).getParent()` */ inline Path getPathParent(std::string path) { return Path(std::move(path)).getParent(); } /** * Helper function to get a Path object representing the extension part of the provided string representation of a path. * @see Path::getExtension() * @param path a `std::string` representation of a path * @returns `Path(path).getExtension()` */ inline Path getPathExtension(std::string path) { return Path(std::move(path)).getExtension(); } /** * Helper function to get a Path object representing the stem part of the provided string representation of a path. * @see Path::getStem() * @param path a `std::string` representation of a path * @returns `Path(path).getStem()` */ inline Path getPathStem(std::string path) { return Path(std::move(path)).getStem(); } /** * Helper function to calculate a relative path from a provided path and a base path. * @see Path::getRelative() * @param path a `std::string` representation of a path * @param base a `std::string` representation of the base path * @returns `Path(path).getRelative(base)` */ inline Path getPathRelative(std::string path, std::string base) { return Path(std::move(path)).getRelative(Path(std::move(base))); } /** * Equality operator. * @param left a `std::string` representation of a Path * @param right a Path * @returns `true` if the paths are equal; `false` otherwise */ inline bool operator==(const std::string& left, const Path& right) { return right == left; } /** * Equality operator. * @param left a NUL-terminated char buffer representation of a Path * @param right a Path * @returns `true` if the paths are equal; `false` otherwise */ inline bool operator==(const char* left, const Path& right) { return right == left; } /** * Inequality operator. * @param left a `std::string` representation of a Path * @param right a Path * @returns `true` if the paths are not equal; `false` otherwise */ inline bool operator!=(const std::string& left, const Path& right) { return right != left; } /** * Inequality operator. * @param left a NUL-terminated char buffer representation of a Path * @param right a Path * @returns `true` if the paths are not equal; `false` otherwise */ inline bool operator!=(const char* left, const Path& right) { return right != left; } //////////////////////////////////////////////////////////////////////////////////////////// // Implementations of large public functions //////////////////////////////////////////////////////////////////////////////////////////// inline Path Path::getParent() const { size_t parentPathEnd = _getFilenameOffset(); if (parentPathEnd == npos) parentPathEnd = m_pathString.length(); size_t slashesDataStart = 0; if (hasRootDirectory()) { slashesDataStart += _getRootDirectoryEndOffset(); } while (parentPathEnd > slashesDataStart && m_pathString.at(parentPathEnd - 1) == kForwardSlashChar) { --parentPathEnd; } if (parentPathEnd == 0) { return {}; } return Path(Sanitized, m_pathString.substr(0, parentPathEnd)); } inline Path Path::join(const Path& joinedPart) const { if (isEmpty()) { return joinedPart; } if (joinedPart.isEmpty()) { return *this; } const bool needSeparator = (m_pathString.back() != kForwardSlashChar) && (joinedPart.m_pathString.front() != kForwardSlashChar); std::string joined; joined.reserve(m_pathString.length() + joinedPart.m_pathString.length() + (needSeparator ? 1 : 0)); joined.assign(m_pathString); if (needSeparator) joined.push_back(kForwardSlashChar); joined.append(joinedPart.m_pathString); return Path(Sanitized, std::move(joined)); } inline Path& Path::replaceExtension(const Path& newExtension) { CARB_ASSERT(std::addressof(newExtension) != this); // Erase the current extension size_t ext = _getExtensionOffset(); if (ext != npos) { m_pathString.erase(ext); } // If the new extension is empty, we're done if (newExtension.isEmpty()) { return *this; } // Append a dot if there isn't one in the new extension if (newExtension.m_pathString.front() != kDotChar) { m_pathString.push_back(kDotChar); } // Append new extension m_pathString.append(newExtension.m_pathString); return *this; } inline Path Path::getNormalized() const { if (isEmpty()) { return {}; } enum class NormalizePartType { Slash, RootName, RootSlash, Dot, DotDot, Name, Error }; struct ParsedPathPartDescription { NormalizePartType type; const char* data; size_t size; ParsedPathPartDescription(const char* partData, size_t partSize, PathTokenType partType) : data(partData), size(partSize) { switch (partType) { case PathTokenType::Slash: type = NormalizePartType::Slash; break; case PathTokenType::RootName: type = NormalizePartType::RootName; break; case PathTokenType::Dot: type = NormalizePartType::Dot; break; case PathTokenType::DotDot: type = NormalizePartType::DotDot; break; case PathTokenType::Name: type = NormalizePartType::Name; break; default: type = NormalizePartType::Error; CARB_LOG_ERROR("Invalid internal token state while normalizing a path"); CARB_ASSERT(false); break; } } ParsedPathPartDescription(const char* partData, size_t partSize, NormalizePartType partType) : type(partType), data(partData), size(partSize) { } }; std::vector<ParsedPathPartDescription> resultPathTokens; size_t prevTokenEndOffset = _getRootDirectoryEndOffset(); const char* prevTokenEnd = prevTokenEndOffset == npos ? nullptr : m_pathString.data() + prevTokenEndOffset; const char* pathDataStart = m_pathString.data(); const size_t pathDataLength = getLength(); if (prevTokenEnd && prevTokenEnd > pathDataStart) { // Adding the root name and the root directory as different elements const char* possibleSlashPos = prevTokenEnd - 1; if (*possibleSlashPos == kForwardSlashChar) { if (possibleSlashPos > pathDataStart) { resultPathTokens.emplace_back( pathDataStart, static_cast<size_t>(possibleSlashPos - pathDataStart), PathTokenType::RootName); } constexpr static auto kForwardSlashChar_ = kForwardSlashChar; // CC-1110 resultPathTokens.emplace_back(&kForwardSlashChar_, 1, NormalizePartType::RootSlash); } else { resultPathTokens.emplace_back( pathDataStart, static_cast<size_t>(prevTokenEnd - pathDataStart), PathTokenType::RootName); } } else { prevTokenEnd = pathDataStart; } bool alreadyNormalized = true; const char* bufferEnd = pathDataStart + pathDataLength; PathTokenType curTokenType = PathTokenType::Name; for (const char* curTokenEnd = _getTokenEnd(prevTokenEnd, bufferEnd, curTokenType); curTokenEnd != nullptr; prevTokenEnd = curTokenEnd, curTokenEnd = _getTokenEnd(prevTokenEnd, bufferEnd, curTokenType)) { switch (curTokenType) { case PathTokenType::Slash: if (resultPathTokens.empty() || resultPathTokens.back().type == NormalizePartType::Slash || resultPathTokens.back().type == NormalizePartType::RootSlash) { // Skip if we already have a slash at the end alreadyNormalized = false; continue; } break; case PathTokenType::Dot: // Just skip it alreadyNormalized = false; continue; case PathTokenType::DotDot: if (resultPathTokens.empty()) { break; } // Check if the previous element is a part of the root name (even without a slash) and skip dot-dot in // such case if (resultPathTokens.back().type == NormalizePartType::RootName || resultPathTokens.back().type == NormalizePartType::RootSlash) { alreadyNormalized = false; continue; } if (resultPathTokens.size() > 1) { CARB_ASSERT(resultPathTokens.back().type == NormalizePartType::Slash); const NormalizePartType tokenTypeBeforeSlash = resultPathTokens[resultPathTokens.size() - 2].type; // Remove <name>/<dot-dot> pattern if (tokenTypeBeforeSlash == NormalizePartType::Name) { resultPathTokens.pop_back(); // remove the last slash resultPathTokens.pop_back(); // remove the last named token alreadyNormalized = false; continue; // and we skip the addition of the dot-dot } } break; case PathTokenType::Name: // No special processing needed break; default: CARB_LOG_ERROR("Invalid internal state while normalizing the path {%s}", getStringBuffer()); CARB_ASSERT(false); alreadyNormalized = false; continue; } resultPathTokens.emplace_back(prevTokenEnd, static_cast<size_t>(curTokenEnd - prevTokenEnd), curTokenType); } if (resultPathTokens.empty()) { constexpr static auto kDotChar_ = kDotChar; // CC-1110 return Path(Sanitized, std::string(&kDotChar_, 1)); } else if (resultPathTokens.back().type == NormalizePartType::Slash && resultPathTokens.size() > 1) { // Removing the trailing slash for special cases like "./" and "../" const size_t indexOfTokenBeforeSlash = resultPathTokens.size() - 2; const NormalizePartType typeOfTokenBeforeSlash = resultPathTokens[indexOfTokenBeforeSlash].type; if (typeOfTokenBeforeSlash == NormalizePartType::Dot || typeOfTokenBeforeSlash == NormalizePartType::DotDot) { resultPathTokens.pop_back(); alreadyNormalized = false; } } if (alreadyNormalized) { return *this; } size_t totalSize = 0; for (auto& token : resultPathTokens) totalSize += token.size; std::string joined; joined.reserve(totalSize); for (auto& token : resultPathTokens) joined.append(token.data, token.size); return Path(Sanitized, std::move(joined)); } inline bool Path::isAbsolute() const noexcept { #if CARB_POSIX return !isEmpty() && m_pathString[0] == kForwardSlashChar; #elif CARB_PLATFORM_WINDOWS // Drive root (D:/abc) case. This is the only position where : is allowed on windows. Checking for separator is // important, because D:temp.txt is a relative path on windows. const char* pathDataStart = m_pathString.data(); const size_t pathDataLength = getLength(); if (pathDataLength > 2 && pathDataStart[1] == kColonChar && pathDataStart[2] == kForwardSlashChar) return true; // Drive letter (D:) case if (pathDataLength == 2 && pathDataStart[1] == kColonChar) return true; // extended drive letter path (ie: prefixed with "//./D:"). if (pathDataLength > 4 && pathDataStart[0] == kForwardSlashChar && pathDataStart[1] == kForwardSlashChar && pathDataStart[2] == kDotChar && pathDataStart[3] == kForwardSlashChar) { // at least a drive name was specified. if (pathDataLength > 6 && pathDataStart[5] == kColonChar) { // a drive plus an absolute path was specified (ie: "//./d:/abc") => succeed. if (pathDataStart[6] == kForwardSlashChar) return true; // a drive and relative path was specified (ie: "//./d:temp.txt") => fail. We need to // specifically fail here because this path would also get picked up by the generic // special path check below and report success erroneously. else return false; } // requesting the full drive volume (ie: "//./d:") => report absolute to match behavior // in the "d:" case above. if (pathDataLength == 6 && pathDataStart[5] == kColonChar) return true; } // check for special paths. This includes all windows paths that begin with "\\" (converted // to Unix path separators for our purposes). This class of paths includes extended path // names (ie: prefixed with "\\?\"), device names (ie: prefixed with "\\.\"), physical drive // paths (ie: prefixed with "\\.\PhysicalDrive<n>"), removable media access (ie: "\\.\X:") // COM ports (ie: "\\.\COM*"), and UNC paths (ie: prefixed with "\\servername\sharename\"). // // Note that it is not necessarily sufficient to get absolute vs relative based solely on // the "//" prefix here without needing to dig further into the specific name used and what // it actually represents. For now, we'll just assume that device, drive, volume, and // port names will not be used here and treat it as a UNC path. Since all extended paths // and UNC paths must always be absolute, this should hold up at least for those. If a // path for a drive, volume, or device is actually passed in here, it will still be treated // as though it were an absolute path. The results of using such a path further may be // undefined however. if (pathDataLength > 2 && pathDataStart[0] == kForwardSlashChar && pathDataStart[1] == kForwardSlashChar && pathDataStart[2] != kForwardSlashChar) return true; return false; #else CARB_UNSUPPORTED_PLATFORM(); #endif } inline Path Path::getRelative(const Path& base) const noexcept { // checking if the operation is possible if (isAbsolute() != base.isAbsolute() || (!hasRootDirectory() && base.hasRootDirectory()) || getRootName() != base.getRootName()) { return {}; } PathTokenType curPathTokenType = PathTokenType::RootName; size_t curPathTokenEndOffset = _getRootDirectoryEndOffset(); const char* curPathTokenEnd = curPathTokenEndOffset == npos ? nullptr : m_pathString.data() + curPathTokenEndOffset; const char* curPathTokenStart = curPathTokenEnd; const char* curPathEnd = m_pathString.data() + m_pathString.length(); PathTokenType basePathTokenType = PathTokenType::RootName; size_t basePathTokenEndOffset = base._getRootDirectoryEndOffset(); const char* basePathTokenEnd = basePathTokenEndOffset == npos ? nullptr : base.m_pathString.data() + basePathTokenEndOffset; const char* basePathEnd = base.m_pathString.data() + base.m_pathString.length(); // finding the first mismatch for (;;) { curPathTokenStart = curPathTokenEnd; curPathTokenEnd = _getTokenEnd(curPathTokenEnd, curPathEnd, curPathTokenType); const char* baseTokenStart = basePathTokenEnd; basePathTokenEnd = _getTokenEnd(basePathTokenEnd, basePathEnd, basePathTokenType); if (!curPathTokenEnd || !basePathTokenEnd) { // Checking if both are null if (curPathTokenEnd == basePathTokenEnd) { constexpr static auto kDotChar_ = kDotChar; // CC-1110 return Path(Sanitized, std::string(&kDotChar_, 1)); } break; } if (curPathTokenType != basePathTokenType || !std::equal(curPathTokenStart, curPathTokenEnd, baseTokenStart, basePathTokenEnd)) { break; } } int requiredDotDotCount = 0; while (basePathTokenEnd) { if (basePathTokenType == PathTokenType::DotDot) { --requiredDotDotCount; } else if (basePathTokenType == PathTokenType::Name) { ++requiredDotDotCount; } basePathTokenEnd = _getTokenEnd(basePathTokenEnd, basePathEnd, basePathTokenType); } if (requiredDotDotCount < 0) { return {}; } if (requiredDotDotCount == 0 && !curPathTokenEnd) { constexpr static auto kDotChar_ = kDotChar; // CC-1110 return Path(Sanitized, std::string(&kDotChar_, 1)); } const size_t leftoverCurPathSymbols = curPathTokenEnd != nullptr ? curPathEnd - curPathTokenStart : 0; constexpr static char kDotDotString[] = ".."; constexpr static size_t kDotDotStrlen = CARB_COUNTOF(kDotDotString) - 1; const size_t requiredResultSize = ((1 /* '/' */) + (kDotDotStrlen)) * requiredDotDotCount + leftoverCurPathSymbols; Path result; result.m_pathString.reserve(requiredResultSize); if (requiredDotDotCount > 0) { result.m_pathString.append(kDotDotString, kDotDotStrlen); --requiredDotDotCount; for (int i = 0; i < requiredDotDotCount; ++i) { result.m_pathString.push_back(kForwardSlashChar); result.m_pathString.append(kDotDotString, kDotDotStrlen); } } bool needsSeparator = !result.m_pathString.empty(); while (curPathTokenEnd) { if (curPathTokenType != PathTokenType::Slash) { if (CARB_LIKELY(needsSeparator)) { result.m_pathString += kForwardSlashChar; } else { needsSeparator = true; } result.m_pathString.append(curPathTokenStart, curPathTokenEnd - curPathTokenStart); } curPathTokenStart = curPathTokenEnd; curPathTokenEnd = _getTokenEnd(curPathTokenEnd, curPathEnd, curPathTokenType); } return result; } } // namespace extras } // namespace carb
46,633
C
29.479739
120
0.599618
omniverse-code/kit/include/carb/extras/SharedMemory.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 Provides a helper class to manage a block of shared memory. */ #pragma once #include "../Defines.h" #include "../Framework.h" #include "../cpp/Optional.h" #include "../extras/ScopeExit.h" #include "../logging/Log.h" #include "../process/Util.h" #include "Base64.h" #include "StringSafe.h" #include "Unicode.h" #include <cstddef> #include <utility> #if CARB_POSIX # include <sys/file.h> # include <sys/mman.h> # include <sys/stat.h> # include <sys/syscall.h> # include <sys/types.h> # include <cerrno> # include <fcntl.h> # include <semaphore.h> # include <unistd.h> # if CARB_PLATFORM_LINUX # include <linux/limits.h> // NAME_MAX # elif CARB_PLATFORM_MACOS # include <sys/posix_shm.h> # endif #elif CARB_PLATFORM_WINDOWS # include "../CarbWindows.h" #endif /** Namespace for all low level Carbonite functionality. */ namespace carb { /** Common namespace for extra helper functions and classes. */ namespace extras { #if !defined(DOXYGEN_SHOULD_SKIP_THIS) namespace detail { # if CARB_POSIX constexpr int kAllReadWrite = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; inline constexpr const char* getGlobalSemaphoreName() { // Don't change this as it is completely ABI breaking to do so. return "/carbonite-sharedmemory"; } inline void probeSharedMemory() { // Probe with a shm_open() call prior to locking the mutex. If the object compiling this does not link librt.so // then an abort can happen below, but while we have the semaphore locked. Since this is a system-wide // semaphore, it can leave this code unable to run in the future. Run shm_open here to make sure that it is // available; if not, an abort will occur but not while we have the system-wide semaphore locked. shm_open("", 0, 0); } class NamedSemaphore { public: NamedSemaphore(const char* name, bool unlinkOnClose = false) : m_name(name), m_unlinkOnClose(unlinkOnClose) { m_sema = sem_open(name, O_CREAT, carb::extras::detail::kAllReadWrite, 1); CARB_FATAL_UNLESS(m_sema, "Failed to create/open shared semaphore {%d/%s}", errno, strerror(errno)); # if CARB_PLATFORM_LINUX // sem_open() is masked by umask(), so force the permissions with chmod(). // NOTE: This assumes that named semaphores are under /dev/shm and are prefixed with sem. This is not ideal, // but there does not appear to be any means to translate a sem_t* to a file descriptor (for fchmod()) // or a path. // NOTE: sem_open() is also affected by umask() on mac, but unfortunately semaphores on mac are not backed // by the filesystem and can therefore not have their permissions modified after creation. size_t len = m_name.length() + 12; char* buf = CARB_STACK_ALLOC(char, len + 1); extras::formatString(buf, len + 1, "/dev/shm/sem.%s", name + 1); // Skip leading / chmod(buf, detail::kAllReadWrite); # endif } ~NamedSemaphore() { int result = sem_close(m_sema); CARB_ASSERT(result == 0, "Failed to close sema {%d/%s}", errno, strerror(errno)); CARB_UNUSED(result); if (m_unlinkOnClose) { sem_unlink(m_name.c_str()); } } bool try_lock() { int val = CARB_RETRY_EINTR(sem_trywait(m_sema)); CARB_FATAL_UNLESS(val == 0 || errno == EAGAIN, "sem_trywait() failed {%d/%s}", errno, strerror(errno)); return val == 0; } void lock() { int result; # if CARB_PLATFORM_LINUX auto printMessage = [](const char* format, ...) { va_list args; char buffer[1024]; va_start(args, format); formatStringV(buffer, CARB_COUNTOF(buffer), format, args); va_end(args); if (g_carbLogFn && g_carbLogLevel <= logging::kLevelWarn) { CARB_LOG_WARN("%s", buffer); } else { fputs(buffer, stderr); } }; constexpr int32_t kTimeoutInSeconds = 5; struct timespec abstime; clock_gettime(CLOCK_REALTIME, &abstime); abstime.tv_sec += kTimeoutInSeconds; // Since these are global semaphores and a process can crash with them in a bad state, wait for a period of time // then log so that we have an entry of what's wrong. result = CARB_RETRY_EINTR(sem_timedwait(m_sema, &abstime)); CARB_FATAL_UNLESS(result == 0 || errno == ETIMEDOUT, "sem_timedwait() failed {%d/%s}", errno, strerror(errno)); if (result == -1 && errno == ETIMEDOUT) { printMessage( "Waiting on global named semaphore %s has taken more than 5 seconds. It may be in a stuck state. " "You may have to delete /dev/shm/sem.%s and restart the application.", m_name.c_str(), m_name.c_str() + 1); CARB_FATAL_UNLESS( CARB_RETRY_EINTR(sem_wait(m_sema)) == 0, "sem_wait() failed {%d/%s}", errno, strerror(errno)); } # elif CARB_PLATFORM_MACOS // mac doesn't support sem_timedwait() and doesn't offer any other named semaphore API // either. For now we'll just do a blocking wait to attempt to acquire the semaphore. // If needed, we can add support for the brief wait before warning of a potential hang // like linux does. It would go something along these lines: // * spawn a thread or schedule a task to send a SIGUSR2 signal to this thread after // the given timeout. // * start an infinite wait on this thread. // * if SIGUSR2 arrives on this thread and interrupts the infinite wait, print the // hang warning message then drop into another infinite wait like linux does. // // Spawning a new thread for each wait operation here is likely a little heavy handed // though, especially if there ends up being a lot of contention on this semaphore. // The alternative would be to have a single shared thread that could handle timeouts // for multiple other threads. result = CARB_RETRY_EINTR(sem_wait(m_sema)); // CC-641 to add hang detection CARB_FATAL_UNLESS(result == 0, "sem_timedwait() failed {%d/%s}", errno, strerror(errno)); # else CARB_UNSUPPORTED_PLATFORM(); # endif } void unlock() { CARB_FATAL_UNLESS(CARB_RETRY_EINTR(sem_post(m_sema)) == 0, "sem_post() failed {%d/%s}", errno, strerror(errno)); } CARB_PREVENT_COPY_AND_MOVE(NamedSemaphore); private: sem_t* m_sema; std::string m_name; bool m_unlinkOnClose; }; # endif } // namespace detail #endif /** A utility helper class to provide shared memory access to one or more processes. The shared * memory area is named so that it can be opened by another process or component using the same * name. Once created, views into the shared memory region can be created. Each successfully * created view will unmap the mapped region once the view object is deleted. This object and * any created view objects exist independently from each other - the ordering of destruction * of each does not matter. The shared memory region will exist in the system until the last * reference to it is released through destruction. * * A shared memory region must be mapped into a view before it can be accessed in memory. A * new view can be created with the createView() function as needed. As long as one SharedMemory * object still references the region, it can still be reopened by another call to open(). Each * view object maps the region to a different location in memory. The view's mapped address will * remain valid as long as the view object exists. Successfully creating a new view object * requires that the mapping was successful and that the mapped memory is valid. The view object * can be wrapped in a smart pointer such as std::unique_ptr<> if needed to manage its lifetime. * A view object should never be copied (byte-wise or otherwise). * * A view can also be created starting at non-zero offsets into the shared memory region. This * is useful for only mapping a small view of a very large shared memory region into the memory * space. Multiple views of the same shared memory region may be created simultaneously. * * When opening a shared memory region, an 'open token' must be acquired first. This token can * be retrieved from any other shared memory region object that either successfully created or * opened the region using getOpenToken(). This token can then be transmitted to any other * client through some means to be used to open the same region. The open token data can be * retrieved as a base64 encoded string for transmission to other processes. The target process * can then create its own local open token from the base64 string using the constructor for * SharedMemory::OpenToken. Open tokens can also be passed around within the same process or * through an existing shared memory region as needed by copying, moving, or assigning it to * another object. * * @note On Linux, this requires that the host app be linked with the "rt" and "pthread" system * libraries. This can be done by adding 'links { "rt", "pthread" }' to the premake script * or adding the "-lrt -lpthread" option to the build command line. */ class SharedMemory { public: /** An opaque token object used to open an existing SHM region or to retrieve from a newly * created SHM region to pass to another client to open it. A token is only valid if it * contains data for a shared memory region that is currently open. It will cause open() * to fail if it is not valid however. */ class OpenToken { public: /** Constructor: initializes an empty token. */ OpenToken() : m_data(nullptr), m_base64(nullptr), m_size(0) { } /** Constructor: creates a new open token from a base64 encoded string. * * @param[in] base64 A base64 encoded data blob containing the open token information. * This may be received through any means from another token. This * string must be null terminated. This may not be `nullptr` or an * empty string. * * @remarks This will create a new open token from a base64 encoded data blob received * from another open token. Both the base64 and decoded representations will * be stored. Only the base64 representation will be able to be retrieved * later. No validation will be done on the token data until it is passed to * SharedMemory::open(). */ OpenToken(const char* base64) : m_data(nullptr), m_base64(nullptr), m_size(0) { Base64 converter(Base64::Variant::eFilenameSafe); size_t size; size_t inSize; if (base64 == nullptr || base64[0] == 0) return; inSize = strlen(base64); m_base64 = new (std::nothrow) char[inSize + 1]; if (m_base64 != nullptr) memcpy(m_base64, base64, (inSize + 1) * sizeof(char)); size = converter.getDecodeOutputSize(inSize); m_data = new (std::nothrow) uint8_t[size]; if (m_data != nullptr) m_size = converter.decode(base64, inSize, m_data, size); } /** Copy constructor: copies an open token from another one. * * @param[in] token The open token to be copied. This does not necessarily need to * be a valid token. */ OpenToken(const OpenToken& token) : m_data(nullptr), m_base64(nullptr), m_size(0) { *this = token; } /** Move constructor: moves an open token from another one to this one. * * @param[inout] token The open token to be moved from. The data in this token will * be stolen into this object and the source token will be cleared * out. */ OpenToken(OpenToken&& token) : m_data(nullptr), m_base64(nullptr), m_size(0) { *this = std::move(token); } ~OpenToken() { clear(); } /** Validity check operator. * * @returns `true` if this object contains token data. * @returns `false` if this object was not successfully constructed or does not contain * any actual token data. */ explicit operator bool() const { return isValid(); } /** Validity check operator. * * @returns `true` if this object does not contain any token data. * @returns `false` if this object contains token data. * */ bool operator!() const { return !isValid(); } /** Token equality comparison operator. * * @param[in] token The token to compare this one to. * @returns `true` if the other token contains the same data this one does. * @returns `false` if the other token contains different data from this one. */ bool operator==(const OpenToken& token) const { if (m_size == 0 && token.m_size == 0) return true; if (m_size != token.m_size) return false; if (m_data == nullptr || token.m_data == nullptr) return false; return memcmp(m_data, token.m_data, m_size) == 0; } /** Token inequality comparison operator. * * @param[in] token The token to compare this one to. * @returns `true` if the other token contains different data from this one. * @returns `false` if the other token contains the same data this one does. */ bool operator!=(const OpenToken& token) const { return !(*this == token); } /** Copy assignment operator. * * @param[in] token The token to be copied. * @returns A reference to this object. */ OpenToken& operator=(const OpenToken& token) { if (this == &token) return *this; clear(); if (token.m_data == nullptr) return *this; m_data = new (std::nothrow) uint8_t[token.m_size]; if (m_data != nullptr) { memcpy(m_data, token.m_data, token.m_size); m_size = token.m_size; } return *this; } /** Move assignment operator. * * @param[inout] token The token to be moved from. This source object will have its * data token into this object, and the source will be cleared. * @returns A reference to this object. */ OpenToken& operator=(OpenToken&& token) { if (this == &token) return *this; clear(); m_size = token.m_size; m_data = token.m_data; m_base64 = token.m_base64; token.m_size = 0; token.m_data = nullptr; token.m_base64 = nullptr; return *this; } /** Retrieves the token data in base64 encoding. * * @returns The token data encoded as a base64 string. This will always be null * terminated. This token data string will be valid as long as this object * still exists. If the caller needs the data to persist, the returned * string must be copied. * @returns `nullptr` if this token doesn't contain any data or memory could not be * allocated to hold the base64 encoded string. */ const char* getBase64Token() { if (m_base64 != nullptr) return m_base64; if (m_size == 0) return nullptr; Base64 converter(Base64::Variant::eFilenameSafe); size_t size; size = converter.getEncodeOutputSize(m_size); m_base64 = new (std::nothrow) char[size]; if (m_base64 == nullptr) return nullptr; converter.encode(m_data, m_size, m_base64, size); return m_base64; } protected: /** Constructor: initializes a new token with a specific data block. * * @param[in] tokenData The data to be copied into the new token. This may not be * `nullptr`. * @param[in] size The size of the @p tokenData block in bytes. * @returns No return value. */ OpenToken(const void* tokenData, size_t size) : m_data(nullptr), m_base64(nullptr), m_size(0) { if (size == 0) return; m_data = new (std::nothrow) uint8_t[size]; if (m_data != nullptr) { memcpy(m_data, tokenData, size); m_size = size; } } /** Tests if this token is valid. * * @returns `true` if this token contains data. Returns `false` otherwise. */ bool isValid() const { return m_data != nullptr && m_size > 0; } /** Retrieves the specific token data from this object. * * @returns The token data contained in this object. */ uint8_t* getToken() const { return reinterpret_cast<uint8_t*>(m_data); } /** Retrieves the size in bytes of the token data in this object. * * @returns The size of the token data in bytes. Returns `0` if this object doesn't * contain any token data. */ size_t getSize() const { return m_size; } /** Clears the contents of this token object. * * @returns No return value. * * @remarks This clears out the contents of this object. Upon return, the token will * no longer be considered valid and can no longer be used to open an existing * shared memory object. */ void clear() { if (m_data != nullptr) delete[] m_data; if (m_base64 != nullptr) delete[] m_base64; m_size = 0; m_data = nullptr; m_base64 = nullptr; } /** The raw binary data for the token. This will be `nullptr` if the token does not * contain any data. */ uint8_t* m_data; /** The base64 encoded version of this token's data. This will be `nullptr` if no base64 * data has been retrieved from this object and it was created from a source other than * a base64 string. */ char* m_base64; /** The size of the binary data blob @ref m_data in bytes. */ size_t m_size; friend class SharedMemory; }; /** Flag to indicate that a unique region name should be generated from the given base name * in create(). This will allow the call to be more likely to succeed even if a region * with the same base name already exists in the system. Note that using this flag will * lead to a slightly longer open token being generated. */ static constexpr uint32_t fCreateMakeUnique = 0x00000001; /** * Flag to indicate that failure should not be reported as an error log. */ static constexpr uint32_t fQuiet = 0x00000002; /** * Flag to indicate that no mutexes should be locked during this operation. * @warning Use of this flag could have interprocess and thread safety issues! Use with utmost caution! * @note Currently only Linux is affected by this flag. */ static constexpr uint32_t fNoMutexLock = 0x00000004; /** Names for the different ways a mapping region can be created and accessed. */ enum class AccessMode { /** Use the default memory access mode for the mapping. When this is specified to create * a view, the same access permissions as were used when creating the shared memory * region will be used. For example, if the SHM region is created as read-only, creating * a view with the default memory access will also be read-only. The actual access mode * that was granted can be retrieved from the View::getAccessMode() function after the * view is created. */ eDefault, /** Open or access the shared memory area as read-only. This access mode cannot be used * to create a new SHM area. This can be used to create a view of any shared memory * region however. */ eReadOnly, /** Create, open, or access the shared memory area as read-write. This access mode must * be used when creating a new shared memory region. It may also be used when opening * a shared memory region, or creating a view of a shared memory region that was opened * as read-write. If this is used to create a view on a SHM region that was opened as * read-only, the creation will fail. */ eReadWrite, }; /** Constructor: initializes a new shared memory manager object. This will not point to any * block of memory. */ SharedMemory() { m_token = nullptr; m_access = AccessMode::eDefault; // collect the system page size and allocation granularity information. #if CARB_PLATFORM_WINDOWS m_handle.handleWin32 = nullptr; CARBWIN_SYSTEM_INFO si; GetSystemInfo((LPSYSTEM_INFO)&si); m_pageSize = si.dwPageSize; m_allocationGranularity = si.dwAllocationGranularity; #elif CARB_POSIX m_handle.handleFd = -1; m_refCount = SEM_FAILED; m_pageSize = getpagesize(); m_allocationGranularity = m_pageSize; #else CARB_UNSUPPORTED_PLATFORM(); #endif } ~SharedMemory() { close(); } //! Result from createOrOpen(). enum Result { eError, //!< An error occurred when attempting to create or open shared memory. eCreated, //!< The call to createOrOpen() created the shared memory by name. eOpened, //!< The call to createOrOpen() opened an existing shared memory by name. }; /** Creates a new shared memory region. * * @param[in] name The name to give to the new shared memory region. This may not be * `nullptr` or an empty string. This must not contain a slash ('/') or * backslash ('\') character and must generally consist of filename safe * ASCII characters. This will be used as the base name for the shared * memory region that is created. This should be shorter than 250 * characters for the most portable behavior. Longer names are allowed * but will be silently truncated to a platform specific limit. This * truncation may lead to unintentional failures if two region names * differ only by truncated characters. * @param[in] size The requested size of the shared memory region in bytes. This may be * any size. This will be silently rounded up to the next system * supported region size. Upon creation, getSize() may be used to * retrieve the actual size of the newly created region. * @param[in] flags Flags to control behavior of creating the new shared memory region. * This may be 0 for default behavior, or may be @ref fCreateMakeUnique * to indicate that the name specified in @p name should be made into a * more unique string so that creating a new region with the same base * name as another region is more likely to succeed (note that it may * still fail for a host of other reasons). This defaults to * @ref fCreateMakeUnique. * @returns `true` if the new shared memory region is successfully created. At this point, * new views to the region may be created with createView(). When this region is * no longer needed, it should be closed by either calling close() or by destroying * this object. This same region may be opened by another client by retrieving its * open token and passing that to the other client. * @returns `false` if the new shared memory region could not be created as a new region. This * can include failing because another shared memory region with the same name * already exists or that the name was invalid (ie: contained invalid characters). * @returns `false` if another shared memory region is currently open on this object. In this * case, close() must be called before attempting to create a new region. * * @remarks This creates a new shared memory region in the system. If successful, this new * region will be guaranteed to be different from all other shared memory regions * in the system. The new region will always be opened for read and write access. * New views into this shared memory region may be created upon successful creation * using createView(). Any created view object will remain valid even if this * object is closed or destroyed. Note however that other clients will only be * able to open this same shared memory region if are least one SharedMemory object * still has the region open in any process in the system. If all references to * the region are closed, all existing views to it will remain valid, but no new * clients will be able to open the same region by name. This is a useful way to * 'lock down' a shared memory region once all expected client(s) have successfully * opened it. * * @note On Linux it is possible to have region creation fail if the @ref fCreateMakeUnique * flag is not used because the region objects were leaked on the filesystem by another * potentially crashed process (or the region was never closed). This is also possible * on Windows, however instead of failing to create the region, an existing region will * be opened instead. In both cases, this will be detected as a failure since a new * unique region could not be created as expected. It is best practice to always use * the @ref fCreateMakeUnique flag here. Similarly, it is always best practice to * close all references to a region after all necessary views have been created if it * is intended to persist for the lifetime of the process. This will guarantee that * all references to the region get released when the process exits (regardless of * method). * * @note On Linux, some malware scanners such as rkhunter check for large shared memory * regions and flag them as potential root kits. It is best practice to use a * descriptive name for a shared memory region so that they can be easily dismissed * as not a problem in a malware report log. */ bool create(const char* name, size_t size, uint32_t flags = fCreateMakeUnique) { return createAndOrOpen(name, size, flags, false, true) == eCreated; } /** * Attempts to create a shared memory region, or if it could not be created, open an existing one by the same name. * * @see create() for more information. * * @note On Windows, the attempt to create or open is performed atomically within the operating system. On Linux, * however, this is not possible. Instead a first attempt is made to create the shared memory region, and if that * fails, an attempt is made to open the shared memory region. * * @note On Windows, if a mapping already exists under the given name and the requested @p size is larger than the * size of the existing mapping, the process to open the mapping is aborted and Result::eError is returned. On * Linux, if the requested @p size is larger than the size of the existing mapping, the mapping grows to accommodate * the requested @p size. It is not possible to grow an existing mapping on Windows. * * @param name The name of the shared memory region. @see create() for more information. * @param size The size of the shared memory region in bytes. @see create() for more information. If the region is * opened, this parameter has different behavior between Windows and Linux. See note above. * @param flags The flags provided to direct creation/opening of the shared memory region. @see create() for more * information. If the region was originally created by passing fCreateMakeUnique to create(), this function will * not be able to open the region as the name was decorated with a unique identifier. Instead use open() to open the * shared memory region using the OpenToken. * @returns A result for the operation. */ Result createOrOpen(const char* name, size_t size, uint32_t flags = 0) { return createAndOrOpen(name, size, flags, true, true); } /** * Opens a shared memory region by name. * * @note On Windows, if a mapping already exists under the given name and the requested @p size is larger than the * size of the existing mapping, the process to open the mapping is aborted and Result::eError is returned. On * Linux, if the requested @p size is larger than the size of the existing mapping, the mapping grows to accommodate * the requested @p size. It is not possible to grow an existing mapping on Windows. * * @param name The name of the shared memory region. @see create() for more information. * @param size The required size of the shared memory region. This parameter has different behavior on Windows and * Linux. See note above. * @param flags The flags provided to direct opening the shared memory region. * @returns `true` if the region was found by name and opened successfully; `false` otherwise. */ bool open(const char* name, size_t size, uint32_t flags = 0) { return createAndOrOpen(name, size, flags, true, false); } /** Opens a shared memory region by token. * * @param[in] openToken The open token to use when opening the shared memory region. This * token contains all the information required to correctly open and * map the same shared memory region. This open token is retrieved * from another SharedMemory object that has the region open. This * is retrieved with getOpenToken(). The token may be encoded into * a base64 string for transmission to another process (ie: over a * socket, pipe, environment variable, command line, etc). The * specific transmission method is left as an exercise for the * caller. Once received, a new open token object may be created * in the target process by passing the base64 string to the * OpenToken() constructor. * @param[in] access The access mode to open the shared memory region in. This will * default to @ref AccessMode::eReadWrite. * @returns `true` if the shared memory region is successfully opened with the requested * access permissions. Once successfully opened, new views may be created and the * open token may also be retrieved from here to pass on to yet another client. * Note that at least one SharedMemory object must still have the region open in * order for the region to be opened in another client with the same open token. * This object must either be closed with close() or destroyed in order to ensure * the region is destroyed properly once all views are unmapped. * @returns `false` if the region could not not be opened. This could include the open token * being invalid or corrupt, the given region no longer being present in the system, * or there being insufficient permission to access it from the calling process. */ bool open(const OpenToken& openToken, AccessMode access = AccessMode::eDefault) { OpenTokenImpl* token; SharedHandle handle; std::string mappingName; if (m_token != nullptr) { CARB_LOG_ERROR( "the previous SHM region has not been closed yet. Please close it before opening a new SHM region."); return false; } // not a valid open token => fail. if (!openToken.isValid()) return false; token = reinterpret_cast<OpenTokenImpl*>(openToken.getToken()); // make sure the token information seems valid. if (openToken.getSize() < offsetof(OpenTokenImpl, name) + token->nameLength + 1) return false; if (token->size == 0 || token->size % m_pageSize != 0) return false; if (access == AccessMode::eDefault) access = AccessMode::eReadWrite; token = reinterpret_cast<OpenTokenImpl*>(malloc(openToken.getSize())); if (token == nullptr) { CARB_LOG_ERROR("failed to allocate memory for the open token for this SHM region."); return false; } memcpy(token, openToken.getToken(), openToken.getSize()); mappingName = getPlatformMappingName(token->name); #if CARB_PLATFORM_WINDOWS std::wstring fname = carb::extras::convertUtf8ToWide(mappingName.c_str()); handle.handleWin32 = OpenFileMappingW(getAccessModeFlags(access, FlagType::eFileFlags), CARBWIN_FALSE, fname.c_str()); if (handle.handleWin32 == nullptr) { CARB_LOG_ERROR("failed to open a file mapping object with the name '%s' {error = %" PRIu32 "}", token->name, GetLastError()); free(token); return false; } #elif CARB_POSIX // create the reference count object. Note that this must already exist in the system // since we are expecting another process to have already created the region. if (!initRefCount(token->name, 0, true)) { CARB_LOG_ERROR("failed to create the reference count object with the name '%s'.", token->name); free(token); return false; } handle.handleFd = shm_open(mappingName.c_str(), getAccessModeFlags(access, FlagType::eFileFlags), 0); // failed to open the SHM region => fail. if (handle.handleFd == -1) { CARB_LOG_ERROR("failed to open or create file mapping object with the name '%s' {errno = %d/%s}", token->name, errno, strerror(errno)); destroyRefCount(token->name); free(token); return false; } #else CARB_UNSUPPORTED_PLATFORM(); #endif m_token = token; m_handle = handle; m_access = access; return true; } /** Represents a single mapped view into an open shared memory region. The region will * remain mapped in memory and valid as long as this object exists. When this view * object is destroyed, the region will be flushed and unmapped. All view objects are * still valid even after the shared memory object that created them have been closed * or destroyed. * * View objects may neither be copied nor manually constructed. They may however be * moved with either a move constructor or move assignment. Note that for safety * reasons, the moved view must be move assigned or move constructed immediately at * declaration time. This eliminates the possibility of an unmapped from being * acquired and prevents the need to check its validity at any given time. Once * moved, the original view object will no longer be valid and should be immediately * deleted. The moved view will not be unmapped by deleting the original view object. */ class View { public: /** Move constructor: moves another view object into this one. * * @param[in] view The other object to move into this one. */ View(View&& view) { m_address = view.m_address; m_size = view.m_size; m_offset = view.m_offset; m_pageOffset = view.m_pageOffset; m_access = view.m_access; view.init(); } ~View() { unmap(); } /** Move assignment operator: moves another object into this one. * * @param[in] view The other object to move into this one. * @returns A reference to this object. */ View& operator=(View&& view) { if (this == &view) return *this; unmap(); m_address = view.m_address; m_size = view.m_size; m_offset = view.m_offset; m_pageOffset = view.m_pageOffset; m_access = view.m_access; view.init(); return *this; } /** Retrieves the mapped address of this view. * * @returns The address of the mapped region. This region will extend from this address * through the following getSize() bytes minus 1. This address will always be * aligned to the system page size. */ void* getAddress() { return reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(m_address) + m_pageOffset); } /** Retrieves the size of this mapped view. * * @returns The total size in bytes of this mapped view. This region will extend from * the mapped address returned from getAddress(). This will always be aligned * to the system page size. This size represents the number of bytes that are * accessible in this view starting at the given offset (getOffset()) in the * original shared memory region. */ size_t getSize() const { return m_size; } /** Retrieves the offset of this view into the original mapping object. * * @returns The offset of this view in bytes into the original shared memory region. * This will always be aligned to the system page size. If this is 0, this * indicates that this view starts at the beginning of the shared memory * region that created it. If this is non-zero, this view only represents * a portion of the original shared memory region. */ size_t getOffset() const { return m_offset; } /** Retrieves the access mode that was used to create this view. * * @returns The access mode used to create this view. This will always be a valid memory * access mode and will never be @ref AccessMode::eDefault. This can be used * to determine what the granted permission to the view is after creation if it * originally asked for the @ref AccessMode::eDefault mode. */ AccessMode getAccessMode() const { return m_access; } protected: // prevent new empty local declarations from being default constructed so that we don't // need to worry about constantly checking for invalid views. /** Constructor: protected default constructor. * @remarks This initializes an empty view object. This is protected to prevent new * empty local declarations from being default constructed so that we don't * need to worry about constantly checking for invalid views. */ View() { init(); } // remove these constructors and operators to prevent multiple copies of the same view // from being created and copied. Doing so could cause other views to be invalidated // unintentionally if a mapping address is reused (which is common). View(const View&) = delete; View& operator=(const View&) = delete; View& operator=(const View*) = delete; /** Maps a view of a shared memory region into this object. * * @param[in] handle The handle to the open shared memory region. This must be a * valid handle to the region. * @param[in] offset The offset in bytes into the shared memory region where the * new mapped view should start. This must be aligned to the * system page size. * @param[in] size The size in bytes of the portion of the shared memory region * that should be mapped into the view. This must not extend * past the end of the original shared memory region once added * to the offset. This must be aligned to the system page size. * @param[in] access The requested memory access mode for the view. This must not * be @ref AccessMode::eDefault. This may not specify greater * permissions than the shared memory region itself allows (ie: * requesting read-write on a read-only shared memory region). * @param[in] allocGran The system allocation granularity in bytes. * @returns `true` if the new view is successfully mapped. * @returns `false` if the new view could not be mapped. */ bool map(SharedHandle handle, size_t offset, size_t size, AccessMode access, size_t allocGran) { void* mapPtr = nullptr; #if CARB_PLATFORM_WINDOWS size_t granOffset = offset & ~(allocGran - 1); m_pageOffset = offset - granOffset; mapPtr = MapViewOfFile(handle.handleWin32, getAccessModeFlags(access, FlagType::eFileFlags), static_cast<DWORD>(granOffset >> 32), static_cast<DWORD>(granOffset), static_cast<SIZE_T>(size + m_pageOffset)); if (mapPtr == nullptr) { CARB_LOG_ERROR( "failed to map %zu bytes from offset %zu {error = %" PRIu32 "}", size, offset, GetLastError()); return false; } #elif CARB_POSIX CARB_UNUSED(allocGran); m_pageOffset = 0; mapPtr = mmap( nullptr, size, getAccessModeFlags(access, FlagType::ePageFlags), MAP_SHARED, handle.handleFd, offset); if (mapPtr == MAP_FAILED) { CARB_LOG_ERROR( "failed to map %zu bytes from offset %zu {errno = %d/%s}", size, offset, errno, strerror(errno)); return false; } #else CARB_UNSUPPORTED_PLATFORM(); #endif m_address = mapPtr; m_size = size; m_offset = offset; m_access = access; return true; } /** Unmaps this view from memory. * * @returns No return value. * * @remarks This unmaps this view from memory. This should only be called on the * destruction of this object. */ void unmap() { if (m_address == nullptr) return; #if CARB_PLATFORM_WINDOWS if (UnmapViewOfFile(m_address) == CARBWIN_FALSE) CARB_LOG_ERROR("failed to unmap the region at %p {error = %" PRIu32 "}", m_address, GetLastError()); #elif CARB_POSIX if (munmap(m_address, m_size) == -1) CARB_LOG_ERROR("failed to unmap the region at %p {errno = %d/%s}", m_address, errno, strerror(errno)); #else CARB_UNSUPPORTED_PLATFORM(); #endif init(); } /** Initializes this object to an empty state. */ void init() { m_address = nullptr; m_size = 0; m_offset = 0; m_pageOffset = 0; m_access = AccessMode::eDefault; } void* m_address; ///< The mapped address of this view. size_t m_size; ///< The size of this view in bytes. size_t m_offset; ///< The offset of this view in bytes into the shared memory region. size_t m_pageOffset; ///< The page offset in bytes from the start of the mapping. AccessMode m_access; ///< The granted access permissions for this view. // The SharedMemory object that creates this view needs to be able to call into map(). friend class SharedMemory; }; /** Creates a new view into this shared memory region. * * @param[in] offset The offset in bytes into the shared memory region where this view * should start. This value should be aligned to the system page size. * If this is not aligned to the system page size, it will be aligned * to the start of the page that the requested offset is in. The actual * mapped offset can be retrieved from the new view object with * getOffset() if the view is successfully mapped. This defaults to 0 * bytes into the shared memory region (ie: the start of the region). * @param[in] size The number of bytes of the shared memory region starting at the * byte offset specified by @p offset to map into the new view. This * should be a multiple of the system page size. If it is not a * multiple of the system page size, it will be rounded up to the * next page size during the mapping. This size will also be clamped * to the size of the shared memory region (less the offset). This * may be 0 to indicate that the remainder of the region starting at * the given offset should be mapped into the new view. This defaults * to 0. * @param[in] access The access mode to use for the new view. This can be set to * @ref AccessMode::eDefault to use the same permissions as were * originally used to open the shared memory region. This will fail * if the requested mode attempts to grant greater permissions to the * shared memory region than were used to open it (ie: cannot create a * read-write view of a read-only shared memory region). This defaults * to @ref AccessMode::eDefault. * @returns A new view object representing the mapped view of the shared memory region. * This must be deleted when the mapped region is no longer needed. * @returns `nullptr` if the new view cannot be created or if an invalid set of parameters is * passed in. * * @remarks This creates a new view into this shared memory region. The default behavior * (with no parameters) is to map the entire shared memory region into the new view. * Multiple views into the same shared memory region can be created simultaneously. * It is safe to close the shared memory region or delete the object after a new * view is successfully created. In this case, the view object and the mapped * memory will still remain valid as long as the view object still exists. This * shared memory object can similarly also safely close and open a new region * while views on the previous region still exist. The previous region will only * be completely invalidated once all views are deleted and all other open * references to the region are closed. * * @note On Windows, the @p offset parameter should be additionally aligned to the system's * allocation granularity (ie: getSystemAllocationGranularity()). Under this object * however, this additional alignment requirement is handled internally so that page * alignment is provided to match Linux behavior. However, this does mean that * additional pages may be mapped into memory that are just transparently skipped by * the view object. When on Windows, it would be a best practice to align the view * offsets to a multiple of the system allocation granularity (usually 64KB) instead * of just the page size (usually 4KB). This larger offset granularity behavior * will also work properly on Linux. */ View* createView(size_t offset = 0, size_t size = 0, AccessMode access = AccessMode::eDefault) const { View* view; // no SHM region is open -> nothing to do => fail. if (m_token == nullptr) return nullptr; // the requested offset is beyond the region => fail. if (offset >= m_token->size) return nullptr; if (access == AccessMode::eDefault) access = m_access; // attempting to map a read/write region on a read-only mapping => fail. else if (access == AccessMode::eReadWrite && m_access == AccessMode::eReadOnly) return nullptr; offset = alignPageFloor(offset); if (size == 0) size = m_token->size; if (offset + size > m_token->size) size = m_token->size - offset; view = new (std::nothrow) View(); if (view == nullptr) return nullptr; if (!view->map(m_handle, offset, size, access, m_allocationGranularity)) { delete view; return nullptr; } return view; } /** Closes this shared memory region. * * @param forceUnlink @b Linux: If `true`, the shared memory region name is disassociated with the currently opened * shared memory. If the shared memory is referenced by other processes (or other SharedMemory objects) it * remains open and valid, but no additional SharedMemory instances will be able to open the same shared memory * region by name. Attempts to open the shared memory by name will fail, and attempts to create the shared memory * by name will create a new shared memory region. If `false`, the shared memory region will be unlinked when the * final SharedMemory object using it has closed. @b Windows: this parameter is ignored. * * @remarks This closes the currently open shared memory region on this object. This will * put the object back into a state where a new region can be opened. This call * will be ignored if no region is currently open. This region can be closed even * if views still exist on the current region. The existing views will not be * closed, invalidated, or unmapped by closing this shared memory region. * * @note The current region will be automatically closed when this object is deleted. */ void close(bool forceUnlink = false) { if (m_token == nullptr) return; #if CARB_PLATFORM_WINDOWS CARB_UNUSED(forceUnlink); if (m_handle.handleWin32 != nullptr) CloseHandle(m_handle.handleWin32); m_handle.handleWin32 = nullptr; #elif CARB_POSIX if (m_handle.handleFd != -1) ::close(m_handle.handleFd); m_handle.handleFd = -1; // check that all references to the SHM region have been released before unlinking // the named filesystem reference to it. The reference count semaphore can also // be unlinked from the filesystem at this point. if (releaseRef() || forceUnlink) { std::string mappingName = getPlatformMappingName(m_token->name); shm_unlink(mappingName.c_str()); destroyRefCount(m_token->name); } // close our local reference to the ref count semaphore. sem_close(m_refCount); m_refCount = SEM_FAILED; #else CARB_UNSUPPORTED_PLATFORM(); #endif free(m_token); m_token = nullptr; m_access = AccessMode::eDefault; } /** * Indicates whether the SharedMemory object is currently open or not. * * @returns `true` if the SharedMemory object has a region open; `false` otherwise. */ bool isOpen() const { return m_token != nullptr; } /** Retrieves the token used to open this same SHM region elsewhere. * * @returns The open token object. This token is valid as long as the SharedMemory object * that returned it has not been closed. If this object needs to persist, it should * be copied to a caller owned buffer. * @returns `nullptr` if no SHM region is currently open on this object. */ OpenToken getOpenToken() { if (m_token == nullptr) return OpenToken(); return OpenToken(m_token, offsetof(OpenTokenImpl, name) + m_token->nameLength + 1); } /** Retrieves the total size of the current shared memory region in bytes. * * @returns The size in bytes of the currently open shared memory region. Note that this * will be aligned to the system page size if the original value passed into the * open() call was not aligned. */ size_t getSize() const { if (m_token == nullptr) return 0; return m_token->size; } /** The maximum access mode allowed for the current shared memory region. * * @returns The memory access mode that the current shared memory region was created with. * This will never be @ref AccessMode::eDefault when this SHM region is valid. * @retval AccessMode::eDefault if no SHM region is currently open on this object. */ AccessMode getAccessMode() const { if (m_token == nullptr) return AccessMode::eDefault; return m_access; } /** Retrieves the system memory page size. * * @returns The size of the system's memory page size in bytes. */ size_t getSystemPageSize() const { return m_pageSize; } /** Retrieves the system allocation granularity. * * @returns The system's allocation granularity in bytes. */ size_t getSystemAllocationGranularity() const { return m_allocationGranularity; } private: /** An opaque token containing the information needed to open the SHM region that is created * here. Note that this structure is tightly packed to avoid having to transfer extra data * between clients. When a new token is returned, it will not include any extra padding * space at the end of the object. */ CARB_IGNOREWARNING_MSC_WITH_PUSH(4200) // nonstandard extension used: zero-sized array in struct/union #pragma pack(push, 1) struct OpenTokenImpl { /** The creation time size of the SHM region in bytes. Note that this is not strictly * needed on Windows since the size of a mapping object can be retrieved at any time * with NtQuerySection(). However, since that is an ntdll level function and has a * slim possibility of changing in a future Windows version, we'll just explicitly * pass over the creation time size when retrieving the token. */ size_t size; /** The length of the @a name string in characters. Note that this is limited to * 16 bits (ie: 65535 characters). This is a system imposed limit on all named * handle objects on Windows and is well beyond the supported length for filenames * on Linux. This is reduced in range to save space in the size of the tokens * that need to be transmitted to other clients that will open the same region. * Also note that this length is present in the token so that the token's size * can be validated for safety and correctness in open(). */ uint16_t nameLength; /** The name that was used to create the SHM region that will be opened using this * token. This will always be null terminated and will contain exactly the number * of characters specified in @a nameLength. */ char name[0]; }; #pragma pack(pop) CARB_IGNOREWARNING_MSC_POP /** Flags to indicate which type of flags to return from getAccessModeFlags(). */ enum class FlagType { eFileFlags, ///< Retrieve the file mapping flags. ePageFlags, ///< Retrieve the page protection flags. }; #if CARB_POSIX struct SemLockGuard { sem_t* mutex_; SemLockGuard(sem_t* mutex) : mutex_(mutex) { CARB_FATAL_UNLESS( CARB_RETRY_EINTR(sem_wait(mutex_)) == 0, "sem_wait() failed {errno = %d/%s}", errno, strerror(errno)); } ~SemLockGuard() { CARB_FATAL_UNLESS( CARB_RETRY_EINTR(sem_post(mutex_)) == 0, "sem_post() failed {errno = %d/%s}", errno, strerror(errno)); } }; #endif size_t alignPageCeiling(size_t size) const { size_t pageSize = getSystemPageSize(); return (size + (pageSize - 1)) & ~(pageSize - 1); } size_t alignPageFloor(size_t size) const { size_t pageSize = getSystemPageSize(); return size & ~(pageSize - 1); } std::string getPlatformMappingName(const char* name, size_t maxLength = 0) { std::string fname; #if CARB_PLATFORM_WINDOWS const char prefix[] = "Local\\"; // all named handle objects have a hard undocumented name length limit of 64KB. This is // due to all ntdll strings using a WORD value as the length in the UNICODE_STRING struct // that is always used for names at the ntdll level. Any names that are beyond this // limit get silently truncated and used as-is. This length limit includes the prefix. // Note that the name strings must still be null terminated even at the ntdll level. if (maxLength == 0) maxLength = (64 * 1024); #elif CARB_POSIX const char prefix[] = "/"; if (maxLength == 0) { # if CARB_PLATFORM_MACOS // Mac OS limits the SHM name to this. maxLength = PSHMNAMLEN; # else // This appears to be the specified length in POSIX. maxLength = NAME_MAX; # endif } #else CARB_UNSUPPORTED_PLATFORM(); #endif fname = std::string(prefix) + name; if (fname.length() > maxLength) { fname.erase(fname.begin() + maxLength, fname.end()); } return fname; } std::string makeUniqueName(const char* name) { std::string str = name; char buffer[256]; // create a unique name be appending the process ID and a random number to the given name. // This should be sufficiently unique for our purposes. This should only add 3-8 new // characters to the name. extras::formatString(buffer, CARB_COUNTOF(buffer), "%" OMNI_PRIxpid "-%x", this_process::getId(), rand()); return std::string(str + buffer); } static constexpr uint32_t getAccessModeFlags(AccessMode access, FlagType type) { switch (access) { default: case AccessMode::eDefault: case AccessMode::eReadWrite: #if CARB_PLATFORM_WINDOWS return type == FlagType::eFileFlags ? CARBWIN_FILE_MAP_ALL_ACCESS : CARBWIN_PAGE_READWRITE; #elif CARB_POSIX return type == FlagType::eFileFlags ? O_RDWR : (PROT_READ | PROT_WRITE); #else CARB_UNSUPPORTED_PLATFORM(); #endif case AccessMode::eReadOnly: #if CARB_PLATFORM_WINDOWS return type == FlagType::eFileFlags ? CARBWIN_FILE_MAP_READ : CARBWIN_PAGE_READONLY; #elif CARB_POSIX return type == FlagType::eFileFlags ? O_RDONLY : PROT_READ; #else CARB_UNSUPPORTED_PLATFORM(); #endif } } Result createAndOrOpen(const char* name, size_t size, uint32_t flags, bool tryOpen, bool tryCreate) { std::string mappingName; std::string rawName; size_t extraSize = 0; OpenTokenImpl* token; SharedHandle handle; bool quiet = !!(flags & fQuiet); /****** check for bad calls and bad parameters ******/ if (m_token != nullptr) { CARB_LOG_WARN( "the previous SHM region has not been closed yet. Please close it before creating a new SHM region."); return eError; } // a valid name is needed => fail. if (name == nullptr || name[0] == 0) return eError; // can't create a zero-sized SHM region => fail. if (size == 0) return eError; // neither create nor open => fail. if (!tryOpen && !tryCreate) return eError; /****** create the named mapping object ******/ bool const unique = (flags & fCreateMakeUnique) != 0; if (unique) rawName = makeUniqueName(name); else rawName = name; // get the platform-specific name for the region using the given name as a template. mappingName = getPlatformMappingName(rawName.c_str()); // make sure the mapping size is aligned to the next system page size. size = alignPageCeiling(size); // create the open token that will be used for other clients. extraSize = rawName.length(); token = reinterpret_cast<OpenTokenImpl*>(malloc(sizeof(OpenTokenImpl) + extraSize + 1)); if (token == nullptr) { if (!quiet) CARB_LOG_ERROR("failed to create a new open token for the SHM region '%s'.", name); return eError; } // store the token information. token->size = size; token->nameLength = extraSize & 0xffff; memcpy(token->name, rawName.c_str(), sizeof(name[0]) * (token->nameLength + 1)); #if CARB_PLATFORM_WINDOWS std::wstring fname = carb::extras::convertUtf8ToWide(mappingName.c_str()); if (!tryCreate) handle.handleWin32 = OpenFileMappingW(CARBWIN_PAGE_READWRITE, CARBWIN_FALSE, fname.c_str()); else handle.handleWin32 = CreateFileMappingW(CARBWIN_INVALID_HANDLE_VALUE, nullptr, CARBWIN_PAGE_READWRITE, static_cast<DWORD>(size >> 32), static_cast<DWORD>(size), fname.c_str()); // the handle was opened successfully => make sure it didn't open an existing object. if (handle.handleWin32 == nullptr || (!tryOpen && (GetLastError() == CARBWIN_ERROR_ALREADY_EXISTS))) { if (!quiet) CARB_LOG_ERROR("failed to create and/or open a file mapping object with the name '%s' {error = %" PRIu32 "}", name, GetLastError()); CloseHandle(handle.handleWin32); free(token); return eError; } bool const wasOpened = (GetLastError() == CARBWIN_ERROR_ALREADY_EXISTS); if (wasOpened) { // We need to use an undocumented function (NtQuerySection) to read the size of the mapping object. using PNtQuerySection = DWORD(__stdcall*)(HANDLE, int, PVOID, ULONG, PSIZE_T); static PNtQuerySection pNtQuerySection = (PNtQuerySection)::GetProcAddress(::GetModuleHandleW(L"ntdll.dll"), "NtQuerySection"); if (pNtQuerySection) { struct /*SECTION_BASIC_INFORMATION*/ { PVOID BaseAddress; ULONG AllocationAttributes; CARBWIN_LARGE_INTEGER MaximumSize; } sbi; SIZE_T read; if (pNtQuerySection(handle.handleWin32, 0 /*SectionBasicInformation*/, &sbi, sizeof(sbi), &read) >= 0) { if (size > (size_t)sbi.MaximumSize.QuadPart) { if (!quiet) CARB_LOG_ERROR("mapping with name '%s' was opened but existing size %" PRId64 " is smaller than requested size %zu", name, sbi.MaximumSize.QuadPart, size); CloseHandle(handle.handleWin32); free(token); return eError; } } } } #elif CARB_POSIX // See the function for an explanation of why this is needed. detail::probeSharedMemory(); // Lock a mutex (named semaphore) while we attempt to initialize the ref-count and shared memory objects. For // uniquely-named objects we use a per-process semaphore, but for globally-named objects we use a global mutex. cpp::optional<detail::NamedSemaphore> processMutex; cpp::optional<std::lock_guard<detail::NamedSemaphore>> lock; if (!(flags & fNoMutexLock)) { if (unique) { // Always get the current process ID since we could fork() and our process ID could change. // NOTE: Do not change this naming. Though PID is not a great unique identifier, it is considered an // ABI break to change this. std::string name = detail::getGlobalSemaphoreName(); name += '-'; name += std::to_string(this_process::getId()); processMutex.emplace(name.c_str(), true); lock.emplace(processMutex.value()); } else { lock.emplace(m_systemMutex); } } // create the reference count object. Note that we don't make sure it's unique in the // system because another process may have crashed or leaked it. if (!tryCreate || !initRefCount(token->name, O_CREAT | O_EXCL, !tryOpen && !quiet)) { // Couldn't create it exclusively. Something else must have created it, so just try to open existing. if (!tryOpen || !initRefCount(token->name, 0, !quiet)) { if (!quiet) CARB_LOG_ERROR( "failed to create/open the reference count object for the new region with the name '%s'.", token->name); free(token); return eError; } } handle.handleFd = tryCreate ? shm_open(mappingName.c_str(), O_RDWR | O_CREAT | O_EXCL, detail::kAllReadWrite) : -1; if (handle.handleFd != -1) { // We created the shared memory region. Since shm_open() is affected by the process umask, use fchmod() to // set the file permissions to all users. fchmod(handle.handleFd, detail::kAllReadWrite); } // failed to open the SHM region => fail. bool wasOpened = false; if (handle.handleFd == -1) { // Couldn't create exclusively. Perhaps it already exists to open. if (tryOpen) { handle.handleFd = shm_open(mappingName.c_str(), O_RDWR, 0); } if (handle.handleFd == -1) { if (!quiet) CARB_LOG_ERROR("failed to create/open SHM region '%s' {errno = %d/%s}", name, errno, strerror(errno)); destroyRefCount(token->name); free(token); return eError; } wasOpened = true; // If the region is too small, extend it while we have the semaphore locked. struct stat statbuf; if (fstat(handle.handleFd, &statbuf) == -1) { if (!quiet) CARB_LOG_ERROR("failed to stat SHM region '%s' {errno = %d, %s}", name, errno, strerror(errno)); ::close(handle.handleFd); free(token); return eError; } if (size > size_t(statbuf.st_size) && ftruncate(handle.handleFd, size) != 0) { if (!quiet) CARB_LOG_ERROR("failed to grow the size of the SHM region '%s' from %zu to %zu bytes {errno = %d/%s}", name, size_t(statbuf.st_size), size, errno, strerror(errno)); ::close(handle.handleFd); free(token); return eError; } } // set the size of the region by truncating the file while we have the semaphore locked. else if (ftruncate(handle.handleFd, size) != 0) { if (!quiet) CARB_LOG_ERROR("failed to set the size of the SHM region '%s' to %zu bytes {errno = %d/%s}", name, size, errno, strerror(errno)); ::close(handle.handleFd); shm_unlink(mappingName.c_str()); destroyRefCount(token->name); free(token); return eError; } #else CARB_UNSUPPORTED_PLATFORM(); #endif /****** save the values for the SHM region ******/ m_token = token; m_handle = handle; m_access = AccessMode::eReadWrite; return wasOpened ? eOpened : eCreated; } #if CARB_POSIX bool initRefCount(const char* name, int flags, bool logError) { // build the name for the semaphore. This needs to start with a slash followed by up to // 250 non-slash ASCII characters. This is the same format as for the SHM region, except // for the maximum length. The name given here will need to be truncated if it is very // long. The system adds "sem." to the name internally which explains why the limit is // not NAME_MAX. std::string mappingName = getPlatformMappingName(name, NAME_MAX - 4); // create the semaphore that will act as the IPC reference count for the SHM region. // Note that this will be created with an initial count of 0, not 1. This is intentional // since we want the last reference to fail the wait operation so that we can atomically // detect the case where the region's file (and the semaphore's) should be unlinked. m_refCount = sem_open(mappingName.c_str(), flags, detail::kAllReadWrite, 0); if (m_refCount == SEM_FAILED) { if (logError) { CARB_LOG_ERROR("failed to create or open a semaphore named \"%s\" {errno = %d/%s}", mappingName.c_str(), errno, strerror(errno)); } return false; } # if CARB_PLATFORM_LINUX else if (flags & O_CREAT) { // sem_open() is masked by umask(), so force the permissions with chmod(). // NOTE: This assumes that named semaphores are under /dev/shm and are prefixed with sem. This is not ideal, // but there does not appear to be any means to translate a sem_t* to a file descriptor (for fchmod()) or a // path. mappingName.replace(0, 1, "/dev/shm/sem."); chmod(mappingName.c_str(), detail::kAllReadWrite); } # endif // only add a new reference to the SHM region when opening the region, not when creating // it. This will cause the last reference to fail the wait in releaseRef() to allow us // to atomically detect the destruction case. if ((flags & O_CREAT) == 0) CARB_RETRY_EINTR(sem_post(m_refCount)); return true; } bool releaseRef() { int result; // waiting on the semaphore will decrement its count by one. When it reaches zero, the // wait will block. However since we're doing a 'try wait' here, that will fail with // errno set to EAGAIN instead of blocking. errno = -1; result = CARB_RETRY_EINTR(sem_trywait(m_refCount)); return (result == -1 && errno == EAGAIN); } void destroyRefCount(const char* name) { std::string mappingName; mappingName = getPlatformMappingName(name, NAME_MAX - 4); sem_unlink(mappingName.c_str()); } /** A semaphore used to handle a reference count to the SHM region itself. This will allow * the SHM region to only be unlinked from the file system once the reference count has * reached zero. This will leave the SHM region valid for other clients to open by name * as long as at least one client still has it open. * * @note This intentionally isn't used as mutex to protect access to a ref count in shared * memory since the semaphore would be necessary anyway in that situation, along with * wasting a full page of shared memory just to contain the ref count and semaphore * object. The semaphore itself already provides the required IPC safe counting * mechanism that we need here. */ sem_t* m_refCount; /** * A semaphore used as a system-wide shared mutex to synchronize the process of creating * ref-count objects and creating/opening existing shared memory objects. */ detail::NamedSemaphore m_systemMutex{ detail::getGlobalSemaphoreName() }; #endif /** The information block used to open this mapping object. This can be retrieved to * open the same SHM region elsewhere. */ OpenTokenImpl* m_token; /** The locally opened handle to the SHM region. */ SharedHandle m_handle; /** The original access mode used when the SHM region was created or opened. This will * dictate the maximum allowed access permissions when mapping views of the region. */ AccessMode m_access; /** The system page size in bytes. Note that this unfortunately cannot be a static member * because that would lead to either missing symbol or multiple definition link errors * depending on whether the symbol were also defined outside the class or not. We'll * just retrieve it on construction instead. */ size_t m_pageSize; /** The system allocation granularity in bytes. Note that this unfortunately cannot be * a static member because that would lead to either missing symbol or multiple * definition link errors depending on whether the symbol were also defined outside * the class or not. We'll just retrieve it on construction instead. */ size_t m_allocationGranularity; }; } // namespace extras } // namespace carb
77,319
C
42.316527
122
0.595533
omniverse-code/kit/include/carb/extras/WindowsPath.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 Carbonite Windows path utilities #pragma once #include "../Defines.h" #if CARB_PLATFORM_WINDOWS || defined(DOXYGEN_BUILD) # include "../CarbWindows.h" # include "../Error.h" # include "Unicode.h" # include <algorithm> # include <string> namespace carb { namespace extras { /** * (Windows only) Converts a UTF-8 file path to Windows system file path. * * Slashes are replaced with backslashes, and @ref fixWindowsPathPrefix() is called. * * @note Use of this function is discouraged. Use @ref carb::filesystem::IFileSystem for filesystem needs. * * @par Errors * Accessible via @ref carb::ErrorApi * * Note: Error state is not cleared on success * * @ref omni::core::kResultFail - UTF-8 to wide conversion failed * * @param path Input string to convert, in UTF-8 encoding. * @return Wide string containing Windows system file path or empty string if conversion cannot be performed. */ std::wstring convertCarboniteToWindowsPath(const std::string& path); /** * (Windows only) Converts Windows system file path to a UTF-8 file path. * * Backslashes are replaced with slashes and the long path prefix is removed if present. * * @note Use of this function is discouraged. Use @ref carb::filesystem::IFileSystem for filesystem needs. * * @par Errors * Accessible via @ref carb::ErrorApi * * Note: Error state is not cleared on success * * @ref omni::core::kResultFail - UTF-8 to wide conversion failed * * @param pathW Input string to convert, in Unicode (Windows native) encoding. * @return UTF-8 encoded file path or empty string if conversion cannot be performed. */ std::string convertWindowsToCarbonitePath(const std::wstring& pathW); /** * (Windows only) Performs fixup on a Windows file path by adding or removing the long path prefix as necessary. * * If the file path is too long and doesn't have long path prefix, the prefix is added. * If the file path is short and has long path prefix, the prefix is removed. * Otherwise, the path is not modified. * * @par Errors * Accessible via @ref carb::ErrorApi * * None * * @param pathW Input string to convert, in Unicode (Windows native) encoding. * @return Valid Windows system file path. */ std::wstring fixWindowsPathPrefix(const std::wstring& pathW); /** * (Windows only) Converts Windows path string into a canonical form. * * @note This uses Windows platform functions to canonicalize the path and is fairly costly. * * @par Errors * Accessible via @ref carb::ErrorApi * * Note: Error state is not cleared on success * * @ref omni::core::kResultFail - An error occurred * * @param pathW Windows system file path, in Unicode (Windows native) encoding. * @return The canonical form of the input path. If an error occurs, @p pathW is returned without modifications. In * order to determine if an error occurred, use @ref carb::ErrorApi. Since error state is not cleared on * success, clear the error state before calling this function if you wish to make sure that it succeeds. */ std::wstring getWindowsCanonicalPath(const std::wstring& pathW); /** * (Windows only) Retrieves the full path and file name of the specified file. * * If it's not possible, original path is returned. * * @par Errors * Accessible via @ref carb::ErrorApi * * Note: Error state is not cleared on success * * @ref omni::core::kResultFail - An error occurred * * Other errors may be reported based on the underlying platform calls * * @param pathW Windows system file path, in Unicode (Windows native) encoding. * @return The full path and file name of the input file. If an error occurs, @p pathW is returned without modification. * In order to determine if an error occurred, use @ref carb::ErrorApi. Since the error state is not cleared on * success, clear the error state before calling this function if you wish to make sure that it succeeds. */ std::wstring getWindowsFullPath(const std::wstring& pathW); /** * (Windows only) Sets the default DLL search directories for the application. * * This calls `SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)`. From the * <a * href="https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories">documentation</a> * this value is the combination of three separate values which comprise the recommended maximum number of directories * an application should include in its DLL search path: * * The application directory * * `%windows%\system32` * * User directories: any path explicitly added by `AddDllDirectory()` or `SetDllDirectory()`. * * See also: <a href="https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order">DLL Search * Order</a> * * @ref ErrorApi state is not changed by this function. */ void adjustWindowsDllSearchPaths(); // // Implementations // inline std::wstring convertCarboniteToWindowsPath(const std::string& path) { std::wstring pathW = convertUtf8ToWide(path); if (pathW == kUnicodeToWideFailure) { ErrorApi::instance().setError(kResultFail); return L""; } std::replace(pathW.begin(), pathW.end(), L'/', L'\\'); return fixWindowsPathPrefix(pathW); } inline std::string convertWindowsToCarbonitePath(const std::wstring& pathW) { bool hasPrefix = (pathW.compare(0, 4, L"\\\\?\\") == 0); std::string path = convertWideToUtf8(pathW.c_str() + (hasPrefix ? 4 : 0)); if (path == kUnicodeToUtf8Failure) { ErrorApi::instance().setError(kResultFail); return ""; } std::replace(path.begin(), path.end(), '\\', '/'); return path; } inline std::wstring fixWindowsPathPrefix(const std::wstring& pathW) { bool hasPrefix = (pathW.compare(0, 4, L"\\\\?\\") == 0); if (pathW.size() >= CARBWIN_MAX_PATH && !hasPrefix) { return L"\\\\?\\" + pathW; } if (pathW.size() < CARBWIN_MAX_PATH && hasPrefix) { return pathW.substr(4, pathW.size() - 4); } return pathW; } inline std::wstring getWindowsCanonicalPath(const std::wstring& pathW) { wchar_t* canonical = nullptr; auto hr = PathAllocCanonicalize(pathW.c_str(), CARBWIN_PATHCCH_ALLOW_LONG_PATHS, &canonical); if (CARBWIN_SUCCEEDED(hr)) { std::wstring result = canonical; LocalFree(canonical); return result; } ErrorApi::instance().setError( omni::core::kResultFail, omni::string{ omni::formatted, "PathAllocCanonicalize failed with HRESULT 0x%08x", hr }); return pathW; } inline std::wstring getWindowsFullPath(const std::wstring& pathW) { // Retrieve the size DWORD size = GetFullPathNameW(pathW.c_str(), 0, nullptr, nullptr); if (size != 0) { std::wstring fullPathName(size - 1, '\0'); size = GetFullPathNameW(pathW.c_str(), size, &fullPathName[0], nullptr); if (size) { // Assert if the Win32 API lied to us. Note that sometimes it does use less than asked for. CARB_ASSERT(size <= fullPathName.size()); fullPathName.resize(size); return fullPathName; } } ErrorApi::setFromWinApiErrorCode(); return pathW; } inline void adjustWindowsDllSearchPaths() { // MSDN: // https://docs.microsoft.com/en-us/windows/desktop/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories // LOAD_LIBRARY_SEARCH_DEFAULT_DIRS // This value is a combination of LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, and // LOAD_LIBRARY_SEARCH_USER_DIRS. SetDefaultDllDirectories(CARBWIN_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); } } // namespace extras } // namespace carb #endif
8,134
C
34.369565
133
0.701746
omniverse-code/kit/include/carb/extras/StringSafe.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 Wrappers for libc string functions to avoid dangerous edge cases. */ #pragma once // for vsnprintf() on windows #if !defined(_CRT_SECURE_NO_WARNINGS) && !defined(DOXYGEN_BUILD) # define _CRT_SECURE_NO_WARNINGS #endif #include "../Defines.h" #include "ScopeExit.h" #include <cstdarg> #include <cstdio> #include <cstring> // 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 pyerrors.h's badness here. As a service to // others, we'll also undefine pyerrors.h's `snprintf` symbol. #if defined(Py_ERRORS_H) && CARB_PLATFORM_WINDOWS # undef vsnprintf # undef snprintf #endif namespace carb { namespace extras { /** Compare two strings in a case sensitive manner. * * @param[in] str1 The first string to compare. This may not be `nullptr`. * @param[in] str2 The second string to compare. This may not be `nullptr`. * @returns `0` if the two strings match. * @returns A negative value if `str1` should be ordered before `str2`. * @returns A positive value if `str1` should be ordered after `str2`. */ inline int32_t compareStrings(const char* str1, const char* str2) { return strcmp(str1, str2); } /** Compare two strings in a case insensitive manner. * * @param[in] str1 The first string to compare. This may not be `nullptr`. * @param[in] str2 The second string to compare. This may not be `nullptr`. * @returns `0` if the two strings match. * @returns A negative value if `str1` should be ordered before `str2`. * @returns A positive value if `str1` should be ordered after `str2`. */ inline int32_t compareStringsNoCase(const char* str1, const char* str2) { #if CARB_PLATFORM_WINDOWS return _stricmp(str1, str2); #else return strcasecmp(str1, str2); #endif } /** * Check if two memory regions overlaps. * * @param[in] ptr1 pointer to a first memory region. * @param[in] size1 size in bytes of the first memory region. * @param[in] ptr2 pointer to a second memory region. * @param[in] size2 size in bytes of the second memory region. * * @return true if memory regions overlaps or false if they are not. */ inline bool isMemoryOverlap(const void* ptr1, size_t size1, const void* ptr2, size_t size2) { // We assume flat memory model. uintptr_t addr1 = uintptr_t(ptr1); uintptr_t addr2 = uintptr_t(ptr2); if (addr1 < addr2) { if (addr2 - addr1 >= size1) { return false; } } else if (addr1 > addr2) { if (addr1 - addr2 >= size2) { return false; } } return true; } /** * Copy a string with optional truncation. * * @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero). * @param[in] dstBufSize size in characters of the destination buffer. * @param[in] srcString pointer to a source string. * * @return a number of copied characters to the destination buffer (not including the trailing \0). * * @remark This function copies up to dstBufSize - 1 characters from the 0-terminated string srcString * to the buffer dstBuf and appends trailing \0 to the result. This function is guarantee that the result * has trailing \0 as long as dstBufSize is larger than 0. */ inline size_t copyStringSafe(char* dstBuf, size_t dstBufSize, const char* srcString) { CARB_ASSERT(dstBuf || dstBufSize == 0); CARB_ASSERT(srcString); if (dstBufSize > 0) { // Compute length of the source string to be copied. size_t copyLength = strlen(srcString); // Check the source and destination are not overlapped. CARB_ASSERT(!isMemoryOverlap(dstBuf, dstBufSize, srcString, copyLength + 1)); if (copyLength >= dstBufSize) { copyLength = dstBufSize - 1; memcpy(dstBuf, srcString, copyLength); } else if (copyLength > 0) { memcpy(dstBuf, srcString, copyLength); } dstBuf[copyLength] = '\0'; return copyLength; } return 0; } /** * Copy slice of string with optional truncation. * * @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero). * @param[in] dstBufSize size in characters of the destination buffer. * @param[in] srcString pointer to a source string (can be nullptr in the case if maxCharacterCount is zero). * @param[in] maxCharacterCount maximum number of characters to be copied from the source string. * * @return a number of copied characters to the destination buffer (not including the trailing \0). * * @remarks This function copies up to min(dstBufSize - 1, maxCharacterCount) characters from the source string * srcString to the buffer dstBuf and appends trailing \0 to the result. This function is guarantee that the result has * trailing \0 as long as dstBufSize is larger than 0. */ inline size_t copyStringSafe(char* dstBuf, size_t dstBufSize, const char* srcString, size_t maxCharacterCount) { CARB_ASSERT(dstBuf || dstBufSize == 0); CARB_ASSERT(srcString || maxCharacterCount == 0); // NOTE: We don't use strncpy_s in implementation even if it's available in the system because it places empty // string to the destination buffer in case of truncation of source string (see the detailed description at // https://en.cppreference.com/w/c/string/byte/strncpy). // Instead, we use always our own implementation which is tolerate to any case of truncation. if (dstBufSize > 0) { // Compute length of the source string slice to be copied. size_t copyLength = (maxCharacterCount > 0) ? strnlen(srcString, CARB_MIN(dstBufSize - 1, maxCharacterCount)) : 0; // Check the source and destination are not overlapped. CARB_ASSERT(!isMemoryOverlap(dstBuf, dstBufSize, srcString, copyLength)); if (copyLength > 0) { memcpy(dstBuf, srcString, copyLength); } dstBuf[copyLength] = '\0'; return copyLength; } return 0; } /** * A vsnprintf wrapper that clamps the return value. * * @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero). * @param[in] dstBufSize size in characters of the destination buffer. * @param[in] fmtString pointer to a format string (passed to the vsnprintf call). * @param[in] argsList arguments list * * @return a number of characters written to the destination buffer (not including the trailing \0). * * @remarks This function is intended to be used in code where an index is incremented by snprintf. * In the following example, if vsnprintf() were used, idx can become larger than * len, causing wraparound errors, but with formatStringV(), idx will never * become larger than len. * * idx += formatStringV(buf, len - idx, ...); * idx += formatStringV(buf, len - idx, ...); * */ inline size_t formatStringV(char* dstBuf, size_t dstBufSize, const char* fmtString, va_list argsList) { CARB_ASSERT(dstBuf || dstBufSize == 0); CARB_ASSERT(fmtString); if (dstBufSize > 0) { int rc = std::vsnprintf(dstBuf, dstBufSize, fmtString, argsList); size_t count = size_t(rc); if (rc < 0) { // We assume no output in a case of I/O error. dstBuf[0] = '\0'; count = 0; } else if (count >= dstBufSize) { // ANSI C always adds the null terminator, older MSVCRT versions do not. dstBuf[dstBufSize - 1] = '\0'; count = (dstBufSize - 1); } return count; } return 0; } /** * A snprintf wrapper that clamps the return value. * * @param[out] dstBuf pointer to a destination buffer (can be nullptr in the case if dstBufSize is zero). * @param[in] dstBufSize size in characters of the destination buffer. * @param[in] fmtString pointer to a format string (passed to the snprintf call). * * @return a number of characters written to the destination buffer (not including the trailing \0). * * @remarks This function is intended to be used in code where an index is incremented by snprintf. * In the following example, if snprintf() were used, idx can become larger than * len, causing wraparound errors, but with formatString(), idx will never * become larger than len. * * idx += formatString(buf, len - idx, ...); * idx += formatString(buf, len - idx, ...); * */ inline size_t formatString(char* dstBuf, size_t dstBufSize, const char* fmtString, ...) CARB_PRINTF_FUNCTION(3, 4); inline size_t formatString(char* dstBuf, size_t dstBufSize, const char* fmtString, ...) { size_t count; va_list argsList; va_start(argsList, fmtString); count = formatStringV(dstBuf, dstBufSize, fmtString, argsList); va_end(argsList); return count; } /** Test if one string is a prefix of the other. * @param[in] str The string to test. * @param[in] prefix The prefix to test on @p str. * @returns `true` if @p str begins with @p prefix. * @returns `false` otherwise. */ inline bool isStringPrefix(const char* str, const char* prefix) { for (size_t i = 0; prefix[i] != '\0'; i++) { if (str[i] != prefix[i]) { return false; } } return true; } /** * Formats as with vsnprintf() and calls a Callable with the result and the size. The memory for the string is managed * for the caller. * \details This function attempts to use the stack first but will fall back to the heap if the given \p fmt and * arguments do not fit on the stack. * \tparam StackSize The size of the stack buffer to reserve. The default is 256 characters. This amount includes the * NUL terminator. * \tparam Callable The type of callable that will be invoked with the formatted string and its size. The type should be * `void(const char*, size_t)`; any return type will be ignored. The size given will not include the NUL terminator. * \param fmt The `printf`-style format string. * \param ap The collection of variadic arguments as initialized by `va_start` or `va_copy`. * \param c The \c Callable that will be invoked after the string format. Any return value is ignored. It is undefined * behavior to use the pointer value passed to \p c after \p c returns. */ template <size_t StackSize = 256, class Callable> void withFormatNV(const char* fmt, va_list ap, Callable&& c) noexcept { char* heap = nullptr; char buffer[StackSize]; va_list ap2; va_copy(ap2, ap); CARB_SCOPE_EXIT { va_end(ap2); delete[] heap; }; constexpr static char kErrorFormat[] = "<vsnprintf failed>"; constexpr static char kErrorAlloc[] = "<failed to allocate>"; // Optimistically try to format char* pbuf = buffer; int isize = std::vsnprintf(pbuf, StackSize, fmt, ap); if (CARB_UNLIKELY(isize < 0)) { c(kErrorFormat, CARB_COUNTOF(kErrorFormat) - 1); return; } auto size = size_t(isize); if (size >= StackSize) { // Need the heap pbuf = heap = new (std::nothrow) char[size + 1]; if (CARB_UNLIKELY(!heap)) { c(kErrorAlloc, CARB_COUNTOF(kErrorAlloc) - 1); return; } isize = std::vsnprintf(pbuf, size + 1, fmt, ap2); if (CARB_UNLIKELY(isize < 0)) { c(kErrorFormat, CARB_COUNTOF(kErrorFormat) - 1); return; } size = size_t(isize); } c(const_cast<const char*>(pbuf), size); } /** * Formats as with vsnprintf() and calls a Callable with the result. The memory for the string is managed for the * caller. * \details This function attempts to use the stack first but will fall back to the heap if the given \p fmt and * arguments do not fit on the stack. * \tparam StackSize The size of the stack buffer to reserve. The default is 256 characters. This amount includes the * NUL terminator. * \tparam Callable The type of callable that will be invoked with the formatted string. The type should be * `void(const char*)`; any return type will be ignored. * \param fmt The `printf`-style format string. * \param ap The collection of variadic arguments as initialized by `va_start` or `va_copy`. * \param c The \c Callable that will be invoked after the string format. Any return value is ignored. It is undefined * behavior to use the pointer value passed to \p c after \p c returns. */ template <size_t StackSize = 256, class Callable> void withFormatV(const char* fmt, va_list ap, Callable&& c) { // Adapt to drop the size withFormatNV<StackSize>(fmt, ap, [&](const char* p, size_t) { c(p); }); } /** * @copydoc CARB_FORMATTED * \param size The size of the stack buffer to reserve. If the formatted string will be larger than this size, a buffer * will be created on the heap instead, and destroyed once the callable returns. */ #define CARB_FORMATTED_SIZE(size, fmt, ...) \ do \ { \ va_list CARB_JOIN(ap, __LINE__); \ va_start(CARB_JOIN(ap, __LINE__), fmt); \ CARB_SCOPE_EXIT \ { \ va_end(CARB_JOIN(ap, __LINE__)); \ }; \ ::carb::extras::withFormatV<size>((fmt), CARB_JOIN(ap, __LINE__), __VA_ARGS__); \ } while (0) /** * Formats a string as if by vsnprintf and invokes a callable with the result. * \details This macro constructs a `va_list`, gathers the variadic parameters with `va_start`, formats the string with * `std::vsnprintf`, and calls a Callable with the formatted string. This function reserves a stack buffer of the size * requested by \c size for \ref CARB_FORMATTED_SIZE or a default size for \ref CARB_FORMATTED, but if the formatted * string will not fit into that buffer, will use the heap to create a larger buffer. * \param fmt The `printf`-style format string. * \param ... A Callable that may be invoked as via `...(p)` where `p` is a `const char*`, such as a lambda, functor or * function pointer. Retaining and reading `p` after the Callable returns is undefined behavior. If an error occurs * with `std::vsnprintf` then `p` will be `<vsnprintf failed>`, or if a heap buffer was required and allocation * failed, then `p` will be `<failed to allocate>`. If you wish the callback to receive the length of the formatted * string as well, use \ref CARB_FORMATTED_N() or \ref CARB_FORMATTED_N_SIZE(). * \note This macro is intended to be used in variadic functions as a simple means of replacing uses of * `std::vsnprintf`. * ```cpp * void myLogFunction(const char* fmt, ...) { * CARB_FORMATTED([&](const char* p) { * log(p); * }); * } * ``` * \see CARB_FORMATTED(), CARB_FORMATTED_SIZE(), CARB_FORMATTED_N(), CARB_FORMATTED_N_SIZE(), * carb::extras::withFormatNV(), carb::extras::withFormatV() */ #define CARB_FORMATTED(fmt, ...) CARB_FORMATTED_SIZE(256, fmt, __VA_ARGS__) /** * @copydoc CARB_FORMATTED_N * \param size The size of the stack buffer to reserve. If the formatted string will be larger than this size, a buffer * will be created on the heap instead, and destroyed once the callable returns. */ #define CARB_FORMATTED_N_SIZE(size, fmt, ...) \ do \ { \ va_list CARB_JOIN(ap, __LINE__); \ va_start(CARB_JOIN(ap, __LINE__), fmt); \ CARB_SCOPE_EXIT \ { \ va_end(CARB_JOIN(ap, __LINE__)); \ }; \ ::carb::extras::withFormatNV<size>((fmt), CARB_JOIN(ap, __LINE__), __VA_ARGS__); \ } while (0) /** * Formats a string as if by vsnprintf and invokes a callable with the result and the length. * \details This macro constructs a `va_list`, gathers the variadic parameters with `va_start`, formats the string with * `std::vsnprintf`, and calls a Callable with the formatted string and length. This function reserves a stack buffer of * the size requested by \c size for \ref CARB_FORMATTED_N_SIZE or a default size for \ref CARB_FORMATTED_N, but if the * formatted string will not fit into the stack buffer, will use the heap to create a larger buffer. * \param fmt The `printf`-style format string. * \param ... A Callable that may be invoked as via `...(p, n)` (where `p` is a `const char*` and `n` is a `size_t`), * such as a lambda, functor or function pointer. Retaining and reading `p` after the Callable returns is undefined * behavior. If an error occurs with `std::vsnprintf` then `p` will be `<vsnprintf failed>`, or if a heap buffer was * required and allocation failed, then `p` will be `<failed to allocate>`. If you do not need the length provided to * the Callable, use \ref CARB_FORMATTED() or \ref CARB_FORMATTED_SIZE() instead. * \note This macro is intended to be used in variadic functions as a simple means of replacing uses of * `std::vsnprintf`. * ```cpp * void myLogFunction(const char* fmt, ...) { * CARB_FORMATTED_N([&](const char* p, size_t len) { * log(p, len); * }); * } * ``` */ #define CARB_FORMATTED_N(fmt, ...) CARB_FORMATTED_N_SIZE(256, fmt, __VA_ARGS__) } // namespace extras } // namespace carb
19,462
C
41.495633
122
0.605693
omniverse-code/kit/include/carb/math/Util.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 Carbonite math utility functions #pragma once #include "../cpp/Bit.h" #include "../Defines.h" #include <array> #if CARB_COMPILER_MSC extern "C" { unsigned char _BitScanReverse(unsigned long* _Index, unsigned long _Mask); unsigned char _BitScanReverse64(unsigned long* _Index, uint64_t _Mask); unsigned char _BitScanForward(unsigned long* _Index, unsigned long _Mask); unsigned char _BitScanForward64(unsigned long* _Index, uint64_t _Mask); } # pragma intrinsic(_BitScanReverse) # pragma intrinsic(_BitScanReverse64) # pragma intrinsic(_BitScanForward) # pragma intrinsic(_BitScanForward64) #elif CARB_COMPILER_GNUC #else CARB_UNSUPPORTED_PLATFORM(); #endif namespace carb { /** Namespace for various math helper functions. */ namespace math { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { // The Helper class is specialized by type and size since many intrinsics have different names for different sizes. This // allows implementation of a helper function in the Helper class for the minimum size supported. Since each size // inherits from the smaller size, the minimum supported size will be selected. This also means that even though a // function is implemented in the size==1 specialization, for instance, it must be understood that T may be larger than // size 1. template <class T, size_t Size = sizeof(T)> class Helper; // Specialization for functions where sizeof(T) >= 1 template <class T> class Helper<T, 1> { public: static_assert(std::numeric_limits<T>::is_specialized, "Requires numeric type"); using Signed = typename std::make_signed_t<T>; using Unsigned = typename std::make_unsigned_t<T>; static int numLeadingZeroBits(const T& val) { # if CARB_COMPILER_MSC unsigned long result; if (_BitScanReverse(&result, (unsigned long)(Unsigned)val)) return int((sizeof(T) * 8 - 1) - result); return int(sizeof(T) * 8); # else constexpr size_t BitDiff = 8 * (sizeof(unsigned int) - sizeof(T)); return val ? int(__builtin_clz((unsigned int)(Unsigned)val) - BitDiff) : int(sizeof(T) * 8); # endif } // BitScanForward implementation for 1-4 byte integers. static int bitScanForward(const T& val) { # if CARB_COMPILER_MSC unsigned long result; if (_BitScanForward(&result, (unsigned long)(Unsigned)val)) { // BitScanForward returns the bit position zero-indexed, but we want to return the bit index + 1 to allow // returning 0 to indicate that no bit is set return (int)(result + 1); } return 0; # else return __builtin_ffs((unsigned int)(Unsigned)val); # endif } // BitScanReverse implementation for 1-4 byte integers. static int bitScanReverse(const T& val) { # if CARB_COMPILER_MSC unsigned long result; if (_BitScanReverse(&result, (unsigned long)(Unsigned)val)) { // BitScanReverse returns the bit position zero-indexed, but we want to return the bit index + 1 to allow // returning 0 to indicate that no bit is set return (int)(result + 1); } return 0; # else // The most significant set bit is calculated from the total number of bits minus the number of leading zeroes return val ? int(int(sizeof(unsigned int) * 8) - __builtin_clz((unsigned int)(Unsigned)val)) : 0; # endif } }; // Specialization for functions where sizeof(T) >= 2 template <class T> class Helper<T, 2> : public Helper<T, 1> { public: using Base = Helper<T, 1>; using typename Base::Signed; using typename Base::Unsigned; }; // Specialization for functions where sizeof(T) >= 4 template <class T> class Helper<T, 4> : public Helper<T, 2> { public: using Base = Helper<T, 2>; using typename Base::Signed; using typename Base::Unsigned; }; // Specialization for functions where sizeof(T) >= 8 template <class T> class Helper<T, 8> : public Helper<T, 4> { public: using Base = Helper<T, 4>; using typename Base::Signed; using typename Base::Unsigned; static int numLeadingZeroBits(const T& val) { # if CARB_COMPILER_MSC unsigned long result; if (_BitScanReverse64(&result, (Unsigned)val)) return int((sizeof(T) * 8 - 1) - result); return int(sizeof(T) * 8); # else constexpr int BitDiff = int(8 * (sizeof(uint64_t) - sizeof(T))); static_assert(BitDiff == 0, "Unexpected size"); return val ? (__builtin_clzll((Unsigned)val) - BitDiff) : int(sizeof(T) * 8); # endif } // BitScanForward implementation for 8 byte integers static int bitScanForward(const T& val) { static_assert(sizeof(T) == sizeof(uint64_t), "Unexpected size"); # if CARB_COMPILER_MSC unsigned long result; if (_BitScanForward64(&result, (Unsigned)val)) { // BitScanForward returns the bit position zero-indexed, but we want to return the bit index + 1 to allow // returning 0 to indicate that no bit is set return (int)(result + 1); } return 0; # else return __builtin_ffsll((Unsigned)val); # endif } // BitScanReverse implementation for 8 byte integers static int bitScanReverse(const T& val) { static_assert(sizeof(T) == sizeof(uint64_t), "Unexpected size"); # if CARB_COMPILER_MSC unsigned long result; if (_BitScanReverse64(&result, (Unsigned)val)) { // BitScanReverse returns the bit position zero-indexed, but we want to return the bit index + 1 to allow // returning 0 to indicate that no bit is set return (int)(result + 1); } return 0; # else return val ? int(int(sizeof(uint64_t) * 8) - __builtin_clzll((Unsigned)val)) : 0; # endif } }; } // namespace detail #endif /** * Returns whether the given integer value is a power of two. * * @param[in] val The non-zero integer value. Negative numbers are treated as unsigned values. * @returns true if the integer value is a power of two; false otherwise. Undefined behavior arises if \p val is zero. */ template <class T> constexpr bool isPowerOf2(const T& val) { // must be an integer type static_assert(std::is_integral<T>::value, "Requires integer type"); CARB_ASSERT(val != 0); // 0 is undefined using Uns = typename std::make_unsigned_t<T>; return (Uns(val) & (Uns(val) - 1)) == 0; } /** * Returns the number of leading zero bits for an integer value. * * @param[in] val The integer value * @returns The number of most-significant zero bits. For a zero value, returns the number of bits for the type T. */ template <class T> int numLeadingZeroBits(const T& val) { // must be an integer type static_assert(std::is_integral<T>::value, "Requires integer type"); return detail::Helper<T>::numLeadingZeroBits(val); } /** * Searches an integer value from least significant bit to most significant bit for the first set (1) bit. * * @param[in] val The integer value * @return One plus the bit position of the first set bit, or zero if \p val is zero. */ template <class T> int bitScanForward(const T& val) { // must be an integer type static_assert(std::numeric_limits<T>::is_integer, "Requires integer type"); return detail::Helper<T>::bitScanForward(val); } /** * Searches an integer value from most significant bit to least significant bit for the first set (1) bit. * * @param[in] val The integer value * @return One plus the bit position of the first set bit, or zero if \p val is zero. */ template <class T> int bitScanReverse(const T& val) { // must be an integer type static_assert(std::numeric_limits<T>::is_integer, "Requires integer type"); return detail::Helper<T>::bitScanReverse(val); } /** * Returns the number of set (1) bits in an integer value. * * @param[in] val The integer value * @return The number of set (1) bits. */ template <class T> int popCount(const T& val) { // must be an integer type static_assert(std::numeric_limits<T>::is_integer, "Requires integer type"); return cpp::popcount(static_cast<typename std::make_unsigned_t<T>>(val)); } } // namespace math } // namespace carb
8,781
C
31.286765
120
0.664617
omniverse-code/kit/include/carb/cpp20/Semaphore.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 Redirection for backwards compatibility #pragma once #include "Atomic.h" #include "../cpp/Semaphore.h" CARB_FILE_DEPRECATED_MSG("Use carb/cpp include path and carb::cpp namespace instead") namespace carb { namespace cpp20 { using ::carb::cpp::binary_semaphore; using ::carb::cpp::counting_semaphore; } // namespace cpp20 } // namespace carb CARB_INCLUDE_PURIFY_TEST({ carb::cpp20::binary_semaphore sema1{ false }; carb::cpp20::counting_semaphore<128> sema2{ 0 }; CARB_UNUSED(sema1, sema2); });
968
C
26.685714
85
0.746901