diff --git a/.gitmodules b/.gitmodules index 244a4906..0c9b0eee 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "nvrhi"] path = nvrhi - url = ../NVRHI.git + url = https://github.com/NVIDIA-RTX/NVRHI.git [submodule "thirdparty/imgui"] path = thirdparty/imgui url = https://github.com/ocornut/imgui diff --git a/README.md b/README.md index 6e099615..6a16f41b 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,10 @@ Supported glTF extensions: In addition to glTF, Donut supports its own [JSON-based scene layout files](doc/SceneFile.md). Those files can load multiple glTF models and combine them into a larger scene graph, also add lights, cameras, animations, and apply animations to scene nodes imported from the models using their paths. +### Scene memory statistics + +For geometry buffer accounting, see [scene geometry memory statistics](doc/MemoryStats.md). + ### Render passes For a full list of render passes, refer to the headers in the [include/donut/render](include/donut/render) folder. diff --git a/doc/MemoryStats.md b/doc/MemoryStats.md new file mode 100644 index 00000000..b44321cc --- /dev/null +++ b/doc/MemoryStats.md @@ -0,0 +1,28 @@ +# Scene geometry memory statistics + +`Scene::getGeometryMemoryStats()` returns current vertex/index buffer totals, deduplicating +shared buffer handles within each category. A handle used in both categories counts once +in each, so adding the categories does not give unique physical memory usage. It keeps +descriptor `capacityBytes` separate from backing-buffer `allocationBytes`, which sums only +successful queries. Check `hasKnownAllocationBytes()` before displaying a complete allocation +total: unavailable resources increment `unknownAllocationCount`, not a known zero. +`resourceCount` includes both known and unknown non-null buffers. Missing graphs, meshes, +buffer groups, and buffer handles contribute nothing; an empty category is known zero. +Re-query after scene resource replacement or removal; the statistics do not retain resources. +The free function `getSceneGeometryMemoryStats(device, scene)` provides the same aggregation +with an explicit device; a null device preserves capacity and counts but makes allocation +sizes unavailable for every counted buffer. + +`tryGetResourceAllocationBytes` uses NVRHI's optional `IResource::queryMemoryRequirements` +and leaves `outBytes` unchanged on failure, including a null device or resource. The helper's +device must be the resource's owning device. It filters D3D11 resources and textures before +calling NVRHI, whose unsupported queries assert in debug builds; these remain unavailable +without modifying the output. Supported resources dispatch the query to their backend. +See [NVRHI's optional memory queries](../nvrhi/doc/memory-queries.md) for +backend support and exceptions, allocation interpretation, and the native +`IDevice::queryTopLevelAccelStructPrebuildInfo` API. Application-specific pooled BLAS/OMM +attribution and statistics UI remain the consuming application's responsibility. + +The headless [memory statistics regression](../tests/src/memory_stats.cpp) covers the public +helper and scene aggregation. Its build conditions and CTest registration are defined in +[tests/test-engine.cmake](../tests/test-engine.cmake). diff --git a/include/donut/engine/MemoryStats.h b/include/donut/engine/MemoryStats.h new file mode 100644 index 00000000..c4f9a817 --- /dev/null +++ b/include/donut/engine/MemoryStats.h @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +* +* Permission is hereby granted, free of charge, to any person obtaining a +* copy of this software and associated documentation files (the "Software"), +* to deal in the Software without restriction, including without limitation +* the rights to use, copy, modify, merge, publish, distribute, sublicense, +* and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in +* all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +* DEALINGS IN THE SOFTWARE. +*/ + +#pragma once + +#include + +#include + +namespace donut::engine +{ + class Scene; + + struct GpuMemoryUsage + { + uint64_t capacityBytes = 0; + uint64_t allocationBytes = 0; + uint32_t resourceCount = 0; + uint32_t unknownAllocationCount = 0; + + [[nodiscard]] bool hasKnownAllocationBytes() const { return unknownAllocationCount == 0; } + }; + + struct SceneGeometryMemoryStats + { + GpuMemoryUsage vertexBuffers; + GpuMemoryUsage indexBuffers; + }; + + // Returns backing-buffer memory requirements, not residency or unique heap allocation bytes. + // Pass the resource's owning device. Unsupported queries leave outBytes unchanged; + // descriptor capacity remains separately available. + bool tryGetResourceAllocationBytes(nvrhi::IDevice* device, nvrhi::IResource* resource, uint64_t& outBytes); + + // Deduplicates buffers within each category. Shared heaps and cross-category aliases need + // application-specific attribution rather than summing these requirements as physical memory. + SceneGeometryMemoryStats getSceneGeometryMemoryStats(nvrhi::IDevice* device, const Scene& scene); +} diff --git a/include/donut/engine/Scene.h b/include/donut/engine/Scene.h index 31886a16..7290897b 100644 --- a/include/donut/engine/Scene.h +++ b/include/donut/engine/Scene.h @@ -22,6 +22,7 @@ #pragma once +#include #include #include #include @@ -145,6 +146,7 @@ namespace donut::engine [[nodiscard]] nvrhi::IBuffer* GetMaterialBuffer() const { return m_MaterialBuffer; } [[nodiscard]] nvrhi::IBuffer* GetGeometryBuffer() const { return m_GeometryBuffer; } [[nodiscard]] nvrhi::IBuffer* GetInstanceBuffer() const { return m_InstanceBuffer; } + [[nodiscard]] SceneGeometryMemoryStats getGeometryMemoryStats() const; // Can return nullptr if not yet created (by Scene::RefreshBuffers) GeometryData* GetGeometryData(const MeshGeometry& geometry) const; diff --git a/nvrhi b/nvrhi index c8d34b4f..d0c8e30d 160000 --- a/nvrhi +++ b/nvrhi @@ -1 +1 @@ -Subproject commit c8d34b4f75956c94bd9c3ce33b87ec88fead3f08 +Subproject commit d0c8e30d5f8d58c3b838b06aa1d8d0a912bea076 diff --git a/src/engine/MemoryStats.cpp b/src/engine/MemoryStats.cpp new file mode 100644 index 00000000..7edc2bc5 --- /dev/null +++ b/src/engine/MemoryStats.cpp @@ -0,0 +1,89 @@ +/* +* Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +* +* Permission is hereby granted, free of charge, to any person obtaining a +* copy of this software and associated documentation files (the "Software"), +* to deal in the Software without restriction, including without limitation +* the rights to use, copy, modify, merge, publish, distribute, sublicense, +* and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in +* all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +* DEALINGS IN THE SOFTWARE. +*/ + +#include +#include +#include + +#include + +namespace donut::engine +{ +namespace +{ + void addBuffer(nvrhi::IDevice* device, nvrhi::IBuffer* buffer, GpuMemoryUsage& stats, + std::unordered_set& visited) + { + if (buffer == nullptr || !visited.insert(buffer).second) + return; + + stats.resourceCount++; + stats.capacityBytes += buffer->getDesc().byteSize; + + uint64_t allocationBytes = 0; + if (tryGetResourceAllocationBytes(device, buffer, allocationBytes)) + stats.allocationBytes += allocationBytes; + else + stats.unknownAllocationCount++; + } +} + +bool tryGetResourceAllocationBytes(nvrhi::IDevice* device, nvrhi::IResource* resource, uint64_t& outBytes) +{ + if (device == nullptr || resource == nullptr) + return false; + + // NVRHI asserts for these unsupported queries in debug builds. + if (device->getGraphicsAPI() == nvrhi::GraphicsAPI::D3D11 || dynamic_cast(resource)) + return false; + + nvrhi::MemoryRequirements requirements; + if (!resource->queryMemoryRequirements(requirements)) + return false; + + outBytes = requirements.size; + return true; +} + +SceneGeometryMemoryStats getSceneGeometryMemoryStats(nvrhi::IDevice* device, const Scene& scene) +{ + SceneGeometryMemoryStats stats; + + const std::shared_ptr sceneGraph = scene.GetSceneGraph(); + if (sceneGraph == nullptr) + return stats; + + std::unordered_set vertexBuffers; + std::unordered_set indexBuffers; + + for (const std::shared_ptr& mesh : sceneGraph->GetMeshes()) + { + if (mesh == nullptr || mesh->buffers == nullptr) + continue; + + addBuffer(device, mesh->buffers->vertexBuffer, stats.vertexBuffers, vertexBuffers); + addBuffer(device, mesh->buffers->indexBuffer, stats.indexBuffers, indexBuffers); + } + + return stats; +} +} diff --git a/src/engine/Scene.cpp b/src/engine/Scene.cpp index 1a2fffff..87f132ad 100644 --- a/src/engine/Scene.cpp +++ b/src/engine/Scene.cpp @@ -1223,6 +1223,11 @@ GeometryData* Scene::GetGeometryData(const MeshGeometry& geometry) const return &m_Resources->geometryData[geometry.globalGeometryIndex]; } +SceneGeometryMemoryStats Scene::getGeometryMemoryStats() const +{ + return getSceneGeometryMemoryStats(m_Device, *this); +} + void Scene::UpdateInstance(const std::shared_ptr& instance) { diff --git a/tests/src/memory_stats.cpp b/tests/src/memory_stats.cpp new file mode 100644 index 00000000..42765e7a --- /dev/null +++ b/tests/src/memory_stats.cpp @@ -0,0 +1,242 @@ +// Headless native-device regression for the public Donut memory statistics APIs. +// No command lists are submitted and no windows or rendering workloads are created. +#include +#include +#include +#include +#include +#include +#if TEST_VALIDATION +#include +#endif +#include +#include +#include +#include +#include +#include +#ifdef _MSC_VER +#include +#endif + +using namespace donut::engine; +using Microsoft::WRL::ComPtr; + +static void check(bool value, const char* message) +{ + if (!value) + throw std::runtime_error(message); +} + +struct Messages : nvrhi::IMessageCallback +{ + unsigned errors = 0; + void message(nvrhi::MessageSeverity severity, const char* text) override + { + if (severity == nvrhi::MessageSeverity::Error || severity == nvrhi::MessageSeverity::Fatal) + ++errors; + std::printf("NVRHI: %s\n", text); + } +}; + +static void expectUsage(const GpuMemoryUsage& usage, uint64_t capacity, uint64_t allocation, + uint32_t count, uint32_t unknown) +{ + check(usage.capacityBytes == capacity, "descriptor capacity total"); + check(usage.allocationBytes == allocation, "backing allocation total"); + check(usage.resourceCount == count, "unique resource count"); + check(usage.unknownAllocationCount == unknown, "unknown allocation count"); + check(usage.hasKnownAllocationBytes() == (unknown == 0), "unknown versus known zero"); +} + +static void expectEmpty(const SceneGeometryMemoryStats& stats) +{ + expectUsage(stats.vertexBuffers, 0, 0, 0, 0); + expectUsage(stats.indexBuffers, 0, 0, 0, 0); +} + +static uint64_t checkAllocation(nvrhi::IDevice* device, nvrhi::IBuffer* buffer, bool supported) +{ + uint64_t bytes = 123; + check(tryGetResourceAllocationBytes(device, buffer, bytes) == supported, "allocation availability"); + if (!supported) + { + check(bytes == 123, "D3D11 optional query preserves output without legacy assertion"); + return 0; + } + + ID3D12Device* nativeDevice = device->getNativeObject(nvrhi::ObjectTypes::D3D12_Device); + ID3D12Resource* nativeBuffer = buffer->getNativeObject(nvrhi::ObjectTypes::D3D12_Resource); + check(nativeDevice && nativeBuffer, "native D3D12 objects"); + const auto desc = nativeBuffer->GetDesc(); + const auto expected = nativeDevice->GetResourceAllocationInfo(0, 1, &desc); + check(bytes == expected.SizeInBytes && bytes > buffer->getDesc().byteSize, + "allocation requirements match native query, not descriptor capacity"); + std::printf("Buffer capacity=%" PRIu64 " allocation=%" PRIu64 "\n", buffer->getDesc().byteSize, bytes); + return bytes; +} + +static void runScenarios(nvrhi::IDevice* device, const char* shaderPath) +{ + const bool supported = device->getGraphicsAPI() == nvrhi::GraphicsAPI::D3D12; + auto a = device->createBuffer(nvrhi::BufferDesc().setByteSize(1024)); + auto b = device->createBuffer(nvrhi::BufferDesc().setByteSize(2048)); + auto c = device->createBuffer(nvrhi::BufferDesc().setByteSize(4096)); + check(a && b && c, "real native buffers"); + const uint64_t aBytes = checkAllocation(device, a, supported); + const uint64_t bBytes = checkAllocation(device, b, supported); + const uint64_t cBytes = checkAllocation(device, c, supported); + std::puts("PASS: real allocation versus descriptor capacity / D3D11 unavailable"); + + uint64_t sentinel = 987; + check(!tryGetResourceAllocationBytes(nullptr, a, sentinel) && sentinel == 987, "null device preserves output"); + check(!tryGetResourceAllocationBytes(device, nullptr, sentinel) && sentinel == 987, "null resource preserves output"); + check(!tryGetResourceAllocationBytes(device, device, sentinel) && sentinel == 987, "unsupported resource preserves output"); + auto texture = device->createTexture(nvrhi::TextureDesc().setWidth(1).setHeight(1).setFormat(nvrhi::Format::RGBA8_UNORM)); + check(texture != nullptr, "create unsupported texture"); + check(!tryGetResourceAllocationBytes(device, texture, sentinel) && sentinel == 987, + "unsupported texture preserves output without assertion"); + std::puts("PASS: null, non-memory resource and texture output preservation"); + + auto fs = std::make_shared(); + fs->mount("/donut", std::filesystem::path(shaderPath)); + ShaderFactory shaders(device, fs, "/"); + Scene scene(device, shaders, fs, nullptr, nullptr, nullptr); + expectEmpty(scene.getGeometryMemoryStats()); // No graph yet. + auto graph = scene.CreateSceneGraph(); + expectEmpty(scene.getGeometryMemoryStats()); // A new graph has no root. + auto root = std::make_shared(); + graph->SetRootNode(root); + expectEmpty(scene.getGeometryMemoryStats()); + + auto partial = std::make_shared(); + partial->buffers = nullptr; + auto partialNode = graph->AttachLeafNode(root, std::make_shared(partial)); + expectEmpty(scene.getGeometryMemoryStats()); + partial->buffers = std::make_shared(); + expectEmpty(scene.getGeometryMemoryStats()); + partial->buffers->vertexBuffer = a; + auto stats = scene.getGeometryMemoryStats(); + expectUsage(stats.vertexBuffers, 1024, aBytes, 1, supported ? 0 : 1); + expectUsage(stats.indexBuffers, 0, 0, 0, 0); + graph->Detach(partialNode); + expectEmpty(scene.getGeometryMemoryStats()); + std::puts("PASS: absent graph, empty and partially populated scenes"); + + auto mesh = std::make_shared(); + mesh->buffers = std::make_shared(); + mesh->buffers->vertexBuffer = a; + mesh->buffers->indexBuffer = b; + auto first = graph->AttachLeafNode(root, std::make_shared(mesh)); + auto repeated = graph->AttachLeafNode(root, std::make_shared(mesh)); + auto sharedGroup = std::make_shared(); + sharedGroup->buffers = mesh->buffers; + auto shared = graph->AttachLeafNode(root, std::make_shared(sharedGroup)); + auto aliases = std::make_shared(); + aliases->buffers = std::make_shared(); + aliases->buffers->vertexBuffer = a; // Same handle, different BufferGroup. + aliases->buffers->indexBuffer = a; // Same handle also counts in the index category. + auto crossCategory = graph->AttachLeafNode(root, std::make_shared(aliases)); + stats = scene.getGeometryMemoryStats(); + expectUsage(stats.vertexBuffers, 1024, aBytes, 1, supported ? 0 : 1); + expectUsage(stats.indexBuffers, 3072, aBytes + bBytes, 2, supported ? 0 : 2); + auto unknown = getSceneGeometryMemoryStats(nullptr, scene); + expectUsage(unknown.vertexBuffers, 1024, 0, 1, 1); + expectUsage(unknown.indexBuffers, 3072, 0, 2, 2); + std::puts("PASS: shared geometry deduplication, cross-category attribution, unknown versus zero"); + + aliases->buffers->vertexBuffer = c; + stats = scene.getGeometryMemoryStats(); + expectUsage(stats.vertexBuffers, 5120, aBytes + cBytes, 2, supported ? 0 : 2); + expectUsage(stats.indexBuffers, 3072, aBytes + bBytes, 2, supported ? 0 : 2); + mesh->buffers->indexBuffer = nullptr; + stats = scene.getGeometryMemoryStats(); + expectUsage(stats.vertexBuffers, 5120, aBytes + cBytes, 2, supported ? 0 : 2); + expectUsage(stats.indexBuffers, 1024, aBytes, 1, supported ? 0 : 1); + graph->Detach(crossCategory); + stats = scene.getGeometryMemoryStats(); + expectUsage(stats.vertexBuffers, 1024, aBytes, 1, supported ? 0 : 1); + expectUsage(stats.indexBuffers, 0, 0, 0, 0); + graph->Detach(first); + graph->Detach(repeated); + stats = scene.getGeometryMemoryStats(); // Shared mesh still retains the buffer. + expectUsage(stats.vertexBuffers, 1024, aBytes, 1, supported ? 0 : 1); + graph->Detach(shared); + expectEmpty(scene.getGeometryMemoryStats()); + expectEmpty(getSceneGeometryMemoryStats(nullptr, scene)); + std::puts("PASS: replacement and removal recompute totals without stale state"); +} + +static void runDevice(nvrhi::IDevice* device, Messages& messages, const char* shaderPath) +{ + check(device != nullptr, "NVRHI device"); + std::puts("Device path: raw"); + runScenarios(device, shaderPath); +#if TEST_VALIDATION + auto validation = nvrhi::validation::createValidationLayer(device); + std::puts("Device path: validation"); + runScenarios(validation, shaderPath); +#endif + device->waitForIdle(); + device->runGarbageCollection(); + check(messages.errors == 0, "no backend or validation errors"); +} + +int main(int argc, char** argv) +{ + // Keep failures headless too, including a regression into D3D11's legacy assert. + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); +#ifdef _MSC_VER + _set_error_mode(_OUT_TO_STDERR); + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); +#endif + try + { + check(argc == 3, "usage: test_memory_stats d3d11|d3d12 shader-directory"); + Messages messages; + const std::string backend = argv[1]; + if (backend == "d3d11") + { + ComPtr native; + ComPtr context; + check(SUCCEEDED(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, 0, nullptr, 0, + D3D11_SDK_VERSION, &native, nullptr, &context)), "D3D11 WARP device"); + nvrhi::d3d11::DeviceDesc desc; + desc.context = context.Get(); + desc.messageCallback = &messages; + auto device = nvrhi::d3d11::createDevice(desc); + runDevice(device, messages, argv[2]); + } + else if (backend == "d3d12") + { + ComPtr factory; + ComPtr adapter; + check(SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))), "DXGI factory"); + check(SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))), "WARP adapter"); + ComPtr native; + check(SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&native))), "D3D12 WARP device"); + ComPtr queue; + D3D12_COMMAND_QUEUE_DESC queueDesc = {}; + check(SUCCEEDED(native->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&queue))), "D3D12 queue"); + nvrhi::d3d12::DeviceDesc desc; + desc.pDevice = native.Get(); + desc.pGraphicsCommandQueue = queue.Get(); + desc.errorCB = &messages; + auto device = nvrhi::d3d12::createDevice(desc); + runDevice(device, messages, argv[2]); + } + else + throw std::runtime_error("unknown backend"); + std::puts("PASS: all memory statistics scenarios"); + return 0; + } + catch (const std::exception& e) + { + std::fprintf(stderr, "FAIL: %s\n", e.what()); + return 1; + } +} diff --git a/tests/test-engine.cmake b/tests/test-engine.cmake index 75525eb9..eb1b064e 100755 --- a/tests/test-engine.cmake +++ b/tests/test-engine.cmake @@ -38,3 +38,23 @@ foreach(test_src ${donut_engine_tests}) endforeach() +# Native headless coverage, using WARP so no physical GPU or desktop is required. +if (WIN32 AND DONUT_WITH_DX11 AND DONUT_WITH_DX12) + add_executable(test_memory_stats src/memory_stats.cpp) + target_link_libraries(test_memory_stats PRIVATE donut_engine dxgi) + if (NOT NVRHI_BUILD_SHARED) + target_link_libraries(test_memory_stats PRIVATE nvrhi_d3d11 nvrhi_d3d12) + endif() + target_compile_definitions(test_memory_stats PRIVATE TEST_VALIDATION=$) + add_dependencies(donut_all_tests test_memory_stats) + set_property(TARGET test_memory_stats PROPERTY FOLDER "Donut/donut_tests/donut_engine_tests") + + set(memory_stats_shader_dir "${donut_BINARY_DIR}/shaders/compiled_shaders") + if (DONUT_SHADERS_OUTPUT_DIR AND NOT DONUT_WITH_STATIC_SHADERS) + set(memory_stats_shader_dir "${DONUT_SHADERS_OUTPUT_DIR}") + endif() + add_test(NAME test_memory_stats_d3d11 COMMAND test_memory_stats d3d11 "${memory_stats_shader_dir}/dxbc") + add_test(NAME test_memory_stats_d3d12 COMMAND test_memory_stats d3d12 "${memory_stats_shader_dir}/dxil") + set_tests_properties(test_memory_stats_d3d11 test_memory_stats_d3d12 PROPERTIES TIMEOUT 60) +endif() +