### Installation and CMake Integration Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Instructions on how to integrate the RTXNTC-Library into your CMake project and link against the libntc library. ```APIDOC ## Installation and CMake Integration Add `RTXNTC-Library` as a CMake subdirectory and link against `libntc`. Include `` in C++ source files. ```cmake # CMakeLists.txt set(LIBNTC_BIN_DIRECTORY "${CMAKE_BINARY_DIR}/bin") add_subdirectory(path/to/RTXNTC-Library) target_link_libraries(my_app PRIVATE libntc) ``` ```cpp // main.cpp #include ``` ``` -------------------------------- ### Install Development Packages (Linux) Source: https://github.com/nvidia-rtx/rtxntc/blob/main/README.md Installs necessary development packages for building the RTXNTC SDK on Debian-based Linux distributions. ```sh sudo apt-get update sudo apt-get install build-essential cmake libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev ``` -------------------------------- ### Shader Compilation Setup Source: https://github.com/nvidia-rtx/rtxntc/blob/main/samples/renderer/CMakeLists.txt Defines shader source files, output directory, and expected byproducts for compilation. Includes common headers and configuration files. ```cmake include(${CMAKE_SOURCE_DIR}/external/donut/compileshaders.cmake) set(shader_sources ForwardShadingCommon.hlsli LegacyForwardShadingPass.hlsl NtcForwardShadingPass_CoopVec.slang NtcForwardShadingPass.hlsl ForwardShadingPassFeedback.hlsl ) set(shader_output_dir "${CMAKE_CURRENT_BINARY_DIR}/compiled_shaders") set(shader_outputs NtcForwardShadingPass LegacyForwardShadingPass ForwardShadingPassFeedback) set(shader_outputs_coopvec_dxil NtcForwardShadingPass_CoopVec.dxil.h) set(shader_outputs_coopvec_spirv NtcForwardShadingPass_CoopVec.spirv.h) set(libntc_include_directory "${CMAKE_SOURCE_DIR}/libraries/RTXNTC-Library/include") set(libstf_include_directory "${CMAKE_SOURCE_DIR}/libraries/RTXTF-Library") ``` -------------------------------- ### Install LibNTC with CMake Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Installation.md Use this CMake snippet to add LibNTC as a subdirectory and link it to your target. Ensure LIB_NTC_BIN_DIRECTORY is set correctly. ```cmake set(LIBNTC_BIN_DIRECTORY "/path/to/your/build/output") add_subdirectory(path/to/RTXNTC-Library) target_link_libraries( PRIVATE libntc) ``` -------------------------------- ### Example NTC Manifest File Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/Manifest.md This JSON structure defines a manifest for a texture set, including diffuse, normal, and roughness maps with specified compression formats and semantic labels. ```json { "textures": [ { "fileName": "PavingStones070_4K.diffuse.tga", "name": "Diffuse", "bcFormat": "BC7", "isSRGB": true, "semantics": { "Albedo": "RGB" } }, { "fileName": "PavingStones070_4K.normal.tga", "name": "Normal", "bcFormat": "BC7", "semantics": { "Normal": "RGB" } }, { "fileName": "PavingStones070_4K.roughness.tga", "name": "Roughness", "bcFormat": "BC4", "semantics": { "Roughness": "R" } } ] } ``` -------------------------------- ### Build RTXNTC SDK with CMake (Linux) Source: https://github.com/nvidia-rtx/rtxntc/blob/main/README.md Steps to build the RTXNTC SDK on Linux using CMake and make. Ensure you have the necessary development packages installed. ```sh mkdir build && cd build cmake .. make -j ``` -------------------------------- ### Convert glTF Materials with Adaptive Compression Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/Renderer.md Use this command for adaptive compression of glTF materials to NTC format, targeting a specific Peak Signal-to-Noise Ratio (PSNR). Ensure Python 3.11 and Pillow are installed, and set the NTC_SDK_PATH environment variable. ```sh # Alternatively, for adaptive compression use: python $NTC_SDK_PATH/support/tools/convert_gltf_materials.py FlightHelmet.gltf --targetPsnr 35.0 --output . ``` -------------------------------- ### Begin and Run Compression Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md Initiate the compression process using `BeginCompression` with optional `CompressionSettings`. Subsequently, repeatedly call `RunCompressionSteps` to perform the compression, checking the status until completion. ```c++ // Default values are OK; these affect training speed and quality. ntc::CompressionSettings settings; ntc::Status ntcStatus = textureSet->BeginCompression(settings); if (ntcStatus != ntc::Status::Ok) // Handle the error. ntc::CompressionStats stats; do { ntcStatus = textureSet->RunCompressionSteps(&stats); if (ntcStatus == ntc::Status::Incomplete || ntcStatus == ntc::Status::Ok) // Provide a progress report to the user. } while (ntcStatus == ntc::Status::Incomplete); if (ntcStatus != ntc::Status::Ok) // Handle the error. ntcStatus = textureSet->FinalizeCompression(); if (ntcStatus != ntc::Status::Ok) // Handle the error here as well. ``` -------------------------------- ### Display BCTest Help Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/BCTest.md Prints the full set of command line options available for BCTest. ```sh bctest --help ``` -------------------------------- ### Retrieve Final Compressed Data Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md After the compression loop, get the index of the optimal run and access the corresponding compressed data. ```c++ int const finalIndex = session->GetIndexOfFinalRun(); std::vector const& finalCompressedData = compressedVersions[finalIndex]; ``` -------------------------------- ### Get BC7 Mode Buffer Footprint Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/BlockCompression.md Use `ITextureMetadata::GetBC7ModeBufferFootprint` to understand how the mode buffer is stored, whether compressed or uncompressed. ```cpp int mipLevel = 0; auto footprint = textureMetadata.GetBC7ModeBufferFootprint(mipLevel); // footprint.isCompressed indicates if GDeflate was used. ``` -------------------------------- ### Initialize Adaptive Compression Session Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md Reset the session with target PSNR and maximum bits per pixel parameters. ```c++ session->Reset(targetPsnr, maxBitsPerPixel); ``` -------------------------------- ### Create Texture Set and Write Channels Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Create a texture set, define per-texture metadata, and upload pixel data before initiating compression. Ensure correct channel mapping and pixel format are specified. ```cpp ntc::TextureSetWrapper textureSet(context); ntc::TextureSetDesc desc; desc.width = 2048; desc.height = 2048; desc.channels = 8; // e.g. albedo(3) + normal(2) + rough(1) + metal(1) + AO(1) desc.mips = 1; ntc::TextureSetFeatures features; // defaults are fine ntc::Status status = context->CreateTextureSet(desc, features, textureSet.ptr()); // Register albedo texture at channels 0-2 ntc::ITextureMetadata* albedoMeta = textureSet->AddTexture(); albedoMeta->SetName("Albedo"); albedoMeta->SetChannels(0, 3); albedoMeta->SetPixelFormat(ntc::PixelFormat::BC7); albedoMeta->SetRgbColorSpace(ntc::ColorSpace::sRGB); albedoMeta->SetAlphaColorSpace(ntc::ColorSpace::Linear); ntc::WriteChannelsParameters wp{}; wp.mipLevel = 0; wp.firstChannel = 0; wp.numChannels = 3; wp.pData = albedoPixels; // uint8_t* RGBA pixels wp.addressSpace = ntc::AddressSpace::Host; wp.width = 2048; wp.height = 2048; wp.pixelStride = 3; wp.rowPitch = 2048 * 3; wp.channelFormat = ntc::PixelFormat::UNORM8; ntc::ColorSpace cs[4] = { ntc::ColorSpace::sRGB, ntc::ColorSpace::sRGB, ntc::ColorSpace::sRGB, ntc::ColorSpace::Linear }; wp.srcColorSpaces = cs; wp.dstColorSpaces = cs; status = textureSet->WriteChannels(wp); if (status != ntc::Status::Ok) fprintf(stderr, "WriteChannels: %s\n", ntc::GetLastErrorMessage()); ``` -------------------------------- ### Upload Latent Data to Texture Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/InferenceOnLoad.md Iterate through mip levels and layers to get footprint information, read data from the NTC file, decompress if necessary, and upload to the GPU texture. ```c++ for (int mipLevel = 0; mipLevel < latentTextureDescSrc.mipLevels; ++mipLevel) { for (int layerIndex = 0; layerIndex < latentTextureDescSrc.arraySize; ++layerIndex) { ntc::LatentTextureFootprint footprint; ntc::Status ntcStatus = textureSetMetadata->GetLatentTextureFootprint(mipLevel, layerIndex, footprint); if (ntcStatus != ntc::Status::Ok) // Handle the error. std::vector latentData; latentData.resize(footprint.buffer.rangeInStream.size); if (!ntcFile->Seek(footprint.buffer.rangeInStream.offset) || !ntcFile->Read(latentData.data(), latentData.size())) // Handle the error. // If the latent data is compressed, decompress it first. if (footprint.buffer.compressionType != ntc::CompressionType::None) { srd::vector decompressedData; decompressedData.resize(footprint.buffer.uncompressedSize); ntcStatus = ntcContext->DecompressBuffer( footprint.buffer.compressionType, latentData.data(), latentData.size(), decompressedData.data(), decompressedData.size(), footprint.buffer.uncompressedCrc32); if (ntcStatus != ntc::Status::Ok) // Handle the error. latentData = std::move(decompressedData); } // ... Upload the data from 'latentData' into the texture at 'mipLevel' and 'layerIndex', // with 'footprint.rowPitch' bytes in each row - API/engine dependent ... } } ``` -------------------------------- ### Create Adaptive Compression Session Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md Instantiate and create the adaptive compression session object using the provided context. ```c++ AdaptiveCompressionSessionWrapper session(context); ntcStatus = context->CreateAdaptiveCompressionSession(session.ptr()); if (ntcStatus != ntc::Status::Ok) // Handle the error. ``` -------------------------------- ### List Vulkan Adapters Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/CommandLineTool.md Lists available graphics adapters compatible with Vulkan. ```sh ntc-cli --listAdapters --vk ``` -------------------------------- ### IAdaptiveCompressionSession Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Facilitates adaptive compression by finding the minimum bits per pixel (BPP) required to achieve a target Peak Signal-to-Noise Ratio (PSNR). It guides the compression process through multiple iterations. ```APIDOC ## `IAdaptiveCompressionSession` — Adaptive Compression (Target PSNR) Find the minimum BPP that achieves a target PSNR by running multiple compression iterations under library guidance. ```cpp ntc::AdaptiveCompressionSessionWrapper session(context); context->CreateAdaptiveCompressionSession(session.ptr()); float targetPsnr = 42.0f; // dB float maxBpp = 10.0f; session->Reset(targetPsnr, maxBpp); std::vector> candidates; while (!session->Finished()) { float bpp; ntc::LatentShape shape; session->GetCurrentPreset(&bpp, &shape); textureSet->SetLatentShape(shape); // Run compression (BeginCompression/RunCompressionSteps/FinalizeCompression) float achievedPsnr = RunCompression(textureSet); // Serialize result to memory size_t sz = textureSet->GetOutputStreamSize(); candidates.emplace_back(sz); textureSet->SaveToMemory(candidates.back().data(), &sz); candidates.back().resize(sz); session->Next(achievedPsnr); } int best = session->GetIndexOfFinalRun(); // candidates[best] is the optimal compressed representation ``` ``` -------------------------------- ### Loading Textures for Compression Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Create a texture set, define per-texture metadata, and upload pixel data before kicking off compression. ```APIDOC ## `IContext::CreateTextureSet` + `ITextureSet::WriteChannels` — Loading Textures for Compression Create a texture set, define per-texture metadata, and upload pixel data before kicking off compression. ```cpp ntc::TextureSetWrapper textureSet(context); ntc::TextureSetDesc desc; desc.width = 2048; desc.height = 2048; desc.channels = 8; // e.g. albedo(3) + normal(2) + rough(1) + metal(1) + AO(1) desc.mips = 1; ntc::TextureSetFeatures features; // defaults are fine ntc::Status status = context->CreateTextureSet(desc, features, textureSet.ptr()); // Register albedo texture at channels 0-2 ntc::ITextureMetadata* albedoMeta = textureSet->AddTexture(); albedoMeta->SetName("Albedo"); albedoMeta->SetChannels(0, 3); albedoMeta->SetPixelFormat(ntc::PixelFormat::BC7); albedoMeta->SetRgbColorSpace(ntc::ColorSpace::sRGB); albedoMeta->SetAlphaColorSpace(ntc::ColorSpace::Linear); ntc::WriteChannelsParameters wp{}; wp.mipLevel = 0; wp.firstChannel = 0; wp.numChannels = 3; wp.pData = albedoPixels; // uint8_t* RGBA pixels wp.addressSpace = ntc::AddressSpace::Host; wp.width = 2048; wp.height = 2048; wp.pixelStride = 3; wp.rowPitch = 2048 * 3; wp.channelFormat = ntc::PixelFormat::UNORM8; ntc::ColorSpace cs[4] = { ntc::ColorSpace::sRGB, ntc::ColorSpace::sRGB, ntc::ColorSpace::sRGB, ntc::ColorSpace::Linear }; wp.srcColorSpaces = cs; wp.dstColorSpaces = cs; status = textureSet->WriteChannels(wp); if (status != ntc::Status::Ok) fprintf(stderr, "WriteChannels: %s\n", ntc::GetLastErrorMessage()); ``` ``` -------------------------------- ### Convert glTF Materials with Fixed BPP Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/Renderer.md Use this command to convert glTF materials to NTC format with a fixed bits per pixel for compression quality. Ensure Python 3.11 and Pillow are installed, and set the NTC_SDK_PATH environment variable. ```sh # For compression with a fixed BPP use: python $NTC_SDK_PATH/support/tools/convert_gltf_materials.py FlightHelmet.gltf --bitsPerPixel 5.0 --output . ``` -------------------------------- ### Create Vulkan NTC Context with Cooperative Vector Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Initialize an NTC context for Vulkan, enabling GPU decompression and optionally Cooperative Vector hardware extensions for improved performance on compatible GPUs. ```cpp ntc::ContextParameters vkParams; vkParams.graphicsApi = ntc::GraphicsAPI::Vulkan; vkParams.vkInstance = vkInstance; vkParams.vkPhysicalDevice = vkPhysicalDevice; vkParams.vkDevice = vkDevice; vkParams.enableCooperativeVector = true; // opt-in to CoopVec ntc::IContext* vkContext = nullptr; ntc::Status vkStatus = ntc::CreateContext(&vkContext, vkParams); // CudaUnavailable is non-fatal: context works for decompression only if (vkStatus != ntc::Status::Ok && vkStatus != ntc::Status::CudaUnavailable) fprintf(stderr, "Error: %s\n", ntc::GetLastErrorMessage()); ``` -------------------------------- ### List DirectX 12 Adapters Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/CommandLineTool.md Lists available graphics adapters compatible with DirectX 12. ```sh ntc-cli --listAdapters --dx12 ``` -------------------------------- ### Create Basic CUDA Context for Compression Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Context.md Use this snippet to create a fundamental CUDA context for compression tasks. Ensure error handling is implemented for the `CreateContext` call. ```c++ ntc::IContext* context = nullptr; ntc::ContextParameters contextParams; ntc::Status ntcStatus = ntc::CreateContext(&context, contextParams); if (ntcStatus != ntc::Status::Ok) { /* Handle the error */ } ``` -------------------------------- ### Project Configuration Source: https://github.com/nvidia-rtx/rtxntc/blob/main/samples/renderer/CMakeLists.txt Defines the project name, description, and programming language. Sets C++ standard to C++17 and enforces its usage. ```cmake project( ntc-renderer DESCRIPTION "Neural Texture Compression Scene Renderer" LANGUAGES CXX ) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) ``` -------------------------------- ### Run Renderer with glTF Model Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/Renderer.md Execute the renderer by providing the path to a processed glTF model as a command-line argument. This command initiates the rendering process. ```sh ntc-renderer ``` -------------------------------- ### Adaptive Compression Loop Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md Iterate through compression runs, obtaining settings, compressing, serializing, and updating the session with PSNR results. ```c++ std::vector> compressedVersions; while (!session->Finished()) { // Obtain the current compression settings from the session float bpp; LatentShape latentShape; session->GetCurrentPreset(&bpp, &latentShape); // Resize the latents in the texture set. // The texture set needs some latent shape when it is created, // but when doing adaptive compression, that shape doesn't matter. ntcStatus = textureSet->SetLatentShape(latentShape); if (ntcStatus != ntc::Status::Ok) // Handle the error. // Perform compression on textureSet and obtain PSNR. // Implementation details omitted here, see the Compression section above. float psnr; CompressTextureSet(textureSet, &psnr); // Serialize the texture set into 'compressedData' std::vector compressedData; size_t bufferSize = textureSet->GetOutputStreamSize(); compressedData.resize(bufferSize); ntcStatus = textureSet->SaveToMemory(compressedData.data(), &bufferSize); if (ntcStatus != ntc::Status::Ok) // Handle the error. // Trim the buffer to the actual size of the saved data compressedData.resize(bufferSize); // Save the compressed data for later use compressedVersions.push_back(serializedData); // Pass the PSNR from the current compression run to the session and let it decide the next step session->Next(psnr); } ``` -------------------------------- ### Create Context Supporting Graphics Operations (Vulkan/DX12) Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Context.md This snippet demonstrates creating a context that supports graphics operations. It includes conditional logic for Vulkan and Direct3D 12, and allows for optional configuration of Cooperative Vector support. Note the `CudaUnavailable` status, which indicates no CUDA device is present and limits context functionality. ```c++ ntc::IContext* context = nullptr; ntc::ContextParameters contextParams; if (using_Vulkan) { contextParams.graphicsApi = ntc::GraphicsAPI::Vulkan; contextParams.vkInstance = vkInstance; contextParams.vkPhysicalDevice = vkPhysicalDevice; contextParams.vkDevice = vkDevice; } else if (using_DX12) { contextParams.graphicsApi = ntc::GraphicsAPI::D3D12; contextParams.d3d12Device = d3d12Device; } // Optionally, use the 'enableCooperativeVector' to disable CoopVec support if needed. contextParams.enableCooperativeVector = ...; ntc::Status ntcStatus = ntc::CreateContext(&context, contextParams); if (ntcStatus != ntc::Status::Ok && ntcStatus != ntc::Status::CudaUnavailable) { // Handle the error. // Note that the CudaUnavailable status exists and is returned when there is no CUDA capable device, // in which case the context will not support compression operations or creating ITextureSet objects. } ``` -------------------------------- ### Create Texture Set Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md Use the `TextureSetWrapper` for RAII-compliant texture set management. Ensure the `context` is valid and `desc` and `features` are properly configured. ```c++ // Use the RAII wrapper to make sure that the texture set is destroyed later. ntc::TextureSetWrapper textureSet(context); ntc::TextureSetDesc desc; desc.width = ...; desc.height = ...; desc.channels = ...; // Total number of channels in all textures, up to 16 desc.mips = ...; ntc::TextureSetFeatures features; // Default values are OK for most use cases ntcStatus = context->CreateTextureSet(desc, features, textureSet.ptr()); if (ntcStatus != ntc::Status::Ok) // Handle the error; ``` -------------------------------- ### Include Directory Configuration Source: https://github.com/nvidia-rtx/rtxntc/blob/main/samples/renderer/CMakeLists.txt Configures include directories for the ntc-renderer target, including build directories, external shaders, and library include paths. ```cmake target_include_directories(ntc-renderer PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") target_include_directories(ntc-renderer PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/../../external/donut/shaders") target_include_directories(ntc-renderer PRIVATE "${libstf_include_directory}") target_include_directories(ntc-renderer PRIVATE "${CMAKE_SOURCE_DIR}/libraries/RTXTS-TTM/include") target_include_directories(ntc-renderer PRIVATE "${implot_dir}") ``` -------------------------------- ### Build RTXNTC SDK with CMake (Windows) Source: https://github.com/nvidia-rtx/rtxntc/blob/main/README.md Steps to build the RTXNTC SDK on Windows using the command line. Ensure you are using the 'x64 Native Tools Command Prompt for VS 2022'. ```sh cd RTXNTC mkdir build cd build cmake .. cmake --build . ``` -------------------------------- ### Query and Upload Inference Weights Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/InferenceOnLoad.md Query inference weights using GetInferenceWeights and upload them to a staging buffer. Handles cases where GPU conversion is necessary. ```c++ void const* pWeightData = nullptr; size_t uploadSize = 0; size_t convertedSize = 0; ntcStatus = metadata->GetInferenceWeights(params.weightType, &pWeightData, &uploadSize, &convertedSize); if (ntcStatus != ntc::Status::Ok) // Handle the error. // ... Upload (pWeightData, uploadSize) to 'stagingBuffer' - API/engine dependent ... if (convertedSize != 0) { // Conversion for CoopVec is needed - perform the conversion on the GPU, moving data from 'stagingBuffer' to 'weightBuffer'. // Note that ConvertInferenceWeights takes graphics-API-specific objects for the command list and buffers. metadata->ConvertInferenceWeights(params.weightType, commandList, stagingBuffer, stagingOffset, weightBuffer, 0); } else { // No conversion is needed - just copy the data from 'stagingBuffer' to 'weightBuffer' (DX12 version below) commandList->CopyBufferRegion(weightBuffer, 0, stagingBuffer, stagingOffset, uploadSize); } ``` -------------------------------- ### Renderer Configuration Options Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/Renderer.md Configure renderer behavior using these command-line arguments. Options include selecting the graphics API, enabling debug modes, specifying the graphics adapter, and setting a custom material directory. ```sh --dx12 # switches to DX12 (only available on Windows when both Vulkan and DX12 backends were built) ``` ```sh --debug # enables the validation layers or debug runtime ``` ```sh --adapter # sets the graphics adapter index ``` ```sh --materialDir # loads the NTC material files from a custom location instead of next to GLTF files ``` -------------------------------- ### Run BC7 Optimization Pass Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/BlockCompression.md Use the `--optimizeBC` action in the NTC command-line tool to enable BC7 acceleration. Requires CUDA and a graphics API (e.g., `--dx12` or `--vk`). ```bash ntc --optimizeBC --dx12 ``` -------------------------------- ### Run ImageDiff Command Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/ImageDiff.md A typical command line for ImageDiff involves specifying the image files to compare. For a full list of options, use the --help flag. ```sh imagediff ... ``` -------------------------------- ### Manage NTC Context Lifecycle Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Demonstrates manual cleanup of an NTC context. An RAII wrapper is also mentioned for automatic resource management. ```cpp // RAII wrapper (auto-destroys on scope exit) // ntc::ContextWrapper ctx; // ntc::CreateContext(..., ctx.ptr()); // Manual cleanup ntc::DestroyContext(context); ``` -------------------------------- ### Running NTC Compression Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Run the iterative CUDA compression loop with progress reporting. ```APIDOC ## `ITextureSet::BeginCompression` / `RunCompressionSteps` / `FinalizeCompression` — Running NTC Compression Run the iterative CUDA compression loop with progress reporting. ```cpp ntc::CompressionSettings settings; // default iterations, learning rate, etc. status = textureSet->BeginCompression(settings); if (status != ntc::Status::Ok) fprintf(stderr, "BeginCompression: %s\n", ntc::GetLastErrorMessage()); ntc::CompressionStats stats; do { status = textureSet->RunCompressionSteps(&stats); if (status == ntc::Status::Incomplete || status == ntc::Status::Ok) printf("Step %d/%d PSNR: %.2f dB\n", stats.completedSteps, stats.totalSteps, stats.psnr); } while (status == ntc::Status::Incomplete); if (status != ntc::Status::Ok) fprintf(stderr, "Compression failed: %s\n", ntc::GetLastErrorMessage()); status = textureSet->FinalizeCompression(); ``` ``` -------------------------------- ### List CUDA Devices Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/CommandLineTool.md Lists available CUDA-enabled GPUs on the system. ```sh ntc-cli --listCudaDevices ``` -------------------------------- ### Configure BC7 Encoding with Mode Buffer Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/BlockCompression.md Set `modeBufferSource`, `modeBufferByteOffset`, etc., in `MakeBlockCompressionComputePassParameters` to utilize the pre-analyzed BC7 mode buffer during encoding. ```cpp MakeBlockCompressionComputePassParameters params = {}; params.modeBufferSource = gpuBuffer; params.modeBufferByteOffset = 0; // ... other parameters ``` -------------------------------- ### GPU Image Quality Comparison with IContext::MakeImageDifferenceComputePass Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Compare two GPU textures and compute per-channel MSE/PSNR metrics entirely on the GPU. This function requires setting up comparison parameters and dispatching a compute pass. ```cpp ntc::MakeImageDifferenceComputePassParameters diffParams; diffParams.srcRect.width = 2048; diffParams.srcRect.height = 2048; diffParams.numChannels = 4; ntc::ComputePassDesc diffPass{}; context->MakeImageDifferenceComputePass(diffParams, &diffPass); // Dispatch diffPass, then read the output buffer back to CPU // and decode results: ntc::ImageDifferenceResult result; ntc::DecodeImageDifferenceResult(gpuResultBuffer, diffParams.numChannels, &result); for (int ch = 0; ch < diffParams.numChannels; ++ch) printf("Channel %d MSE=%.6f PSNR=%.2f dB\n", ch, result.msePerChannel[ch], result.psnrPerChannel[ch]); printf("Overall PSNR: %.2f dB\n", result.psnrOverall); ``` -------------------------------- ### Adaptive Compression with IAdaptiveCompressionSession Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Finds the minimum bits per pixel (BPP) to achieve a target PSNR by running multiple compression iterations. Requires an existing texture set and compression implementation. ```cpp ntc::AdaptiveCompressionSessionWrapper session(context); context->CreateAdaptiveCompressionSession(session.ptr()); float targetPsnr = 42.0f; // dB float maxBpp = 10.0f; session->Reset(targetPsnr, maxBpp); std::vector> candidates; while (!session->Finished()) { float bpp; ntc::LatentShape shape; session->GetCurrentPreset(&bpp, &shape); textureSet->SetLatentShape(shape); // Run compression (BeginCompression/RunCompressionSteps/FinalizeCompression) float achievedPsnr = RunCompression(textureSet); // Serialize result to memory size_t sz = textureSet->GetOutputStreamSize(); candidates.emplace_back(sz); textureSet->SaveToMemory(candidates.back().data(), &sz); candidates.back().resize(sz); session->Next(achievedPsnr); } int best = session->GetIndexOfFinalRun(); // candidates[best] is the optimal compressed representation ``` -------------------------------- ### Run NTC Compression Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Initiate and monitor the iterative CUDA compression loop. Check the status after each step to ensure completion or handle errors. ```cpp ntc::CompressionSettings settings; // default iterations, learning rate, etc. status = textureSet->BeginCompression(settings); if (status != ntc::Status::Ok) fprintf(stderr, "BeginCompression: %s\n", ntc::GetLastErrorMessage()); ntc::CompressionStats stats; do { status = textureSet->RunCompressionSteps(&stats); if (status == ntc::Status::Incomplete || status == ntc::Status::Ok) printf("Step %d/%d PSNR: %.2f dB\n", stats.completedSteps, stats.totalSteps, stats.psnr); } while (status == ntc::Status::Incomplete); if (status != ntc::Status::Ok) fprintf(stderr, "Compression failed: %s\n", ntc::GetLastErrorMessage()); status = textureSet->FinalizeCompression(); ``` -------------------------------- ### Run BCTest for Image Compression Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/BCTest.md Compresses images in a specified path using a given format and outputs quality metrics to stdout and a CSV file. GPU encoding performance is also measured. ```sh bctest --source --format bc7 --vk --csv ``` -------------------------------- ### Compile All Shaders Source: https://github.com/nvidia-rtx/rtxntc/blob/main/samples/renderer/CMakeLists.txt Uses 'donut_compile_shaders_all_platforms' to compile all shader sources for all platforms. Configures output formats, include paths, and shader make options for DXIL and SPIR-V. ```cmake donut_compile_shaders_all_platforms( TARGET ntc-renderer-shaders PROJECT_NAME "NTC Renderer" CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/Shaders.cfg SOURCES ${shader_sources} BYPRODUCTS_NO_EXT ${shader_outputs} OUTPUT_FORMAT HEADER OUTPUT_BASE ${shader_output_dir} INCLUDES ${libntc_include_directory} ${libstf_include_directory} SHADERMAKE_OPTIONS "--hlsl2021 ${debug_option}" SHADERMAKE_OPTIONS_DXIL "--shaderModel 6_5" SHADERMAKE_OPTIONS_SPIRV "--vulkanVersion 1.2" ) ``` -------------------------------- ### Save Texture Set to File Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md Use convenience functions like ITextureSet::SaveToFile for simplified data saving. The output stream is managed automatically. ```cpp // Handle the error. // outputStream will be destroyed and file will be closed at the end of the code block. ``` -------------------------------- ### Perform Regression Testing with Baseline Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/BCTest.md Loads original test results from a CSV file to compute differences against current test results, saving the differences to the output CSV file. ```sh bctest --loadBaseline ``` -------------------------------- ### Clone RTXNTC SDK Recursively (Windows) Source: https://github.com/nvidia-rtx/rtxntc/blob/main/README.md Use this command to clone the RTXNTC repository and its submodules on Windows. ```sh git clone --recursive https://github.com/NVIDIA-RTX/RTXNTC.git ``` -------------------------------- ### Describe Texture Set File Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/CommandLineTool.md Retrieves and displays information about a compressed texture set file. ```sh ntc-cli --loadCompressed \ --describe ``` ```sh ntc-cli -d ``` -------------------------------- ### NTC Manifest File for Texture Bundles Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Define texture properties like channel packing, color spaces, semantic labels, and BCn output formats using a JSON manifest file. This allows for declarative specification of texture bundles. ```json { "textures": [ { "fileName": "albedo.tga", "name": "Albedo", "bcFormat": "BC7", "isSRGB": true, "semantics": { "Albedo": "RGB" } }, { "fileName": "normal.tga", "name": "Normal", "bcFormat": "BC7", "channelSwizzle": "RG", "semantics": { "Normal": "RG" } }, { "fileName": "orm.tga", "name": "ORM", "bcFormat": "BC7", "channelSwizzle": "RGB", "semantics": { "Occlusion": "R", "Roughness": "G", "Metalness": "B" } }, { "fileName": "opacity.tga", "name": "Opacity", "bcFormat": "BC4", "channelSwizzle": "R", "lossFunctionScale": 2.0, "semantics": { "AlphaMask": "R" } } ] } ``` ```sh # Use the manifest with ntc-cli ntc-cli --loadManifest material.json -g -c -b 5 -D -o material.ntc ``` -------------------------------- ### Upload Texture Data to Texture Set Source: https://github.com/nvidia-rtx/rtxntc/blob/main/docs/integration/Compression.md Upload texture data and metadata to the texture set before compression. This involves iterating through textures, setting metadata like name, channels, and pixel format, and then writing the pixel data using `WriteChannels`. ```c++ // Sort-of-pseudocode, assuming that 'texture' has all those members... int firstChannel = 0; for (auto& texture : textures) { // Determine the color spaces for the RGB and A channels of the texture ntc::ColorSpace rgbColorSpace = texture->isSRGB ? ntc::ColorSpace::sRGB : ntc::ColorSpace::Linear; ntc::ColorSpace alphaColorSpace = ntc::ColorSpace::Linear; ntc::ColorSpace colorSpaces[4] = { rgbColorSpace, rgbColorSpace, rgbColorSpace, alphaColorSpace }; ntc::ITextureMetadata* textureMetadata = textureSet->AddTexture(); textureMetadata->SetName(texture->name); // Some string identifier, not necessarily a file name textureMetadata->SetChannels(firstChannel, texture->numChannels); textureMetadata->SetPixelFormat(ntc::PixelFormat::BC7); // This is the desired output pixel format, not input textureMetadata->SetRgbColorSpace(rgbColorSpace); textureMetadata->SetAlphaColorSpace(alphaColorSpace); // Fill out the WriteChannels parameters structure ntc::WriteChannelsParameters params; params.mipLevel = 0; params.firstChannel = firstChannel; params.numChannels = texture->numCchannels; params.pData = texture->pixelData; // This is where the source data is located. params.addressSpace = ntc::AddressSpace::Host; // ...or Device if it's on the same CUDA device params.width = texture->width; params.height = texture->height; params.pixelStride = size_t(texture->numChannels); params.rowPitch = size_t(image.width * texture->numChannels); params.channelFormat = ntc::PixelFormat::UNORM8; // This is the input pixel format. params.srcColorSpaces = colorSpaces; params.dstColorSpaces = colorSpaces; ntc::Status ntcStatus = textureSet->WriteChannels(params); if (ntcStatus != ntc::Status::Ok) { // Handle the error. Use ntc::GetLastErrorMessage() for details. } // Allocate sequential channels of the texture set to each texture. // You can use other allocation schemes, such as using fixed channel indices // for specific PBR semantics. firstChannel += texture->numChannels; } ``` -------------------------------- ### ntc::CreateContext — Creating a LibNTC Context Source: https://context7.com/nvidia-rtx/rtxntc/llms.txt Demonstrates how to create a LibNTC context, which is the root object for all LibNTC operations. Supports CUDA-only and Vulkan contexts, with options for enabling Cooperative Vector hardware extensions. ```APIDOC ## `ntc::CreateContext` — Creating a LibNTC Context A context is the root object for all LibNTC operations. Pass graphics API handles to enable GPU decompression. All `IContext` methods are thread-safe. ```cpp // CUDA-only context (compression) ntc::IContext* context = nullptr; ntc::ContextParameters params; ntc::Status status = ntc::CreateContext(&context, params); if (status != ntc::Status::Ok) fprintf(stderr, "CreateContext failed: %s\n", ntc::GetLastErrorMessage()); // Vulkan context (compression + graphics decompression) ntc::ContextParameters vkParams; vkParams.graphicsApi = ntc::GraphicsAPI::Vulkan; vkParams.vkInstance = vkInstance; vkParams.vkPhysicalDevice = vkPhysicalDevice; vkParams.vkDevice = vkDevice; vkParams.enableCooperativeVector = true; // opt-in to CoopVec ntc::IContext* vkContext = nullptr; ntc::Status vkStatus = ntc::CreateContext(&vkContext, vkParams); // CudaUnavailable is non-fatal: context works for decompression only if (vkStatus != ntc::Status::Ok && vkStatus != ntc::Status::CudaUnavailable) fprintf(stderr, "Error: %s\n", ntc::GetLastErrorMessage()); // RAII wrapper (auto-destroys on scope exit) // ntc::ContextWrapper ctx; // ntc::CreateContext(..., ctx.ptr()); // Manual cleanup ntc::DestroyContext(context); ``` ```