diff --git a/src/airconv/airconv_public.h b/src/airconv/airconv_public.h index e8bf54aa6..6e60f527c 100644 --- a/src/airconv/airconv_public.h +++ b/src/airconv/airconv_public.h @@ -5,7 +5,7 @@ #ifndef __AIRCONV_H #define __AIRCONV_H -#define AIRCONV_VERSION 26 +#define AIRCONV_VERSION 30 #ifdef __cplusplus #include diff --git a/src/airconv/dxbc_converter_ts.cpp b/src/airconv/dxbc_converter_ts.cpp index 94a55c3a7..0975af309 100644 --- a/src/airconv/dxbc_converter_ts.cpp +++ b/src/airconv/dxbc_converter_ts.cpp @@ -116,8 +116,7 @@ get_max_potential_workload_count(uint32_t max_tess_factor, SM50ShaderInternal *p case microsoft::D3D11_SB_TESSELLATOR_DOMAIN_TRI: return std::ceil((max_tess_factor - 1) / 4.0) * 3 + (max_tess_factor & 1); case microsoft::D3D11_SB_TESSELLATOR_DOMAIN_QUAD: - return std::ceil((max_tess_factor - 1) / 4.0) * 4 + (max_tess_factor & 1); - ; + return max_tess_factor + ((max_tess_factor & 1) == 0); } } @@ -275,7 +274,7 @@ convert_dxbc_vertex_hull_shader( uint32_t max_workload_count = get_max_potential_workload_count(factor_int, pHullStage); - func_signature.UseMaxMeshWorkgroupSize(max_workload_count); + func_signature.UseMaxMeshWorkgroupSize(max_workload_count * patch_per_group); constexpr uint32_t size_workload_info = sizeof(TessMeshWorkload); @@ -283,7 +282,7 @@ convert_dxbc_vertex_hull_shader( context, {hs_output_per_group_type, hs_pcout_per_group_scaler_type, types._int, llvm::ArrayType::get(types._int, max_workload_count * patch_per_group * size_workload_info / 4)}, - "payload" + "payload", true ); uint32_t payload_struct_size = module.getDataLayout().getTypeAllocSize(payload_struct_type); @@ -910,7 +909,7 @@ convert_dxbc_tesselator_domain_shader( context, {hs_output_per_group_type, hs_pcout_per_group_scaler_type, types._int, llvm::ArrayType::get(types._int, max_workload_count * patch_per_group * size_workload_info / 4)}, - "payload" + "payload", true ); uint32_t payload_struct_size = module.getDataLayout().getTypeAllocSize(payload_struct_type); diff --git a/src/airconv/nt/dxil_converter_base.cpp b/src/airconv/nt/dxil_converter_base.cpp index 75076fadc..7e07088ab 100644 --- a/src/airconv/nt/dxil_converter_base.cpp +++ b/src/airconv/nt/dxil_converter_base.cpp @@ -48,8 +48,10 @@ Converter::Converter(EntryPoint const &entry, dxmt::dxbc::context &ctx) : air(ctx.air), entry(entry) { for (const auto &property : entry.properties) { - if (property.tag == EntryPropertyTag::HSState) + if (property.tag == EntryPropertyTag::HSState) { pcf_ = property.hs_state.patch_constant_function; + output_control_point_count_ = property.hs_state.output_control_point_count; + } } } @@ -135,6 +137,20 @@ Converter::Run(llvm::BasicBlock *ReturnBB) { return PCFStart; } + if (output_control_point_count_) { + auto cp_active = llvm::BasicBlock::Create(air.getContext(), "cp_active", ctx.function); + auto cp_end = llvm::BasicBlock::Create(air.getContext(), "cp_end", ctx.function); + ir.SetInsertPoint(cp_active); + auto is_active_control_point_thread = ctx.builder.CreateICmp( + llvm::CmpInst::ICMP_ULT, ctx.resource.thread_id_in_patch, ctx.builder.getInt32(output_control_point_count_) + ); + ir.CreateCondBr(is_active_control_point_thread, block_map_[&entry.function->getEntryBlock()], cp_end); + ir.SetInsertPoint(cp_end); + air.CreateBarrier(llvm::air::MemFlags::Threadgroup); + ir.CreateBr(pcf_ ? PCFStart : ReturnBB); + return cp_active; + } + return block_map_[&entry.function->getEntryBlock()]; } diff --git a/src/airconv/nt/dxil_converter_base.hpp b/src/airconv/nt/dxil_converter_base.hpp index 9df9b206a..f1516a812 100644 --- a/src/airconv/nt/dxil_converter_base.hpp +++ b/src/airconv/nt/dxil_converter_base.hpp @@ -42,6 +42,7 @@ class Converter { const EntryPoint &entry; const llvm::Function *pcf_ = nullptr; + uint32_t output_control_point_count_ = 0; llvm::DenseMap value_map_; llvm::DenseMap block_map_; llvm::DenseMap type_map_; diff --git a/src/d3d12/d3d12_command_allocator.cpp b/src/d3d12/d3d12_command_allocator.cpp index b67a737f6..69c319ba3 100644 --- a/src/d3d12/d3d12_command_allocator.cpp +++ b/src/d3d12/d3d12_command_allocator.cpp @@ -134,6 +134,9 @@ MTLD3D12CommandAllocatorImpl::Reset() { case EncoderType::Resolve: reinterpret_cast(next)->~ResolveEncoderData(); break; + case EncoderType::OcclusionQueryResolve: + reinterpret_cast(next)->~OcclusionQueryResolveEncoderData(); + break; } next = next->next; } @@ -204,7 +207,7 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectComputeCommand(MTLD3D12CommandSignat auto &cmd_setpso_res = EncodeComputeCommand(); cmd_setpso_res.type = WMTComputeCommandSetPSO; - cmd_setpso_res.pso = pCmdSig->compute_resolver; + cmd_setpso_res.pso = pCmdSig->resolver; cmd_setpso_res.threadgroup_size = {1, 1, 1}; auto &cmd_argbuf_res = EncodeComputeCommand(); @@ -214,8 +217,8 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectComputeCommand(MTLD3D12CommandSignat cmd_argbuf_res.index = 30; auto &cmd_dispatch_res = EncodeComputeCommand(); - cmd_dispatch_res.type = WMTComputeCommandDispatch; - cmd_dispatch_res.size = {1, 1, 1}; + cmd_dispatch_res.type = WMTComputeCommandDispatchThreads; + cmd_dispatch_res.size = {MaxCount, 1, 1}; auto &cmd_setpso = EncodeComputeCommand(); cmd_setpso.type = WMTComputeCommandSetPSO; @@ -236,95 +239,96 @@ MTLD3D12CommandAllocatorImpl::EncodeIndirectComputeCommand(MTLD3D12CommandSignat IndirectRenderCommandData * MTLD3D12CommandAllocatorImpl::EncodeIndirectRenderCommand( - MTLD3D12CommandSignature *pCmdSig, MTLD3D12GraphicsPipelineState *pPSO, size_t MaxCount + MTLD3D12CommandSignature *pCmdSig, MTLD3D12GraphicsPipelineState *pPSO, size_t MaxCount, + D3D12_PRIMITIVE_TOPOLOGY Topology ) { - WMTIndirectCommandBufferInfo info; - info.inherit_buffers = !(pCmdSig->UpdateVertexBuffers || pCmdSig->UpdateIndexBuffer || pCmdSig->UpdateRootArguments); - info.inherit_pso = 1; - info.inherit_cull_mode = 1; - info.inherit_fill_mode = 1; - info.inherit_front_facing = 1; - info.inherit_depth_bias = 1; - info.inherit_depth_clip_mode = 1; - info.inherit_depth_stencil_state = 1; - info.support_color_attachment_mapping = 0; - info.support_dynamic_attribute_stride = 0; - info.support_ray_tracing = 0; - info.type = pCmdSig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED ? WMTIndirectCommandTypeDrawIndexed - : WMTIndirectCommandTypeDraw; - info.max_vertex_buffer_binding = 31; - info.max_fragment_buffer_binding = 31; - info.max_object_buffer_binding = 0; - info.max_mesh_buffer_binding = 0; - info.max_kernel_buffer_binding = 0; - info.max_kernel_threadgroup_memory_binding = 0; - info.max_object_threadgroup_memory_binding = 0; - info.gpu_resource_id = 0; - - auto icb = device_->GetMTLDevice().newIndirectCommandBuffer(info, MaxCount, WMTResourceStorageModePrivate); + bool use_emulated_mesh = pPSO->is_geometry || pPSO->is_tess; + bool encode_binding = + use_emulated_mesh || pCmdSig->UpdateVertexBuffers || pCmdSig->UpdateIndexBuffer || pCmdSig->UpdateRootArguments; auto [Ptr, Offset] = AllocateGPUHeap(sizeof(IndirectRenderCommandData), 16); auto data = reinterpret_cast(Ptr); - data->cmd_buf = info.gpu_resource_id; - data->max_count = MaxCount; + uint32_t cmd_flags = 0; + if (pPSO->is_geometry) + cmd_flags |= kIndirectRenderCommandFlagIsGeometry; + if (pPSO->is_tess) + cmd_flags |= kIndirectRenderCommandFlagIsTessellation; - { - // populated outside - data->max_count_buffer = 0; - data->argument_buffer = 0; - data->rootsig_qwords = 0; - data->rootsig_qwords_stride = 0; - data->static_samplers = 0; - data->vertex_buffer = 0; - data->vertex_argbuf_stride = 0; - data->primitive_type = 0; - data->index_buffer = 0; - data->index_buffer_format = {}; - } - - { - /** - * TODO: move these out? - */ - - auto &cmd_use_icb = EncodeRenderCommand(); - cmd_use_icb.type = WMTRenderCommandUseResource; - cmd_use_icb.stages = WMTRenderStageVertex; + data->cmd_buf = 0; + data->max_count = MaxCount; + data->max_count_buffer = 0; + data->argument_buffer = 0; + data->rootsig_qwords = 0; + data->rootsig_qwords_stride = 0; + data->static_samplers = 0; + data->vertex_buffer = 0; + data->vertex_argbuf_stride = 0; + data->primitive_type = 0; + data->index_buffer = 0; + data->index_buffer_format = {}; + data->dyn_ib_args = 0; + data->flags = cmd_flags; + data->vertex_increment_per_warp = 0; + data->vertex_per_warp = 0; + + if (!use_emulated_mesh || device_->mesh_icb_supported) { + WMTIndirectCommandBufferInfo info; + info.inherit_buffers = !encode_binding; + info.inherit_pso = 1; + info.inherit_cull_mode = 1; + info.inherit_fill_mode = 1; + info.inherit_front_facing = 1; + info.inherit_depth_bias = 1; + info.inherit_depth_clip_mode = 1; + info.inherit_depth_stencil_state = 1; + info.support_color_attachment_mapping = 0; + info.support_dynamic_attribute_stride = 0; + info.support_ray_tracing = 0; + info.type = use_emulated_mesh ? WMTIndirectCommandTypeDrawMeshThreadgroups + : pCmdSig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED ? WMTIndirectCommandTypeDrawIndexed + : WMTIndirectCommandTypeDraw; + info.max_vertex_buffer_binding = 31; + info.max_fragment_buffer_binding = 31; + info.max_object_buffer_binding = 31; + info.max_mesh_buffer_binding = 31; + info.max_kernel_buffer_binding = 0; + info.max_kernel_threadgroup_memory_binding = 0; + info.max_object_threadgroup_memory_binding = 0; + info.gpu_resource_id = 0; + auto icb = device_->GetMTLDevice().newIndirectCommandBuffer(info, MaxCount, WMTResourceStorageModePrivate | WMTResourceHazardTrackingModeUntracked); + + data->cmd_buf = info.gpu_resource_id; + + auto &cmd_use_icb = EncodeRenderPrepassCommand(); + cmd_use_icb.type = WMTComputeCommandUseResource; cmd_use_icb.usage = WMTResourceUsageRead | WMTResourceUsageWrite; cmd_use_icb.resource = icb; - auto &cmd_setpso_res = EncodeRenderCommand(); - cmd_setpso_res.type = WMTRenderCommandSetPSO; - cmd_setpso_res.pso = pCmdSig->render_resolver; - - auto &cmd_argbuf_res = EncodeRenderCommand(); - cmd_argbuf_res.type = WMTRenderCommandSetVertexBuffer; - cmd_argbuf_res.buffer = gpu_heap_buffer_; - cmd_argbuf_res.offset = Offset; - cmd_argbuf_res.index = 30; + auto &cmd = EncodeRenderCommand(); + cmd.type = WMTRenderCommandExecuteCommandsInBuffer; + cmd.indirect_command_buffer = icb; + cmd.location = 0; + cmd.length = MaxCount; - auto &cmd_draw_res = EncodeRenderCommand(); - cmd_draw_res.type = WMTRenderCommandDraw; - cmd_draw_res.primitive_type = WMTPrimitiveTypePoint; - cmd_draw_res.vertex_start = 0; - cmd_draw_res.vertex_count = 1; - cmd_draw_res.base_instance = 0; - cmd_draw_res.instance_count = 1; - - auto &cmd_setpso = EncodeRenderCommand(); - cmd_setpso.type = WMTRenderCommandSetPSO; - cmd_setpso.pso = pPSO->GetRenderPipelineVariant({} /* FIXME: value should not matter here until gs/ts */); + icb_.push_back(std::move(icb)); } - auto &cmd = EncodeRenderCommand(); - cmd.type = WMTRenderCommandExecuteCommandsInBuffer; - cmd.indirect_command_buffer = icb; - cmd.location = 0; - cmd.length = MaxCount; + auto &cmd_setpso_res = EncodeRenderPrepassCommand(); + cmd_setpso_res.type = WMTComputeCommandSetPSO; + cmd_setpso_res.pso = pCmdSig->resolver; + cmd_setpso_res.threadgroup_size = {32, 1, 1}; - icb_.push_back(std::move(icb)); + auto &cmd_argbuf_res = EncodeRenderPrepassCommand(); + cmd_argbuf_res.type = WMTComputeCommandSetBuffer; + cmd_argbuf_res.buffer = gpu_heap_buffer_; + cmd_argbuf_res.offset = Offset; + cmd_argbuf_res.index = 30; + + auto &cmd_draw_res = EncodeRenderPrepassCommand(); + cmd_draw_res.type = WMTComputeCommandDispatchThreads; + cmd_draw_res.size = {MaxCount, 1, 1}; return data; } @@ -347,12 +351,7 @@ SimpleCommandContext::getComputePipeline(std::stri template <> void SimpleCommandContext::startComputePass() { - ctx.InvalidateCurrentPass(); - auto compute = ctx.AllocatePass(); - compute->type = EncoderType::Compute; - compute->cmd_head.type = WMTComputeCommandNop; - compute->cmd_head.next.set(0); - compute->cmd_tail = (wmtcmd_base *)&compute->cmd_head; + ctx.AllocatePass(); } template <> @@ -437,19 +436,7 @@ SimpleCommandContext::getDefaultLibrary() { template <> void SimpleCommandContext::startRenderPass() { - ctx.InvalidateCurrentPass(); - auto render = ctx.AllocatePass(); - render->type = EncoderType::Render; - render->cmd_head.type = WMTRenderCommandNop; - render->cmd_head.next.set(0); - render->cmd_tail = (wmtcmd_base *)&render->cmd_head; - render->dsv_planar_flags = 0; - render->dsv_readonly_flags = 0; - render->render_target_count = 0; - render->render_target_width = 16384; - render->render_target_height = 16384; - render->render_target_array_length = 0; - render->default_raster_sample_count = 1; + ctx.AllocatePass(); } template <> diff --git a/src/d3d12/d3d12_command_allocator.hpp b/src/d3d12/d3d12_command_allocator.hpp index 482792a07..8f92a670a 100644 --- a/src/d3d12/d3d12_command_allocator.hpp +++ b/src/d3d12/d3d12_command_allocator.hpp @@ -52,6 +52,9 @@ struct IndirectComputeCommandData { uint32_t tgsize_z; }; +constexpr uint32_t kIndirectRenderCommandFlagIsGeometry = 1 << 0; +constexpr uint32_t kIndirectRenderCommandFlagIsTessellation = 1 << 1; + struct IndirectRenderCommandData { uint64_t cmd_buf; uint64_t max_count; @@ -65,6 +68,16 @@ struct IndirectRenderCommandData { uint64_t index_buffer; DXGI_FORMAT index_buffer_format; uint32_t vertex_argbuf_stride; + uint64_t dyn_ib_args; + uint32_t flags; + union { + uint32_t vertex_per_warp; + uint32_t control_point_count; + }; + union { + uint32_t vertex_increment_per_warp; + uint32_t threads_per_patch; + }; }; class MTLD3D12CommandAllocatorImpl : public MTLD3D12Pageable { @@ -142,10 +155,9 @@ class MTLD3D12CommandAllocatorImpl : public MTLD3D12Pageable T * AllocatePass() { + assert(!encoder_current); auto p = (new (AllocateCPUHeap(sizeof(T), alignof(T))) T()); encoder_current = p; return p; @@ -195,6 +208,18 @@ class MTLD3D12CommandAllocatorImpl : public MTLD3D12Pageable + cmd_struct & + EncodeRenderPrepassCommand() { + assert(encoder_current->type == EncoderType::Render); + auto encoder = static_cast(encoder_current); + auto storage = (cmd_struct *)AllocateCPUHeap(sizeof(cmd_struct), 16); + encoder->cmd_prepass_tail->next.set(storage); + encoder->cmd_prepass_tail = (wmtcmd_base *)storage; + storage->next.set(nullptr); + return *storage; + } + template cmd_struct & EncodeBlitCommand() { @@ -239,7 +264,10 @@ class MTLD3D12CommandAllocatorImpl : public MTLD3D12Pageable namespace dxmt { @@ -30,12 +31,12 @@ enum class EncoderType { Blit, Compute, Resolve, + OcclusionQueryResolve, }; struct EncoderData { EncoderType type; EncoderData *next = nullptr; - uint64_t id; }; struct ClearEncoderData : EncoderData { @@ -44,13 +45,16 @@ struct ClearEncoderData : EncoderData { std::pair depth_stencil; }; TextureViewRef attachment; - unsigned clear_dsv; - unsigned array_length; - unsigned width; - unsigned height; - unsigned depth_plane; + unsigned clear_dsv = 0; + unsigned array_length = 0; + unsigned width = 0; + unsigned height = 0; + unsigned depth_plane = 0; - ClearEncoderData() {} + ClearEncoderData() { + type = EncoderType::Clear; + color = {0, 0, 0, 0}; + } }; struct RenderEncoderColorAttachmentData { @@ -88,35 +92,77 @@ struct RenderEncoderStencilAttachmentData { }; struct RenderEncoderData : EncoderData { - std::array colors; - RenderEncoderDepthAttachmentData depth; - RenderEncoderStencilAttachmentData stencil; - uint8_t default_raster_sample_count; - uint16_t render_target_array_length; - uint32_t render_target_height; - uint32_t render_target_width; + std::array colors{{}}; + RenderEncoderDepthAttachmentData depth{}; + RenderEncoderStencilAttachmentData stencil{}; + uint8_t default_raster_sample_count = 0; + uint16_t render_target_array_length = 0; + uint32_t render_target_height = 16384; + uint32_t render_target_width = 16384; wmtcmd_render_nop cmd_head; wmtcmd_base *cmd_tail; - uint8_t dsv_planar_flags; - uint8_t dsv_readonly_flags; - uint8_t render_target_count; + wmtcmd_compute_nop cmd_prepass_head; + wmtcmd_base *cmd_prepass_tail; + uint8_t dsv_planar_flags = 0; + uint8_t dsv_readonly_flags = 0; + uint8_t render_target_count = 0; bool use_visibility_result = 0; - bool use_tessellation = 0; - bool use_geometry = 0; + + RenderEncoderData() { + type = EncoderType::Render; + cmd_head.type = WMTRenderCommandNop; + cmd_head.next.set(nullptr); + cmd_tail = (wmtcmd_base *)&cmd_head; + cmd_prepass_head.type = WMTComputeCommandNop; + cmd_prepass_head.next.set(nullptr); + cmd_prepass_tail = (wmtcmd_base *)&cmd_prepass_head; + } }; struct BlitEncoderData : EncoderData { wmtcmd_blit_nop cmd_head; wmtcmd_base *cmd_tail; + + BlitEncoderData() { + type = EncoderType::Blit; + cmd_head.type = WMTBlitCommandNop; + cmd_head.next.set(0); + cmd_tail = (wmtcmd_base *)&cmd_head; + } }; struct ComputeEncoderData : EncoderData { wmtcmd_compute_nop cmd_head; wmtcmd_base *cmd_tail; + + ComputeEncoderData() { + type = EncoderType::Compute; + cmd_head.type = WMTComputeCommandNop; + cmd_head.next.set(0); + cmd_tail = (wmtcmd_base *)&cmd_head; + } }; struct ResolveEncoderData : EncoderData { TextureViewRef src; TextureViewRef dst; + + ResolveEncoderData() { + type = EncoderType::Resolve; + } +}; + +struct OcclusionQueryResolveInfo { + uint64_t visibility_offset_start; + uint64_t visibility_offset_end; + uint64_t resolve_dst; +}; + +struct OcclusionQueryResolveEncoderData : EncoderData { + small_vector info; + + OcclusionQueryResolveEncoderData() { + type = EncoderType::OcclusionQueryResolve; + } }; }; // namespace dxmt diff --git a/src/d3d12/d3d12_command_list.cpp b/src/d3d12/d3d12_command_list.cpp index 2199b87c1..5d32bf51c 100644 --- a/src/d3d12/d3d12_command_list.cpp +++ b/src/d3d12/d3d12_command_list.cpp @@ -17,8 +17,10 @@ */ #include "d3d12_command_allocator.hpp" +#include "d3d12_occlusion_query.hpp" #include "com/com_pointer.hpp" #include "dxmt_format.hpp" +#include "dxmt_occlusion_query.hpp" namespace dxmt { @@ -195,6 +197,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild allocator_; + EncoderType list_current_encoder_type_ = EncoderType::Null; + /* state */ Flags dirty_state_; @@ -231,6 +235,11 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild(pDevice) {} @@ -291,6 +300,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild::max(); + visibility_result_count = 0; return allocator_->StartRecord(&entry); } @@ -324,23 +334,61 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild::max()) + return E_FAIL; // the command list has already been closed + + if (!occlusion_query_state_.Flush([this](auto info) { ResolveOcclusionQueryData(info); })) { + ERR("D3D12CommandList::Close(): exists outstanding `BeginQuery()` of occlusion queries"); + cmdlist_valid_ = false; + } + + EndCommandListPass(); + visibility_result_count = vro_state_.reset(); + HRESULT hr = allocator_->EndRecord(&encoder_count); + if (!cmdlist_valid_) return E_FAIL; - return allocator_->EndRecord(&encoder_count); + return hr; }; HRESULT STDMETHODCALLTYPE Reset(ID3D12CommandAllocator *pAllocator, ID3D12PipelineState *pInitialState) { if (encoder_count == std::numeric_limits::max()) + return E_FAIL; // still recording + if (!cmdlist_valid_) return E_FAIL; return Initialize(pAllocator, pInitialState); }; void STDMETHODCALLTYPE ClearState(ID3D12PipelineState *pPipelineState) { - allocator_->InvalidateCurrentPass(); + EndCommandListPass(); ResetState(pPipelineState); }; + void + EndCommandListPass() { + assert((list_current_encoder_type_ == EncoderType::Null) ^ !!allocator_->encoder_current); + assert(!allocator_->encoder_current || allocator_->encoder_current->type == list_current_encoder_type_); + + if (list_current_encoder_type_ != EncoderType::Null) { + if (list_current_encoder_type_ == EncoderType::Render) + vro_state_.endEncoder(); + list_current_encoder_type_ = EncoderType::Null; + allocator_->InvalidateCurrentPass(); + } + } + + template + EncoderDataType * + StartCommandListPass() { + if (list_current_encoder_type_ != EncoderType::Null) + EndCommandListPass(); + auto encoder = allocator_->AllocatePass(); + list_current_encoder_type_ = encoder->type; + if (list_current_encoder_type_ == EncoderType::Render) + vro_state_.beginEncoder(); + return encoder; + } + std::tuple PopulateVertexBufferTable(uint32_t Count) { auto slot_mask = pso_graphics_ ? pso_graphics_->slot_mask : 0; @@ -373,16 +421,9 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Render) { + if (list_current_encoder_type_ != EncoderType::Render) { - allocator_->InvalidateCurrentPass(); - auto render = allocator_->AllocatePass(); - render->type = EncoderType::Render; - render->cmd_head.type = WMTRenderCommandNop; - render->cmd_head.next.set(0); - render->cmd_tail = (wmtcmd_base *)&render->cmd_head; - render->dsv_planar_flags = 0; - render->dsv_readonly_flags = 0; + auto render = StartCommandListPass(); render->render_target_count = num_rtvs; unsigned render_target_width = 16384, render_target_height = 16384, render_target_array_length = 0; @@ -427,6 +468,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChilddsv_planar_flags = dsv_planar_flags; + render->dsv_readonly_flags = AttachmentDesc.Flags; render_target_width = std::min(render_target_width, AttachmentDesc.Width); render_target_height = std::min(render_target_height, AttachmentDesc.Height); render_target_array_length = std::max(render_target_array_length, AttachmentDesc.RenderTargetArrayLength); @@ -621,6 +663,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildAllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS), 32); DXMT_DRAW_DYNAMIC_IB_ARGUMENTS *draw_argument = reinterpret_cast(Ptr); @@ -701,6 +746,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildAllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS), 32); DXMT_DRAW_DYNAMIC_IB_ARGUMENTS *draw_argument = reinterpret_cast(Ptr); @@ -800,13 +848,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Compute) { - allocator_->InvalidateCurrentPass(); - auto compute = allocator_->AllocatePass(); - compute->type = EncoderType::Compute; - compute->cmd_head.type = WMTComputeCommandNop; - compute->cmd_head.next.set(0); - compute->cmd_tail = (wmtcmd_base *)&compute->cmd_head; + if (list_current_encoder_type_ != EncoderType::Compute) { + StartCommandListPass(); dirty_state_.set(DirtyState::ComputeRootArguments, DirtyState::ComputeRootSignature); dirty_state_.set(DirtyState::ComputePipelineState); } @@ -861,13 +904,8 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildencoder_current || allocator_->encoder_current->type != EncoderType::Blit) { - allocator_->InvalidateCurrentPass(); - auto render = allocator_->AllocatePass(); - render->type = EncoderType::Blit; - render->cmd_head.type = WMTBlitCommandNop; - render->cmd_head.next.set(0); - render->cmd_tail = (wmtcmd_base *)&render->cmd_head; + if (list_current_encoder_type_ != EncoderType::Blit) { + StartCommandListPass(); } return true; } @@ -1151,9 +1189,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); - auto resolve = allocator_->AllocatePass(); - resolve->type = EncoderType::Resolve; + auto resolve = StartCommandListPass(); MTL_DXGI_FORMAT_DESC format_desc; if (FAILED(MTLQueryDXGIFormat(device_->GetMTLDevice(), Format, format_desc))) { @@ -1186,7 +1222,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildsrc = src->view(src_view); resolve->dst = dst->view(dst_view); } - allocator_->InvalidateCurrentPass(); + EndCommandListPass(); }; void STDMETHODCALLTYPE @@ -1465,7 +1501,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildInvalidateCurrentPass(); + EndCommandListPass(); num_rtvs = NumRTV; for (unsigned i = 0; i < NumRTV; i++) { @@ -1489,6 +1525,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.begin(AttachmentDesc.Texture, AttachmentDesc.View, 0, CheckedFlags); for (unsigned i = 0; i < RectCount; i++) { auto rect = Rects[i]; @@ -1503,9 +1540,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.end(); return; } - allocator_->InvalidateCurrentPass(); - auto encoder_info = allocator_->AllocatePass(); - encoder_info->type = EncoderType::Clear; + auto encoder_info = StartCommandListPass(); encoder_info->clear_dsv = CheckedFlags; encoder_info->depth_stencil = {Depth, Stencil}; encoder_info->attachment = AttachmentDesc.Texture->view(AttachmentDesc.View); @@ -1514,7 +1549,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildheight = AttachmentDesc.Height; encoder_info->depth_plane = 0; - allocator_->InvalidateCurrentPass(); + EndCommandListPass(); }; void STDMETHODCALLTYPE @@ -1526,6 +1561,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.begin(AttachmentDesc.Texture, AttachmentDesc.View, AttachmentDesc.DepthPlane); for (unsigned i = 0; i < RectCount; i++) { auto rect = Rects[i]; @@ -1543,9 +1579,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildclear_rtv_.end(); return; } - allocator_->InvalidateCurrentPass(); - auto encoder_info = allocator_->AllocatePass(); - encoder_info->type = EncoderType::Clear; + auto encoder_info = StartCommandListPass(); encoder_info->clear_dsv = 0; encoder_info->color = {Color[0], Color[1], Color[2], Color[3]}; SanitizeRTVClearColor(AttachmentDesc.Texture->pixelFormat(AttachmentDesc.View), encoder_info->color); @@ -1554,8 +1588,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildwidth = AttachmentDesc.Width; encoder_info->height = AttachmentDesc.Height; encoder_info->depth_plane = AttachmentDesc.DepthPlane; - - allocator_->InvalidateCurrentPass(); + EndCommandListPass(); }; void STDMETHODCALLTYPE @@ -1567,6 +1600,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildGetDescriptor(Index); auto color = std::array({Values[0], Values[1], Values[2], Values[3]}); D3D12_RECT full_rect; + EndCommandListPass(); switch (Descriptor.type) { case ShaderVisibleDescriptorType::UAVBuffer: { allocator_->clear_uav_.begin(color, Descriptor.UAVBuffer.buffer); @@ -1621,6 +1655,7 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildGetDescriptor(Index); auto color = std::array({Values[0], Values[1], Values[2], Values[3]}); D3D12_RECT full_rect; + EndCommandListPass(); switch (Descriptor.type) { case ShaderVisibleDescriptorType::UAVBuffer: { allocator_->clear_uav_.begin(color, Descriptor.UAVBuffer.buffer); @@ -1672,12 +1707,40 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild(pHeap), Index, vro_state_.getNextReadOffset() + )) { + ERR("D3D12CommandList::BeginQuery(): exists outstanding `BeginQuery()` of occlusion query at index ", Index); + cmdlist_valid_ = false; + } + break; + } + default: { + DEBUG("BeginQuery ", Type); + break; + } + } }; void STDMETHODCALLTYPE EndQuery(ID3D12QueryHeap *pHeap, D3D12_QUERY_TYPE Type, UINT Index) { - DEBUG("EndQuery"); + switch (Type) { + case D3D12_QUERY_TYPE_OCCLUSION: + case D3D12_QUERY_TYPE_BINARY_OCCLUSION: { + if (!occlusion_query_state_.End(static_cast(pHeap), Index, vro_state_.getNextReadOffset())) { + ERR("D3D12CommandList::EndQuery(): called without corresponding `BeginQuery()` at index ", Index); + cmdlist_valid_ = false; + } + break; + } + default: { + DEBUG("EndQuery ", Type); + break; + } + } }; void STDMETHODCALLTYPE @@ -1685,18 +1748,80 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChild(pHeap); + OcclusionQueryResolveInfo info; + for (unsigned i = 0; i < QueryCount; i++) { + if (occlusion_query_state_.GetResolveInfo(heap, StartIndex + i, info)) { + if (~info.visibility_offset_start) + ResolveOcclusionQueryData(info); + } else { + ERR("D3D12CommandList::ResolveQueryData(): `BeginQuery()` without corresponding `EndQuery()` at index ", StartIndex + i); + cmdlist_valid_ = false; + } + } + + if (!PreBlit()) + return; + + auto Dst = static_cast(pDstBuffer); + for (unsigned i = 0; i < QueryCount; i++) { + auto &cmd_cp = allocator_->EncodeBlitCommand(); + cmd_cp.type = WMTBlitCommandCopyFromBufferToBuffer; + cmd_cp.src = heap->query_heap; + cmd_cp.dst = Dst->buffer->current()->buffer(); + cmd_cp.src_offset = sizeof(uint64_t) * ((StartIndex + i) * 2 + (Type == D3D12_QUERY_TYPE_BINARY_OCCLUSION)); + cmd_cp.dst_offset = AlignedDstBufferOffset + sizeof(uint64_t) * i; + cmd_cp.copy_length = sizeof(uint64_t); + } + + return; + } + DEBUG("ResolveQueryData ", Type); }; + void + BumpVisibilityResultOffset() { + assert(allocator_->encoder_current->type == EncoderType::Render); + auto encoder = static_cast(allocator_->encoder_current); + bool has_outstanding_query = occlusion_query_state_.HasOutstandingQuery(); + encoder->use_visibility_result = encoder->use_visibility_result || has_outstanding_query; + + uint64_t offset; + if (vro_state_.tryGetNextWriteOffset(has_outstanding_query, offset)) { + auto &cmd = allocator_->EncodeRenderCommand(); + cmd.type = WMTRenderCommandSetVisibilityMode; + if (~offset == 0) { + cmd.mode = WMTVisibilityResultModeDisabled; + cmd.offset = 0; + } else { + cmd.mode = WMTVisibilityResultModeCounting; + cmd.offset = offset * sizeof(uint64_t); + } + } + } + + void + ResolveOcclusionQueryData(OcclusionQueryResolveInfo const &info) { + if (list_current_encoder_type_ != EncoderType::OcclusionQueryResolve) + StartCommandListPass(); + auto encoder = static_cast(allocator_->encoder_current); + encoder->info.push_back(info); + } + void STDMETHODCALLTYPE SetPredication(ID3D12Resource *pBuffer, UINT64 AlignedBufferOffset, D3D12_PREDICATION_OP Op) { IMPLEMENT_ME }; void STDMETHODCALLTYPE SetMarker(UINT Metadata, const void *data, UINT size) { IMPLEMENT_ME }; - void STDMETHODCALLTYPE BeginEvent(UINT Metadata, const void *data, UINT size) { IMPLEMENT_ME }; + void STDMETHODCALLTYPE BeginEvent(UINT Metadata, const void *data, UINT size) { + // TODO: no-op for now + }; - void STDMETHODCALLTYPE EndEvent() { IMPLEMENT_ME }; + void STDMETHODCALLTYPE EndEvent() { + // TODO: no-op for now + }; void STDMETHODCALLTYPE ExecuteIndirect( ID3D12CommandSignature *pCommandSignature, UINT MaxCommandCount, ID3D12Resource *pArgBuffer, @@ -1735,20 +1860,37 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildUpdateRootArguments || sig->UpdateIndexBuffer || sig->UpdateVertexBuffers; + bool encode_binding = sig->UpdateRootArguments || sig->UpdateIndexBuffer || sig->UpdateVertexBuffers || + pso_graphics_->is_geometry || pso_graphics_->is_tess; DrawCallStatus status = PreDraw(encode_binding); if (status == DrawCallStatus::Invalid) return; - if (status != DrawCallStatus::Ordinary) { - IMPLEMENT_ME // TODO: (potential) emulated pipeline - } - auto cmd = allocator_->EncodeIndirectRenderCommand(sig, pso_graphics_.ptr(), MaxCommandCount); + BumpVisibilityResultOffset(); + auto cmd = allocator_->EncodeIndirectRenderCommand(sig, pso_graphics_.ptr(), MaxCommandCount, topology_); cmd->max_count_buffer = CountBufferAddress; cmd->argument_buffer = ArgBufferAddress; cmd->primitive_type = primitive_type; - cmd->index_buffer = index_buffer_address; - cmd->index_buffer_format = index_type == WMTIndexTypeUInt32 ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; + if (sig->CommandType == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED) { + cmd->index_buffer = index_buffer_address; + cmd->index_buffer_format = index_type == WMTIndexTypeUInt32 ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; + } else { + cmd->index_buffer = 0; + cmd->index_buffer_format = DXGI_FORMAT_UNKNOWN; + } + if (status == DrawCallStatus::Geometry) { + std::tie(cmd->vertex_per_warp, cmd->vertex_increment_per_warp) = get_gs_vertex_count(topology_); + } + if (status == DrawCallStatus::Tessellation) { + cmd->control_point_count = cp_count; + cmd->threads_per_patch = pso_graphics_->tess_threads_per_patch; + } + if (status != DrawCallStatus::Ordinary) { + if (!device_->mesh_icb_supported) + return ExecuteIndirectMeshUnroll(cmd, MaxCommandCount); + auto [Unused, Offset] = allocator_->AllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS) * MaxCommandCount, 32); + cmd->dyn_ib_args = allocator_->gpu_heap_buffer_address_ + Offset; + } if (!encode_binding) return; cmd->rootsig_qwords = EncodeRootArgument(rootsig_graphics_.ptr(), rootarg_graphics_staging_, MaxCommandCount); @@ -1761,6 +1903,94 @@ class MTLD3D12GraphicsCommandListImpl : public MTLD3D12DeviceChildvertex_argbuf_stride = VBStride; }; + void + ExecuteIndirectMeshUnroll(IndirectRenderCommandData *cmd, UINT MaxCommandCount) { + auto [_, IBArgOffset] = allocator_->AllocateGPUHeap(sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS) * MaxCommandCount, 32); + cmd->dyn_ib_args = allocator_->gpu_heap_buffer_address_ + IBArgOffset; + auto [__, DrawArgOffset] = allocator_->AllocateGPUHeap(sizeof(D3D12_DISPATCH_ARGUMENTS) * MaxCommandCount, 32); + cmd->static_samplers = allocator_->gpu_heap_buffer_address_ + DrawArgOffset; + auto RAOffset = EncodeRootArgument(rootsig_graphics_.ptr(), rootarg_graphics_staging_, MaxCommandCount); + cmd->rootsig_qwords = RAOffset; + cmd->rootsig_qwords += allocator_->gpu_heap_buffer_address_; + cmd->rootsig_qwords_stride = rootsig_graphics_->UploadQwords; + auto [VBOffset, VBStride] = PopulateVertexBufferTable(MaxCommandCount); + cmd->vertex_buffer = allocator_->gpu_heap_buffer_address_ + VBOffset; + cmd->vertex_argbuf_stride = VBStride; + + { + auto SSOffset = EncodeStaticSamplers(rootsig_graphics_.ptr()); + auto &cmd_fsargbuf = allocator_->EncodeRenderCommand(); + cmd_fsargbuf.type = WMTRenderCommandSetFragmentBuffer; + cmd_fsargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_fsargbuf.offset = SSOffset; + cmd_fsargbuf.index = SM50_BINDING_INDEX_STATIC_SAMPLERS; + auto &cmd_osargbuf = allocator_->EncodeRenderCommand(); + cmd_osargbuf.type = WMTRenderCommandSetObjectBuffer; + cmd_osargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_osargbuf.offset = SSOffset; + cmd_osargbuf.index = SM50_BINDING_INDEX_STATIC_SAMPLERS; + auto &cmd_msargbuf = allocator_->EncodeRenderCommand(); + cmd_msargbuf.type = WMTRenderCommandSetMeshBuffer; + cmd_msargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_msargbuf.offset = SSOffset; + cmd_msargbuf.index = SM50_BINDING_INDEX_STATIC_SAMPLERS; + } + + for (unsigned i = 0; i < MaxCommandCount; i++) { + + auto IBArgOffsetLocal = IBArgOffset + i * sizeof(DXMT_DRAW_DYNAMIC_IB_ARGUMENTS); + auto VBOffsetLocal = VBOffset + i * VBStride; + auto RAOffsetLocal = RAOffset + i * sizeof(uint64_t) * rootsig_graphics_->UploadQwords; + + auto &cmd_osvb = allocator_->EncodeRenderCommand(); + cmd_osvb.type = WMTRenderCommandSetObjectBuffer; + cmd_osvb.buffer = allocator_->gpu_heap_buffer_; + cmd_osvb.offset = VBOffsetLocal; + cmd_osvb.index = SM50_BINDING_INDEX_VERTEX_BUFFER; + + auto &cmd_osdrawarg = allocator_->EncodeRenderCommand(); + cmd_osdrawarg.type = WMTRenderCommandSetObjectBuffer; + cmd_osdrawarg.buffer = allocator_->gpu_heap_buffer_; + cmd_osdrawarg.offset = IBArgOffsetLocal; + cmd_osdrawarg.index = SM50_BINDING_INDEX_DRAW_ARGUMENTS; + + auto &cmd_fsargbuf = allocator_->EncodeRenderCommand(); + cmd_fsargbuf.type = WMTRenderCommandSetFragmentBuffer; + cmd_fsargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_fsargbuf.offset = RAOffsetLocal; + cmd_fsargbuf.index = SM50_BINDING_INDEX_ROOT_ARGUMENTS; + auto &cmd_osargbuf = allocator_->EncodeRenderCommand(); + cmd_osargbuf.type = WMTRenderCommandSetObjectBuffer; + cmd_osargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_osargbuf.offset = RAOffsetLocal; + cmd_osargbuf.index = SM50_BINDING_INDEX_ROOT_ARGUMENTS; + auto &cmd_msargbuf = allocator_->EncodeRenderCommand(); + cmd_msargbuf.type = WMTRenderCommandSetMeshBuffer; + cmd_msargbuf.buffer = allocator_->gpu_heap_buffer_; + cmd_msargbuf.offset = RAOffsetLocal; + cmd_msargbuf.index = SM50_BINDING_INDEX_ROOT_ARGUMENTS; + + auto &cmd_mesh = allocator_->EncodeRenderCommand(); + cmd_mesh.type = WMTRenderCommandDrawMeshThreadgroupsIndirect; + cmd_mesh.indirect_args_buffer = allocator_->gpu_heap_buffer_; + cmd_mesh.indirect_args_offset = DrawArgOffset + i * sizeof(D3D12_DISPATCH_ARGUMENTS); + if (pso_graphics_->is_geometry) { + auto [vertex_per_warp, _] = get_gs_vertex_count(topology_); + cmd_mesh.object_threadgroup_size = {vertex_per_warp, 1, 1}; + cmd_mesh.mesh_threadgroup_size = {1, 1, 1}; + } else if (pso_graphics_->is_tess) { + auto PatchPerGroup = 32 / pso_graphics_->tess_threads_per_patch; + auto ThreadsPerPatch = pso_graphics_->tess_threads_per_patch; + cmd_mesh.object_threadgroup_size = {ThreadsPerPatch, PatchPerGroup, 1}; + cmd_mesh.mesh_threadgroup_size = {32, 1, 1}; + } else { + // unreachable + cmd_mesh.object_threadgroup_size = {0, 0, 0}; + cmd_mesh.mesh_threadgroup_size = {0, 0, 0}; + } + } + } + void STDMETHODCALLTYPE AtomicCopyBufferUINT( ID3D12Resource *pDstBuffer, UINT64 DstOffset, ID3D12Resource *pSrcBuffer, UINT64 SrcOffset, UINT Dependencies, diff --git a/src/d3d12/d3d12_command_queue.cpp b/src/d3d12/d3d12_command_queue.cpp index 57b0332cf..744adcbe2 100644 --- a/src/d3d12/d3d12_command_queue.cpp +++ b/src/d3d12/d3d12_command_queue.cpp @@ -42,12 +42,15 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable queue_; WMT::Reference fence_; + WMT::Reference pso_occlusion_query_resolve_; + std::atomic_uint64_t inflight_cmdbuf_seq_ = 1; std::atomic_uint64_t inflight_cmdbuf_count_ = 0; std::atomic_uint64_t inflight_cmdbuf_stop_ = 0; struct InflightCommandBuffer { WMT::Reference cmdbuf{}; + small_vector, 1> visibility_buffers; HANDLE semaphore{}; }; @@ -141,6 +144,13 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable err; + auto occlusion_query_resolve_function = device_->GetLib().getLibrary().newFunction("cs_occlusion_query_resolve"); + pso_occlusion_query_resolve_ = metal_device.newComputePipelineState(occlusion_query_resolve_function, err); + + if (err || !pso_occlusion_query_resolve_) + return E_FAIL; + return S_OK; } @@ -203,6 +213,14 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable(ppCommandLists[i]); + WMT::Reference visibility_buffer; + if (pCommandList->visibility_result_count) { + WMTBufferInfo info; + info.length = pCommandList->visibility_result_count * sizeof(uint64_t); + info.memory.set(nullptr); + info.options = WMTResourceStorageModePrivate | WMTResourceHazardTrackingModeUntracked; + visibility_buffer = device_->GetMTLDevice().newBuffer(info); + } EncoderData *current = pCommandList->entry; while (current) { switch (current->type) { @@ -294,9 +312,18 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageablerender_target_array_length; render_pass_info.render_target_width = data->render_target_width; render_pass_info.render_target_height = data->render_target_height; + if (data->use_visibility_result) + render_pass_info.visibility_buffer = visibility_buffer; + } + if (data->cmd_prepass_tail->type != WMTComputeCommandNop) { + auto encoder = cmdbuf.computeCommandEncoder(false); + encoder.waitForFence(fence_); + encoder.encodeCommands(&data->cmd_prepass_head); + encoder.updateFence(fence_); + encoder.endEncoding(); } auto encoder = cmdbuf.renderCommandEncoder(render_pass_info); - encoder.waitForFence(fence_, WMTRenderStageVertex); + encoder.waitForFence(fence_, WMTRenderStageVertex | WMTRenderStageObject | WMTRenderStageMesh); encoder.encodeCommands(&data->cmd_head); encoder.updateFence(fence_, WMTRenderStageFragment); encoder.endEncoding(); @@ -338,9 +365,49 @@ class MTLD3D12CommandQueueImpl : public MTLD3D12Pageable(current); + auto encoder = cmdbuf.computeCommandEncoder(false); + encoder.waitForFence(fence_); + + { + wmtcmd_compute_setbytes cmd_setbytes; + cmd_setbytes.index = 0; + cmd_setbytes.bytes.set(data->info.data()); + cmd_setbytes.length = data->info.size() * sizeof(OcclusionQueryResolveInfo); + cmd_setbytes.type = WMTComputeCommandSetBytes; + + wmtcmd_compute_setbuffer cmd_setbuffer; + cmd_setbytes.next.set(&cmd_setbuffer); + cmd_setbuffer.type = WMTComputeCommandSetBuffer; + cmd_setbuffer.index = 1; + cmd_setbuffer.buffer = visibility_buffer; + cmd_setbuffer.offset = 0; + + wmtcmd_compute_setpso cmd_setpso; + cmd_setbuffer.next.set(&cmd_setpso); + cmd_setpso.type = WMTComputeCommandSetPSO; + cmd_setpso.threadgroup_size = {1, 1, 1}; + cmd_setpso.pso = pso_occlusion_query_resolve_; + + wmtcmd_compute_dispatch cmd_dispatch; + cmd_setpso.next.set(&cmd_dispatch); + cmd_dispatch.type = WMTComputeCommandDispatch; + cmd_dispatch.size = {data->info.size(), 1, 1}; + + cmd_dispatch.next.set(nullptr); + encoder.encodeCommands((wmtcmd_compute_nop *)&cmd_setbytes); + } + + encoder.updateFence(fence_); + encoder.endEncoding(); + break; + } } current = current->next; } + if (visibility_buffer) + scope.inflight.visibility_buffers.push_back(std::move(visibility_buffer)); } }; diff --git a/src/d3d12/d3d12_command_signature.cpp b/src/d3d12/d3d12_command_signature.cpp index 0a046e28b..ce756c736 100644 --- a/src/d3d12/d3d12_command_signature.cpp +++ b/src/d3d12/d3d12_command_signature.cpp @@ -17,6 +17,7 @@ */ #include "com/com_pointer.hpp" +#include "d3d12_command_allocator.hpp" #include "d3d12_device.hpp" #include "d3d12_pageable.hpp" @@ -71,6 +72,16 @@ struct dxmt_vertex_buffer { uint length; }; +struct dxmt_dynamic_ib_arguments { + uint vertex_per_instance; + uint instance_count; + uint start_vertex; + uint base_vertex; + uint start_instance; + uint index_format; + device void * index_buffer; +}; + struct dxmt_render_command_data { command_buffer cmd_buf; ulong max_count; @@ -84,6 +95,10 @@ struct dxmt_render_command_data { device void * index_buffer; uint index_buffer_format; uint vertex_argbuf_stride; + device dxmt_dynamic_ib_arguments * dyn_ib_args; + uint flags; + uint mesh_arg1; + uint mesh_arg2; }; )"; @@ -101,6 +116,8 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageablemesh_icb_supported; + source << kSharedHeader; source << "struct __attribute__ ((packed)) d3d12_arguments {\n"; @@ -175,44 +192,62 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable(" "command_data.argument_buffer + i * " << pDesc->ByteStride << ")[0];\n"; if (is_compute) { source << "compute_command cmd(command_data.cmd_buf, i);\n"; + source << "cmd.reset();\n"; } else { + source << "bool is_geometry = command_data.flags & " << kIndirectRenderCommandFlagIsGeometry << ";\n"; + source << "bool is_tessellation = command_data.flags & " << kIndirectRenderCommandFlagIsTessellation << ";\n"; + source << "bool is_mesh_emulated = is_geometry || is_tessellation;\n"; source << "render_command cmd(command_data.cmd_buf, i);\n"; + if (mesh_icb_supported) { + source << "cmd.reset();\n"; + } else { + source + << "auto device & mesh_args = reinterpret_cast(command_data.static_samplers)[i];\n"; + source << "if (!is_mesh_emulated) { cmd.reset(); } else { mesh_args = 0; }\n"; + } } - source << "cmd.reset();\n"; - source << "if (i >= count) continue;\n"; + source << "if (i >= count) return;\n"; source << "device ulong * rootsig_qwords = command_data.rootsig_qwords + " "(i * command_data.rootsig_qwords_stride);\n"; - if (!is_compute) + if (!is_compute) { source << "device dxmt_vertex_buffer * vertex_buffer = " "reinterpret_cast(command_data.vertex_buffer + " "(i * command_data.vertex_argbuf_stride));\n"; + source << "device dxmt_dynamic_ib_arguments * dyn_ib_args = &command_data.dyn_ib_args[i];\n"; + if (mesh_icb_supported) + source << "if (is_mesh_emulated) {\n"; + else + source << "if (0) {\n"; + source << "cmd.set_object_buffer(vertex_buffer," << SM50_BINDING_INDEX_VERTEX_BUFFER << ");\n"; + source << "cmd.set_object_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; + source << "cmd.set_object_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "cmd.set_object_buffer(dyn_ib_args," << SM50_BINDING_INDEX_DRAW_ARGUMENTS << ");\n"; + source << "cmd.set_mesh_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; + source << "cmd.set_mesh_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "cmd.set_fragment_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; + source << "cmd.set_fragment_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "} \n"; + } if (UpdateRootArguments || UpdateVertexBuffers || UpdateIndexBuffer) { if (!is_compute) { + source << "if (!is_mesh_emulated) {\n"; source << "cmd.set_vertex_buffer(vertex_buffer," << SM50_BINDING_INDEX_VERTEX_BUFFER << ");\n"; source << "cmd.set_vertex_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; source << "cmd.set_vertex_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; source << "cmd.set_fragment_buffer(rootsig_qwords," << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; source << "cmd.set_fragment_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; + source << "}\n"; } else { source << "cmd.set_kernel_buffer(rootsig_qwords, " << SM50_BINDING_INDEX_ROOT_ARGUMENTS << ");\n"; source << "cmd.set_kernel_buffer(command_data.static_samplers," << SM50_BINDING_INDEX_STATIC_SAMPLERS << ");\n"; @@ -223,10 +258,41 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12PageablepArgumentDescs[i]; switch (arg.Type) { case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: { - source << "cmd.draw_primitives((primitive_type)command_data.primitive_type, " - "arg.draw.start_vertex_location, " - "arg.draw.vertex_count_per_instance, arg.draw.instance_count, " - "arg.draw.start_instance_location);\n"; + source << "if (is_mesh_emulated) {\n" + " dyn_ib_args->vertex_per_instance = arg.draw.vertex_count_per_instance;\n" + " dyn_ib_args->instance_count = arg.draw.instance_count;\n" + " dyn_ib_args->start_vertex = arg.draw.start_vertex_location;\n" + " dyn_ib_args->base_vertex = 0;\n" + " dyn_ib_args->start_instance = arg.draw.start_instance_location;\n" + " dyn_ib_args->index_format = 0;\n" + " dyn_ib_args->index_buffer = 0;\n" + "}\n" + "if (is_geometry) {\n" + " uint warp_count = arg.draw.vertex_count_per_instance" + " ? (arg.draw.vertex_count_per_instance - 1) / command_data.mesh_arg2 + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw.instance_count, 1)," + " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n"; + else + source << "mesh_args = uint3(warp_count, arg.draw.instance_count, 1);\n"; + source << "} else if (is_tessellation) {\n" + " uint patch_per_instance = arg.draw.vertex_count_per_instance / command_data.mesh_arg1;\n" + " uint patch_per_group = 32 / command_data.mesh_arg2;\n" + " uint patch_per_object = patch_per_instance" + " ? (patch_per_instance - 1) / patch_per_group + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw.instance_count, 1)," + " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n"; + else + source << "mesh_args = uint3(patch_per_object, arg.draw.instance_count, 1);\n"; + source << "} else {\n" + " cmd.draw_primitives((primitive_type)command_data.primitive_type," + " arg.draw.start_vertex_location," + " arg.draw.vertex_count_per_instance, arg.draw.instance_count," + " arg.draw.start_instance_location);\n" + "}\n"; break; } case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: { @@ -234,19 +300,49 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable(ib) + arg.draw_indexed.start_index_location, " - "arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location, " - "arg.draw_indexed.start_instance_location);\n"; - source << "} else {\n"; - source << "cmd.draw_indexed_primitives((primitive_type)command_data.primitive_type, " - "arg.draw_indexed.index_count_per_instance, " - "reinterpret_cast(ib) + arg.draw_indexed.start_index_location, " - "arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location, " - "arg.draw_indexed.start_instance_location);\n"; - source << "}\n"; + source << "if (is_mesh_emulated) {\n" + " dyn_ib_args->vertex_per_instance = arg.draw_indexed.index_count_per_instance;\n" + " dyn_ib_args->instance_count = arg.draw_indexed.instance_count;\n" + " dyn_ib_args->start_vertex = arg.draw_indexed.start_index_location;\n" + " dyn_ib_args->base_vertex = arg.draw_indexed.base_vertex_location;\n" + " dyn_ib_args->start_instance = arg.draw_indexed.start_instance_location;\n" + " dyn_ib_args->index_format = command_data.index_buffer_format;\n" + " dyn_ib_args->index_buffer = ib;\n" + "}\n" + "if (is_geometry) {\n" + " uint warp_count = arg.draw_indexed.index_count_per_instance" + " ? (arg.draw_indexed.index_count_per_instance - 1) / command_data.mesh_arg2 + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(warp_count, arg.draw_indexed.instance_count, 1), " + " uint3(command_data.mesh_arg1, 1, 1), uint3(1, 1, 1));\n"; + else + source << "mesh_args = uint3(warp_count, arg.draw_indexed.instance_count, 1);\n"; + source << "} else if (is_tessellation) {\n" + " uint patch_per_instance = arg.draw_indexed.index_count_per_instance / command_data.mesh_arg1;\n" + " uint patch_per_group = 32 / command_data.mesh_arg2;\n" + " uint patch_per_object = patch_per_instance" + " ? (patch_per_instance - 1) / patch_per_group + 1" + " : 0;\n"; + if (mesh_icb_supported) + source << "cmd.draw_mesh_threadgroups(uint3(patch_per_object, arg.draw_indexed.instance_count, 1), " + " uint3(command_data.mesh_arg2, patch_per_group, 1), uint3(32, 1, 1));\n"; + else + source << "mesh_args = uint3(patch_per_object, arg.draw_indexed.instance_count, 1);\n"; + source + << "} else if (ib32bit) {\n" + " cmd.draw_indexed_primitives((primitive_type)command_data.primitive_type," + " arg.draw_indexed.index_count_per_instance," + " reinterpret_cast(ib) + arg.draw_indexed.start_index_location," + " arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location," + " arg.draw_indexed.start_instance_location);\n" + "} else {\n" + " cmd.draw_indexed_primitives((primitive_type)command_data.primitive_type," + " arg.draw_indexed.index_count_per_instance," + " reinterpret_cast(ib) + arg.draw_indexed.start_index_location," + " arg.draw_indexed.instance_count, arg.draw_indexed.base_vertex_location," + " arg.draw_indexed.start_instance_location);\n" + "}\n"; break; } case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: { @@ -316,8 +412,7 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12Pageable err; auto lib = device_->GetMTLDevice().newLibraryWithSource(source.view(), err); @@ -334,15 +429,7 @@ class MTLD3D12CommandSignatureImpl : public MTLD3D12PageableGetMTLDevice().newComputePipelineState(function, err); - } else { - WMTRenderPipelineInfo info; - WMT::InitializeRenderPipelineInfo(info); - info.rasterization_enabled = false; - info.vertex_function = function; - render_resolver = device_->GetMTLDevice().newRenderPipelineState(info, err); - } + resolver = device_->GetMTLDevice().newComputePipelineState(function, err); if (err) { ERR("Failed to compile command signature resolve pso: ", err.description().getUTF8String()); diff --git a/src/d3d12/d3d12_device.cpp b/src/d3d12/d3d12_device.cpp index 039c10658..ef399403e 100644 --- a/src/d3d12/d3d12_device.cpp +++ b/src/d3d12/d3d12_device.cpp @@ -71,6 +71,8 @@ class MTLD3D12DeviceImpl : public MTLD3D12Object> { info.depth_compare_function = WMTCompareFunctionAlways; default_depth_stencil_state = GetMTLDevice().newDepthStencilState(info); + mesh_icb_supported = GetMTLDevice().supportsFamily(WMTGPUFamilyApple9); + return S_OK; }; @@ -104,7 +106,7 @@ class MTLD3D12DeviceImpl : public MTLD3D12Object> { if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12Device) || riid == __uuidof(ID3D12Device1) || riid == __uuidof(ID3D12Device2) || riid == __uuidof(ID3D12Device3) || - riid == __uuidof(ID3D12Device4)) { + riid == __uuidof(ID3D12Device4) || riid == __uuidof(ID3D12Device5)) { *ppvObject = ref(this); return S_OK; } @@ -1209,6 +1211,53 @@ class MTLD3D12DeviceImpl : public MTLD3D12Object> { return __ret; } + HRESULT STDMETHODCALLTYPE + CreateLifetimeTracker(ID3D12LifetimeOwner *pOwner, REFIID riid, void **ppTracker) { + return E_NOTIMPL; + } + + void STDMETHODCALLTYPE + RemoveDevice() {} + + HRESULT STDMETHODCALLTYPE + EnumerateMetaCommands(UINT *pCount, D3D12_META_COMMAND_DESC *pDescs) { + *pCount = 0; + return S_OK; + } + + HRESULT STDMETHODCALLTYPE + EnumerateMetaCommandParameters( + REFGUID id, D3D12_META_COMMAND_PARAMETER_STAGE Stage, UINT *pTotalSizeInBytes, UINT *pParameterCount, + D3D12_META_COMMAND_PARAMETER_DESC *pParameterDescs + ) { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE + CreateMetaCommand( + REFGUID id, UINT NodeMask, const void *pCreationParameters, SIZE_T SizeInBytes, REFIID riid, void **ppCommand + ) { + return DXGI_ERROR_UNSUPPORTED; + } + + HRESULT STDMETHODCALLTYPE + CreateStateObject(const D3D12_STATE_OBJECT_DESC *pDesc, REFIID riid, void **ppStateObject) { + return E_NOTIMPL; + } + + void STDMETHODCALLTYPE + GetRaytracingAccelerationStructurePrebuildInfo( + const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS *pDesc, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO *pInfo + ) {} + + D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS STDMETHODCALLTYPE + CheckDriverMatchingIdentifier( + D3D12_SERIALIZED_DATA_TYPE Type, const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER *pIdentifier + ) { + return D3D12_DRIVER_MATCHING_IDENTIFIER_UNRECOGNIZED; + } + WMT::ResidencySet GetGlobalResidencySet() { return residency_set_; diff --git a/src/d3d12/d3d12_device.hpp b/src/d3d12/d3d12_device.hpp index 0897a7d2e..b5ef8da5d 100644 --- a/src/d3d12/d3d12_device.hpp +++ b/src/d3d12/d3d12_device.hpp @@ -44,6 +44,7 @@ class MTLD3D12GraphicsCommandList : public ID3D12GraphicsCommandList2 { public: EncoderData *entry; size_t encoder_count; + size_t visibility_result_count; }; class MTLD3D12CommandAllocator : public ID3D12CommandAllocator { @@ -115,8 +116,7 @@ class MTLD3D12CommandSignature : public ID3D12CommandSignature { UINT UpdateVertexBuffers : 1; UINT UpdateIndexBuffer : 1; - WMT::Reference render_resolver; - WMT::Reference compute_resolver; + WMT::Reference resolver; virtual void AddRefPrivate() = 0; virtual void ReleasePrivate() = 0; @@ -124,6 +124,9 @@ class MTLD3D12CommandSignature : public ID3D12CommandSignature { class MTLD3D12QueryHeap : public ID3D12QueryHeap { public: + WMT::Reference query_heap; + uint64_t query_heap_address; + size_t query_count; }; class MTLD3D12PipelineState : public ID3D12PipelineState { @@ -167,7 +170,7 @@ class MTLD3D12ComputePipelineState : public MTLD3D12PipelineState { virtual void ReleasePrivate() = 0; }; -class MTLD3D12Device : public ID3D12Device4 { +class MTLD3D12Device : public ID3D12Device5 { public: virtual WMT::Device GetMTLDevice() = 0; @@ -194,6 +197,8 @@ class MTLD3D12Device : public ID3D12Device4 { EventListener event_listener; WMT::Reference default_depth_stencil_state; + + bool mesh_icb_supported; }; HRESULT diff --git a/src/d3d12/d3d12_occlusion_query.cpp b/src/d3d12/d3d12_occlusion_query.cpp new file mode 100644 index 000000000..43d8f0320 --- /dev/null +++ b/src/d3d12/d3d12_occlusion_query.cpp @@ -0,0 +1,105 @@ +/* + * Copyright 2026 Feifan He for CodeWeavers + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#include "d3d12_occlusion_query.hpp" + +namespace dxmt { + +bool +CommandListOcclusionQueryState::Begin(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset) { + + auto iter = queries_.find({pHeap, Index}); + if (iter != queries_.end()) { + auto &state = iter->second; + if (state.is_resolvable) { + DEBUG("BeginQuery: discarded unresolved data"); + state.is_resolvable = false; + state.offset_start = Offset; + return true; + } + // duplicated Begin() + return false; + } + OcclusionQueryState state; + state.offset_start = Offset; + state.offset_end = 0; + state.is_resolvable = false; + queries_.insert({{pHeap, Index}, state}); + return true; +} + +bool +CommandListOcclusionQueryState::End(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset) { + auto iter = queries_.find({pHeap, Index}); + if (iter == queries_.end()) { + // no Begin() + return false; + } + auto &state = iter->second; + state.offset_end = Offset; + state.is_resolvable = true; + return true; +} + +bool +CommandListOcclusionQueryState::GetResolveInfo( + MTLD3D12QueryHeap *pHeap, UINT Index, OcclusionQueryResolveInfo &InfoOut +) { + auto iter = queries_.find({pHeap, Index}); + if (iter == queries_.end()) { + InfoOut.visibility_offset_start = ~0ull; + InfoOut.visibility_offset_end = ~0ull; + InfoOut.resolve_dst = 0; + return true; + } + auto &state = iter->second; + if (state.is_resolvable) { + InfoOut.visibility_offset_start = state.offset_start; + InfoOut.visibility_offset_end = state.offset_end; + InfoOut.resolve_dst = pHeap->query_heap_address + Index * sizeof(uint64_t) * 2; + queries_.erase(iter); + return true; + } + // no End() + return false; +} + +bool +CommandListOcclusionQueryState::HasOutstandingQuery() { + return std::any_of(queries_.rbegin(), queries_.rend(), [](auto pair) { return !pair.second.is_resolvable; }); +} + +bool +CommandListOcclusionQueryState::Flush(std::function fn) { + std::erase_if(queries_, [fn = std::move(fn)](auto pair) { + auto &[heap, index] = pair.first; + auto &state = pair.second; + if (state.is_resolvable) { + OcclusionQueryResolveInfo InfoOut; + InfoOut.visibility_offset_start = state.offset_start; + InfoOut.visibility_offset_end = state.offset_end; + InfoOut.resolve_dst = heap->query_heap_address + index * sizeof(uint64_t) * 2; + fn(InfoOut); + return true; + } + return false; + }); + return queries_.size() == 0; +} + +} // namespace dxmt \ No newline at end of file diff --git a/src/d3d12/d3d12_occlusion_query.hpp b/src/d3d12/d3d12_occlusion_query.hpp new file mode 100644 index 000000000..491d0667c --- /dev/null +++ b/src/d3d12/d3d12_occlusion_query.hpp @@ -0,0 +1,41 @@ +/* + * Copyright 2026 Feifan He for CodeWeavers + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#pragma once +#include "d3d12_device.hpp" + +namespace dxmt { + +class CommandListOcclusionQueryState { + + struct OcclusionQueryState { + uint64_t offset_start = 0; + uint64_t offset_end = 0; + bool is_resolvable = false; + }; + + std::map, OcclusionQueryState> queries_; + +public: + bool Begin(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset); + bool End(MTLD3D12QueryHeap *pHeap, UINT Index, UINT64 Offset); + bool GetResolveInfo(MTLD3D12QueryHeap *pHeap, UINT Index, OcclusionQueryResolveInfo &InfoOut); + bool HasOutstandingQuery(); + bool Flush(std::function fn); +}; +} // namespace dxmt diff --git a/src/d3d12/d3d12_query_heap.cpp b/src/d3d12/d3d12_query_heap.cpp index 904c58f7b..75fef855b 100644 --- a/src/d3d12/d3d12_query_heap.cpp +++ b/src/d3d12/d3d12_query_heap.cpp @@ -27,9 +27,39 @@ class MTLD3D12QueryHeapImpl : public MTLD3D12Pageable { HRESULT Initialize(const D3D12_QUERY_HEAP_DESC *pDesc) { + query_count = pDesc->Count; + + /** + Two uint64_t are allocated for each occlusion query slot, one for binary occlusion. + We need to store both numerical and binary value because we implement `ResolveQueryData` as a blit, where + `D3D12_QUERY_TYPE` actually matters + */ + auto query_size = pDesc->Type == D3D12_QUERY_HEAP_TYPE_OCCLUSION ? sizeof(uint64_t) * 2 : sizeof(uint64_t); + + WMTBufferInfo info; + info.memory.set(nullptr); + info.length = query_size * query_count; + info.options = WMTResourceStorageModePrivate | WMTResourceHazardTrackingModeUntracked; + + query_heap = device_->GetMTLDevice().newBuffer(info); + + if (!query_heap) { + ERR("MTLD3D12QueryHeapImpl: failed to allocate query heap"); + return E_OUTOFMEMORY; + } + query_heap_address = info.gpu_address; + device_->RegisterResidency(query_heap); return S_OK; } + ~MTLD3D12QueryHeapImpl() { + if (query_heap) { + device_->UnregisterResidency(query_heap); + } + query_heap = {}; + query_heap_address = 0; + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { diff --git a/src/d3d12/meson.build b/src/d3d12/meson.build index ce23ea65b..175fb703d 100644 --- a/src/d3d12/meson.build +++ b/src/d3d12/meson.build @@ -9,6 +9,7 @@ d3d12_src = [ 'd3d12_device.cpp', 'd3d12_fence.cpp', 'd3d12_heap.cpp', + 'd3d12_occlusion_query.cpp', 'd3d12_pipeline_compute.cpp', 'd3d12_pipeline_graphics.cpp', 'd3d12_query_heap.cpp', diff --git a/src/dxmt/dxmt_command.metal b/src/dxmt/dxmt_command.metal index 516f49e29..c52a94959 100644 --- a/src/dxmt/dxmt_command.metal +++ b/src/dxmt/dxmt_command.metal @@ -564,13 +564,10 @@ struct DXMTClearUintMetadata { [[kernel]] void cs_clear_texture3d_float( texture3d tex [[texture(0)]], constant DXMTClearFloatMetadata& meta [[buffer(1)]], - uint2 pos [[thread_position_in_grid]] + uint3 pos [[thread_position_in_grid]] ) { - auto depth = tex.get_depth(); - for (uint i = 0; i < depth; i++) { - uint2 final_pos = meta.offset + pos; - tex.write(meta.value, uint3(final_pos.x, final_pos.y, i)); - } + uint2 final_pos = meta.offset + pos.xy; + tex.write(meta.value, uint3(final_pos.x, final_pos.y, pos.z)); } [[kernel]] void cs_clear_texture2d_uint( @@ -592,13 +589,10 @@ struct DXMTClearUintMetadata { [[kernel]] void cs_clear_texture3d_uint( texture3d tex [[texture(0)]], constant DXMTClearUintMetadata& meta [[buffer(1)]], - uint2 pos [[thread_position_in_grid]] + uint3 pos [[thread_position_in_grid]] ) { - auto depth = tex.get_depth(); - for (uint i = 0; i < depth; i++) { - uint2 final_pos = meta.offset + pos; - tex.write(meta.value, uint3(final_pos.x, final_pos.y, i)); - } + uint2 final_pos = meta.offset + pos.xy; + tex.write(meta.value, uint3(final_pos.x, final_pos.y, pos.z)); } [[kernel]] void cs_clear_tbuffer_float( @@ -653,3 +647,27 @@ struct DXMTClearUintMetadata { [[kernel]] void tile_barrier(ushort2 pos [[thread_position_in_threadgroup]]) { // empty } + +struct DXMTOcclusionQueryResolveInfo { + ulong visibility_offset_start; + ulong visibility_offset_end; + device ulong2 * resolve_dst; +}; + +[[kernel]] void cs_occlusion_query_resolve( + uint id [[threadgroup_position_in_grid]], + constant DXMTOcclusionQueryResolveInfo* infos [[buffer(0)]], + constant ulong* visibility_buffer [[buffer(1)]] +) { + constant auto& info = infos[id]; + if (info.visibility_offset_end <= info.visibility_offset_start) { + *info.resolve_dst = 0; + return; + } + ulong accum = 0; + for (auto i = info.visibility_offset_start; i < info.visibility_offset_end; i++) { + accum += visibility_buffer[i]; + } + *info.resolve_dst = ulong2(accum, !!accum); + return; +} \ No newline at end of file