From 1fc1ff430912d6742a0c98dd2bd88f26fd284377 Mon Sep 17 00:00:00 2001 From: PyZik <98541963+PyZikYG@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:53:02 +0500 Subject: [PATCH 1/2] d3d12: execute fixed-count indirect mesh dispatches on Vulkan Preserve graphics state and replay a strided DISPATCH_MESH argument buffer through VK_EXT_mesh_shader. --- docs/d3d12_vulkan.md | 12 ++++++++---- runtime/shims/d3d12_com.cpp | 20 +++++++++++++------- runtime/shims/d3d12_vulkan_device.cpp | 4 ++-- runtime/src/command_list.h | 19 +++++++++++++++---- runtime/src/vulkan_backend.h | 2 ++ runtime/src/vulkan_replay.h | 22 ++++++++++++++++++++-- runtime/test/d3d12_mesh_test.cpp | 20 +++++++++++++++++--- 7 files changed, 77 insertions(+), 22 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e23985ecb3..a1f47e5494 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -9,9 +9,9 @@ hand-written RDNA2 run through the translator in `d3d12_translated_draw_test`, a `d3d12_m2_textured_test`. `D3D12XboxCreateDevice` uses it when `LEONIDA_D3D12=vulkan` is set and the host PC device otherwise. Root signatures (packed into the 32 user-data dwords), graphics and compute PSOs, draws, dispatches, `ExecuteIndirect`, and presentation through `PresentX` or a DXGI swapchain are implemented -and have GPU tests; which present path the game uses is still open (question 6). Shader-resource views of buffers, -pipeline-state streams (`CreatePipelineState`), tessellation and stream-output pipelines are not implemented, and -mesh shaders are reported as not supported (stream PSOs and mesh shaders: D3D-29, #1712). The device reports +and have GPU tests; which present path the game uses is still open (question 6). Buffer SRVs and pipeline-state +streams (`CreatePipelineState`) are implemented. Mesh PSOs, `DispatchMesh`, and fixed-count indirect mesh dispatches +are supported with `VK_EXT_mesh_shader`. The device reports `RaytracingTier` as `NOT_SUPPORTED`, yet `BuildRaytracingAccelerationStructure` builds XDXR BVH4 structures on the GPU (section 4.8).** This is the plan for replacing the console's `d3d12_xs.dll` with an implementation that records D3D12 commands and replays them on @@ -3764,7 +3764,11 @@ Not implemented yet: - `D3D12_COMMAND_SIGNATURE_DESC` describes the argument stride and a list of argument types. Simple draw, draw-indexed, dispatch and mesh-dispatch signatures map to `vkCmdDraw*Indirect`, `vkCmdDispatchIndirect` and `vkCmdDrawMeshTasksIndirectEXT`; use the `*Count` variants (`VK_KHR_draw_indirect_count`, core 1.2) when the - `ExecuteIndirect` call supplies a count buffer. + `ExecuteIndirect` call supplies a count buffer for draw or draw-indexed signatures. +- A single `DISPATCH_MESH` argument is supported on direct lists with a fixed command count. Recording captures + the graphics PSO, root arguments and render targets as `DispatchMesh` does. Vulkan reads the three group counts + from the argument buffer at execution, using the signature's byte stride. Mesh signatures with additional + arguments and mesh execution with a GPU count buffer are still unsupported. - Signatures that change root constants, vertex/index buffers or descriptors per argument cannot be expressed by one Vulkan indirect call. Use a compute expansion pass that writes a Vulkan-shaped indirect buffer, or `VK_NV_device_generated_commands` on NVIDIA. Start with the simple signatures; the trace will show which diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 883cce32a1..e3f1beb86f 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -992,13 +992,19 @@ class GraphicsCommandList final return check(false); } if (kind == leonida::IndirectKind::dispatch_mesh) { - // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the - // first such call says so. The list stays valid. - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12: ExecuteIndirect with a DISPATCH_MESH signature is not replayed yet; " - "nothing was recorded\n"); - return; + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT || count_buffer) return check(false); + if (!max_command_count) return; + if (!graphics_pipeline_ || !graphics_.layout) return check(false); + if (!any_nonempty_viewport()) return; + const auto arguments = resource_id(argument_buffer); + if (!arguments) return check(false); + leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_, + scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_}; + draw.mesh = true; + draw.viewports = draw_viewports(); + draw.mesh_indirect = leonida::MeshIndirectArguments{arguments, argument_buffer_offset, stride, + max_command_count}; + return check(list_.draw(std::move(draw))); } leonida::ExecuteIndirect cmd{}; cmd.kind = kind; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 4a892c21af..b523248fc0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -11709,8 +11709,8 @@ class Device final case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: kind = leonida::IndirectKind::draw_indexed; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: kind = leonida::IndirectKind::dispatch; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: - // As DispatchMesh: only a device with mesh shaders (MeshShaderTier 1) takes it. - if (!state_.info.mesh_shader) return E_NOTIMPL; + if (desc->NumArgumentDescs != 1 || !state_.info.mesh_shader || + !state_.context->vk.vkCmdDrawMeshTasksIndirectEXT) return E_NOTIMPL; kind = leonida::IndirectKind::dispatch_mesh; break; default: return E_NOTIMPL; diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 010abbbc01..b99184ca4a 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -431,6 +431,13 @@ struct DrawViewports { // and index buffers and the topology. // Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations // during command list recording (D3D-289). +struct MeshIndirectArguments { + ResourceId buffer; + std::uint64_t offset; + std::uint32_t stride; + std::uint32_t count; +}; + struct Draw { std::uintptr_t pipeline = 0; std::array user_data{}; @@ -451,6 +458,7 @@ struct Draw { std::uint32_t first_instance = 0; bool mesh = false; std::shared_ptr viewports; // non-null when >1 viewport or >1 scissor was bound + std::optional mesh_indirect; }; // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. @@ -599,8 +607,6 @@ enum class IndirectKind : std::uint8_t { draw = 0, draw_indexed = 1, dispatch = 2, - // D3D12_DISPATCH_MESH_ARGUMENTS. Created on a device with mesh shaders; ExecuteIndirect with it records nothing - // yet (the replay is #3777's), so a title that only creates such a signature at startup goes on. dispatch_mesh = 3, }; @@ -762,15 +768,20 @@ class CommandList { // not recorded. bool draw(const Draw& draw) { if (!draw.pipeline) return false; - if (!draw.count || !draw.instances || (draw.mesh && !draw.first)) return !closed_; + if (!has_draw_work(draw)) return !closed_; return append(draw); } bool draw(Draw&& draw) { if (!draw.pipeline) return false; - if (!draw.count || !draw.instances) return !closed_; + if (!has_draw_work(draw)) return !closed_; return append(std::move(draw)); } + static bool has_draw_work(const Draw& draw) { + if (draw.mesh_indirect) return draw.mesh_indirect->count != 0; + return draw.count && draw.instances && (!draw.mesh || draw.first); + } + // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view. bool clear_render_target(const TargetView& target, const ClearColor& color, std::span rects = {}) { if (!valid(target)) return false; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 5c3e884ba6..afce780c2f 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -120,6 +120,7 @@ struct VulkanDeviceFunctions { X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ + X(vkCmdDrawMeshTasksIndirectEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) #define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; @@ -1046,6 +1047,7 @@ class VulkanContext { replay_.set_blend_constants = vk.vkCmdSetBlendConstants; replay_.draw = vk.vkCmdDraw; replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled + replay_.draw_mesh_tasks_indirect = vk.vkCmdDrawMeshTasksIndirectEXT; replay_.draw_indexed = vk.vkCmdDrawIndexed; replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { const auto it = graphics_pipelines_.find(id); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 2fef871943..f8428a175c 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -977,6 +977,7 @@ struct ReplayFunctions { PFN_vkCmdDraw draw = nullptr; unsigned* mesh_draw_count = nullptr; // opt-in count for this submission PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported + PFN_vkCmdDrawMeshTasksIndirectEXT draw_mesh_tasks_indirect = nullptr; PFN_vkCmdDrawIndexed draw_indexed = nullptr; std::function graphics_pipeline; // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is @@ -1751,6 +1752,7 @@ inline VkDeviceSize indirect_record_size(IndirectKind kind) { case IndirectKind::draw: return sizeof(VkDrawIndirectCommand); case IndirectKind::draw_indexed: return sizeof(VkDrawIndexedIndirectCommand); case IndirectKind::dispatch: return sizeof(VkDispatchIndirectCommand); + case IndirectKind::dispatch_mesh: return 0; // Mesh dispatches use Draw to capture graphics state. } return 0; } @@ -2388,7 +2390,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct // A null pipeline with a variant builder is one built at its first draw: variant 0 (all slots bound). if (!pipeline || (!pipeline->pipeline && !pipeline->variant)) return unresolved_at(__LINE__); if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; - if (draw.mesh && !vk.draw_mesh_tasks) return unsupported_at(__LINE__); + if (draw.mesh_indirect && !vk.draw_mesh_tasks_indirect) return unsupported_at(__LINE__); + if (draw.mesh && !draw.mesh_indirect && !vk.draw_mesh_tasks) return unsupported_at(__LINE__); if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) return unsupported_at(__LINE__); if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); @@ -3685,6 +3688,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); } else if (const auto* draw = std::get_if(&command)) { + if (draw->mesh_indirect) { + const auto& args = *draw->mesh_indirect; + if (!bind(args.buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; + constexpr VkDeviceSize record_size = sizeof(VkDrawMeshTasksIndirectCommandEXT); + if (!draw->mesh || !args.count || args.stride < record_size || args.stride % 4 || + !detail::indirect_range(p.binding, args.offset, VkDeviceSize(args.count - 1) * args.stride + record_size)) + return ReplayResult::invalid_indirect_arguments; + } if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count]; prepared_draw.reset(); @@ -4892,7 +4903,14 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], &d.vertex_sizes[slot], &d.vertex_strides[slot]); } - if (draw->mesh) { + if (draw->mesh_indirect) { + const auto& args = *draw->mesh_indirect; + const VkDeviceSize offset = p.binding.buffer_offset + args.offset; + // A single record per call also works without Vulkan's multiDrawIndirect feature. + for (std::uint32_t record = 0; record < args.count; ++record) + vk.draw_mesh_tasks_indirect(command_buffer, p.binding.buffer, + offset + VkDeviceSize(record) * args.stride, 1, args.stride); + } else if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); if (vk.mesh_draw_count) ++*vk.mesh_draw_count; } else if (draw->topology == topology_quad_list) { diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 2d9bc5212e..d9849e5b8e 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -7,7 +7,8 @@ // refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and // state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL. // - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; -// DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the +// ExecuteIndirect with a padded DISPATCH_MESH signature runs an empty grid and then a (1, 1, 2) grid. The grid +// moved by (1, -1) with a green tint fills the top half of the bottom-right quadrant, so the // Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the // bottom-left quadrant (yellow). Each pixel is read back and compared. // - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: @@ -394,7 +395,19 @@ int main(int argc, char** argv) { std::uint8_t* up = nullptr; EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); for (int i = 0; i < 3; ++i) std::memcpy(up + 256 * i, tints[i], sizeof(tints[i])); + constexpr UINT mesh_args_offset = 1024; + struct MeshRecord { + D3D12_DISPATCH_MESH_ARGUMENTS grid; + UINT padding; + }; + const MeshRecord mesh_args[] = {{{0, 0, 0}, 0}, {{1, 1, 2}, 0}}; + std::memcpy(up + mesh_args_offset, mesh_args, sizeof(mesh_args)); const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress(); + const D3D12_INDIRECT_ARGUMENT_DESC mesh_argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC mesh_signature_desc{sizeof(MeshRecord), 1, &mesh_argument, 0}; + Ref mesh_signature; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&mesh_signature_desc, nullptr, + IID_PPV_ARGS(&mesh_signature.p)))); const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; Ref rtv_heap; @@ -439,7 +452,7 @@ int main(int argc, char** argv) { // of the bottom-right quadrant. list->SetGraphicsRoot32BitConstants(0, 2, down_right, 0); list->SetGraphicsRootConstantBufferView(1, upload_va + 256); - list6->DispatchMesh(1, 1, 2); + list->ExecuteIndirect(mesh_signature.p, 2, upload.p, mesh_args_offset, nullptr, 0); // The stream's VS PSO: a full-screen triangle through a viewport on the bottom-left quadrant, yellow. const D3D12_VIEWPORT bottom_left{0, float(size / 2), float(size / 2), float(size / 2), 0, 1}; list->RSSetViewports(1, &bottom_left); @@ -714,6 +727,7 @@ int main(int argc, char** argv) { for (auto* p : {&mesh_pso, &vs_pso, &refused}) p->reset(); root.reset(); rtv_heap.reset(); + mesh_signature.reset(); list6.reset(); list.reset(); allocator.reset(); @@ -745,7 +759,7 @@ int main(int argc, char** argv) { return 1; } std::printf("D3D-29: mesh tier 1; mesh and VS PSOs from pipeline state streams (9 refused as invalid, 2 as not " - "implemented); DispatchMesh over X, Y and Z and a stream VS draw matched all %u pixels; wrong-kind " + "implemented); direct and indirect mesh dispatches and a stream VS draw matched all %u pixels; wrong-kind " "draws fail at execution, oversized grids at Close; statistics queries around mesh draws resolve\n", size * size); return 0; From 434339571809687dec8c50b565e3e4d34a72511a Mon Sep 17 00:00:00 2001 From: PyZik <98541963+PyZikYG@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:29:01 +0500 Subject: [PATCH 2/2] d3d12: use GPU count buffers for indirect mesh dispatches --- docs/d3d12_vulkan.md | 13 ++++---- runtime/shims/d3d12_com.cpp | 9 ++++-- runtime/src/command_list.h | 2 ++ runtime/src/vulkan_replay.h | 24 +++++++++++++-- runtime/test/d3d12_mesh_test.cpp | 49 +++++++++++++++++++++++++++---- runtime/test/replay_cpu_bench.cpp | 1 + 6 files changed, 81 insertions(+), 17 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index a1f47e5494..cad94f5189 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -10,8 +10,8 @@ hand-written RDNA2 run through the translator in `d3d12_translated_draw_test`, a set and the host PC device otherwise. Root signatures (packed into the 32 user-data dwords), graphics and compute PSOs, draws, dispatches, `ExecuteIndirect`, and presentation through `PresentX` or a DXGI swapchain are implemented and have GPU tests; which present path the game uses is still open (question 6). Buffer SRVs and pipeline-state -streams (`CreatePipelineState`) are implemented. Mesh PSOs, `DispatchMesh`, and fixed-count indirect mesh dispatches -are supported with `VK_EXT_mesh_shader`. The device reports +streams (`CreatePipelineState`) are implemented. Mesh PSOs, `DispatchMesh`, and indirect mesh dispatches +are supported with `VK_EXT_mesh_shader`; GPU count buffers have additional requirements (section 4.7). The device reports `RaytracingTier` as `NOT_SUPPORTED`, yet `BuildRaytracingAccelerationStructure` builds XDXR BVH4 structures on the GPU (section 4.8).** This is the plan for replacing the console's `d3d12_xs.dll` with an implementation that records D3D12 commands and replays them on @@ -3765,10 +3765,13 @@ Not implemented yet: draw-indexed, dispatch and mesh-dispatch signatures map to `vkCmdDraw*Indirect`, `vkCmdDispatchIndirect` and `vkCmdDrawMeshTasksIndirectEXT`; use the `*Count` variants (`VK_KHR_draw_indirect_count`, core 1.2) when the `ExecuteIndirect` call supplies a count buffer for draw or draw-indexed signatures. -- A single `DISPATCH_MESH` argument is supported on direct lists with a fixed command count. Recording captures +- A single `DISPATCH_MESH` argument is supported on direct lists. Recording captures the graphics PSO, root arguments and render targets as `DispatchMesh` does. Vulkan reads the three group counts - from the argument buffer at execution, using the signature's byte stride. Mesh signatures with additional - arguments and mesh execution with a GPU count buffer are still unsupported. + from the argument buffer at execution, using the signature's byte stride. With a count buffer, the same GPU helper + as compute indirect dispatch prepares compact mesh records and zeroes those beyond the clamped count before + rendering. This requires buffer device addresses and keeps the helper dispatch outside pipeline statistics queries. + Fixed counts work on mesh-capable devices without that path. + Mesh signatures with additional arguments are still unsupported. - Signatures that change root constants, vertex/index buffers or descriptors per argument cannot be expressed by one Vulkan indirect call. Use a compute expansion pass that writes a Vulkan-shaped indirect buffer, or `VK_NV_device_generated_commands` on NVIDIA. Start with the simple signatures; the trace will show which diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index e3f1beb86f..9382bca8a2 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -99,6 +99,8 @@ const char* name(leonida::ReplayResult result) { case leonida::ReplayResult::invalid_query: return "invalid query"; case leonida::ReplayResult::invalid_indirect_arguments: return "invalid indirect argument or count buffer range"; case leonida::ReplayResult::invalid_draw: return "draw kind does not match the pipeline (mesh or vertex)"; + case leonida::ReplayResult::unsupported_mesh_indirect_count: + return "GPU mesh indirect count could not be prepared (requires buffer device addresses and compute scratch)"; case leonida::ReplayResult::unsupported: return "unsupported"; } return "?"; @@ -992,18 +994,19 @@ class GraphicsCommandList final return check(false); } if (kind == leonida::IndirectKind::dispatch_mesh) { - if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT || count_buffer) return check(false); + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); if (!max_command_count) return; if (!graphics_pipeline_ || !graphics_.layout) return check(false); if (!any_nonempty_viewport()) return; const auto arguments = resource_id(argument_buffer); - if (!arguments) return check(false); + const auto count = count_buffer ? resource_id(count_buffer) : 0; + if (!arguments || (count_buffer && !count)) return check(false); leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_, scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_}; draw.mesh = true; draw.viewports = draw_viewports(); draw.mesh_indirect = leonida::MeshIndirectArguments{arguments, argument_buffer_offset, stride, - max_command_count}; + max_command_count, count, count_buffer_offset}; return check(list_.draw(std::move(draw))); } leonida::ExecuteIndirect cmd{}; diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index b99184ca4a..5c37e801f0 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -436,6 +436,8 @@ struct MeshIndirectArguments { std::uint64_t offset; std::uint32_t stride; std::uint32_t count; + ResourceId count_buffer = 0; + std::uint64_t count_offset = 0; }; struct Draw { diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index f8428a175c..e11b5dab54 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -857,6 +857,7 @@ enum class ReplayResult { invalid_query, invalid_indirect_arguments, invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has + unsupported_mesh_indirect_count, unsupported }; @@ -3695,6 +3696,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!draw->mesh || !args.count || args.stride < record_size || args.stride % 4 || !detail::indirect_range(p.binding, args.offset, VkDeviceSize(args.count - 1) * args.stride + record_size)) return ReplayResult::invalid_indirect_arguments; + if (args.count_buffer) { + const ResourceBinding* count = resolve(args.count_buffer); + if (!count || !count->buffer) return ReplayResult::unresolved_resource; + if (!detail::indirect_range(*count, args.count_offset, sizeof(std::uint32_t))) + return ReplayResult::invalid_indirect_arguments; + // Clamp the GPU count before executing any draw, including when the count is UINT32_MAX. + if (!vk.prepare_counted_dispatch || !vk.emit_counted_dispatch || + (statistics_active && !statistics_helpers) || + !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + args.offset, + count->buffer, count->buffer_offset + args.count_offset, + args.stride, args.count, p.counted_dispatch)) + return ReplayResult::unsupported_mesh_indirect_count; + } } if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count]; @@ -4034,6 +4048,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ end_statistics(); if (std::holds_alternative(command) && prepared.draws[p.draw].quad_indices.buffer) vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); + if (std::holds_alternative(command) && p.counted_dispatch.indirect) + vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); begin_statistics(); } if (const auto* predication = std::get_if(&command)) { @@ -4905,11 +4921,13 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } if (draw->mesh_indirect) { const auto& args = *draw->mesh_indirect; - const VkDeviceSize offset = p.binding.buffer_offset + args.offset; + const bool counted = p.counted_dispatch.indirect != VK_NULL_HANDLE; + const VkBuffer buffer = counted ? p.counted_dispatch.indirect : p.binding.buffer; + const VkDeviceSize offset = counted ? p.counted_dispatch.offset : p.binding.buffer_offset + args.offset; + const VkDeviceSize stride = counted ? sizeof(VkDrawMeshTasksIndirectCommandEXT) : args.stride; // A single record per call also works without Vulkan's multiDrawIndirect feature. for (std::uint32_t record = 0; record < args.count; ++record) - vk.draw_mesh_tasks_indirect(command_buffer, p.binding.buffer, - offset + VkDeviceSize(record) * args.stride, 1, args.stride); + vk.draw_mesh_tasks_indirect(command_buffer, buffer, offset + record * stride, 1, 0); } else if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); if (vk.mesh_draw_count) ++*vk.mesh_draw_count; diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index d9849e5b8e..a3f7e71975 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -7,7 +7,8 @@ // refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and // state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL. // - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; -// ExecuteIndirect with a padded DISPATCH_MESH signature runs an empty grid and then a (1, 1, 2) grid. The grid +// ExecuteIndirect with a padded DISPATCH_MESH signature runs a (1, 1, 2) grid. With indirect counts enabled, +// a GPU copy sets the count to 1 and suppresses a second nonempty grid. The grid // moved by (1, -1) with a green tint fills the top half of the bottom-right quadrant, so the // Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the // bottom-left quadrant (yellow). Each pixel is read back and compared. @@ -106,6 +107,7 @@ int main(int argc, char** argv) { EXPECT(SetEnvironmentVariableW(L"LEONIDA_XS_STREAM_ENUM", pc_only ? L"0" : L"1")); vktest::Device d; d.request_mesh_shader = true; + d.request_buffer_device_address = true; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) { std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); @@ -234,6 +236,7 @@ int main(int argc, char** argv) { constexpr UINT size = 64; std::vector pixels(size * 256); + const bool counted_mesh = d.buffer_device_address; { Ref device; Ref root; @@ -370,7 +373,7 @@ int main(int argc, char** argv) { const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - Ref upload, readback, target; + Ref upload, readback, target, count_buffer; const auto upload_desc = buffer_desc(4096); EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, @@ -379,6 +382,13 @@ int main(int argc, char** argv) { EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); + constexpr UINT count_offset = 4; + if (counted_mesh) { + const auto count_desc = buffer_desc(count_offset + sizeof(UINT)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &count_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&count_buffer.p)))); + } D3D12_RESOURCE_DESC rt_desc{}; rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; rt_desc.Width = rt_desc.Height = size; @@ -400,8 +410,11 @@ int main(int argc, char** argv) { D3D12_DISPATCH_MESH_ARGUMENTS grid; UINT padding; }; - const MeshRecord mesh_args[] = {{{0, 0, 0}, 0}, {{1, 1, 2}, 0}}; + const MeshRecord mesh_args[] = {{{0, 0, 0}, 0}, {{1, 1, 2}, 0}, {{2, 2, 1}, 0}}; std::memcpy(up + mesh_args_offset, mesh_args, sizeof(mesh_args)); + constexpr UINT count_upload_offset = mesh_args_offset + sizeof(mesh_args); + const UINT mesh_counts[] = {1, UINT32_MAX}; + std::memcpy(up + count_upload_offset, mesh_counts, sizeof(mesh_counts)); const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress(); const D3D12_INDIRECT_ARGUMENT_DESC mesh_argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; const D3D12_COMMAND_SIGNATURE_DESC mesh_signature_desc{sizeof(MeshRecord), 1, &mesh_argument, 0}; @@ -448,11 +461,33 @@ int main(int argc, char** argv) { list->SetGraphicsRootConstantBufferView(1, upload_va); list6->DispatchMesh(0, 1, 1); list6->DispatchMesh(2, 2, 1); + const auto copy_count = [&](UINT offset) { + list->CopyBufferRegion(count_buffer.p, count_offset, upload.p, offset, sizeof(UINT)); + const auto to_indirect = transition(count_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list->ResourceBarrier(1, &to_indirect); + }; + if (counted_mesh) copy_count(count_upload_offset); // Mesh draw 2: groups (0,0,0) and (0,0,1), columns 0 and 1 of row 0, moved by (1, -1), green -> the top half // of the bottom-right quadrant. list->SetGraphicsRoot32BitConstants(0, 2, down_right, 0); list->SetGraphicsRootConstantBufferView(1, upload_va + 256); - list->ExecuteIndirect(mesh_signature.p, 2, upload.p, mesh_args_offset, nullptr, 0); + // A count of one suppresses the second record, which would paint over the blue pixels below the green band. + if (counted_mesh) { + list->ExecuteIndirect(mesh_signature.p, 2, upload.p, mesh_args_offset + sizeof(MeshRecord), + count_buffer.p, count_offset); + const auto to_count_copy = transition(count_buffer.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_DEST); + list->ResourceBarrier(1, &to_count_copy); + copy_count(count_upload_offset + sizeof(UINT)); + // UINT32_MAX must be clamped to one, so only the upper band of the top-right quadrant changes. + const float up_right[2] = {1, 0}; + list->SetGraphicsRoot32BitConstants(0, 2, up_right, 0); + list->ExecuteIndirect(mesh_signature.p, 1, upload.p, mesh_args_offset + sizeof(MeshRecord), + count_buffer.p, count_offset); + } else { + list->ExecuteIndirect(mesh_signature.p, 2, upload.p, mesh_args_offset, nullptr, 0); + } // The stream's VS PSO: a full-screen triangle through a viewport on the bottom-left quadrant, yellow. const D3D12_VIEWPORT bottom_left{0, float(size / 2), float(size / 2), float(size / 2), 0, 1}; list->RSSetViewports(1, &bottom_left); @@ -723,7 +758,7 @@ int main(int argc, char** argv) { std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n"); } - for (auto* r : {&upload, &readback, &target}) r->reset(); + for (auto* r : {&upload, &readback, &target, &count_buffer}) r->reset(); for (auto* p : {&mesh_pso, &vs_pso, &refused}) p->reset(); root.reset(); rtv_heap.reset(); @@ -741,10 +776,11 @@ int main(int argc, char** argv) { for (UINT row = 0; row < size; ++row) { for (UINT col = 0; col < size; ++col) { const bool top = row < size / 2, left = col < size / 2; + const bool green = !left && ((counted_mesh && row < size / 4) || (!top && row < size * 3 / 4)); using Pixel = std::array; const Pixel want = top && left ? Pixel{255, 0, 0, 255} : !top && left ? Pixel{255, 255, 0, 255} - : !top && !left && row < size * 3 / 4 ? Pixel{0, 255, 0, 255} + : green ? Pixel{0, 255, 0, 255} : Pixel{0, 0, 255, 255}; const std::uint8_t* got = pixels.data() + row * 256 + col * 4; if (std::equal(want.begin(), want.end(), got)) continue; @@ -754,6 +790,7 @@ int main(int argc, char** argv) { } } EXPECT(!mismatches); + std::printf("mesh indirect used %s\n", counted_mesh ? "a GPU count buffer" : "a fixed count (GPU count unavailable)"); if (d.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp index e4c15cd339..28292e9675 100644 --- a/runtime/test/replay_cpu_bench.cpp +++ b/runtime/test/replay_cpu_bench.cpp @@ -495,6 +495,7 @@ const char* result_name(ReplayResult r) { case ReplayResult::invalid_predication: return "invalid_predication"; case ReplayResult::invalid_query: return "invalid_query"; case ReplayResult::invalid_indirect_arguments: return "invalid_indirect_arguments"; + case ReplayResult::unsupported_mesh_indirect_count: return "unsupported_mesh_indirect_count"; case ReplayResult::invalid_draw: return "invalid_draw"; case ReplayResult::unsupported: return "unsupported"; }