### Get Vulkan Extensions and Features Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md For Vulkan, invoke these helper functions to retrieve required device and instance extensions, and device features. Ensure these are available and enabled during device creation. ```cpp uint32_t GetVulkanDeviceExtensions(char const* const*& outStringArray); uint32_t GetVulkanInstanceExtensions(char const* const*& outStringArray); uint32_t GetVulkanDeviceFeatures(char const* const*& outStringArray); ``` -------------------------------- ### Custom Resolve Pass Example Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md An example of a custom compute pass for resolving radiance, useful when the application relies on a split signal. ```APIDOC ## Custom Resolve Pass ### Description If the application relies on a split signal, then the library call can be skipped in favor of defining a custom compute pass. This example demonstrates how to handle diffuse and specular results separately. ### Shader Code Example ```cpp void CustomResolve(int3 DispatchThreadID : SV_DispatchThreadID) { const uint2 launchIndex = DispatchThreadID.xy; if(any(launchIndex >= screenResolution)) return; const uint sampleIndex = 0; const uint samplesPerPixel = 1; const uint pathIndex = NrcGetPathInfoIndex(screenResolution, launchIndex, sampleIndex, samplesPerPixel); const NrcQueryPathInfo path = NrcUnpackQueryPathInfo(nrcQueryPathInfo[pathIndex]); if (path.queryBufferIndex < 0xFFFFFFFF) { float3 radiance = NrcUnpackRadiance(nrcQueryRadiance[path.queryBufferIndex], radianceUnpackMultiplier) * path.prefixThroughput; uint uBrdfType = brdfTypeTarget[launchIndex]; if(uBrdfType == BRDF_SPECULAR) specularPathTracingTarget[launchIndex] += float4(radiance, 0.0f); if(uBrdfType == BRDF_DIFFUSE) diffusePathTracingTarget[launchIndex] += float4(radiance, 0.0f); } } ``` ``` -------------------------------- ### Custom Resolve Pass Example (HLSL) Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Example HLSL code for a custom resolve pass, useful for split-signal denoising workflows where the built-in resolve is replaced. This snippet shows how to unpack path info and radiance. ```hlsl // Custom resolve (split diffuse/specular for NRD denoiser) // In HLSL compute shader: // const uint pathIndex = NrcGetPathInfoIndex(screenRes, launchIndex, sampleIdx, spp); // const NrcQueryPathInfo path = NrcUnpackQueryPathInfo(nrcQueryPathInfo[pathIndex]); // if (path.queryBufferIndex < 0xFFFFFFFF) { // float3 rad = NrcUnpackRadiance(nrcQueryRadiance[path.queryBufferIndex], unpackMul) // * path.prefixThroughput; // specularTarget[launchIndex] += float4(rad, 0); // or diffuseTarget // } ``` -------------------------------- ### Context::BeginFrame Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Begins a new NRC frame at the start of every frame. It clears the counters buffer and uploads FrameSettings to the GPU. This must be followed by PopulateShaderConstants to fill the constant buffer for pathtracer shaders. ```APIDOC ## Context::BeginFrame — Begin a new NRC frame Called at the start of every frame. Internally clears the counters buffer and uploads `FrameSettings` to the GPU. Must be followed by `PopulateShaderConstants` to fill the constant buffer passed into the pathtracer shaders. ```cpp nrc::FrameSettings frameSettings; frameSettings.resolveMode = nrc::ResolveMode::AddQueryResultToOutput; frameSettings.radianceCacheDirect = false; // Don't cache direct lighting frameSettings.terminationHeuristicThreshold = 0.02f; frameSettings.selfTrainingAttenuation = 1.0f; nrcContext->BeginFrame(cmdList, frameSettings); // Populate the NrcConstants struct for use in path tracing shaders NrcConstants nrcConstants; nrcContext->PopulateShaderConstants(nrcConstants); // Bind nrcConstants inside your pathtracer constant buffer ``` ``` -------------------------------- ### Begin NRC Frame Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md At the start of each frame, invoke BeginFrame to populate internal data and clear the Counter buffer. Requires a graphics command list and frame settings. ```cpp // This function populates internal data and clears the `Counter` buffer. Status BeginFrame(ID3D12GraphicsCommandList4* cmdList, const FrameSettings& frameSettings); ``` -------------------------------- ### Custom Resolve Pass Implementation Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md Define a custom compute pass for split signals instead of using the in-built resolve pass. This example demonstrates probabilistic BRDF selection and writing to separate diffuse and specular buffers. ```hlsl void CustomResolve(int3 DispatchThreadID : SV_DispatchThreadID) { const uint2 launchIndex = DispatchThreadID.xy; if(any(launchIndex >= screenResolution)) return; const uint sampleIndex = 0; const uint samplesPerPixel = 1; const uint pathIndex = NrcGetPathInfoIndex(screenResolution, launchIndex, sampleIndex, samplesPerPixel); const NrcQueryPathInfo path = NrcUnpackQueryPathInfo(nrcQueryPathInfo[pathIndex]); if (path.queryBufferIndex < 0xFFFFFFFF) { float3 radiance = NrcUnpackRadiance(nrcQueryRadiance[path.queryBufferIndex], radianceUnpackMultiplier) * path.prefixThroughput; uint uBrdfType = brdfTypeTarget[launchIndex]; if(uBrdfType == BRDF_SPECULAR) specularPathTracingTarget[launchIndex] += float4(radiance, 0.0f); if(uBrdfType == BRDF_DIFFUSE) diffusePathTracingTarget[launchIndex] += float4(radiance, 0.0f); } } ``` -------------------------------- ### Get Shader Profile from Name Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Determines the DXC shader profile (e.g., 'cs', 'vs', 'ps') based on the file extension of an HLSL shader file. ```cmake function(util_get_shader_profile_from_name FILE_NAME DXC_PROFILE) get_filename_component(EXTENSION ${FILE_NAME} EXT) if ("${EXTENSION}" STREQUAL ".cs.hlsl") set(DXC_PROFILE "cs" PARENT_SCOPE) endif() if ("${EXTENSION}" STREQUAL ".vs.hlsl") set(DXC_PROFILE "vs" PARENT_SCOPE) endif() if ("${EXTENSION}" STREQUAL ".gs.hlsl") set(DXC_PROFILE "gs" PARENT_SCOPE) endif() if ("${EXTENSION}" STREQUAL ".ps.hlsl") set(DXC_PROFILE "ps" PARENT_SCOPE) endif() endfunction() ``` -------------------------------- ### Clone and Build RTXGI Pathtracer Sample Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Clone the RTXGI repository recursively to include submodules, then configure the build using CMake. The generated solution can be used to run the 'Pathtracer' project. ```bash # Clone recursively (required for submodules: Donut, NRD, etc.) git clone --progress --recursive --branch main -v \ "https://github.com/NVIDIAGameWorks/RTXGI.git" "rtxgi" # Configure with CMake (from repo root) cmake -S . -B build # Open generated solution # build/rtxgi2_samples.sln -> run "Pathtracer" project # Vulkan backend: launch with -vk flag ``` -------------------------------- ### Initialize Hash Grid Parameters Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/SharcGuide.md Initializes parameters for the HashGridDebugColoredHash function. Ensure 'g_Constants.cameraPosition' and 'g_Constants.sharcSceneScale' are set appropriately before calling. ```C++ HashGridParameters gridParameters; gridParameters.cameraPosition = g_Constants.cameraPosition; gridParameters.logarithmBase = SHARC_GRID_LOGARITHM_BASE; gridParameters.sceneScale = g_Constants.sharcSceneScale; gridParameters.levelBias = SHARC_GRID_LEVEL_BIAS; float3 color = HashGridDebugColoredHash(positionWorld, gridParameters); ``` -------------------------------- ### Initialize and Update SHaRC Path Tracing Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Initializes SHaRC state and updates the cache during the Update pass. Throughput resets at each bounce. Use `SharcUpdateHit` for cache writes and `SharcUpdateMiss` for environment hits. ```hlsl #define SHARC_UPDATE 1 #include "SharcCommon.h" // Set up SharcParameters once per dispatch SharcParameters sharcParams; sharcParams.gridParameters.cameraPosition = g_Lighting.sharcCameraPosition.xyz; sharcParams.gridParameters.sceneScale = g_Lighting.sharcSceneScale; sharcParams.gridParameters.logarithmBase = SHARC_GRID_LOGARITHM_BASE; sharcParams.gridParameters.levelBias = SHARC_GRID_LEVEL_BIAS; sharcParams.hashMapData.capacity = g_Lighting.sharcEntriesNum; sharcParams.hashMapData.hashEntriesBuffer = u_SharcHashEntriesBuffer; sharcParams.accumulationBuffer = u_SharcAccumulationBuffer; sharcParams.resolvedBuffer = u_SharcResolvedBuffer; sharcParams.radianceScale = SHARC_RADIANCE_SCALE; sharcParams.enableAntiFireflyFilter = g_Lighting.sharcEnableAntifirefly; // Per-path state SharcState sharcState; SharcInit(sharcState); // Per-bounce (inside the path tracing loop): SharcHitData hitData; hitData.positionWorld = hitPosition; hitData.normalWorld = geometryNormal; // hitData.materialDemodulation = float3(1,1,1); // optional, with SHARC_MATERIAL_DEMODULATION float3 directRadiance = evaluateDirectLight(/* ... */); if (!SharcUpdateHit(sharcParams, sharcState, hitData, directRadiance, Rand(rngState))) break; // Path terminated by SHaRC; cache entry written SharcSetThroughput(sharcState, throughput); // Update stored throughput after BRDF sampling // On miss: // SharcUpdateMiss(sharcParams, sharcState, skyColor); ``` -------------------------------- ### Query Vulkan Device and Instance Extensions Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Call these functions before Vulkan device creation to obtain all required extensions for the NRC library. The returned extension names must be merged into your existing extension lists for device and instance creation. ```cpp #include // Extensions char const* const* deviceExtNames = nullptr; uint32_t deviceExtCount = nrc::vulkan::GetVulkanDeviceExtensions(deviceExtNames); char const* const* instExtNames = nullptr; uint32_t instExtCount = nrc::vulkan::GetVulkanInstanceExtensions(instExtNames); // Required features (must also be enabled on device creation): // VK_EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME // VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME VkDeviceCreateInfo deviceCI = {}; // ... merge deviceExtNames into your existing extensions list ... deviceCI.enabledExtensionCount = /* your count */ + deviceExtCount; deviceCI.ppEnabledExtensionNames = /* merged array */; ``` -------------------------------- ### Initialize NRC Library Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md Call this function during the application's Init() step to set up NRC's global settings and initialize the library. You can hook a logger callback and specify memory management mode. ```cpp nrc::Status status = nrc::d3d12::Initialize(globalSettings); ``` -------------------------------- ### Begin NRC Frame and Populate Shader Constants Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Begin a new NRC frame by clearing counters and uploading frame settings. Must be followed by Populating Shader Constants to fill the constant buffer for pathtracer shaders. ```cpp nrc::FrameSettings frameSettings; frameSettings.resolveMode = nrc::ResolveMode::AddQueryResultToOutput; frameSettings.radianceCacheDirect = false; // Don't cache direct lighting frameSettings.terminationHeuristicThreshold = 0.02f; frameSettings.selfTrainingAttenuation = 1.0f; nrcContext->BeginFrame(cmdList, frameSettings); // Populate the NrcConstants struct for use in path tracing shaders NrcConstants nrcConstants; nrcContext->PopulateShaderConstants(nrcConstants); // Bind nrcConstants inside your pathtracer constant buffer ``` -------------------------------- ### Create Executable and Link Libraries Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Samples/Pathtracer/CMakeLists.txt Defines the main executable for the Pathtracer and links it with required Donut and NRD libraries. It also sets target properties and adds dependencies. ```cmake add_executable(${project} WIN32 ${sources}) target_link_libraries(${project} donut_render donut_app donut_engine NRD) add_dependencies(${project} ${project}_shaders nrd_shaders) set_target_properties(${project} PROPERTIES FOLDER ${folder}) ADD_DEFINITIONS(-DUNICODE) ADD_DEFINITIONS(-D_UNICODE) # NRC libs if(NRC_DEV_BUILD) target_link_libraries(${project} debug "${NRC_LIB_DIR}/${NRC_LIBRARY_NAME_D3D12_DEBUG}.lib") target_link_libraries(${project} optimized "${NRC_LIB_DIR}/${NRC_LIBRARY_NAME_D3D12_RELEASE}.lib") else() target_link_libraries(${project} "${NRC_LIB_DIR}/${NRC_LIBRARY_NAME_D3D12_RELEASE}.lib") endif() if(DONUT_WITH_VULKAN AND SETUP_NRC_WITH_VULKAN) if(NRC_DEV_BUILD) target_link_libraries(${project} debug "${NRC_LIB_DIR}/${NRC_LIBRARY_NAME_VULKAN_DEBUG}.lib") target_link_libraries(${project} optimized "${NRC_LIB_DIR}/${NRC_LIBRARY_NAME_VULKAN_RELEASE}.lib") else() target_link_libraries(${project} "${NRC_LIB_DIR}/${NRC_LIBRARY_NAME_VULKAN_RELEASE}.lib") endif() endif() # NRC includes include_directories("${NRC_DIR}/include" "${NRD_PATH}/Include") ``` -------------------------------- ### Clone RTXGI SDK Repository Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/QuickStart.md Use this command to clone the RTXGI SDK repository recursively, ensuring all submodules are included. Specify your preferred local path for the repository. ```bash git clone --progress --recursive --branch main -v "https://github.com/NVIDIAGameWorks/RTXGI.git" "local-repo-path" ``` -------------------------------- ### Create NRC Context Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md After initializing the library, create an NRC context using the native device. The neural network is not created at this stage. ```cpp status = nrc::d3d12::Context::Create(nativeDevice5, m_nrcContext); ``` -------------------------------- ### Initialize NRC Library with Global Settings Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Initializes the NRC library globally for a specific graphics API (D3D12 or Vulkan). Must be called once before creating any contexts. Configure logging, memory management, and optional custom allocators via GlobalSettings. DLL signature verification is recommended on Windows before initialization. ```cpp #include // or for Vulkan // Configure global settings nrc::GlobalSettings globalSettings; globalSettings.loggerFn = [](const char* msg, nrc::LogLevel level) { OutputDebugStringA(msg); }; globalSettings.memoryLoggerFn = [](nrc::MemoryEventType type, size_t size, const char* name) { // Track allocations/deallocations }; globalSettings.enableGPUMemoryAllocation = true; // SDK manages GPU buffers globalSettings.enableDebugBuffers = true; // Enable in development only // Optional: DLL signature verification (Windows) nrc::Status sigStatus = nrc::security::VerifySignature(L"C:\\path\\NRC_D3D12.dll"); assert(sigStatus == nrc::Status::OK); // Initialize library nrc::Status status = nrc::d3d12::Initialize(globalSettings); assert(status == nrc::Status::OK); ``` -------------------------------- ### Initialize NRC Context and Path State in Ray Generation Shader Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Sets up per-dispatch NRC context and per-path state at the beginning of each ray generation shader thread. Ensure NRC buffers are bound and a random value is used for path jitter. ```hlsl #define ENABLE_NRC 1 #include "Nrc.hlsli" [shader("raygeneration")] void RayGen() { const uint2 launchIndex = DispatchRaysIndex().xy; uint rngState = InitRNG(launchIndex, DispatchRaysDimensions().xy, g_Global.frameIndex); // Bind NRC structured buffers NrcBuffers nrcBuffers; nrcBuffers.queryPathInfo = queryPathInfo; nrcBuffers.trainingPathInfo = trainingPathInfo; nrcBuffers.trainingPathVertices = trainingPathVertices; nrcBuffers.queryRadianceParams = queryRadianceParams; nrcBuffers.countersData = countersData; // Create the per-dispatch context and per-path state NrcContext nrcContext = NrcCreateContext(g_Lighting.nrcConstants, nrcBuffers, launchIndex); NrcPathState nrcPathState = NrcCreatePathState(g_Lighting.nrcConstants, Rand(rngState)); NrcSetSampleIndex(nrcContext, 0 /* sampleIndex */); // ... } ``` -------------------------------- ### Configure NRC Context with SDK-Managed Memory Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Configure the NRC context, allocating GPU memory and instantiating the neural network. This is the simplest path when the SDK manages buffers internally. ```cpp nrc::ContextSettings contextSettings; contextSettings.frameDimensions = { 1920, 1080 }; // Compute ideal training resolution (~4% of frame pixels) contextSettings.trainingDimensions = nrc::computeIdealTrainingDimensions({ 1920, 1080 }); contextSettings.maxPathVertices = 8; contextSettings.samplesPerPixel = 1; // SDK-managed memory (simplest path) nrc::Status status = nrcContext->Configure(contextSettings); assert(status == nrc::Status::OK); ``` -------------------------------- ### NRC Integration with G-Buffer Ray Generation Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md Illustrates NRC integration within a ray generation function, handling both update and query modes. It prepares NRC buffers, sets launch indices based on mode, and processes hits and misses. ```cpp // Prepare NRC buffers: queryPathInfo, trainingPathInfo, trainingPathVertices, queryRadianceParams, countersData, debugTrainingPathInfo. void RayGenFunc() { // Prepare launchIndex, launchDimensions if (NrcIsUpdateMode()) launchIndex = (float2(DispatchRaysIndex().xy) + Rng::GetFloat2()) * nrcTrainingDownscaleFactor; else launchIndex = DispatchRaysIndex().xy; // Load data from G-Buffer... // Flag G-Buffer miss to write it to NRC later // Only 1 SPP during NRC Update pass const uint samplesPerPixel = NrcIsUpdateMode() ? 1 : nrcConstants.samplesPerPixel; // Prepare NRC context NrcBuffers nrcBuffers = {queryPathInfo, trainingPathInfo, ...}; NrcContext nrcContext = NrcCreateContext(nrcConstants, nrcBuffers, DispatchRaysIndex().xy); for (int sampleIndex = 0; sampleIndex < samplesPerPixel; sampleIndex++) { // Initialize NRC data for path and sample index traced in this thread NrcSetSampleIndex(nrcContext, sampleIndex); NrcPathState nrcPathState = NrcCreatePathState(rand(rngState)); if (NrcIsUpdateMode()) {/*Add random offset to pixel's coords...*/} if(flagGbufferMiss) { NrcUpdateOnMiss(nrcPathState); break; } else { NrcSurfaceAttributes surfaceAttributes = gBufferData; NrcProgressState nrcProgressState = NrcUpdateOnHit(...); // Update NRC state on hit if (nrcProgressState == NrcProgressState::TerminateImmediately) break; NrcSetBrdfPdf(nrcPathState, brdfPdf) } // Prepare Payload and other data... for (int bounce = 1; bounce < gData.maxPathVertices; bounce++) { TraceRay(...); if (!payload.hasHit()) NrcUpdateOnMiss(nrcPathState); // Handle miss // Decode material properties... NrcSurfaceAttributes surfaceAttributes = decodedMaterial; // Passed to NrcUpdateOnHit NrcProgressState nrcProgressState = NrcUpdateOnHit(...); // Update NRC state on hit if (nrcProgressState == NrcProgressState::TerminateImmediately) break; // Account for emissives and evaluate NEE with RIS... // Terminate loop early on last bounce (don't sample BRDF) if (bounce == gData.maxPathVertices - 1) { NrcSetDebugPathTerminationReason(...); break; } // Terminate loop after emissives and direct light if CreateQuery requests delayed termination. // If direct lighting isn't cached (radianceCacheDirect is false) // add direct lighting on hit where we query NRC before terminating the loop. if (nrcProgressState == NrcProgressState::TerminateAfterDirectLighting) break; // Sample BRDF to generate the next ray and run MIS... if(!evaluateCombinedBRDF(...) NrcSetDebugPathTerminationReason(nrcPathState, BRDFAbsorption); NrcSetBrdfPdf(nrcPathState, brdfPdf); } // End of path NrcWriteFinalPathInfo(nrcContext, nrcPathState, throughput, radiance); } // End of SPP loop } ``` -------------------------------- ### RTXGI Directory Structure Change Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Changelog.md The Donut framework is now located inside `/external` and no longer resides directly in the repo root. ```c++ /external ``` -------------------------------- ### Copy Agility SDK Binaries Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Samples/Pathtracer/CMakeLists.txt Configures post-build custom commands to copy necessary Agility SDK DLLs to the runtime output directory. This ensures the application can find the required DirectX 12 Agility SDK components. ```cmake # Copy Agility SDK binaries (if needed) one level below project executable to avoid known issues. # Details in the section "Known Issues" https://devblogs.microsoft.com/directx/gettingstarted-dx12agility/ add_custom_command(TARGET ${project} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/../../External/AgilitySDK/build/native/bin/x64/D3D12Core.dll ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/D3D12/D3D12Core.dll ) add_custom_command(TARGET ${project} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/../../External/AgilitySDK/build/native/bin/x64/d3d12SDKLayers.dll ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/D3D12/d3d12SDKLayers.dll ) ``` -------------------------------- ### Context::Configure Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Configures the NRC context, allocating GPU memory and instantiating the neural network. This should be called after Create and whenever ContextSettings change. It supports both SDK-managed and app-managed memory allocations. ```APIDOC ## Context::Configure — Configure the NRC context (creates the neural network) Called at least once after `Create`, and again whenever `ContextSettings` change (e.g., resolution change, level load). This allocates GPU memory and instantiates the neural network. If `enableGPUMemoryAllocation` is `true`, the SDK manages buffers internally; otherwise, pass app-created buffers via the optional `Buffers*` parameter. ### SDK-Managed Memory ```cpp nrc::ContextSettings contextSettings; contextSettings.frameDimensions = { 1920, 1080 }; // Compute ideal training resolution (~4% of frame pixels) contextSettings.trainingDimensions = nrc::computeIdealTrainingDimensions({ 1920, 1080 }); contextSettings.maxPathVertices = 8; contextSettings.samplesPerPixel = 1; nrc::Status status = nrcContext->Configure(contextSettings); assert(status == nrc::Status::OK); ``` ### App-Managed Memory ```cpp nrc::ContextSettings contextSettings; contextSettings.frameDimensions = { 1920, 1080 }; // Compute ideal training resolution (~4% of frame pixels) contextSettings.trainingDimensions = nrc::computeIdealTrainingDimensions({ 1920, 1080 }); contextSettings.maxPathVertices = 8; contextSettings.samplesPerPixel = 1; nrc::BuffersAllocationInfo allocInfo; nrc::d3d12::Context::GetBuffersAllocationInfo(contextSettings, allocInfo); // ... create buffers using allocInfo.elementCount / elementSize per BufferIdx ... nrc::d3d12::Buffers appBuffers; // populate with your ID3D12Resource* per BufferIdx status = nrcContext->Configure(contextSettings, &appBuffers); ``` ``` -------------------------------- ### nrc::d3d12::Initialize / nrc::vulkan::Initialize Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Initializes the NRC library globally for a given graphics API. This function must be called once before creating any contexts and accepts a GlobalSettings struct for configuration. ```APIDOC ## nrc::d3d12::Initialize / nrc::vulkan::Initialize ### Description Initializes the NRC library globally for a given graphics API. This function must be called once before creating any contexts and accepts a `GlobalSettings` struct for configuration. ### Method `nrc::d3d12::Initialize(const GlobalSettings& settings)` or `nrc::vulkan::Initialize(const GlobalSettings& settings)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **globalSettings** (nrc::GlobalSettings) - Required - Struct containing global settings for the NRC library, including logger callbacks, memory management mode, and custom CPU allocators. - **loggerFn** (function pointer) - Optional - Callback function for logging messages. - **memoryLoggerFn** (function pointer) - Optional - Callback function for tracking memory allocations/deallocations. - **enableGPUMemoryAllocation** (bool) - Optional - If true, the SDK manages GPU buffer allocations. - **enableDebugBuffers** (bool) - Optional - If true, enables debug buffers (recommended for development only). ### Request Example ```cpp #include // or for Vulkan nrc::GlobalSettings globalSettings; globalSettings.loggerFn = [](const char* msg, nrc::LogLevel level) { OutputDebugStringA(msg); }; globalSettings.memoryLoggerFn = [](nrc::MemoryEventType type, size_t size, const char* name) { // Track allocations/deallocations }; globalSettings.enableGPUMemoryAllocation = true; globalSettings.enableDebugBuffers = true; // Optional: DLL signature verification (Windows) nrc::Status sigStatus = nrc::security::VerifySignature(L"C:\\path\\NRC_D3D12.dll"); assert(sigStatus == nrc::Status::OK); // Initialize library nrc::Status status = nrc::d3d12::Initialize(globalSettings); assert(status == nrc::Status::OK); ``` ### Response #### Success Response (nrc::Status::OK) Indicates successful initialization. #### Response Example `nrc::Status::OK` ``` -------------------------------- ### Configure NRC Context with App-Managed Memory Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Configure the NRC context with app-created buffers for fine-grained control over memory management. Ensure buffers are created using the provided allocation info. ```cpp // App-managed memory (optional, for fine-grained control) nrc::BuffersAllocationInfo allocInfo; nrc::d3d12::Context::GetBuffersAllocationInfo(contextSettings, allocInfo); // ... create buffers using allocInfo.elementCount / elementSize per BufferIdx ... nrc::d3d12::Buffers appBuffers; // populate with your ID3D12Resource* per BufferIdx status = nrcContext->Configure(contextSettings, &appBuffers); ``` -------------------------------- ### QueryAndTrain Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md Queries radiance at specified points and trains the neural network using the gathered data. This is an all-in-one API call that handles both prediction and optimization. ```APIDOC ## QueryAndTrain ### Description Once the pathtracer passes complete, the neural network predicts radiance at the query points. Internally, the NRC library propagates the radiance based on the predicted values and the path data. This is immediately followed by the training of the network which relies on the training data from the propagation. This optimizes the network to produce accurate radiance predictions. ### Method Signature ```cpp Status QueryAndTrain(ID3D12GraphicsCommandList4* cmdList, float* trainingLossPtr) ``` ### Parameters - **cmdList** (ID3D12GraphicsCommandList4*): A pointer to the graphics command list. - **trainingLossPtr** (float*): A pointer to a float where the training loss will be stored. ``` -------------------------------- ### Generate Shader Configuration File Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Generates a configuration file for shaders by iterating through HLSL files in a specified directory and formatting their compilation arguments. ```cmake function(util_generate_shader_config_file OUT_FILE_NAME DIR DEFINES) file(GLOB_RECURSE HLSL_FILES "${CMAKE_CURRENT_SOURCE_DIR}/${DIR}/*.hlsl") set(out_content "") foreach(FILE_NAME ${HLSL_FILES}) get_filename_component(NAME_ONLY ${FILE_NAME} NAME) set(DXC_PROFILE "") util_get_shader_profile_from_name(${FILE_NAME} DXC_PROFILE) set(out_content "${out_content}${DIR}/${NAME_ONLY} -T ${DXC_PROFILE} -E main ${DEFINES}\n") endforeach() file(WRITE ${OUT_FILE_NAME} ${out_content}) endfunction() ``` -------------------------------- ### SHaRC Buffer Allocation (D3D12) Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Defines the creation of three structured buffers required for SHaRC: hash entries, accumulation, and resolved buffers. These must be zero-cleared at load time. Recommended baseline size is 2^22 entries. ```cpp // C++ resource creation (D3D12 example) const uint32_t SHARC_CAPACITY = 1u << 22; // 4M entries // Hash entries buffer: 8 bytes/entry = 32 MiB D3D12_RESOURCE_DESC hashEntriesDesc = CD3DX12_RESOURCE_DESC::Buffer( SHARC_CAPACITY * sizeof(uint64_t), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); // Accumulation buffer: 16 bytes/entry = 64 MiB (SharcAccumulationData) D3D12_RESOURCE_DESC accumDesc = CD3DX12_RESOURCE_DESC::Buffer( SHARC_CAPACITY * 16, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); // Resolved buffer: 16 bytes/entry = 64 MiB (SharcPackedData) D3D12_RESOURCE_DESC resolvedDesc = CD3DX12_RESOURCE_DESC::Buffer( SHARC_CAPACITY * 16, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); // ⚠️ All three buffers MUST be zero-cleared before first use // (clear once at load time, not every frame) ``` -------------------------------- ### Copy RTXGI Runtime Libraries Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Samples/Pathtracer/CMakeLists.txt Copies NVRTC, CUDART, and NVRTC-builtins libraries to the runtime output directory after the project is built. ```cmake file(GLOB NVRTC64_PATH "${NRC_DIR}/bin/nvrtc64_*") file(GLOB CUDART64_PATH "${NRC_DIR}/bin/cudart64_*") file(GLOB NVRTC_BUILTINS64 "${NRC_DIR}/bin/nvrtc-builtins64_*") add_custom_command( TARGET ${project} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "${NVRTC64_PATH}" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} COMMAND ${CMAKE_COMMAND} -E copy "${CUDART64_PATH}" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} COMMAND ${CMAKE_COMMAND} -E copy "${NVRTC_BUILTINS64}" ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} ) ``` -------------------------------- ### Define ShaderMake General Arguments Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Sets general arguments for ShaderMake, including include paths for NRD shader resources and libraries. ```cmake set ( SHADERMAKE_GENERAL_ARGS "-I ${CMAKE_CURRENT_SOURCE_DIR}/RayTracingDenoiser/External/MathLib -I ${CMAKE_CURRENT_SOURCE_DIR}/RayTracingDenoiser/Shaders/Include -I ${CMAKE_CURRENT_SOURCE_DIR}/RayTracingDenoiser/Shaders/Resources" ) ``` -------------------------------- ### NRC Training Iterations Configuration Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Changelog.md Expose the ability to configure the number of training iterations in NRC. ```c++ number of training iterations ``` -------------------------------- ### nrc::d3d12::Context::Create Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Creates an NRC context bound to a specific D3D12 or Vulkan device. The context holds all state for one instance of the NRC and must be configured subsequently. ```APIDOC ## nrc::d3d12::Context::Create ### Description Creates an NRC context bound to a specific D3D12 or Vulkan device. The context holds all state for one instance of the NRC and must be configured subsequently. ### Method `nrc::d3d12::Context::Create(ID3D12Device5* device, nrc::d3d12::Context*& context)` or `nrc::vulkan::Context::Create(VkDevice device, VkPhysicalDevice physicalDevice, VkInstance instance, nrc::vulkan::Context*& context)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **device** (ID3D12Device5* or VkDevice) - Required - The graphics device to bind the context to. - **context** (nrc::d3d12::Context*& or nrc::vulkan::Context*&) - Output parameter - A reference to a pointer that will be set to the newly created NRC context. - **physicalDevice** (VkPhysicalDevice) - Required for Vulkan - The physical Vulkan device. - **instance** (VkInstance) - Required for Vulkan - The Vulkan instance. ### Request Example ```cpp // D3D12 ID3D12Device5* device5 = nullptr; nativeDevice->QueryInterface(IID_PPV_ARGS(&device5)); nrc::d3d12::Context* nrcContext = nullptr; nrc::Status status = nrc::d3d12::Context::Create(device5, nrcContext); assert(status == nrc::Status::OK); // Vulkan equivalent // nrc::vulkan::Context::Create(vkDevice, vkPhysicalDevice, vkInstance, nrcContext); ``` ### Response #### Success Response (nrc::Status::OK) Indicates successful context creation. The `nrcContext` pointer will be populated. #### Response Example `nrc::Status::OK` ``` -------------------------------- ### Enable SHARC Fade Acceleration Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Changelog.md When enabled, each resolve entry tracks luminance to accelerate convergence by resetting history if fading is detected. Requires SharcResolveParameters::frameIndex to be set. ```c++ #define SHARC_ENABLE_FADE_ACCELERATION ``` -------------------------------- ### RTXGI Cache Visualization Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Changelog.md Addition of cache visualization with a material demodulation toggle. ```c++ cache visualization ``` ```c++ material demodulation toggle ``` -------------------------------- ### Query Vulkan Extensions Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Query the required Vulkan extensions for the NRC library. These must be called before Vulkan device creation. ```APIDOC ## GetVulkanDeviceExtensions / GetVulkanInstanceExtensions — Query required Vulkan extensions Must be called before Vulkan device creation to include all extensions and features required by the NRC library. ```cpp #include // Extensions char const* const* deviceExtNames = nullptr; uint32_t deviceExtCount = nrc::vulkan::GetVulkanDeviceExtensions(deviceExtNames); char const* const* instExtNames = nullptr; uint32_t instExtCount = nrc::vulkan::GetVulkanInstanceExtensions(instExtNames); // Required features (must also be enabled on device creation): // VK_EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME // VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME VkDeviceCreateInfo deviceCI = {}; // ... merge deviceExtNames into your existing extensions list ... deviceCI.enabledExtensionCount = /* your count */ + deviceExtCount; deviceCI.ppEnabledExtensionNames = /* merged array */; ``` ``` -------------------------------- ### Perform In-built Resolve Pass Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md Use this API to compute the final radiance by combining predicted radiance with path throughput. Assumes the signal is already combined. ```cpp Status Resolve(ID3D12GraphicsCommandList4* cmdList, ID3D12Resource* outputBuffer); ``` -------------------------------- ### Run Neural Network Inference and Training Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Dispatch neural network inference and training after pathtracer passes are complete. This propagates training radiance and predicts radiance at query points. Optionally returns training loss. ```cpp float trainingLoss = 0.f; bool calculateLoss = true; // Set false in production to save perf nrc::Status status = nrcContext->QueryAndTrain(cmdList, calculateLoss ? &trainingLoss : nullptr); assert(status == nrc::Status::OK); // trainingLoss can be displayed in the UI or logged for debugging convergence ``` -------------------------------- ### Set Global Binary Output Path Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Configures the global binary output directory, used by NRD for custom output paths. This is a cache variable. ```cmake set(GLOBAL_BIN_OUTPUT_PATH ${CMAKE_BINARY_DIR} CACHE STRING "") ``` -------------------------------- ### Query and Train Neural Network Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md Call this API after pathtracer passes are complete to predict radiance and train the neural network. It optimizes the network for accurate radiance predictions. ```cpp Status QueryAndTrain(ID3D12GraphicsCommandList4* cmdList, float* trainingLossPtr) ``` -------------------------------- ### Create NRC Context for D3D12 Device Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Creates an NRC context associated with a D3D12 device. This context will manage the state for a single NRC instance. The neural network is not created here; call `Configure` subsequently. The Vulkan equivalent uses `nrc::vulkan::Context::Create`. ```cpp // D3D12 ID3D12Device5* device5 = nullptr; nativeDevice->QueryInterface(IID_PPV_ARGS(&device5)); nrc::d3d12::Context* nrcContext = nullptr; nrc::Status status = nrc::d3d12::Context::Create(device5, nrcContext); assert(status == nrc::Status::OK); // Vulkan equivalent // nrc::vulkan::Context::Create(vkDevice, vkPhysicalDevice, vkInstance, nrcContext); ``` -------------------------------- ### Validate Cache Occupancy Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/SharcGuide.md Use HashGridDebugOccupancy() to validate cache occupancy. This function helps visualize cache usage, with typical occupancy ranging from 10-20% for static cameras. ```c++ HashGridDebugOccupancy() ``` -------------------------------- ### Configure NRC Context Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Docs/NrcGuide.md Call Configure at least once after initialization, especially if ContextSettings have changed (e.g., screen resolution). This performs memory allocations and reloads the neural network configuration. If using app-side memory management, pass your buffers here. ```cpp Configure(const ContextSettings& contextSettings, const Buffers* buffers = nullptr); ``` -------------------------------- ### Context::QueryAndTrain Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Dispatches neural network inference and training after pathtracer passes are completed. It propagates training radiance, runs inference, and trains the network. Optionally returns the training loss. ```APIDOC ## Context::QueryAndTrain — Run neural network inference and training Dispatched after both pathtracer passes (Update and Query) have completed and their command lists are recorded. Internally: propagates training radiance backward along training paths, runs the neural network inference to predict radiance at query points, then trains the network on the propagated data. Returns optional training loss. ```cpp float trainingLoss = 0.f; bool calculateLoss = true; // Set false in production to save perf nrc::Status status = nrcContext->QueryAndTrain(cmdList, calculateLoss ? &trainingLoss : nullptr); assert(status == nrc::Status::OK); // trainingLoss can be displayed in the UI or logged for debugging convergence ``` ``` -------------------------------- ### Compile Shaders with Donut Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Samples/Pathtracer/CMakeLists.txt Compiles HLSL shaders into SPIR-V and DXIL formats using the donut_compile_shaders macro. It specifies source files, output directories, and shader model versions. ```cmake file(GLOB shaders "*.hlsl" "*.hlsli") file(GLOB sources "*.cpp" "*.h") set(project Pathtracer) set(folder "Samples/Pathtracer") option (NRD_EMBEDS_SPIRV_SHADERS "NRD embeds SPIRV shaders" OFF) option (NRD_EMBEDS_DXIL_SHADERS "NRD embeds DXIL shaders" OFF) option (NRD_EMBEDS_DXBC_SHADERS "NRD embeds DXBC shaders" OFF) set(NRC_LIB_DIR ${NRC_DIR}/Lib) # Is the NRC package a dev package (internal), or production if(EXISTS ${NRC_LIB_DIR}/NRC_D3D12_relwithdebinfo.lib OR EXISTS ${NRC_LIB_DIR}/NRC_D3D12_debug.lib) set (NRC_DEV_BUILD true) else() set (NRC_DEV_BUILD false) endif() if(NRC_DEV_BUILD) set(NRC_LIBRARY_NAME_D3D12_DEBUG NRC_D3D12_debug) set(NRC_LIBRARY_NAME_D3D12_RELEASE NRC_D3D12_relwithdebinfo) if(DONUT_WITH_VULKAN AND SETUP_NRC_WITH_VULKAN) set(NRC_LIBRARY_NAME_VULKAN_DEBUG NRC_Vulkan_debug) set(NRC_LIBRARY_NAME_VULKAN_RELEASE NRC_Vulkan_relwithdebinfo) endif() else() set(NRC_LIBRARY_NAME_D3D12_DEBUG NRC_D3D12) set(NRC_LIBRARY_NAME_D3D12_RELEASE NRC_D3D12) if(DONUT_WITH_VULKAN AND SETUP_NRC_WITH_VULKAN) set(NRC_LIBRARY_NAME_VULKAN_DEBUG NRC_Vulkan) set(NRC_LIBRARY_NAME_VULKAN_RELEASE NRC_Vulkan) endif() endif() # Set SHARC includes set(SHARC_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../Libraries) # Shader Model 6_6 requires Agility SDK on Windows 10. if(DONUT_WITH_VULKAN) set (SHADERMAKE_GENERAL_ARGS_SPIRV "--shaderModel 6_6 -I ${NRC_DIR}/include -I ${SHARC_INCLUDE_DIR}/Sharc/include --vulkanMemoryLayout dx") endif() set (SHADERMAKE_GENERAL_ARGS_DXIL "--shaderModel 6_6 --platform DXIL --WX --PDB -I ${NRC_DIR}/include -I ${SHARC_INCLUDE_DIR}/Sharc/include") donut_compile_shaders( TARGET ${project}_shaders CONFIG ${CMAKE_CURRENT_SOURCE_DIR}/Shaders.cfg SOURCES ${shaders} FOLDER ${folder} SPIRV_DXC ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/spirv DXIL ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/shaders/${project}/dxil SHADERMAKE_OPTIONS_SPIRV ${SHADERMAKE_GENERAL_ARGS_SPIRV} SHADERMAKE_OPTIONS_DXIL ${SHADERMAKE_GENERAL_ARGS_DXIL} ) ``` -------------------------------- ### Configure NRD DXC Path Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Sets the path to the DXC shader compiler executable for the NRD (NVIDIA Real-Time Denoiser) library. This is a cache variable. ```cmake set(NRD_DXC_PATH "${DXC_DXIL_EXECUTABLE}" CACHE STRING "DXC shader compiler path for NRD") ``` -------------------------------- ### SHaRC Dynamic Parameters Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Changelog.md Added extra dynamic parameters to give more control with multiple SHaRC instances. ```c++ extra dynamic parameters ``` -------------------------------- ### Configure NRD Project Folder Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Sets the relative path to the NRD project folder within the main project. ```cmake set(NRD_PROJECT_FOLDER "External/RayTracingDenoiser") ``` -------------------------------- ### Query Current SDK Memory Consumption Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Calculates the total memory consumed by the SDK's buffers. Useful for understanding resource allocation at specific resolutions and settings. ```cpp // Query current SDK memory consumption size_t totalBytes = 0; const nrc::d3d12::Buffers& buffers = *(nrcContext->GetBuffers()); for (const nrc::d3d12::BufferInfo& buf : buffers.buffers) totalBytes += buf.allocatedSize; // totalBytes ≈ 192 MB at 1920×1080, 8 bounces, 1 SPP ``` -------------------------------- ### SHARC Linear Probe Window Size Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Changelog.md Default value for SHARC_LINEAR_PROBE_WINDOW_SIZE increased from 4 to 8. ```c++ #define SHARC_LINEAR_PROBE_WINDOW_SIZE 8 ``` -------------------------------- ### Configure NRD Shader Output Path Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Sets the output path for NRD shaders. This is a cache variable. ```cmake set(NRD_SHADER_OUTPUT_PATH "${SHADER_OUTPUT_PATH}" CACHE STRING "") ``` -------------------------------- ### RTXGI Pathtracer VSync Option Source: https://github.com/nvidia-rtx/rtxgi/blob/main/Changelog.md Addition of a VSync option to the pathtracer sample to simulate a 60Hz scenario. ```c++ VSync option ``` -------------------------------- ### Context::Destroy + Shutdown Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Tears down the NRC context and shuts down the library. Destroy should be called for each context before application shutdown, and Shutdown should be called once at application exit. ```APIDOC ## Context::Destroy + Shutdown — Tear down NRC ```cpp // Destroy all contexts before shutdown nrc::d3d12::Context::Destroy(*nrcContext); nrcContext = nullptr; // Shut down the library (once, at app exit) nrc::d3d12::Shutdown(); ``` ``` -------------------------------- ### Finalize and Write NRC Path Data Source: https://context7.com/nvidia-rtx/rtxgi/llms.txt Call this function once per sample at the end of the per-sample loop to write accumulated path data (throughput, radiance) to NRC buffers. This data is used by `QueryAndTrain`. ```hlsl // After the bounce loop, for each SPP sample: NrcWriteFinalPathInfo(nrcContext, nrcPathState, throughput, sampleRadiance); ``` -------------------------------- ### Generate NRD Shader Configuration Source: https://github.com/nvidia-rtx/rtxgi/blob/main/External/CMakeLists.txt Generates the 'nrd.cfg' file using the `util_generate_shader_config_file` function, specifying shader source directory and compiler definitions. ```cmake util_generate_shader_config_file( "nrd.cfg" "RayTracingDenoiser/Shaders/Source" "-D NRD_COMPILER_DXC=1 -D NRD_NORMAL_ENCODING=${NRD_NORMAL_ENCODING} -D NRD_ROUGHNESS_ENCODING=${NRD_ROUGHNESS_ENCODING}" ) ```