diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 46ea96aaf7..73bb224cd0 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4155,7 +4155,9 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") target_compile_options(d3d12_msaa_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) - set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_custom_samples COMMAND d3d12_msaa_draw_test --custom-samples) + add_test(NAME d3d12_sample_grid_reset COMMAND d3d12_msaa_draw_test --sample-grid) + set_tests_properties(d3d12_msaa_draw d3d12_custom_samples d3d12_sample_grid_reset PROPERTIES SKIP_RETURN_CODE 77) # Geometry shaders: a VS+GS+PS pipeline whose GS emits each triangle twice. add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_GS_DOUBLE} ${LEONIDA_TEST_PS}) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4a61ffadbc..015354719c 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -414,6 +414,7 @@ class GraphicsCommandList final if (list_.closed()) return; if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (!list_.closed()) check(list_.set_predication({0, 0, 0})); + if (custom_samples_) check(list_.set_sample_positions({})); reset_state(state); } @@ -804,6 +805,24 @@ class GraphicsCommandList final check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource})); } + void STDMETHODCALLTYPE SetSamplePositions(UINT samples, UINT pixels, D3D12_SAMPLE_POSITION* positions) override { + d3d12_trace::record("ID3D12GraphicsCommandList1::SetSamplePositions"); + if (list_.closed() || type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return; + leonida::SamplePositions pattern{}; + if (samples || pixels || positions) { + if (!positions || !leonida::SamplePositions::valid_grid(samples, pixels)) return; + pattern.samples = samples; + pattern.pixels = pixels; + for (UINT i = 0; i < samples * pixels; ++i) { + const auto p = positions[i]; + if (p.X < -8 || p.X > 7 || p.Y < -8 || p.Y > 7) return; + pattern.positions[i] = {p.X, p.Y}; + } + } + check(list_.set_sample_positions(pattern)); + custom_samples_ = samples != 0; + } + void STDMETHODCALLTYPE ResolveSubresourceRegion(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, ID3D12Resource* src, UINT src_subresource, D3D12_RECT* rect, DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) override { @@ -1577,6 +1596,7 @@ class GraphicsCommandList final leonida::CommandList list_; bool invalid_ = false; UINT front_stencil_ref_ = 0; + bool custom_samples_ = false; UINT back_stencil_ref_ = 0; RootState compute_; RootState graphics_; @@ -1794,6 +1814,7 @@ class GraphicsCommandList final void reset_state(ID3D12PipelineState* state) { front_stencil_ref_ = back_stencil_ref_ = 0; + custom_samples_ = false; compute_ = {}; graphics_ = {}; cbv_srv_uav_heap_ = nullptr; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 3bad0b7671..5295faac23 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -146,6 +146,7 @@ struct VulkanDeviceInfo { // VK_EXT_conservative_rasterization is enabled on the logical device. Tier 1/2 depend on the physical // precision/overestimation properties; Tier 2 also requires post-snap degenerate triangles. bool conservative_rasterization = false; + bool sample_locations = false; // Opt in only for shader libraries whose InnerCoverage input contract uses FullyCoveredEXT. The device // still checks physical Tier 2 and fullyCoveredFragmentShaderInputVariable properties. The standalone // device leaves this false until the Xbox PS input mapping is confirmed (synthetic GLSL is not that ABI). diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 031fa22e12..2b72943c78 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2511,7 +2511,8 @@ struct TextureCreateInfo { VkImageFormatListCreateInfo format_list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; std::array view_formats{}; - TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable) { + TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable, + VkSampleCountFlags programmable_samples) { const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; @@ -2524,6 +2525,9 @@ struct TextureCreateInfo { info.mipLevels = desc.MipLevels; info.arrayLayers = volume ? 1 : desc.DepthOrArraySize; info.samples = VkSampleCountFlagBits(std::max(1u, desc.SampleDesc.Count)); + if ((programmable_samples & info.samples) && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) && + (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) + info.flags |= VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT; info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; @@ -3003,6 +3007,8 @@ struct DeviceState { std::uint32_t f16_half_top_location = 29; float max_sampler_lod_bias = 0; D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; + VkSampleCountFlags sample_grid_1 = 0, sample_grid_4 = 0; + D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; bool conservative_post_depth_coverage = false; // VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use. VkResolveModeFlags depth_resolve_modes = 0; @@ -9114,7 +9120,7 @@ class Resource final HRESULT create_sparse_image() { auto& vk = device_.context->vk; const auto format = device_.texture_format(desc_); - TextureCreateInfo create(desc_, format, false); + TextureCreateInfo create(desc_, format, false, device_.sample_grid_1); create.info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT; HRESULT support = device_.check_image_support(create.info); @@ -9220,7 +9226,7 @@ class Resource final !desc_.DepthOrArraySize || desc_.DepthOrArraySize > slice_limit || desc_.MipLevels > mips) return E_INVALIDARG; } - TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); + TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format), device_.sample_grid_1); VkImageCreateInfo& info = create.info; if (!castable.empty()) { // D3D12 always allows a view in the resource's own format, whether or not the castable list names @@ -9488,6 +9494,7 @@ class Resource final binding.volume = volume; binding.line = one_d; binding.samples = samples; + binding.sample_locations_depth = (info.flags & VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT) != 0; binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0; binding.sampled = (info.usage & VK_IMAGE_USAGE_SAMPLED_BIT) != 0; binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0; @@ -12476,6 +12483,8 @@ class PipelineState final recipe_.conservative = r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; recipe_.multisample = multisample; graphics_.samples = samples; + graphics_.sample_grid_1 = device_.sample_grid_1; + graphics_.sample_grid_4 = device_.sample_grid_4; recipe_.sample_mask = sample_mask; recipe_.depth = depth; recipe_.blends = std::move(blends); @@ -13046,7 +13055,7 @@ class PipelineState final // A mesh pipeline takes neither the topology nor the strides as dynamic state // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066). // With multiViewport enabled, VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT allow 1..16 dynamic viewports/scissors. - VkDynamicState dyn_list[8]{}; + VkDynamicState dyn_list[9]{}; std::uint32_t dyn_count = 0; dyn_list[dyn_count++] = graphics_.viewport_with_count ? VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT : VK_DYNAMIC_STATE_VIEWPORT; @@ -13064,6 +13073,15 @@ class PipelineState final dynamic.dynamicStateCount = dyn_count; dynamic.pDynamicStates = dyn_list; + VkPipelineSampleLocationsStateCreateInfoEXT custom{VK_STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT}; + if (unbound & leonida::GraphicsPipeline::custom_samples) { + dyn_list[dyn_count++] = VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT; + dynamic.dynamicStateCount = dyn_count; + custom.sampleLocationsEnable = VK_TRUE; + custom.sampleLocationsInfo.sType = VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT; + custom.pNext = multisample.pNext; + multisample.pNext = &custom; + } // A lazy pipeline's stages get their modules here, for this one call (Vulkan lets a module go once the // pipeline exists), so the driver holds no SPIR-V for pipelines that are not drawn. auto bytes = stage_bytes_; @@ -14714,6 +14732,38 @@ class Device final if (info.conservative_rasterization) resolve.pNext = &conservative; VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve}; get_props2(info.physical, &props); + if (info.sample_locations) { + VkPhysicalDeviceSampleLocationsPropertiesEXT locations{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 sample_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &locations}; + get_props2(info.physical, &sample_props); + const auto get_grid = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMultisamplePropertiesEXT")); + if (get_grid && props.properties.limits.standardSampleLocations && locations.variableSampleLocations && locations.sampleLocationSubPixelBits >= 4 && + locations.sampleLocationCoordinateRange[0] <= 0 && locations.sampleLocationCoordinateRange[1] >= 15.f / 16) { + for (unsigned samples = 1; samples <= 16; samples *= 2) { + if (!(locations.sampleLocationSampleCounts & samples)) continue; + VkMultisamplePropertiesEXT grid{VK_STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT}; + get_grid(info.physical, VkSampleCountFlagBits(samples), &grid); + const auto extent = grid.maxSampleLocationGridSize; + if (extent.width && extent.height) state_.sample_grid_1 |= samples; + if (samples <= 4 && extent.width >= 2 && extent.height >= 2 && + extent.width % 2 == 0 && extent.height % 2 == 0) state_.sample_grid_4 |= samples; + } + const auto counts = (props.properties.limits.framebufferColorSampleCounts | + props.properties.limits.framebufferDepthSampleCounts | + props.properties.limits.framebufferStencilSampleCounts | + props.properties.limits.framebufferNoAttachmentsSampleCounts) & 31u; + // Four repeating pixels can name at most sixteen sample locations altogether. + const auto grid_counts = counts & (VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT); + const auto tier1_counts = counts & (VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT); + if (counts && (state_.sample_grid_1 & counts) == counts && + (state_.sample_grid_4 & grid_counts) == grid_counts) + state_.sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2; + else if (tier1_counts && (state_.sample_grid_1 & tier1_counts) == tier1_counts) + state_.sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_1; + } + } state_.conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER(leonida::conservative_raster::tier( info.conservative_rasterization, props.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize, conservative.degenerateTrianglesRasterized == VK_TRUE, @@ -19733,7 +19783,7 @@ class Device final auto* opts = static_cast(data); *opts = {}; opts->DepthBoundsTestSupported = state_.info.features.depthBounds ? TRUE : FALSE; - opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; + opts->ProgrammableSamplePositionsTier = state_.sample_positions_tier; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS3: { @@ -20514,7 +20564,7 @@ class Device final return kInvalidAllocation; } VkMemoryRequirements need{}; - const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format)); + const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format), state_.sample_grid_1); if (!state_.memory_requirements(create.info, need)) return kInvalidAllocation; if (tiled) { leonida::ResourceTiling tiling; @@ -22287,6 +22337,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin info.conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; }); + info.sample_locations = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME) == 0; + }); const bool has_host_image_copy = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME) == 0; }); @@ -22617,6 +22670,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); + if (info.sample_locations) device_extensions.push_back(VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME); if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index d7d7396408..ba0761e469 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -578,6 +578,20 @@ struct Predication { std::uint32_t op; // d3d12_predication }; +struct SamplePosition { + std::int8_t x, y; +}; + +struct SamplePositions { + std::uint32_t samples = 0; + std::uint32_t pixels = 0; + std::array positions{}; + + static constexpr bool valid_grid(std::uint32_t samples, std::uint32_t pixels) { + return (pixels == 1 || pixels == 4) && samples && !(samples & (samples - 1)) && samples <= 16 / pixels; + } +}; + // Query heaps are identified like resources, by the COM object's pointer value. A heap's type and size are checked // at replay, when the heap is known. using QueryHeapId = std::uintptr_t; @@ -705,7 +719,7 @@ struct AccelerationStructurePostbuild { using Command = std::variant; @@ -900,6 +914,8 @@ class CommandList { return true; } + bool set_sample_positions(const SamplePositions& pattern) { return append(pattern); } + // SetPredication. Turning it off ignores the offset and op, as D3D12 does. bool set_predication(const Predication& predication) { if (!predication.buffer) return append(Predication{0, 0, 0}); diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 18bcc07baa..69f9089ed0 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -125,8 +125,8 @@ struct VulkanDeviceFunctions { X(vkCmdPushConstants) X(vkCmdDispatch) \ X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ - X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) X(vkCmdSetDepthBounds) \ - X(vkCmdSetBlendConstants) X(vkCmdDraw) \ + X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ + X(vkCmdSetDepthBounds) X(vkCmdSetBlendConstants) X(vkCmdDraw) X(vkCmdSetSampleLocationsEXT) \ 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(vkCmdDrawMeshTasksIndirectCountEXT) \ @@ -1191,6 +1191,7 @@ class VulkanContext { replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; replay_.set_stencil_reference = vk.vkCmdSetStencilReference; + replay_.set_sample_locations = vk.vkCmdSetSampleLocationsEXT; replay_.set_blend_constants = vk.vkCmdSetBlendConstants; replay_.set_depth_bounds = vk.vkCmdSetDepthBounds; replay_.draw = vk.vkCmdDraw; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 4f3c476541..02b1c1513c 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -106,6 +106,7 @@ struct ResourceBinding { // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (the GPU has no D24): footprint copies of the depth plane convert // (depth24.h) and clears quantise to 24 bits. bool depth24_as_float = false; + bool sample_locations_depth = false; bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first // A D3D12 R32G32B32 texture (12 bytes a texel) held in an R32G32B32A32 image (16): footprints keep D3D12's 12 // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96). @@ -908,6 +909,7 @@ struct GraphicsPipeline { // and stencil. Null when it cannot be built. static constexpr std::uint32_t unbound_depth = 1u << 8; static constexpr std::uint32_t rectangle_stage = 1u << 9; + static constexpr std::uint32_t custom_samples = 1u << 10; // programmable sample positions are dynamic state // IA topology requiring a fourth-corner geometry stage. Zero when the PSO already contains the stage. std::uint32_t rectangle_variant_topology = 0; std::function variant; @@ -919,6 +921,7 @@ struct GraphicsPipeline { void* request_context = nullptr; bool large = false; // as ComputePipeline::large std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count + VkSampleCountFlags sample_grid_1 = 0, sample_grid_4 = 0; bool async_build = false; bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation std::uint64_t estimate = 0; // as ComputePipeline::estimate @@ -1223,6 +1226,7 @@ struct ReplayFunctions { PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; + PFN_vkCmdSetSampleLocationsEXT set_sample_locations = nullptr; PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; PFN_vkCmdSetDepthBounds set_depth_bounds = nullptr; // for depth-bounds pipelines only PFN_vkCmdDraw draw = nullptr; @@ -1793,14 +1797,53 @@ inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkI return range; } +// Vulkan's Standard Sample Locations table, expressed relative to the pixel centre in sixteenths. +inline const SamplePosition* standard_sample_positions(unsigned samples) { + static constexpr SamplePosition one[] = {{0, 0}}; + static constexpr SamplePosition two[] = {{4, 4}, {-4, -4}}; + static constexpr SamplePosition four[] = {{-2, -6}, {6, -2}, {-6, 2}, {2, 6}}; + static constexpr SamplePosition eight[] = {{1, -3}, {-1, 3}, {5, 1}, {-3, -5}, {-5, 5}, {-7, -1}, {3, 7}, {7, -7}}; + static constexpr SamplePosition sixteen[] = {{1, 1}, {-1, -3}, {-3, 2}, {4, -1}, {-5, -2}, {2, 5}, {5, 3}, {3, -5}, + {-2, 6}, {0, -7}, {-4, -6}, {-6, 4}, {-8, 0}, {7, -4}, {6, 7}, {-7, -8}}; + switch (samples) { + case 1: return one; + case 2: return two; + case 4: return four; + case 8: return eight; + case 16: return sixteen; + default: return nullptr; + } +} + +struct VulkanSampleLocations { + std::array positions; + VkSampleLocationsInfoEXT info; + + const VkSampleLocationsInfoEXT* set(unsigned samples, const SamplePositions* pattern) { + const bool custom = pattern && pattern->samples == samples && SamplePositions::valid_grid(samples, pattern->pixels); + const auto* source = custom ? pattern->positions.data() : standard_sample_positions(samples); + if (!source) return nullptr; + const unsigned side = custom && pattern->pixels == 4 ? 2 : 1; + const unsigned count = samples * side * side; + for (unsigned i = 0; i < count; ++i) + positions[i] = {(source[i].x + 8) / 16.f, (source[i].y + 8) / 16.f}; + info = {VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, nullptr, VkSampleCountFlagBits(samples), {side, side}, + count, positions.data()}; + return &info; + } +}; + inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, - VkPipelineStageFlags dst_stages) { + VkPipelineStageFlags dst_stages, const SamplePositions* active_samples = nullptr) { restrict_to_queue(vk, src_stages, src_access); restrict_to_queue(vk, dst_stages, dst_access); VkImageMemoryBarrier barrier{}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + VulkanSampleLocations locations; + if (resource.sample_locations_depth && old_layout != VK_IMAGE_LAYOUT_UNDEFINED && old_layout != new_layout) + barrier.pNext = locations.set(resource.samples, active_samples); barrier.srcAccessMask = src_access; barrier.dstAccessMask = dst_access; barrier.oldLayout = old_layout; @@ -1990,7 +2033,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com // when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run // expects; with not_zeroed, it is only moved. The tracker records it. inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, - ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker) { + ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker, const SamplePositions* active_samples = nullptr) { constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; for (auto& piece : pieces) { if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; @@ -2003,7 +2046,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer (vk.compute_copy_aspects(resource.format) & piece.range.aspectMask) == piece.range.aspectMask; if (resource.not_zeroed || (!can_clear && !color && !compute_depth)) { image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } else if (fmt.block > 1 || !can_clear) { const bool can_zero = vk.copy_buffer_to_image && @@ -2012,7 +2055,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); bool zeroed = true; for (auto aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) if (piece.range.aspectMask & aspect) @@ -2020,16 +2063,16 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer image_barrier(vk, command_buffer, resource, piece.range, dst, layout, zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } else { image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } } else { const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); if (piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) { const VkClearColorValue zero{}; vk.clear_color_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); @@ -2038,7 +2081,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer vk.clear_depth_stencil_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); } image_barrier(vk, command_buffer, resource, piece.range, dst, layout, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } piece.layout = layout; if (tracker) tracker->set(id, piece.range, layout); @@ -2548,10 +2591,10 @@ inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p) // promotion lets the copy run in place. Anything else is moved to `wanted` and tracked. inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, ResourceId id, const VkImageSubresourceRange& range, - VkImageLayout wanted, VkAccessFlags access, LayoutTracker* tracker) { + VkImageLayout wanted, VkAccessFlags access, LayoutTracker* tracker, const SamplePositions* active_samples = nullptr) { const VkImageLayout target = image_layout(resource, wanted); auto pieces = current(tracker, id, range, target); - initialize(vk, command_buffer, resource, id, pieces, target, tracker); + initialize(vk, command_buffer, resource, id, pieces, target, tracker, active_samples); // D3D12 orders back-to-back copies and resolves on a resource that stays in COPY_DEST or COPY_SOURCE without a // barrier from the application; Vulkan does not. A piece already in the transfer layout gets no layout // transition, so an earlier transfer write to it is ordered here instead (write-after-write and read-after-write, @@ -2573,7 +2616,7 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm } image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, - VK_PIPELINE_STAGE_TRANSFER_BIT); + VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); } if (tracker) tracker->set(id, range, target); return target; @@ -2584,14 +2627,14 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm template void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, const LayoutPieces& pieces, VkImageLayout target, const VulkanAccess& state, - VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) { + VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body, const SamplePositions* active_samples = nullptr) { for (const auto& piece : pieces) { if (piece.layout == target) { memory_barrier(vk, command_buffer, state.access, state.stages, target_access, target_stages); continue; } image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, state.access, state.stages, - target_access, target_stages); + target_access, target_stages, active_samples); } body(); for (const auto& piece : pieces) { @@ -2600,7 +2643,7 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const continue; } image_barrier(vk, command_buffer, resource, piece.range, target, piece.layout, target_access, target_stages, - state.access, state.stages); + state.access, state.stages, active_samples); } } @@ -2714,7 +2757,7 @@ namespace detail { // typeless texture is viewed as the format the pipeline renders. template ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, Resolve&& resolve, - const ReplayFunctions& vk, PreparedDraw& p) { + const ReplayFunctions& vk, PreparedDraw& p, const SamplePositions* pattern) { if (arguments) { const IndirectDrawArgs& arg = *arguments; const VkDeviceSize record_size = draw.mesh ? sizeof(VkDrawMeshTasksIndirectCommandEXT) @@ -2859,6 +2902,12 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R for (std::size_t slot = 0; slot < p.colors.size(); ++slot) if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; + if (pattern) { + const auto counts = pattern->pixels == 1 ? pipeline->sample_grid_1 : pipeline->sample_grid_4; + if (!vk.set_sample_locations || !SamplePositions::valid_grid(pattern->samples, pattern->pixels) || + pattern->samples != pipeline->samples || !(counts & pattern->samples)) return unsupported_at(__LINE__); + unbound |= GraphicsPipeline::custom_samples; + } if (pipeline->requested) pipeline->requested(pipeline->request_context, unbound); if (unbound || !p.pipeline) { const bool indirect_rect_variant = arguments && (unbound & GraphicsPipeline::rectangle_stage); @@ -3026,10 +3075,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { // Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const PreparedDraw::Attachment& a, VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, - LayoutTracker* tracker, bool separate) { + LayoutTracker* tracker, bool separate, const SamplePositions* active_samples = nullptr) { const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate); auto pieces = current(tracker, a.id, range, layout); - initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker); + initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker, active_samples); for (const auto& piece : pieces) { if (piece.layout == layout) { // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier. @@ -3037,7 +3086,7 @@ inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buf continue; } image_barrier(vk, command_buffer, a.binding, piece.range, piece.layout, layout, - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages); + VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages, active_samples); } if (tracker) tracker->set(a.id, range, layout); } @@ -3481,6 +3530,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun std::uint32_t so_active = 0; out.wrote_readback = false; out.readback_src_stages = 0; + const SamplePositions* sample_positions = nullptr; // Successive plane transfers use the same transient range and order their buffer accesses in emit(). VkBuffer plane_scratch = VK_NULL_HANDLE; @@ -4014,6 +4064,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; } + } else if (const auto* pattern = std::get_if(&command)) { + sample_positions = pattern->samples ? pattern : nullptr; } else if (const auto* predication = std::get_if(&command)) { predicated = predication->buffer != 0; if (!predicated) continue; @@ -4300,7 +4352,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun auto& prepared_draw = out.draws[out.draw_count]; prepared_draw.reset(); p.draw = std::uint32_t(out.draw_count++); - if (const auto r = detail::prepare_draw(*draw.state, draw.arguments, resolve, vk, prepared_draw); + if (const auto r = detail::prepare_draw(*draw.state, draw.arguments, resolve, vk, prepared_draw, + sample_positions); r != ReplayResult::success) { const bool strict = strict_replay(); if (r != ReplayResult::unresolved_resource || strict) return r; @@ -4649,6 +4702,7 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& template inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { + const SamplePositions* active_samples = nullptr; std::uint32_t own_labels = 0; std::uint32_t& labels = open_labels ? *open_labels : own_labels; const auto commands = prepared.list->commands(); @@ -4706,6 +4760,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); begin_statistics(); } + if (const auto* pattern = std::get_if(&command)) { + active_samples = pattern->samples ? pattern : nullptr; + continue; + } if (const auto* predication = std::get_if(&command)) { // Conditional rendering cannot nest, so a new predicate ends the previous one first. if (predicate.buffer) vk.end_conditional_rendering(command_buffer); @@ -4747,10 +4805,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const auto range = detail::planes_for_layout(p.binding, p.range, separate); const VkImageLayout new_layout = image_layout(p.binding, to.layout); auto pieces = detail::current(tracker, id, range, image_layout(p.binding, from.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker, active_samples); for (const auto& piece : pieces) detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, - from.access, from.stages, to.access, to.stages); + from.access, from.stages, to.access, to.stages, active_samples); if (tracker) tracker->set(id, range, new_layout); finish_depth_uav_barrier(p, new_layout, end_statistics, begin_statistics); } else if (std::holds_alternative(command)) { @@ -4817,7 +4875,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL : image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); pieces = detail::current(tracker, id, range, before); - if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); + if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker, active_samples); } const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); @@ -4827,6 +4885,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (pieces.size() > few.size()) many.resize(pieces.size()); VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); std::uint32_t barrier_count = 0; + detail::VulkanSampleLocations locations; + const auto* depth_locations = p.binding.sample_locations_depth ? locations.set(p.binding.samples, active_samples) : nullptr; for (const auto& piece : pieces) { // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order. if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue; @@ -4837,7 +4897,9 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ b.srcAccessMask = src.access; b.dstAccessMask = dst.access; b.oldLayout = piece.layout; - b.newLayout = release ? piece.layout : new_layout; + const VkImageLayout to = release ? piece.layout : new_layout; + if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED && piece.layout != to) b.pNext = depth_locations; + b.newLayout = to; b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; b.image = p.binding.image; @@ -4858,7 +4920,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker, active_samples); auto clear_value=color_clear->color; if(p.binding.rgba4_render_fallback)for(auto& channel:clear_value) channel=std::nearbyint(std::clamp(channel,0.0f,1.0f)*15.0f)/15.0f; @@ -4868,7 +4930,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ state, transfer_dst.access, transfer_dst.stages, [&] { vk.clear_color_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), &color, 1, &p.range); - }); + }, active_samples); continue; } const VkImageLayout attachment = image_layout(p.binding, state.layout); @@ -4889,7 +4951,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ attachment_clear.clearValue.color = color; vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); vk.end_rendering(command_buffer); - }); + }, active_samples); } else if (const auto* depth_clear = std::get_if(&command)) { if (p.skip) continue; if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); @@ -4897,7 +4959,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const auto range = detail::planes_for_layout(p.binding, p.range, separate); const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker, active_samples); float depth = p.binding.xbox_depth16_stencil8 ? detail::quantize_depth16(depth_clear->depth) : p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h : p.binding.format == VK_FORMAT_D16_UNORM @@ -4912,7 +4974,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ state, transfer_dst.access, transfer_dst.stages, [&] { vk.clear_depth_stencil_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), &value, 1, &p.range); - }); + }, active_samples); continue; } const VkImageLayout attachment = image_layout(p.binding, state.layout); @@ -4933,7 +4995,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ attachment_clear.clearValue.depthStencil = value; vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); vk.end_rendering(command_buffer); - }); + }, active_samples); } else if (const auto* uav = std::get_if(&command)) { if (p.skip) continue; if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); @@ -4960,7 +5022,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // Cleared in place in GENERAL, the UAV layout, which transfer clears and attachments both accept. const VkImageLayout layout = image_layout(p.binding, state.layout); auto pieces = detail::current(tracker, id, p.range, layout); - detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker); + detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker, active_samples); if (p.clear_pattern_bytes) { detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { @@ -4993,14 +5055,14 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } } } - }); + }, active_samples); continue; } if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { vk.clear_color_image(command_buffer, p.binding.image, layout, &p.clear_color, 1, &p.range); - }); + }, active_samples); continue; } detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, @@ -5021,7 +5083,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ attachment_clear.clearValue.color = p.clear_color; vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); vk.end_rendering(command_buffer); - }); + }, active_samples); } else if (std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command)) { if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); @@ -5048,14 +5110,14 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // synchronization-validation run). const VkImageLayout src_layout = detail::copy_layout( vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.staged, std::uint32_t(p.staged_reads.size()), p.staged_reads.data()); detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); const VkImageLayout dst_layout = detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); } else if (!p.image_copies.empty()) { @@ -5065,10 +5127,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT, - tracker); + tracker, active_samples); const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); const auto count = std::uint32_t(p.image_copies.size()); const auto depth_stencil = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; if (std::holds_alternative(command) && @@ -5119,13 +5181,13 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } const VkImageLayout dst_layout = detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); vk.copy_buffer_to_image(command_buffer, source, p.binding.image, dst_layout, std::uint32_t(regions->size()), regions->data()); } else { const VkImageLayout src_layout = detail::copy_layout( vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); if (!p.has_depth24) { const auto target = p.tile_scratch ? p.tile_scratch : p.binding.buffer; vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, target, @@ -5175,15 +5237,15 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const VkImageLayout dest_layout = image_layout(p.binding, dest_state.layout); auto source_pieces = detail::current( tracker, src_id, detail::planes_for_layout(p.source, p.source_range, separate), source_layout); - detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker); + detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker, active_samples); auto dest_pieces = detail::current( tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); - detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker); + detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker, active_samples); // The texels around the rectangle, kept in `staged` across the resolve (keep_around_resolve). const auto keep = [&](VkImageLayout wanted, VkAccessFlags access, auto&& copy) { const VkImageLayout layout = image_layout(p.binding, wanted); detail::round_trip(vk, command_buffer, p.binding, dest_pieces, layout, dest_state, access, - VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); }); + VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); }, active_samples); }; const auto bands = std::uint32_t(p.staged_reads.size()); if (p.staged) { @@ -5230,8 +5292,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ else rendering.pStencilAttachment = &info; vk.begin_rendering(command_buffer, &rendering); vk.end_rendering(command_buffer); - }); - }); + }, active_samples); + }, active_samples); if (p.staged) { keep(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, [&](VkImageLayout layout) { vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, bands, @@ -5242,10 +5304,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ } const VkImageLayout src_layout = detail::copy_layout( vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); const VkImageLayout dst_layout = detail::copy_layout( vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); vk.resolve_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, 1, &p.resolve); } else if (const auto* marker = std::get_if(&command)) { if (!vk.insert_label || !vk.begin_label || !vk.end_label) continue; @@ -5275,7 +5337,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) detail::image_barrier(vk, command_buffer, p.binding, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); } } else if (const auto* label_write=std::get_if(&command)) { vk.gpu_label(command_buffer, *label_write); @@ -5534,7 +5596,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (!a.id) continue; // an unbound slot: no image view, writes are dropped const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); detail::to_attachment(vk, command_buffer, a, layout, color_access, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate); + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate, active_samples); colors[slot].imageView = a.view; colors[slot].imageLayout = layout; colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; @@ -5544,7 +5606,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ if (d.depth.id) { const VkImageLayout layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, - separate); + separate, active_samples); depth.imageView = d.depth.view; depth.imageLayout = layout; depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; @@ -5624,6 +5686,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); } + if (active_samples) { + detail::VulkanSampleLocations locations; + vk.set_sample_locations(command_buffer, locations.set(active_samples->samples, active_samples)); + } vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); vk.set_blend_constants(command_buffer, draw->blend_factor.data()); diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp index ea81503e6e..e6b299590c 100644 --- a/runtime/test/command_list_test.cpp +++ b/runtime/test/command_list_test.cpp @@ -279,6 +279,22 @@ int main() { CHECK(std::get(predicated.commands()[1]).offset == 16); const auto& off = std::get(predicated.commands()[2]); CHECK(off.buffer == 0 && off.offset == 0 && off.op == 0); + CHECK(SamplePositions::valid_grid(16, 1)); + CHECK(SamplePositions::valid_grid(4, 4)); + CHECK(!SamplePositions::valid_grid(8, 4)); + CHECK(!SamplePositions::valid_grid(3, 1)); + CHECK(!SamplePositions::valid_grid(4, 0)); + CommandList sampled; + SamplePositions pattern{4, 4}; + pattern.positions[15] = {-8, 7}; + CHECK(sampled.set_sample_positions(pattern)); + pattern.positions[15] = {0, 0}; + CHECK(sampled.set_sample_positions({})); + CHECK(sampled.close()); + CHECK(!sampled.set_sample_positions(pattern)); + const auto& recorded_pattern = std::get(sampled.commands()[0]); + CHECK(recorded_pattern.positions[15].x == -8 && recorded_pattern.positions[15].y == 7); + CHECK(std::get(sampled.commands()[1]).samples == 0); // Queries: timestamps only end; other queries are begun and ended in one list, with the same type, and are not // begun twice or resolved while running. Resolve offsets are multiples of 8; a resolve of nothing records nothing. namespace q = d3d12_query; diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp index 3437fe0301..69e3f96240 100644 --- a/runtime/test/d3d12_msaa_draw_test.cpp +++ b/runtime/test/d3d12_msaa_draw_test.cpp @@ -46,11 +46,23 @@ D3D12_CPU_DESCRIPTOR_HANDLE heap_start(ID3D12DescriptorHeap* heap) { } // namespace -int main() { +int main(int argc, char** argv) { + const bool grid = argc == 2 && std::strcmp(argv[1], "--sample-grid") == 0; + const bool custom = grid || (argc == 2 && std::strcmp(argv[1], "--custom-samples") == 0); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU (hosted CI): ctest skips EXPECT(device_status == vktest::DeviceStatus::ready); + if (custom && !d.sample_locations) return 77; + if (grid) { + const auto query = reinterpret_cast( + d.instance_proc(d.instance, "vkGetPhysicalDeviceMultisamplePropertiesEXT")); + VkMultisamplePropertiesEXT props{VK_STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT}; + if (!query) return 77; + query(d.physical, VK_SAMPLE_COUNT_4_BIT, &props); + if (props.maxSampleLocationGridSize.width % 2 || props.maxSampleLocationGridSize.height % 2 || + !props.maxSampleLocationGridSize.width || !props.maxSampleLocationGridSize.height) return 77; + } const auto vs_program = fssm_program({0x56530001, 0xbf810000}); const auto ps_program = fssm_program({0x50530001, 0xbf810000}); @@ -83,6 +95,7 @@ int main() { info.queue = d.queue; info.queue_family = d.family; info.buffer_device_address = true; + info.sample_locations = custom && d.sample_locations; info.shader_dir = library.string(); ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); @@ -90,6 +103,12 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); + D3D12_FEATURE_DATA_D3D12_OPTIONS2 options{}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &options, sizeof(options)))); + if (!custom) EXPECT(options.ProgrammableSamplePositionsTier == D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED); + if (custom && options.ProgrammableSamplePositionsTier == D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED) return 77; + if (grid && options.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2) return 77; + std::printf("OPTIONS2 programmable sample positions tier %u\n", unsigned(options.ProgrammableSamplePositionsTier)); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_msaa_draw_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", rt::d3d12::device_max_push_constants_size(inner)); @@ -252,10 +271,39 @@ int main() { list->ResourceBarrier(1, &to_vertex); const FLOAT blue[4] = {0, 0, 1, 1}; list->ClearRenderTargetView(rtv, blue, 0, nullptr); + common_state(rtv, grid ? nullptr : &dsv); + if (custom) { + Ref list1; + EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list1.p)))); + D3D12_SAMPLE_POSITION locations[16]{}; + for (unsigned pixel = 0; pixel < 4; ++pixel) { + const int corner = (pixel & 1) ? 4 : -6; + for (int i = 0; i < 4; ++i) + locations[4 * pixel + i] = {INT8(corner + (i & 1)), INT8(corner + (i >> 1))}; + } + list1->SetSamplePositions(4, grid ? 4 : 1, locations); + } list->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); - common_state(rtv, &dsv); list->SetGraphicsRootConstantBufferView(1, upload_va + 512); // red + if (grid) { + const D3D12_RECT top{0, 0, size, size / 2}; + list->RSSetScissorRects(1, &top); + list->DrawInstanced(3, 1, 0, 0); + Ref list1; + EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list1.p)))); + list1->SetSamplePositions(0, 0, nullptr); + const D3D12_RECT bottom{0, size / 2, size, size}; + list->RSSetScissorRects(1, &bottom); + } list->DrawInstanced(3, 1, 0, 0); + if (!grid) { + const D3D12_RESOURCE_BARRIER depth_transitions[] = { + transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(depth.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_DEPTH_WRITE)}; + list->ResourceBarrier(2, depth_transitions); + list->SetGraphicsRootConstantBufferView(1, upload_va + 768); + list->DrawInstanced(3, 1, 0, 0); // equal depth fails LESS, so the original red must survive + } list->SetPipelineState(masked.p); list->SetGraphicsRootConstantBufferView(1, upload_va + 768); // green, sample 0 only list->DrawIndexedInstanced(6, 1, 0, 0, 0); @@ -330,6 +378,10 @@ int main() { // One of four samples green, three blue: 63.75 and 191.25, rounded either way by the resolve. if (got[0] != 0 || std::abs(int(got[1]) - 64) > 1 || std::abs(int(got[2]) - 191) > 1 || got[3] != 255) report(col, row, got, "0,64,191,255 (+-1)"); + } else if (custom && col + row == size - 1) { + const int red = grid && row >= size / 2 ? 128 : grid && (col & 1) ? 0 : 255; + if (std::abs(int(got[0]) - red) > 1 || got[1] || std::abs(int(got[2]) - (255 - red)) > 1 || got[3] != 255) + report(col, row, got, "coverage from the active sample pattern"); } else if (distance > margin) { if (!(got[0] == 255 && got[1] == 0 && got[2] == 0 && got[3] == 255)) report(col, row, got, "red"); } else if (distance < -margin) { @@ -343,7 +395,7 @@ int main() { } } EXPECT(!mismatches); - EXPECT(edge_mixed > 0); // single-sampled rendering leaves no partial pixels + if (!custom) EXPECT(edge_mixed > 0); if (d.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp index 3a096c27af..ec4b468e9e 100644 --- a/runtime/test/replay_texture_barrier_test.cpp +++ b/runtime/test/replay_texture_barrier_test.cpp @@ -479,6 +479,42 @@ int main() { } depth_uav_barriers(cb); + + { + image.format = VK_FORMAT_D32_SFLOAT; + image.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + image.samples = 4; + image.mip_levels = 1; + image.sample_locations_depth = true; + LayoutTracker depth_tracker; + depth_tracker.track(id, image, transfer_src); + vk.pipeline_barrier2 = [](VkCommandBuffer, const VkDependencyInfo* info) { + const auto& barrier = info->pImageMemoryBarriers[0]; + const auto* pattern = static_cast(barrier.pNext); + expect(pattern && pattern->sType == VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, "depth sample locations"); + if (!pattern) return; + const bool custom = barrier.oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + expect(pattern->sampleLocationsCount == 4 && pattern->sampleLocationsPerPixel == VK_SAMPLE_COUNT_4_BIT && + pattern->sampleLocationGridSize.width == 1 && pattern->sampleLocationGridSize.height == 1, + "depth sample grid"); + expect(pattern->pSampleLocations[0].x == (custom ? 0.f : 0.375f) && + pattern->pSampleLocations[0].y == (custom ? 0.9375f : 0.125f), "depth sample before and after reset"); + ++g_calls; + }; + g_calls = 0; + SamplePositions pattern{4, 1}; + pattern.positions[0] = {-8, 7}; + CommandList list; + expect(list.set_sample_positions(pattern) && + list.barrier(TextureBarrier{y::copy, y::copy, a::copy_source, a::copy_dest, l::copy_source, l::copy_dest, id, all, 0}) && + list.set_sample_positions({}) && + list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source, l::copy_dest, l::copy_source, id, all, 0}) && + list.close(), "record depth transitions"); + PreparedList prepared; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare depth transitions"); + emit(prepared, cb, vk, &depth_tracker); + expect(g_calls == 2, "both depth transitions emitted"); + } if (failures) return 1; std::printf("replay_texture_barrier_test: OK\n"); return 0; diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 8369d594c7..6a97b529ab 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -135,6 +135,7 @@ class Device { bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available + bool sample_locations = false; bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled bool mesh_shader_queries = false; // the meshShaderQueries feature is enabled on the device @@ -723,6 +724,10 @@ class Device { return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; }); if (conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); + sample_locations = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME) == 0; + }); + if (sample_locations) device_extensions.push_back(VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME); if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (conditional_rendering) device_extensions.push_back(conditional_extension);